blob: e9a3b03483625ff292da293c339736371eb3af5d [file] [log] [blame]
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- 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 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 "clang/AST/Mangle.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/ABI.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/raw_ostream.h"
33
34#define MANGLE_CHECKER 0
35
36#if MANGLE_CHECKER
37#include <cxxabi.h>
38#endif
39
40using namespace clang;
41
42namespace {
43
44/// \brief Retrieve the declaration context that should be used when mangling
45/// the given declaration.
46static const DeclContext *getEffectiveDeclContext(const Decl *D) {
47 // The ABI assumes that lambda closure types that occur within
48 // default arguments live in the context of the function. However, due to
49 // the way in which Clang parses and creates function declarations, this is
50 // not the case: the lambda closure type ends up living in the context
51 // where the function itself resides, because the function declaration itself
52 // had not yet been created. Fix the context here.
53 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
54 if (RD->isLambda())
55 if (ParmVarDecl *ContextParam
56 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
57 return ContextParam->getDeclContext();
58 }
59
60 return D->getDeclContext();
61}
62
63static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
64 return getEffectiveDeclContext(cast<Decl>(DC));
65}
66
67static const CXXRecordDecl *GetLocalClassDecl(const NamedDecl *ND) {
68 const DeclContext *DC = dyn_cast<DeclContext>(ND);
69 if (!DC)
70 DC = getEffectiveDeclContext(ND);
71 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
72 const DeclContext *Parent = getEffectiveDeclContext(cast<Decl>(DC));
73 if (isa<FunctionDecl>(Parent))
74 return dyn_cast<CXXRecordDecl>(DC);
75 DC = Parent;
76 }
77 return 0;
78}
79
80static const FunctionDecl *getStructor(const FunctionDecl *fn) {
81 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
82 return ftd->getTemplatedDecl();
83
84 return fn;
85}
86
87static const NamedDecl *getStructor(const NamedDecl *decl) {
88 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
89 return (fn ? getStructor(fn) : decl);
90}
91
92static const unsigned UnknownArity = ~0U;
93
94class ItaniumMangleContext : public MangleContext {
95 llvm::DenseMap<const TagDecl *, uint64_t> AnonStructIds;
96 unsigned Discriminator;
97 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
98
99public:
100 explicit ItaniumMangleContext(ASTContext &Context,
101 DiagnosticsEngine &Diags)
102 : MangleContext(Context, Diags) { }
103
104 uint64_t getAnonymousStructId(const TagDecl *TD) {
105 std::pair<llvm::DenseMap<const TagDecl *,
106 uint64_t>::iterator, bool> Result =
107 AnonStructIds.insert(std::make_pair(TD, AnonStructIds.size()));
108 return Result.first->second;
109 }
110
111 void startNewFunction() {
112 MangleContext::startNewFunction();
113 mangleInitDiscriminator();
114 }
115
116 /// @name Mangler Entry Points
117 /// @{
118
119 bool shouldMangleDeclName(const NamedDecl *D);
120 void mangleName(const NamedDecl *D, raw_ostream &);
121 void mangleThunk(const CXXMethodDecl *MD,
122 const ThunkInfo &Thunk,
123 raw_ostream &);
124 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
125 const ThisAdjustment &ThisAdjustment,
126 raw_ostream &);
127 void mangleReferenceTemporary(const VarDecl *D,
128 raw_ostream &);
129 void mangleCXXVTable(const CXXRecordDecl *RD,
130 raw_ostream &);
131 void mangleCXXVTT(const CXXRecordDecl *RD,
132 raw_ostream &);
133 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
134 const CXXRecordDecl *Type,
135 raw_ostream &);
136 void mangleCXXRTTI(QualType T, raw_ostream &);
137 void mangleCXXRTTIName(QualType T, raw_ostream &);
138 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
139 raw_ostream &);
140 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
141 raw_ostream &);
142
143 void mangleItaniumGuardVariable(const VarDecl *D, raw_ostream &);
144
145 void mangleInitDiscriminator() {
146 Discriminator = 0;
147 }
148
149 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
150 // Lambda closure types with external linkage (indicated by a
151 // non-zero lambda mangling number) have their own numbering scheme, so
152 // they do not need a discriminator.
153 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND))
154 if (RD->isLambda() && RD->getLambdaManglingNumber() > 0)
155 return false;
156
157 unsigned &discriminator = Uniquifier[ND];
158 if (!discriminator)
159 discriminator = ++Discriminator;
160 if (discriminator == 1)
161 return false;
162 disc = discriminator-2;
163 return true;
164 }
165 /// @}
166};
167
168/// CXXNameMangler - Manage the mangling of a single name.
169class CXXNameMangler {
170 ItaniumMangleContext &Context;
171 raw_ostream &Out;
172
173 /// The "structor" is the top-level declaration being mangled, if
174 /// that's not a template specialization; otherwise it's the pattern
175 /// for that specialization.
176 const NamedDecl *Structor;
177 unsigned StructorType;
178
179 /// SeqID - The next subsitution sequence number.
180 unsigned SeqID;
181
182 class FunctionTypeDepthState {
183 unsigned Bits;
184
185 enum { InResultTypeMask = 1 };
186
187 public:
188 FunctionTypeDepthState() : Bits(0) {}
189
190 /// The number of function types we're inside.
191 unsigned getDepth() const {
192 return Bits >> 1;
193 }
194
195 /// True if we're in the return type of the innermost function type.
196 bool isInResultType() const {
197 return Bits & InResultTypeMask;
198 }
199
200 FunctionTypeDepthState push() {
201 FunctionTypeDepthState tmp = *this;
202 Bits = (Bits & ~InResultTypeMask) + 2;
203 return tmp;
204 }
205
206 void enterResultType() {
207 Bits |= InResultTypeMask;
208 }
209
210 void leaveResultType() {
211 Bits &= ~InResultTypeMask;
212 }
213
214 void pop(FunctionTypeDepthState saved) {
215 assert(getDepth() == saved.getDepth() + 1);
216 Bits = saved.Bits;
217 }
218
219 } FunctionTypeDepth;
220
221 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
222
223 ASTContext &getASTContext() const { return Context.getASTContext(); }
224
225public:
226 CXXNameMangler(ItaniumMangleContext &C, raw_ostream &Out_,
227 const NamedDecl *D = 0)
228 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
229 SeqID(0) {
230 // These can't be mangled without a ctor type or dtor type.
231 assert(!D || (!isa<CXXDestructorDecl>(D) &&
232 !isa<CXXConstructorDecl>(D)));
233 }
234 CXXNameMangler(ItaniumMangleContext &C, raw_ostream &Out_,
235 const CXXConstructorDecl *D, CXXCtorType Type)
236 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
237 SeqID(0) { }
238 CXXNameMangler(ItaniumMangleContext &C, raw_ostream &Out_,
239 const CXXDestructorDecl *D, CXXDtorType Type)
240 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
241 SeqID(0) { }
242
243#if MANGLE_CHECKER
244 ~CXXNameMangler() {
245 if (Out.str()[0] == '\01')
246 return;
247
248 int status = 0;
249 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
250 assert(status == 0 && "Could not demangle mangled name!");
251 free(result);
252 }
253#endif
254 raw_ostream &getStream() { return Out; }
255
256 void mangle(const NamedDecl *D, StringRef Prefix = "_Z");
257 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
258 void mangleNumber(const llvm::APSInt &I);
259 void mangleNumber(int64_t Number);
260 void mangleFloat(const llvm::APFloat &F);
261 void mangleFunctionEncoding(const FunctionDecl *FD);
262 void mangleName(const NamedDecl *ND);
263 void mangleType(QualType T);
264 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
265
266private:
267 bool mangleSubstitution(const NamedDecl *ND);
268 bool mangleSubstitution(QualType T);
269 bool mangleSubstitution(TemplateName Template);
270 bool mangleSubstitution(uintptr_t Ptr);
271
272 void mangleExistingSubstitution(QualType type);
273 void mangleExistingSubstitution(TemplateName name);
274
275 bool mangleStandardSubstitution(const NamedDecl *ND);
276
277 void addSubstitution(const NamedDecl *ND) {
278 ND = cast<NamedDecl>(ND->getCanonicalDecl());
279
280 addSubstitution(reinterpret_cast<uintptr_t>(ND));
281 }
282 void addSubstitution(QualType T);
283 void addSubstitution(TemplateName Template);
284 void addSubstitution(uintptr_t Ptr);
285
286 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
287 NamedDecl *firstQualifierLookup,
288 bool recursive = false);
289 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
290 NamedDecl *firstQualifierLookup,
291 DeclarationName name,
292 unsigned KnownArity = UnknownArity);
293
294 void mangleName(const TemplateDecl *TD,
295 const TemplateArgument *TemplateArgs,
296 unsigned NumTemplateArgs);
297 void mangleUnqualifiedName(const NamedDecl *ND) {
298 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
299 }
300 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
301 unsigned KnownArity);
302 void mangleUnscopedName(const NamedDecl *ND);
303 void mangleUnscopedTemplateName(const TemplateDecl *ND);
304 void mangleUnscopedTemplateName(TemplateName);
305 void mangleSourceName(const IdentifierInfo *II);
306 void mangleLocalName(const NamedDecl *ND);
307 void mangleLambda(const CXXRecordDecl *Lambda);
308 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
309 bool NoFunction=false);
310 void mangleNestedName(const TemplateDecl *TD,
311 const TemplateArgument *TemplateArgs,
312 unsigned NumTemplateArgs);
313 void manglePrefix(NestedNameSpecifier *qualifier);
314 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
315 void manglePrefix(QualType type);
316 void mangleTemplatePrefix(const TemplateDecl *ND);
317 void mangleTemplatePrefix(TemplateName Template);
318 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
319 void mangleQualifiers(Qualifiers Quals);
320 void mangleRefQualifier(RefQualifierKind RefQualifier);
321
322 void mangleObjCMethodName(const ObjCMethodDecl *MD);
323
324 // Declare manglers for every type class.
325#define ABSTRACT_TYPE(CLASS, PARENT)
326#define NON_CANONICAL_TYPE(CLASS, PARENT)
327#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
328#include "clang/AST/TypeNodes.def"
329
330 void mangleType(const TagType*);
331 void mangleType(TemplateName);
332 void mangleBareFunctionType(const FunctionType *T,
333 bool MangleReturnType);
334 void mangleNeonVectorType(const VectorType *T);
335
336 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
337 void mangleMemberExpr(const Expr *base, bool isArrow,
338 NestedNameSpecifier *qualifier,
339 NamedDecl *firstQualifierLookup,
340 DeclarationName name,
341 unsigned knownArity);
342 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
343 void mangleCXXCtorType(CXXCtorType T);
344 void mangleCXXDtorType(CXXDtorType T);
345
346 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
347 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
348 unsigned NumTemplateArgs);
349 void mangleTemplateArgs(const TemplateArgumentList &AL);
350 void mangleTemplateArg(TemplateArgument A);
351
352 void mangleTemplateParameter(unsigned Index);
353
354 void mangleFunctionParam(const ParmVarDecl *parm);
355};
356
357}
358
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000359bool ItaniumMangleContext::shouldMangleDeclName(const NamedDecl *D) {
360 // In C, functions with no attributes never need to be mangled. Fastpath them.
361 if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
362 return false;
363
364 // Any decl can be declared with __asm("foo") on it, and this takes precedence
365 // over all other naming in the .o file.
366 if (D->hasAttr<AsmLabelAttr>())
367 return true;
368
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000369 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolad2fdd422013-02-14 01:47:04 +0000370 if (FD) {
371 LanguageLinkage L = FD->getLanguageLinkage();
372 // Overloadable functions need mangling.
373 if (FD->hasAttr<OverloadableAttr>())
374 return true;
375
376 // C functions and "main" are not mangled.
377 if (FD->isMain() || L == CLanguageLinkage)
378 return false;
379
380 // C++ functions and those whose names are not a simple identifier need
381 // mangling.
382 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
383 return true;
384 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000385
386 // Otherwise, no mangling is done outside C++ mode.
387 if (!getASTContext().getLangOpts().CPlusPlus)
388 return false;
389
Rafael Espindolad2fdd422013-02-14 01:47:04 +0000390 const VarDecl *VD = dyn_cast<VarDecl>(D);
391 if (VD) {
392 // C variables are not mangled.
393 if (VD->isExternC())
394 return false;
395
396 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000397 const DeclContext *DC = getEffectiveDeclContext(D);
398 // Check for extern variable declared locally.
399 if (DC->isFunctionOrMethod() && D->hasLinkage())
400 while (!DC->isNamespace() && !DC->isTranslationUnit())
401 DC = getEffectiveParentContext(DC);
402 if (DC->isTranslationUnit() && D->getLinkage() != InternalLinkage)
403 return false;
404 }
405
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000406 return true;
407}
408
409void CXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
410 // Any decl can be declared with __asm("foo") on it, and this takes precedence
411 // over all other naming in the .o file.
412 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
413 // If we have an asm name, then we use it as the mangling.
414
415 // Adding the prefix can cause problems when one file has a "foo" and
416 // another has a "\01foo". That is known to happen on ELF with the
417 // tricks normally used for producing aliases (PR9177). Fortunately the
418 // llvm mangler on ELF is a nop, so we can just avoid adding the \01
419 // marker. We also avoid adding the marker if this is an alias for an
420 // LLVM intrinsic.
421 StringRef UserLabelPrefix =
422 getASTContext().getTargetInfo().getUserLabelPrefix();
423 if (!UserLabelPrefix.empty() && !ALA->getLabel().startswith("llvm."))
424 Out << '\01'; // LLVM IR Marker for __asm("foo")
425
426 Out << ALA->getLabel();
427 return;
428 }
429
430 // <mangled-name> ::= _Z <encoding>
431 // ::= <data name>
432 // ::= <special-name>
433 Out << Prefix;
434 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
435 mangleFunctionEncoding(FD);
436 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
437 mangleName(VD);
438 else
439 mangleName(cast<FieldDecl>(D));
440}
441
442void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
443 // <encoding> ::= <function name> <bare-function-type>
444 mangleName(FD);
445
446 // Don't mangle in the type if this isn't a decl we should typically mangle.
447 if (!Context.shouldMangleDeclName(FD))
448 return;
449
450 // Whether the mangling of a function type includes the return type depends on
451 // the context and the nature of the function. The rules for deciding whether
452 // the return type is included are:
453 //
454 // 1. Template functions (names or types) have return types encoded, with
455 // the exceptions listed below.
456 // 2. Function types not appearing as part of a function name mangling,
457 // e.g. parameters, pointer types, etc., have return type encoded, with the
458 // exceptions listed below.
459 // 3. Non-template function names do not have return types encoded.
460 //
461 // The exceptions mentioned in (1) and (2) above, for which the return type is
462 // never included, are
463 // 1. Constructors.
464 // 2. Destructors.
465 // 3. Conversion operator functions, e.g. operator int.
466 bool MangleReturnType = false;
467 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
468 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
469 isa<CXXConversionDecl>(FD)))
470 MangleReturnType = true;
471
472 // Mangle the type of the primary template.
473 FD = PrimaryTemplate->getTemplatedDecl();
474 }
475
476 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
477 MangleReturnType);
478}
479
480static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
481 while (isa<LinkageSpecDecl>(DC)) {
482 DC = getEffectiveParentContext(DC);
483 }
484
485 return DC;
486}
487
488/// isStd - Return whether a given namespace is the 'std' namespace.
489static bool isStd(const NamespaceDecl *NS) {
490 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
491 ->isTranslationUnit())
492 return false;
493
494 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
495 return II && II->isStr("std");
496}
497
498// isStdNamespace - Return whether a given decl context is a toplevel 'std'
499// namespace.
500static bool isStdNamespace(const DeclContext *DC) {
501 if (!DC->isNamespace())
502 return false;
503
504 return isStd(cast<NamespaceDecl>(DC));
505}
506
507static const TemplateDecl *
508isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
509 // Check if we have a function template.
510 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
511 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
512 TemplateArgs = FD->getTemplateSpecializationArgs();
513 return TD;
514 }
515 }
516
517 // Check if we have a class template.
518 if (const ClassTemplateSpecializationDecl *Spec =
519 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
520 TemplateArgs = &Spec->getTemplateArgs();
521 return Spec->getSpecializedTemplate();
522 }
523
524 return 0;
525}
526
527static bool isLambda(const NamedDecl *ND) {
528 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
529 if (!Record)
530 return false;
531
532 return Record->isLambda();
533}
534
535void CXXNameMangler::mangleName(const NamedDecl *ND) {
536 // <name> ::= <nested-name>
537 // ::= <unscoped-name>
538 // ::= <unscoped-template-name> <template-args>
539 // ::= <local-name>
540 //
541 const DeclContext *DC = getEffectiveDeclContext(ND);
542
543 // If this is an extern variable declared locally, the relevant DeclContext
544 // is that of the containing namespace, or the translation unit.
545 // FIXME: This is a hack; extern variables declared locally should have
546 // a proper semantic declaration context!
547 if (isa<FunctionDecl>(DC) && ND->hasLinkage() && !isLambda(ND))
548 while (!DC->isNamespace() && !DC->isTranslationUnit())
549 DC = getEffectiveParentContext(DC);
550 else if (GetLocalClassDecl(ND)) {
551 mangleLocalName(ND);
552 return;
553 }
554
555 DC = IgnoreLinkageSpecDecls(DC);
556
557 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
558 // Check if we have a template.
559 const TemplateArgumentList *TemplateArgs = 0;
560 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
561 mangleUnscopedTemplateName(TD);
562 mangleTemplateArgs(*TemplateArgs);
563 return;
564 }
565
566 mangleUnscopedName(ND);
567 return;
568 }
569
570 if (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)) {
571 mangleLocalName(ND);
572 return;
573 }
574
575 mangleNestedName(ND, DC);
576}
577void CXXNameMangler::mangleName(const TemplateDecl *TD,
578 const TemplateArgument *TemplateArgs,
579 unsigned NumTemplateArgs) {
580 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
581
582 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
583 mangleUnscopedTemplateName(TD);
584 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
585 } else {
586 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
587 }
588}
589
590void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
591 // <unscoped-name> ::= <unqualified-name>
592 // ::= St <unqualified-name> # ::std::
593
594 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
595 Out << "St";
596
597 mangleUnqualifiedName(ND);
598}
599
600void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
601 // <unscoped-template-name> ::= <unscoped-name>
602 // ::= <substitution>
603 if (mangleSubstitution(ND))
604 return;
605
606 // <template-template-param> ::= <template-param>
607 if (const TemplateTemplateParmDecl *TTP
608 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
609 mangleTemplateParameter(TTP->getIndex());
610 return;
611 }
612
613 mangleUnscopedName(ND->getTemplatedDecl());
614 addSubstitution(ND);
615}
616
617void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
618 // <unscoped-template-name> ::= <unscoped-name>
619 // ::= <substitution>
620 if (TemplateDecl *TD = Template.getAsTemplateDecl())
621 return mangleUnscopedTemplateName(TD);
622
623 if (mangleSubstitution(Template))
624 return;
625
626 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
627 assert(Dependent && "Not a dependent template name?");
628 if (const IdentifierInfo *Id = Dependent->getIdentifier())
629 mangleSourceName(Id);
630 else
631 mangleOperatorName(Dependent->getOperator(), UnknownArity);
632
633 addSubstitution(Template);
634}
635
636void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
637 // ABI:
638 // Floating-point literals are encoded using a fixed-length
639 // lowercase hexadecimal string corresponding to the internal
640 // representation (IEEE on Itanium), high-order bytes first,
641 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
642 // on Itanium.
643 // The 'without leading zeroes' thing seems to be an editorial
644 // mistake; see the discussion on cxx-abi-dev beginning on
645 // 2012-01-16.
646
647 // Our requirements here are just barely weird enough to justify
648 // using a custom algorithm instead of post-processing APInt::toString().
649
650 llvm::APInt valueBits = f.bitcastToAPInt();
651 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
652 assert(numCharacters != 0);
653
654 // Allocate a buffer of the right number of characters.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000655 SmallVector<char, 20> buffer;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000656 buffer.set_size(numCharacters);
657
658 // Fill the buffer left-to-right.
659 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
660 // The bit-index of the next hex digit.
661 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
662
663 // Project out 4 bits starting at 'digitIndex'.
664 llvm::integerPart hexDigit
665 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
666 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
667 hexDigit &= 0xF;
668
669 // Map that over to a lowercase hex digit.
670 static const char charForHex[16] = {
671 '0', '1', '2', '3', '4', '5', '6', '7',
672 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
673 };
674 buffer[stringIndex] = charForHex[hexDigit];
675 }
676
677 Out.write(buffer.data(), numCharacters);
678}
679
680void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
681 if (Value.isSigned() && Value.isNegative()) {
682 Out << 'n';
683 Value.abs().print(Out, /*signed*/ false);
684 } else {
685 Value.print(Out, /*signed*/ false);
686 }
687}
688
689void CXXNameMangler::mangleNumber(int64_t Number) {
690 // <number> ::= [n] <non-negative decimal integer>
691 if (Number < 0) {
692 Out << 'n';
693 Number = -Number;
694 }
695
696 Out << Number;
697}
698
699void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
700 // <call-offset> ::= h <nv-offset> _
701 // ::= v <v-offset> _
702 // <nv-offset> ::= <offset number> # non-virtual base override
703 // <v-offset> ::= <offset number> _ <virtual offset number>
704 // # virtual base override, with vcall offset
705 if (!Virtual) {
706 Out << 'h';
707 mangleNumber(NonVirtual);
708 Out << '_';
709 return;
710 }
711
712 Out << 'v';
713 mangleNumber(NonVirtual);
714 Out << '_';
715 mangleNumber(Virtual);
716 Out << '_';
717}
718
719void CXXNameMangler::manglePrefix(QualType type) {
720 if (const TemplateSpecializationType *TST =
721 type->getAs<TemplateSpecializationType>()) {
722 if (!mangleSubstitution(QualType(TST, 0))) {
723 mangleTemplatePrefix(TST->getTemplateName());
724
725 // FIXME: GCC does not appear to mangle the template arguments when
726 // the template in question is a dependent template name. Should we
727 // emulate that badness?
728 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
729 addSubstitution(QualType(TST, 0));
730 }
731 } else if (const DependentTemplateSpecializationType *DTST
732 = type->getAs<DependentTemplateSpecializationType>()) {
733 TemplateName Template
734 = getASTContext().getDependentTemplateName(DTST->getQualifier(),
735 DTST->getIdentifier());
736 mangleTemplatePrefix(Template);
737
738 // FIXME: GCC does not appear to mangle the template arguments when
739 // the template in question is a dependent template name. Should we
740 // emulate that badness?
741 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
742 } else {
743 // We use the QualType mangle type variant here because it handles
744 // substitutions.
745 mangleType(type);
746 }
747}
748
749/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
750///
751/// \param firstQualifierLookup - the entity found by unqualified lookup
752/// for the first name in the qualifier, if this is for a member expression
753/// \param recursive - true if this is being called recursively,
754/// i.e. if there is more prefix "to the right".
755void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
756 NamedDecl *firstQualifierLookup,
757 bool recursive) {
758
759 // x, ::x
760 // <unresolved-name> ::= [gs] <base-unresolved-name>
761
762 // T::x / decltype(p)::x
763 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
764
765 // T::N::x /decltype(p)::N::x
766 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
767 // <base-unresolved-name>
768
769 // A::x, N::y, A<T>::z; "gs" means leading "::"
770 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
771 // <base-unresolved-name>
772
773 switch (qualifier->getKind()) {
774 case NestedNameSpecifier::Global:
775 Out << "gs";
776
777 // We want an 'sr' unless this is the entire NNS.
778 if (recursive)
779 Out << "sr";
780
781 // We never want an 'E' here.
782 return;
783
784 case NestedNameSpecifier::Namespace:
785 if (qualifier->getPrefix())
786 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
787 /*recursive*/ true);
788 else
789 Out << "sr";
790 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
791 break;
792 case NestedNameSpecifier::NamespaceAlias:
793 if (qualifier->getPrefix())
794 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
795 /*recursive*/ true);
796 else
797 Out << "sr";
798 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
799 break;
800
801 case NestedNameSpecifier::TypeSpec:
802 case NestedNameSpecifier::TypeSpecWithTemplate: {
803 const Type *type = qualifier->getAsType();
804
805 // We only want to use an unresolved-type encoding if this is one of:
806 // - a decltype
807 // - a template type parameter
808 // - a template template parameter with arguments
809 // In all of these cases, we should have no prefix.
810 if (qualifier->getPrefix()) {
811 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
812 /*recursive*/ true);
813 } else {
814 // Otherwise, all the cases want this.
815 Out << "sr";
816 }
817
818 // Only certain other types are valid as prefixes; enumerate them.
819 switch (type->getTypeClass()) {
820 case Type::Builtin:
821 case Type::Complex:
822 case Type::Pointer:
823 case Type::BlockPointer:
824 case Type::LValueReference:
825 case Type::RValueReference:
826 case Type::MemberPointer:
827 case Type::ConstantArray:
828 case Type::IncompleteArray:
829 case Type::VariableArray:
830 case Type::DependentSizedArray:
831 case Type::DependentSizedExtVector:
832 case Type::Vector:
833 case Type::ExtVector:
834 case Type::FunctionProto:
835 case Type::FunctionNoProto:
836 case Type::Enum:
837 case Type::Paren:
838 case Type::Elaborated:
839 case Type::Attributed:
840 case Type::Auto:
841 case Type::PackExpansion:
842 case Type::ObjCObject:
843 case Type::ObjCInterface:
844 case Type::ObjCObjectPointer:
845 case Type::Atomic:
846 llvm_unreachable("type is illegal as a nested name specifier");
847
848 case Type::SubstTemplateTypeParmPack:
849 // FIXME: not clear how to mangle this!
850 // template <class T...> class A {
851 // template <class U...> void foo(decltype(T::foo(U())) x...);
852 // };
853 Out << "_SUBSTPACK_";
854 break;
855
856 // <unresolved-type> ::= <template-param>
857 // ::= <decltype>
858 // ::= <template-template-param> <template-args>
859 // (this last is not official yet)
860 case Type::TypeOfExpr:
861 case Type::TypeOf:
862 case Type::Decltype:
863 case Type::TemplateTypeParm:
864 case Type::UnaryTransform:
865 case Type::SubstTemplateTypeParm:
866 unresolvedType:
867 assert(!qualifier->getPrefix());
868
869 // We only get here recursively if we're followed by identifiers.
870 if (recursive) Out << 'N';
871
872 // This seems to do everything we want. It's not really
873 // sanctioned for a substituted template parameter, though.
874 mangleType(QualType(type, 0));
875
876 // We never want to print 'E' directly after an unresolved-type,
877 // so we return directly.
878 return;
879
880 case Type::Typedef:
881 mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier());
882 break;
883
884 case Type::UnresolvedUsing:
885 mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl()
886 ->getIdentifier());
887 break;
888
889 case Type::Record:
890 mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier());
891 break;
892
893 case Type::TemplateSpecialization: {
894 const TemplateSpecializationType *tst
895 = cast<TemplateSpecializationType>(type);
896 TemplateName name = tst->getTemplateName();
897 switch (name.getKind()) {
898 case TemplateName::Template:
899 case TemplateName::QualifiedTemplate: {
900 TemplateDecl *temp = name.getAsTemplateDecl();
901
902 // If the base is a template template parameter, this is an
903 // unresolved type.
904 assert(temp && "no template for template specialization type");
905 if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType;
906
907 mangleSourceName(temp->getIdentifier());
908 break;
909 }
910
911 case TemplateName::OverloadedTemplate:
912 case TemplateName::DependentTemplate:
913 llvm_unreachable("invalid base for a template specialization type");
914
915 case TemplateName::SubstTemplateTemplateParm: {
916 SubstTemplateTemplateParmStorage *subst
917 = name.getAsSubstTemplateTemplateParm();
918 mangleExistingSubstitution(subst->getReplacement());
919 break;
920 }
921
922 case TemplateName::SubstTemplateTemplateParmPack: {
923 // FIXME: not clear how to mangle this!
924 // template <template <class U> class T...> class A {
925 // template <class U...> void foo(decltype(T<U>::foo) x...);
926 // };
927 Out << "_SUBSTPACK_";
928 break;
929 }
930 }
931
932 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
933 break;
934 }
935
936 case Type::InjectedClassName:
937 mangleSourceName(cast<InjectedClassNameType>(type)->getDecl()
938 ->getIdentifier());
939 break;
940
941 case Type::DependentName:
942 mangleSourceName(cast<DependentNameType>(type)->getIdentifier());
943 break;
944
945 case Type::DependentTemplateSpecialization: {
946 const DependentTemplateSpecializationType *tst
947 = cast<DependentTemplateSpecializationType>(type);
948 mangleSourceName(tst->getIdentifier());
949 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
950 break;
951 }
952 }
953 break;
954 }
955
956 case NestedNameSpecifier::Identifier:
957 // Member expressions can have these without prefixes.
958 if (qualifier->getPrefix()) {
959 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
960 /*recursive*/ true);
961 } else if (firstQualifierLookup) {
962
963 // Try to make a proper qualifier out of the lookup result, and
964 // then just recurse on that.
965 NestedNameSpecifier *newQualifier;
966 if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) {
967 QualType type = getASTContext().getTypeDeclType(typeDecl);
968
969 // Pretend we had a different nested name specifier.
970 newQualifier = NestedNameSpecifier::Create(getASTContext(),
971 /*prefix*/ 0,
972 /*template*/ false,
973 type.getTypePtr());
974 } else if (NamespaceDecl *nspace =
975 dyn_cast<NamespaceDecl>(firstQualifierLookup)) {
976 newQualifier = NestedNameSpecifier::Create(getASTContext(),
977 /*prefix*/ 0,
978 nspace);
979 } else if (NamespaceAliasDecl *alias =
980 dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) {
981 newQualifier = NestedNameSpecifier::Create(getASTContext(),
982 /*prefix*/ 0,
983 alias);
984 } else {
985 // No sensible mangling to do here.
986 newQualifier = 0;
987 }
988
989 if (newQualifier)
990 return mangleUnresolvedPrefix(newQualifier, /*lookup*/ 0, recursive);
991
992 } else {
993 Out << "sr";
994 }
995
996 mangleSourceName(qualifier->getAsIdentifier());
997 break;
998 }
999
1000 // If this was the innermost part of the NNS, and we fell out to
1001 // here, append an 'E'.
1002 if (!recursive)
1003 Out << 'E';
1004}
1005
1006/// Mangle an unresolved-name, which is generally used for names which
1007/// weren't resolved to specific entities.
1008void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
1009 NamedDecl *firstQualifierLookup,
1010 DeclarationName name,
1011 unsigned knownArity) {
1012 if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup);
1013 mangleUnqualifiedName(0, name, knownArity);
1014}
1015
1016static const FieldDecl *FindFirstNamedDataMember(const RecordDecl *RD) {
1017 assert(RD->isAnonymousStructOrUnion() &&
1018 "Expected anonymous struct or union!");
1019
1020 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1021 I != E; ++I) {
1022 if (I->getIdentifier())
1023 return *I;
1024
1025 if (const RecordType *RT = I->getType()->getAs<RecordType>())
1026 if (const FieldDecl *NamedDataMember =
1027 FindFirstNamedDataMember(RT->getDecl()))
1028 return NamedDataMember;
1029 }
1030
1031 // We didn't find a named data member.
1032 return 0;
1033}
1034
1035void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1036 DeclarationName Name,
1037 unsigned KnownArity) {
1038 // <unqualified-name> ::= <operator-name>
1039 // ::= <ctor-dtor-name>
1040 // ::= <source-name>
1041 switch (Name.getNameKind()) {
1042 case DeclarationName::Identifier: {
1043 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
1044 // We must avoid conflicts between internally- and externally-
1045 // linked variable and function declaration names in the same TU:
1046 // void test() { extern void foo(); }
1047 // static void foo();
1048 // This naming convention is the same as that followed by GCC,
1049 // though it shouldn't actually matter.
1050 if (ND && ND->getLinkage() == InternalLinkage &&
1051 getEffectiveDeclContext(ND)->isFileContext())
1052 Out << 'L';
1053
1054 mangleSourceName(II);
1055 break;
1056 }
1057
1058 // Otherwise, an anonymous entity. We must have a declaration.
1059 assert(ND && "mangling empty name without declaration");
1060
1061 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1062 if (NS->isAnonymousNamespace()) {
1063 // This is how gcc mangles these names.
1064 Out << "12_GLOBAL__N_1";
1065 break;
1066 }
1067 }
1068
1069 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1070 // We must have an anonymous union or struct declaration.
1071 const RecordDecl *RD =
1072 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
1073
1074 // Itanium C++ ABI 5.1.2:
1075 //
1076 // For the purposes of mangling, the name of an anonymous union is
1077 // considered to be the name of the first named data member found by a
1078 // pre-order, depth-first, declaration-order walk of the data members of
1079 // the anonymous union. If there is no such data member (i.e., if all of
1080 // the data members in the union are unnamed), then there is no way for
1081 // a program to refer to the anonymous union, and there is therefore no
1082 // need to mangle its name.
1083 const FieldDecl *FD = FindFirstNamedDataMember(RD);
1084
1085 // It's actually possible for various reasons for us to get here
1086 // with an empty anonymous struct / union. Fortunately, it
1087 // doesn't really matter what name we generate.
1088 if (!FD) break;
1089 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1090
1091 mangleSourceName(FD->getIdentifier());
1092 break;
1093 }
1094
1095 // We must have an anonymous struct.
1096 const TagDecl *TD = cast<TagDecl>(ND);
1097 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1098 assert(TD->getDeclContext() == D->getDeclContext() &&
1099 "Typedef should not be in another decl context!");
1100 assert(D->getDeclName().getAsIdentifierInfo() &&
1101 "Typedef was not named!");
1102 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1103 break;
1104 }
1105
1106 // <unnamed-type-name> ::= <closure-type-name>
1107 //
1108 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1109 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1110 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1111 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1112 mangleLambda(Record);
1113 break;
1114 }
1115 }
1116
1117 int UnnamedMangle = Context.getASTContext().getUnnamedTagManglingNumber(TD);
1118 if (UnnamedMangle != -1) {
1119 Out << "Ut";
1120 if (UnnamedMangle != 0)
1121 Out << llvm::utostr(UnnamedMangle - 1);
1122 Out << '_';
1123 break;
1124 }
1125
1126 // Get a unique id for the anonymous struct.
1127 uint64_t AnonStructId = Context.getAnonymousStructId(TD);
1128
1129 // Mangle it as a source name in the form
1130 // [n] $_<id>
1131 // where n is the length of the string.
1132 SmallString<8> Str;
1133 Str += "$_";
1134 Str += llvm::utostr(AnonStructId);
1135
1136 Out << Str.size();
1137 Out << Str.str();
1138 break;
1139 }
1140
1141 case DeclarationName::ObjCZeroArgSelector:
1142 case DeclarationName::ObjCOneArgSelector:
1143 case DeclarationName::ObjCMultiArgSelector:
1144 llvm_unreachable("Can't mangle Objective-C selector names here!");
1145
1146 case DeclarationName::CXXConstructorName:
1147 if (ND == Structor)
1148 // If the named decl is the C++ constructor we're mangling, use the type
1149 // we were given.
1150 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1151 else
1152 // Otherwise, use the complete constructor name. This is relevant if a
1153 // class with a constructor is declared within a constructor.
1154 mangleCXXCtorType(Ctor_Complete);
1155 break;
1156
1157 case DeclarationName::CXXDestructorName:
1158 if (ND == Structor)
1159 // If the named decl is the C++ destructor we're mangling, use the type we
1160 // were given.
1161 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1162 else
1163 // Otherwise, use the complete destructor name. This is relevant if a
1164 // class with a destructor is declared within a destructor.
1165 mangleCXXDtorType(Dtor_Complete);
1166 break;
1167
1168 case DeclarationName::CXXConversionFunctionName:
1169 // <operator-name> ::= cv <type> # (cast)
1170 Out << "cv";
1171 mangleType(Name.getCXXNameType());
1172 break;
1173
1174 case DeclarationName::CXXOperatorName: {
1175 unsigned Arity;
1176 if (ND) {
1177 Arity = cast<FunctionDecl>(ND)->getNumParams();
1178
1179 // If we have a C++ member function, we need to include the 'this' pointer.
1180 // FIXME: This does not make sense for operators that are static, but their
1181 // names stay the same regardless of the arity (operator new for instance).
1182 if (isa<CXXMethodDecl>(ND))
1183 Arity++;
1184 } else
1185 Arity = KnownArity;
1186
1187 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1188 break;
1189 }
1190
1191 case DeclarationName::CXXLiteralOperatorName:
1192 // FIXME: This mangling is not yet official.
1193 Out << "li";
1194 mangleSourceName(Name.getCXXLiteralIdentifier());
1195 break;
1196
1197 case DeclarationName::CXXUsingDirective:
1198 llvm_unreachable("Can't mangle a using directive name!");
1199 }
1200}
1201
1202void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1203 // <source-name> ::= <positive length number> <identifier>
1204 // <number> ::= [n] <non-negative decimal integer>
1205 // <identifier> ::= <unqualified source code identifier>
1206 Out << II->getLength() << II->getName();
1207}
1208
1209void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1210 const DeclContext *DC,
1211 bool NoFunction) {
1212 // <nested-name>
1213 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1214 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1215 // <template-args> E
1216
1217 Out << 'N';
1218 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1219 mangleQualifiers(Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
1220 mangleRefQualifier(Method->getRefQualifier());
1221 }
1222
1223 // Check if we have a template.
1224 const TemplateArgumentList *TemplateArgs = 0;
1225 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1226 mangleTemplatePrefix(TD);
1227 mangleTemplateArgs(*TemplateArgs);
1228 }
1229 else {
1230 manglePrefix(DC, NoFunction);
1231 mangleUnqualifiedName(ND);
1232 }
1233
1234 Out << 'E';
1235}
1236void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1237 const TemplateArgument *TemplateArgs,
1238 unsigned NumTemplateArgs) {
1239 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1240
1241 Out << 'N';
1242
1243 mangleTemplatePrefix(TD);
1244 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1245
1246 Out << 'E';
1247}
1248
1249void CXXNameMangler::mangleLocalName(const NamedDecl *ND) {
1250 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1251 // := Z <function encoding> E s [<discriminator>]
1252 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1253 // _ <entity name>
1254 // <discriminator> := _ <non-negative number>
1255 const DeclContext *DC = getEffectiveDeclContext(ND);
1256 if (isa<ObjCMethodDecl>(DC) && isa<FunctionDecl>(ND)) {
1257 // Don't add objc method name mangling to locally declared function
1258 mangleUnqualifiedName(ND);
1259 return;
1260 }
1261
1262 Out << 'Z';
1263
1264 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC)) {
1265 mangleObjCMethodName(MD);
1266 } else if (const CXXRecordDecl *RD = GetLocalClassDecl(ND)) {
1267 mangleFunctionEncoding(cast<FunctionDecl>(getEffectiveDeclContext(RD)));
1268 Out << 'E';
1269
1270 // The parameter number is omitted for the last parameter, 0 for the
1271 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1272 // <entity name> will of course contain a <closure-type-name>: Its
1273 // numbering will be local to the particular argument in which it appears
1274 // -- other default arguments do not affect its encoding.
1275 bool SkipDiscriminator = false;
1276 if (RD->isLambda()) {
1277 if (const ParmVarDecl *Parm
1278 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl())) {
1279 if (const FunctionDecl *Func
1280 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1281 Out << 'd';
1282 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1283 if (Num > 1)
1284 mangleNumber(Num - 2);
1285 Out << '_';
1286 SkipDiscriminator = true;
1287 }
1288 }
1289 }
1290
1291 // Mangle the name relative to the closest enclosing function.
1292 if (ND == RD) // equality ok because RD derived from ND above
1293 mangleUnqualifiedName(ND);
1294 else
1295 mangleNestedName(ND, DC, true /*NoFunction*/);
1296
1297 if (!SkipDiscriminator) {
1298 unsigned disc;
1299 if (Context.getNextDiscriminator(RD, disc)) {
1300 if (disc < 10)
1301 Out << '_' << disc;
1302 else
1303 Out << "__" << disc << '_';
1304 }
1305 }
1306
1307 return;
1308 }
1309 else
1310 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1311
1312 Out << 'E';
1313 mangleUnqualifiedName(ND);
1314}
1315
1316void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1317 // If the context of a closure type is an initializer for a class member
1318 // (static or nonstatic), it is encoded in a qualified name with a final
1319 // <prefix> of the form:
1320 //
1321 // <data-member-prefix> := <member source-name> M
1322 //
1323 // Technically, the data-member-prefix is part of the <prefix>. However,
1324 // since a closure type will always be mangled with a prefix, it's easier
1325 // to emit that last part of the prefix here.
1326 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1327 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1328 Context->getDeclContext()->isRecord()) {
1329 if (const IdentifierInfo *Name
1330 = cast<NamedDecl>(Context)->getIdentifier()) {
1331 mangleSourceName(Name);
1332 Out << 'M';
1333 }
1334 }
1335 }
1336
1337 Out << "Ul";
1338 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1339 getAs<FunctionProtoType>();
1340 mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
1341 Out << "E";
1342
1343 // The number is omitted for the first closure type with a given
1344 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1345 // (in lexical order) with that same <lambda-sig> and context.
1346 //
1347 // The AST keeps track of the number for us.
1348 unsigned Number = Lambda->getLambdaManglingNumber();
1349 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1350 if (Number > 1)
1351 mangleNumber(Number - 2);
1352 Out << '_';
1353}
1354
1355void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1356 switch (qualifier->getKind()) {
1357 case NestedNameSpecifier::Global:
1358 // nothing
1359 return;
1360
1361 case NestedNameSpecifier::Namespace:
1362 mangleName(qualifier->getAsNamespace());
1363 return;
1364
1365 case NestedNameSpecifier::NamespaceAlias:
1366 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1367 return;
1368
1369 case NestedNameSpecifier::TypeSpec:
1370 case NestedNameSpecifier::TypeSpecWithTemplate:
1371 manglePrefix(QualType(qualifier->getAsType(), 0));
1372 return;
1373
1374 case NestedNameSpecifier::Identifier:
1375 // Member expressions can have these without prefixes, but that
1376 // should end up in mangleUnresolvedPrefix instead.
1377 assert(qualifier->getPrefix());
1378 manglePrefix(qualifier->getPrefix());
1379
1380 mangleSourceName(qualifier->getAsIdentifier());
1381 return;
1382 }
1383
1384 llvm_unreachable("unexpected nested name specifier");
1385}
1386
1387void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1388 // <prefix> ::= <prefix> <unqualified-name>
1389 // ::= <template-prefix> <template-args>
1390 // ::= <template-param>
1391 // ::= # empty
1392 // ::= <substitution>
1393
1394 DC = IgnoreLinkageSpecDecls(DC);
1395
1396 if (DC->isTranslationUnit())
1397 return;
1398
1399 if (const BlockDecl *Block = dyn_cast<BlockDecl>(DC)) {
1400 manglePrefix(getEffectiveParentContext(DC), NoFunction);
1401 SmallString<64> Name;
1402 llvm::raw_svector_ostream NameStream(Name);
1403 Context.mangleBlock(Block, NameStream);
1404 NameStream.flush();
1405 Out << Name.size() << Name;
1406 return;
1407 }
1408
1409 const NamedDecl *ND = cast<NamedDecl>(DC);
1410 if (mangleSubstitution(ND))
1411 return;
1412
1413 // Check if we have a template.
1414 const TemplateArgumentList *TemplateArgs = 0;
1415 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1416 mangleTemplatePrefix(TD);
1417 mangleTemplateArgs(*TemplateArgs);
1418 }
1419 else if(NoFunction && (isa<FunctionDecl>(ND) || isa<ObjCMethodDecl>(ND)))
1420 return;
1421 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1422 mangleObjCMethodName(Method);
1423 else {
1424 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1425 mangleUnqualifiedName(ND);
1426 }
1427
1428 addSubstitution(ND);
1429}
1430
1431void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1432 // <template-prefix> ::= <prefix> <template unqualified-name>
1433 // ::= <template-param>
1434 // ::= <substitution>
1435 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1436 return mangleTemplatePrefix(TD);
1437
1438 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1439 manglePrefix(Qualified->getQualifier());
1440
1441 if (OverloadedTemplateStorage *Overloaded
1442 = Template.getAsOverloadedTemplate()) {
1443 mangleUnqualifiedName(0, (*Overloaded->begin())->getDeclName(),
1444 UnknownArity);
1445 return;
1446 }
1447
1448 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1449 assert(Dependent && "Unknown template name kind?");
1450 manglePrefix(Dependent->getQualifier());
1451 mangleUnscopedTemplateName(Template);
1452}
1453
1454void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND) {
1455 // <template-prefix> ::= <prefix> <template unqualified-name>
1456 // ::= <template-param>
1457 // ::= <substitution>
1458 // <template-template-param> ::= <template-param>
1459 // <substitution>
1460
1461 if (mangleSubstitution(ND))
1462 return;
1463
1464 // <template-template-param> ::= <template-param>
1465 if (const TemplateTemplateParmDecl *TTP
1466 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1467 mangleTemplateParameter(TTP->getIndex());
1468 return;
1469 }
1470
1471 manglePrefix(getEffectiveDeclContext(ND));
1472 mangleUnqualifiedName(ND->getTemplatedDecl());
1473 addSubstitution(ND);
1474}
1475
1476/// Mangles a template name under the production <type>. Required for
1477/// template template arguments.
1478/// <type> ::= <class-enum-type>
1479/// ::= <template-param>
1480/// ::= <substitution>
1481void CXXNameMangler::mangleType(TemplateName TN) {
1482 if (mangleSubstitution(TN))
1483 return;
1484
1485 TemplateDecl *TD = 0;
1486
1487 switch (TN.getKind()) {
1488 case TemplateName::QualifiedTemplate:
1489 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1490 goto HaveDecl;
1491
1492 case TemplateName::Template:
1493 TD = TN.getAsTemplateDecl();
1494 goto HaveDecl;
1495
1496 HaveDecl:
1497 if (isa<TemplateTemplateParmDecl>(TD))
1498 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1499 else
1500 mangleName(TD);
1501 break;
1502
1503 case TemplateName::OverloadedTemplate:
1504 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1505
1506 case TemplateName::DependentTemplate: {
1507 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1508 assert(Dependent->isIdentifier());
1509
1510 // <class-enum-type> ::= <name>
1511 // <name> ::= <nested-name>
1512 mangleUnresolvedPrefix(Dependent->getQualifier(), 0);
1513 mangleSourceName(Dependent->getIdentifier());
1514 break;
1515 }
1516
1517 case TemplateName::SubstTemplateTemplateParm: {
1518 // Substituted template parameters are mangled as the substituted
1519 // template. This will check for the substitution twice, which is
1520 // fine, but we have to return early so that we don't try to *add*
1521 // the substitution twice.
1522 SubstTemplateTemplateParmStorage *subst
1523 = TN.getAsSubstTemplateTemplateParm();
1524 mangleType(subst->getReplacement());
1525 return;
1526 }
1527
1528 case TemplateName::SubstTemplateTemplateParmPack: {
1529 // FIXME: not clear how to mangle this!
1530 // template <template <class> class T...> class A {
1531 // template <template <class> class U...> void foo(B<T,U> x...);
1532 // };
1533 Out << "_SUBSTPACK_";
1534 break;
1535 }
1536 }
1537
1538 addSubstitution(TN);
1539}
1540
1541void
1542CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1543 switch (OO) {
1544 // <operator-name> ::= nw # new
1545 case OO_New: Out << "nw"; break;
1546 // ::= na # new[]
1547 case OO_Array_New: Out << "na"; break;
1548 // ::= dl # delete
1549 case OO_Delete: Out << "dl"; break;
1550 // ::= da # delete[]
1551 case OO_Array_Delete: Out << "da"; break;
1552 // ::= ps # + (unary)
1553 // ::= pl # + (binary or unknown)
1554 case OO_Plus:
1555 Out << (Arity == 1? "ps" : "pl"); break;
1556 // ::= ng # - (unary)
1557 // ::= mi # - (binary or unknown)
1558 case OO_Minus:
1559 Out << (Arity == 1? "ng" : "mi"); break;
1560 // ::= ad # & (unary)
1561 // ::= an # & (binary or unknown)
1562 case OO_Amp:
1563 Out << (Arity == 1? "ad" : "an"); break;
1564 // ::= de # * (unary)
1565 // ::= ml # * (binary or unknown)
1566 case OO_Star:
1567 // Use binary when unknown.
1568 Out << (Arity == 1? "de" : "ml"); break;
1569 // ::= co # ~
1570 case OO_Tilde: Out << "co"; break;
1571 // ::= dv # /
1572 case OO_Slash: Out << "dv"; break;
1573 // ::= rm # %
1574 case OO_Percent: Out << "rm"; break;
1575 // ::= or # |
1576 case OO_Pipe: Out << "or"; break;
1577 // ::= eo # ^
1578 case OO_Caret: Out << "eo"; break;
1579 // ::= aS # =
1580 case OO_Equal: Out << "aS"; break;
1581 // ::= pL # +=
1582 case OO_PlusEqual: Out << "pL"; break;
1583 // ::= mI # -=
1584 case OO_MinusEqual: Out << "mI"; break;
1585 // ::= mL # *=
1586 case OO_StarEqual: Out << "mL"; break;
1587 // ::= dV # /=
1588 case OO_SlashEqual: Out << "dV"; break;
1589 // ::= rM # %=
1590 case OO_PercentEqual: Out << "rM"; break;
1591 // ::= aN # &=
1592 case OO_AmpEqual: Out << "aN"; break;
1593 // ::= oR # |=
1594 case OO_PipeEqual: Out << "oR"; break;
1595 // ::= eO # ^=
1596 case OO_CaretEqual: Out << "eO"; break;
1597 // ::= ls # <<
1598 case OO_LessLess: Out << "ls"; break;
1599 // ::= rs # >>
1600 case OO_GreaterGreater: Out << "rs"; break;
1601 // ::= lS # <<=
1602 case OO_LessLessEqual: Out << "lS"; break;
1603 // ::= rS # >>=
1604 case OO_GreaterGreaterEqual: Out << "rS"; break;
1605 // ::= eq # ==
1606 case OO_EqualEqual: Out << "eq"; break;
1607 // ::= ne # !=
1608 case OO_ExclaimEqual: Out << "ne"; break;
1609 // ::= lt # <
1610 case OO_Less: Out << "lt"; break;
1611 // ::= gt # >
1612 case OO_Greater: Out << "gt"; break;
1613 // ::= le # <=
1614 case OO_LessEqual: Out << "le"; break;
1615 // ::= ge # >=
1616 case OO_GreaterEqual: Out << "ge"; break;
1617 // ::= nt # !
1618 case OO_Exclaim: Out << "nt"; break;
1619 // ::= aa # &&
1620 case OO_AmpAmp: Out << "aa"; break;
1621 // ::= oo # ||
1622 case OO_PipePipe: Out << "oo"; break;
1623 // ::= pp # ++
1624 case OO_PlusPlus: Out << "pp"; break;
1625 // ::= mm # --
1626 case OO_MinusMinus: Out << "mm"; break;
1627 // ::= cm # ,
1628 case OO_Comma: Out << "cm"; break;
1629 // ::= pm # ->*
1630 case OO_ArrowStar: Out << "pm"; break;
1631 // ::= pt # ->
1632 case OO_Arrow: Out << "pt"; break;
1633 // ::= cl # ()
1634 case OO_Call: Out << "cl"; break;
1635 // ::= ix # []
1636 case OO_Subscript: Out << "ix"; break;
1637
1638 // ::= qu # ?
1639 // The conditional operator can't be overloaded, but we still handle it when
1640 // mangling expressions.
1641 case OO_Conditional: Out << "qu"; break;
1642
1643 case OO_None:
1644 case NUM_OVERLOADED_OPERATORS:
1645 llvm_unreachable("Not an overloaded operator");
1646 }
1647}
1648
1649void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1650 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1651 if (Quals.hasRestrict())
1652 Out << 'r';
1653 if (Quals.hasVolatile())
1654 Out << 'V';
1655 if (Quals.hasConst())
1656 Out << 'K';
1657
1658 if (Quals.hasAddressSpace()) {
1659 // Extension:
1660 //
1661 // <type> ::= U <address-space-number>
1662 //
1663 // where <address-space-number> is a source name consisting of 'AS'
1664 // followed by the address space <number>.
1665 SmallString<64> ASString;
Tanya Lattnerf21107b2013-02-08 01:07:32 +00001666 ASString = "AS" + llvm::utostr_32(
1667 Context.getASTContext().getTargetAddressSpace(Quals.getAddressSpace()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001668 Out << 'U' << ASString.size() << ASString;
1669 }
1670
1671 StringRef LifetimeName;
1672 switch (Quals.getObjCLifetime()) {
1673 // Objective-C ARC Extension:
1674 //
1675 // <type> ::= U "__strong"
1676 // <type> ::= U "__weak"
1677 // <type> ::= U "__autoreleasing"
1678 case Qualifiers::OCL_None:
1679 break;
1680
1681 case Qualifiers::OCL_Weak:
1682 LifetimeName = "__weak";
1683 break;
1684
1685 case Qualifiers::OCL_Strong:
1686 LifetimeName = "__strong";
1687 break;
1688
1689 case Qualifiers::OCL_Autoreleasing:
1690 LifetimeName = "__autoreleasing";
1691 break;
1692
1693 case Qualifiers::OCL_ExplicitNone:
1694 // The __unsafe_unretained qualifier is *not* mangled, so that
1695 // __unsafe_unretained types in ARC produce the same manglings as the
1696 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1697 // better ABI compatibility.
1698 //
1699 // It's safe to do this because unqualified 'id' won't show up
1700 // in any type signatures that need to be mangled.
1701 break;
1702 }
1703 if (!LifetimeName.empty())
1704 Out << 'U' << LifetimeName.size() << LifetimeName;
1705}
1706
1707void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1708 // <ref-qualifier> ::= R # lvalue reference
1709 // ::= O # rvalue-reference
1710 // Proposal to Itanium C++ ABI list on 1/26/11
1711 switch (RefQualifier) {
1712 case RQ_None:
1713 break;
1714
1715 case RQ_LValue:
1716 Out << 'R';
1717 break;
1718
1719 case RQ_RValue:
1720 Out << 'O';
1721 break;
1722 }
1723}
1724
1725void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1726 Context.mangleObjCMethodName(MD, Out);
1727}
1728
1729void CXXNameMangler::mangleType(QualType T) {
1730 // If our type is instantiation-dependent but not dependent, we mangle
1731 // it as it was written in the source, removing any top-level sugar.
1732 // Otherwise, use the canonical type.
1733 //
1734 // FIXME: This is an approximation of the instantiation-dependent name
1735 // mangling rules, since we should really be using the type as written and
1736 // augmented via semantic analysis (i.e., with implicit conversions and
1737 // default template arguments) for any instantiation-dependent type.
1738 // Unfortunately, that requires several changes to our AST:
1739 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1740 // uniqued, so that we can handle substitutions properly
1741 // - Default template arguments will need to be represented in the
1742 // TemplateSpecializationType, since they need to be mangled even though
1743 // they aren't written.
1744 // - Conversions on non-type template arguments need to be expressed, since
1745 // they can affect the mangling of sizeof/alignof.
1746 if (!T->isInstantiationDependentType() || T->isDependentType())
1747 T = T.getCanonicalType();
1748 else {
1749 // Desugar any types that are purely sugar.
1750 do {
1751 // Don't desugar through template specialization types that aren't
1752 // type aliases. We need to mangle the template arguments as written.
1753 if (const TemplateSpecializationType *TST
1754 = dyn_cast<TemplateSpecializationType>(T))
1755 if (!TST->isTypeAlias())
1756 break;
1757
1758 QualType Desugared
1759 = T.getSingleStepDesugaredType(Context.getASTContext());
1760 if (Desugared == T)
1761 break;
1762
1763 T = Desugared;
1764 } while (true);
1765 }
1766 SplitQualType split = T.split();
1767 Qualifiers quals = split.Quals;
1768 const Type *ty = split.Ty;
1769
1770 bool isSubstitutable = quals || !isa<BuiltinType>(T);
1771 if (isSubstitutable && mangleSubstitution(T))
1772 return;
1773
1774 // If we're mangling a qualified array type, push the qualifiers to
1775 // the element type.
1776 if (quals && isa<ArrayType>(T)) {
1777 ty = Context.getASTContext().getAsArrayType(T);
1778 quals = Qualifiers();
1779
1780 // Note that we don't update T: we want to add the
1781 // substitution at the original type.
1782 }
1783
1784 if (quals) {
1785 mangleQualifiers(quals);
1786 // Recurse: even if the qualified type isn't yet substitutable,
1787 // the unqualified type might be.
1788 mangleType(QualType(ty, 0));
1789 } else {
1790 switch (ty->getTypeClass()) {
1791#define ABSTRACT_TYPE(CLASS, PARENT)
1792#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1793 case Type::CLASS: \
1794 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1795 return;
1796#define TYPE(CLASS, PARENT) \
1797 case Type::CLASS: \
1798 mangleType(static_cast<const CLASS##Type*>(ty)); \
1799 break;
1800#include "clang/AST/TypeNodes.def"
1801 }
1802 }
1803
1804 // Add the substitution.
1805 if (isSubstitutable)
1806 addSubstitution(T);
1807}
1808
1809void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1810 if (!mangleStandardSubstitution(ND))
1811 mangleName(ND);
1812}
1813
1814void CXXNameMangler::mangleType(const BuiltinType *T) {
1815 // <type> ::= <builtin-type>
1816 // <builtin-type> ::= v # void
1817 // ::= w # wchar_t
1818 // ::= b # bool
1819 // ::= c # char
1820 // ::= a # signed char
1821 // ::= h # unsigned char
1822 // ::= s # short
1823 // ::= t # unsigned short
1824 // ::= i # int
1825 // ::= j # unsigned int
1826 // ::= l # long
1827 // ::= m # unsigned long
1828 // ::= x # long long, __int64
1829 // ::= y # unsigned long long, __int64
1830 // ::= n # __int128
1831 // UNSUPPORTED: ::= o # unsigned __int128
1832 // ::= f # float
1833 // ::= d # double
1834 // ::= e # long double, __float80
1835 // UNSUPPORTED: ::= g # __float128
1836 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1837 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1838 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1839 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1840 // ::= Di # char32_t
1841 // ::= Ds # char16_t
1842 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1843 // ::= u <source-name> # vendor extended type
1844 switch (T->getKind()) {
1845 case BuiltinType::Void: Out << 'v'; break;
1846 case BuiltinType::Bool: Out << 'b'; break;
1847 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
1848 case BuiltinType::UChar: Out << 'h'; break;
1849 case BuiltinType::UShort: Out << 't'; break;
1850 case BuiltinType::UInt: Out << 'j'; break;
1851 case BuiltinType::ULong: Out << 'm'; break;
1852 case BuiltinType::ULongLong: Out << 'y'; break;
1853 case BuiltinType::UInt128: Out << 'o'; break;
1854 case BuiltinType::SChar: Out << 'a'; break;
1855 case BuiltinType::WChar_S:
1856 case BuiltinType::WChar_U: Out << 'w'; break;
1857 case BuiltinType::Char16: Out << "Ds"; break;
1858 case BuiltinType::Char32: Out << "Di"; break;
1859 case BuiltinType::Short: Out << 's'; break;
1860 case BuiltinType::Int: Out << 'i'; break;
1861 case BuiltinType::Long: Out << 'l'; break;
1862 case BuiltinType::LongLong: Out << 'x'; break;
1863 case BuiltinType::Int128: Out << 'n'; break;
1864 case BuiltinType::Half: Out << "Dh"; break;
1865 case BuiltinType::Float: Out << 'f'; break;
1866 case BuiltinType::Double: Out << 'd'; break;
1867 case BuiltinType::LongDouble: Out << 'e'; break;
1868 case BuiltinType::NullPtr: Out << "Dn"; break;
1869
1870#define BUILTIN_TYPE(Id, SingletonId)
1871#define PLACEHOLDER_TYPE(Id, SingletonId) \
1872 case BuiltinType::Id:
1873#include "clang/AST/BuiltinTypes.def"
1874 case BuiltinType::Dependent:
1875 llvm_unreachable("mangling a placeholder type");
1876 case BuiltinType::ObjCId: Out << "11objc_object"; break;
1877 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
1878 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
Guy Benyeib13621d2012-12-18 14:38:23 +00001879 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
1880 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
1881 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
1882 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
1883 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
1884 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001885 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001886 case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001887 }
1888}
1889
1890// <type> ::= <function-type>
1891// <function-type> ::= [<CV-qualifiers>] F [Y]
1892// <bare-function-type> [<ref-qualifier>] E
1893// (Proposal to cxx-abi-dev, 2012-05-11)
1894void CXXNameMangler::mangleType(const FunctionProtoType *T) {
1895 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
1896 // e.g. "const" in "int (A::*)() const".
1897 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
1898
1899 Out << 'F';
1900
1901 // FIXME: We don't have enough information in the AST to produce the 'Y'
1902 // encoding for extern "C" function types.
1903 mangleBareFunctionType(T, /*MangleReturnType=*/true);
1904
1905 // Mangle the ref-qualifier, if present.
1906 mangleRefQualifier(T->getRefQualifier());
1907
1908 Out << 'E';
1909}
1910void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
1911 llvm_unreachable("Can't mangle K&R function prototypes");
1912}
1913void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
1914 bool MangleReturnType) {
1915 // We should never be mangling something without a prototype.
1916 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1917
1918 // Record that we're in a function type. See mangleFunctionParam
1919 // for details on what we're trying to achieve here.
1920 FunctionTypeDepthState saved = FunctionTypeDepth.push();
1921
1922 // <bare-function-type> ::= <signature type>+
1923 if (MangleReturnType) {
1924 FunctionTypeDepth.enterResultType();
1925 mangleType(Proto->getResultType());
1926 FunctionTypeDepth.leaveResultType();
1927 }
1928
1929 if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
1930 // <builtin-type> ::= v # void
1931 Out << 'v';
1932
1933 FunctionTypeDepth.pop(saved);
1934 return;
1935 }
1936
1937 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1938 ArgEnd = Proto->arg_type_end();
1939 Arg != ArgEnd; ++Arg)
1940 mangleType(Context.getASTContext().getSignatureParameterType(*Arg));
1941
1942 FunctionTypeDepth.pop(saved);
1943
1944 // <builtin-type> ::= z # ellipsis
1945 if (Proto->isVariadic())
1946 Out << 'z';
1947}
1948
1949// <type> ::= <class-enum-type>
1950// <class-enum-type> ::= <name>
1951void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
1952 mangleName(T->getDecl());
1953}
1954
1955// <type> ::= <class-enum-type>
1956// <class-enum-type> ::= <name>
1957void CXXNameMangler::mangleType(const EnumType *T) {
1958 mangleType(static_cast<const TagType*>(T));
1959}
1960void CXXNameMangler::mangleType(const RecordType *T) {
1961 mangleType(static_cast<const TagType*>(T));
1962}
1963void CXXNameMangler::mangleType(const TagType *T) {
1964 mangleName(T->getDecl());
1965}
1966
1967// <type> ::= <array-type>
1968// <array-type> ::= A <positive dimension number> _ <element type>
1969// ::= A [<dimension expression>] _ <element type>
1970void CXXNameMangler::mangleType(const ConstantArrayType *T) {
1971 Out << 'A' << T->getSize() << '_';
1972 mangleType(T->getElementType());
1973}
1974void CXXNameMangler::mangleType(const VariableArrayType *T) {
1975 Out << 'A';
1976 // decayed vla types (size 0) will just be skipped.
1977 if (T->getSizeExpr())
1978 mangleExpression(T->getSizeExpr());
1979 Out << '_';
1980 mangleType(T->getElementType());
1981}
1982void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
1983 Out << 'A';
1984 mangleExpression(T->getSizeExpr());
1985 Out << '_';
1986 mangleType(T->getElementType());
1987}
1988void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
1989 Out << "A_";
1990 mangleType(T->getElementType());
1991}
1992
1993// <type> ::= <pointer-to-member-type>
1994// <pointer-to-member-type> ::= M <class type> <member type>
1995void CXXNameMangler::mangleType(const MemberPointerType *T) {
1996 Out << 'M';
1997 mangleType(QualType(T->getClass(), 0));
1998 QualType PointeeType = T->getPointeeType();
1999 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2000 mangleType(FPT);
2001
2002 // Itanium C++ ABI 5.1.8:
2003 //
2004 // The type of a non-static member function is considered to be different,
2005 // for the purposes of substitution, from the type of a namespace-scope or
2006 // static member function whose type appears similar. The types of two
2007 // non-static member functions are considered to be different, for the
2008 // purposes of substitution, if the functions are members of different
2009 // classes. In other words, for the purposes of substitution, the class of
2010 // which the function is a member is considered part of the type of
2011 // function.
2012
2013 // Given that we already substitute member function pointers as a
2014 // whole, the net effect of this rule is just to unconditionally
2015 // suppress substitution on the function type in a member pointer.
2016 // We increment the SeqID here to emulate adding an entry to the
2017 // substitution table.
2018 ++SeqID;
2019 } else
2020 mangleType(PointeeType);
2021}
2022
2023// <type> ::= <template-param>
2024void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2025 mangleTemplateParameter(T->getIndex());
2026}
2027
2028// <type> ::= <template-param>
2029void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2030 // FIXME: not clear how to mangle this!
2031 // template <class T...> class A {
2032 // template <class U...> void foo(T(*)(U) x...);
2033 // };
2034 Out << "_SUBSTPACK_";
2035}
2036
2037// <type> ::= P <type> # pointer-to
2038void CXXNameMangler::mangleType(const PointerType *T) {
2039 Out << 'P';
2040 mangleType(T->getPointeeType());
2041}
2042void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2043 Out << 'P';
2044 mangleType(T->getPointeeType());
2045}
2046
2047// <type> ::= R <type> # reference-to
2048void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2049 Out << 'R';
2050 mangleType(T->getPointeeType());
2051}
2052
2053// <type> ::= O <type> # rvalue reference-to (C++0x)
2054void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2055 Out << 'O';
2056 mangleType(T->getPointeeType());
2057}
2058
2059// <type> ::= C <type> # complex pair (C 2000)
2060void CXXNameMangler::mangleType(const ComplexType *T) {
2061 Out << 'C';
2062 mangleType(T->getElementType());
2063}
2064
2065// ARM's ABI for Neon vector types specifies that they should be mangled as
2066// if they are structs (to match ARM's initial implementation). The
2067// vector type must be one of the special types predefined by ARM.
2068void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2069 QualType EltType = T->getElementType();
2070 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2071 const char *EltName = 0;
2072 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2073 switch (cast<BuiltinType>(EltType)->getKind()) {
2074 case BuiltinType::SChar: EltName = "poly8_t"; break;
2075 case BuiltinType::Short: EltName = "poly16_t"; break;
2076 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2077 }
2078 } else {
2079 switch (cast<BuiltinType>(EltType)->getKind()) {
2080 case BuiltinType::SChar: EltName = "int8_t"; break;
2081 case BuiltinType::UChar: EltName = "uint8_t"; break;
2082 case BuiltinType::Short: EltName = "int16_t"; break;
2083 case BuiltinType::UShort: EltName = "uint16_t"; break;
2084 case BuiltinType::Int: EltName = "int32_t"; break;
2085 case BuiltinType::UInt: EltName = "uint32_t"; break;
2086 case BuiltinType::LongLong: EltName = "int64_t"; break;
2087 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2088 case BuiltinType::Float: EltName = "float32_t"; break;
2089 default: llvm_unreachable("unexpected Neon vector element type");
2090 }
2091 }
2092 const char *BaseName = 0;
2093 unsigned BitSize = (T->getNumElements() *
2094 getASTContext().getTypeSize(EltType));
2095 if (BitSize == 64)
2096 BaseName = "__simd64_";
2097 else {
2098 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2099 BaseName = "__simd128_";
2100 }
2101 Out << strlen(BaseName) + strlen(EltName);
2102 Out << BaseName << EltName;
2103}
2104
2105// GNU extension: vector types
2106// <type> ::= <vector-type>
2107// <vector-type> ::= Dv <positive dimension number> _
2108// <extended element type>
2109// ::= Dv [<dimension expression>] _ <element type>
2110// <extended element type> ::= <element type>
2111// ::= p # AltiVec vector pixel
2112// ::= b # Altivec vector bool
2113void CXXNameMangler::mangleType(const VectorType *T) {
2114 if ((T->getVectorKind() == VectorType::NeonVector ||
2115 T->getVectorKind() == VectorType::NeonPolyVector)) {
2116 mangleNeonVectorType(T);
2117 return;
2118 }
2119 Out << "Dv" << T->getNumElements() << '_';
2120 if (T->getVectorKind() == VectorType::AltiVecPixel)
2121 Out << 'p';
2122 else if (T->getVectorKind() == VectorType::AltiVecBool)
2123 Out << 'b';
2124 else
2125 mangleType(T->getElementType());
2126}
2127void CXXNameMangler::mangleType(const ExtVectorType *T) {
2128 mangleType(static_cast<const VectorType*>(T));
2129}
2130void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2131 Out << "Dv";
2132 mangleExpression(T->getSizeExpr());
2133 Out << '_';
2134 mangleType(T->getElementType());
2135}
2136
2137void CXXNameMangler::mangleType(const PackExpansionType *T) {
2138 // <type> ::= Dp <type> # pack expansion (C++0x)
2139 Out << "Dp";
2140 mangleType(T->getPattern());
2141}
2142
2143void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2144 mangleSourceName(T->getDecl()->getIdentifier());
2145}
2146
2147void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2148 // We don't allow overloading by different protocol qualification,
2149 // so mangling them isn't necessary.
2150 mangleType(T->getBaseType());
2151}
2152
2153void CXXNameMangler::mangleType(const BlockPointerType *T) {
2154 Out << "U13block_pointer";
2155 mangleType(T->getPointeeType());
2156}
2157
2158void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2159 // Mangle injected class name types as if the user had written the
2160 // specialization out fully. It may not actually be possible to see
2161 // this mangling, though.
2162 mangleType(T->getInjectedSpecializationType());
2163}
2164
2165void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2166 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2167 mangleName(TD, T->getArgs(), T->getNumArgs());
2168 } else {
2169 if (mangleSubstitution(QualType(T, 0)))
2170 return;
2171
2172 mangleTemplatePrefix(T->getTemplateName());
2173
2174 // FIXME: GCC does not appear to mangle the template arguments when
2175 // the template in question is a dependent template name. Should we
2176 // emulate that badness?
2177 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2178 addSubstitution(QualType(T, 0));
2179 }
2180}
2181
2182void CXXNameMangler::mangleType(const DependentNameType *T) {
2183 // Typename types are always nested
2184 Out << 'N';
2185 manglePrefix(T->getQualifier());
2186 mangleSourceName(T->getIdentifier());
2187 Out << 'E';
2188}
2189
2190void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2191 // Dependently-scoped template types are nested if they have a prefix.
2192 Out << 'N';
2193
2194 // TODO: avoid making this TemplateName.
2195 TemplateName Prefix =
2196 getASTContext().getDependentTemplateName(T->getQualifier(),
2197 T->getIdentifier());
2198 mangleTemplatePrefix(Prefix);
2199
2200 // FIXME: GCC does not appear to mangle the template arguments when
2201 // the template in question is a dependent template name. Should we
2202 // emulate that badness?
2203 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2204 Out << 'E';
2205}
2206
2207void CXXNameMangler::mangleType(const TypeOfType *T) {
2208 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2209 // "extension with parameters" mangling.
2210 Out << "u6typeof";
2211}
2212
2213void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2214 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2215 // "extension with parameters" mangling.
2216 Out << "u6typeof";
2217}
2218
2219void CXXNameMangler::mangleType(const DecltypeType *T) {
2220 Expr *E = T->getUnderlyingExpr();
2221
2222 // type ::= Dt <expression> E # decltype of an id-expression
2223 // # or class member access
2224 // ::= DT <expression> E # decltype of an expression
2225
2226 // This purports to be an exhaustive list of id-expressions and
2227 // class member accesses. Note that we do not ignore parentheses;
2228 // parentheses change the semantics of decltype for these
2229 // expressions (and cause the mangler to use the other form).
2230 if (isa<DeclRefExpr>(E) ||
2231 isa<MemberExpr>(E) ||
2232 isa<UnresolvedLookupExpr>(E) ||
2233 isa<DependentScopeDeclRefExpr>(E) ||
2234 isa<CXXDependentScopeMemberExpr>(E) ||
2235 isa<UnresolvedMemberExpr>(E))
2236 Out << "Dt";
2237 else
2238 Out << "DT";
2239 mangleExpression(E);
2240 Out << 'E';
2241}
2242
2243void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2244 // If this is dependent, we need to record that. If not, we simply
2245 // mangle it as the underlying type since they are equivalent.
2246 if (T->isDependentType()) {
2247 Out << 'U';
2248
2249 switch (T->getUTTKind()) {
2250 case UnaryTransformType::EnumUnderlyingType:
2251 Out << "3eut";
2252 break;
2253 }
2254 }
2255
2256 mangleType(T->getUnderlyingType());
2257}
2258
2259void CXXNameMangler::mangleType(const AutoType *T) {
2260 QualType D = T->getDeducedType();
2261 // <builtin-type> ::= Da # dependent auto
2262 if (D.isNull())
2263 Out << "Da";
2264 else
2265 mangleType(D);
2266}
2267
2268void CXXNameMangler::mangleType(const AtomicType *T) {
2269 // <type> ::= U <source-name> <type> # vendor extended type qualifier
2270 // (Until there's a standardized mangling...)
2271 Out << "U7_Atomic";
2272 mangleType(T->getValueType());
2273}
2274
2275void CXXNameMangler::mangleIntegerLiteral(QualType T,
2276 const llvm::APSInt &Value) {
2277 // <expr-primary> ::= L <type> <value number> E # integer literal
2278 Out << 'L';
2279
2280 mangleType(T);
2281 if (T->isBooleanType()) {
2282 // Boolean values are encoded as 0/1.
2283 Out << (Value.getBoolValue() ? '1' : '0');
2284 } else {
2285 mangleNumber(Value);
2286 }
2287 Out << 'E';
2288
2289}
2290
2291/// Mangles a member expression.
2292void CXXNameMangler::mangleMemberExpr(const Expr *base,
2293 bool isArrow,
2294 NestedNameSpecifier *qualifier,
2295 NamedDecl *firstQualifierLookup,
2296 DeclarationName member,
2297 unsigned arity) {
2298 // <expression> ::= dt <expression> <unresolved-name>
2299 // ::= pt <expression> <unresolved-name>
2300 if (base) {
2301 if (base->isImplicitCXXThis()) {
2302 // Note: GCC mangles member expressions to the implicit 'this' as
2303 // *this., whereas we represent them as this->. The Itanium C++ ABI
2304 // does not specify anything here, so we follow GCC.
2305 Out << "dtdefpT";
2306 } else {
2307 Out << (isArrow ? "pt" : "dt");
2308 mangleExpression(base);
2309 }
2310 }
2311 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
2312}
2313
2314/// Look at the callee of the given call expression and determine if
2315/// it's a parenthesized id-expression which would have triggered ADL
2316/// otherwise.
2317static bool isParenthesizedADLCallee(const CallExpr *call) {
2318 const Expr *callee = call->getCallee();
2319 const Expr *fn = callee->IgnoreParens();
2320
2321 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2322 // too, but for those to appear in the callee, it would have to be
2323 // parenthesized.
2324 if (callee == fn) return false;
2325
2326 // Must be an unresolved lookup.
2327 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2328 if (!lookup) return false;
2329
2330 assert(!lookup->requiresADL());
2331
2332 // Must be an unqualified lookup.
2333 if (lookup->getQualifier()) return false;
2334
2335 // Must not have found a class member. Note that if one is a class
2336 // member, they're all class members.
2337 if (lookup->getNumDecls() > 0 &&
2338 (*lookup->decls_begin())->isCXXClassMember())
2339 return false;
2340
2341 // Otherwise, ADL would have been triggered.
2342 return true;
2343}
2344
2345void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2346 // <expression> ::= <unary operator-name> <expression>
2347 // ::= <binary operator-name> <expression> <expression>
2348 // ::= <trinary operator-name> <expression> <expression> <expression>
2349 // ::= cv <type> expression # conversion with one argument
2350 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2351 // ::= st <type> # sizeof (a type)
2352 // ::= at <type> # alignof (a type)
2353 // ::= <template-param>
2354 // ::= <function-param>
2355 // ::= sr <type> <unqualified-name> # dependent name
2356 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2357 // ::= ds <expression> <expression> # expr.*expr
2358 // ::= sZ <template-param> # size of a parameter pack
2359 // ::= sZ <function-param> # size of a function parameter pack
2360 // ::= <expr-primary>
2361 // <expr-primary> ::= L <type> <value number> E # integer literal
2362 // ::= L <type <value float> E # floating literal
2363 // ::= L <mangled-name> E # external name
2364 // ::= fpT # 'this' expression
2365 QualType ImplicitlyConvertedToType;
2366
2367recurse:
2368 switch (E->getStmtClass()) {
2369 case Expr::NoStmtClass:
2370#define ABSTRACT_STMT(Type)
2371#define EXPR(Type, Base)
2372#define STMT(Type, Base) \
2373 case Expr::Type##Class:
2374#include "clang/AST/StmtNodes.inc"
2375 // fallthrough
2376
2377 // These all can only appear in local or variable-initialization
2378 // contexts and so should never appear in a mangling.
2379 case Expr::AddrLabelExprClass:
2380 case Expr::DesignatedInitExprClass:
2381 case Expr::ImplicitValueInitExprClass:
2382 case Expr::ParenListExprClass:
2383 case Expr::LambdaExprClass:
2384 llvm_unreachable("unexpected statement kind");
2385
2386 // FIXME: invent manglings for all these.
2387 case Expr::BlockExprClass:
2388 case Expr::CXXPseudoDestructorExprClass:
2389 case Expr::ChooseExprClass:
2390 case Expr::CompoundLiteralExprClass:
2391 case Expr::ExtVectorElementExprClass:
2392 case Expr::GenericSelectionExprClass:
2393 case Expr::ObjCEncodeExprClass:
2394 case Expr::ObjCIsaExprClass:
2395 case Expr::ObjCIvarRefExprClass:
2396 case Expr::ObjCMessageExprClass:
2397 case Expr::ObjCPropertyRefExprClass:
2398 case Expr::ObjCProtocolExprClass:
2399 case Expr::ObjCSelectorExprClass:
2400 case Expr::ObjCStringLiteralClass:
2401 case Expr::ObjCBoxedExprClass:
2402 case Expr::ObjCArrayLiteralClass:
2403 case Expr::ObjCDictionaryLiteralClass:
2404 case Expr::ObjCSubscriptRefExprClass:
2405 case Expr::ObjCIndirectCopyRestoreExprClass:
2406 case Expr::OffsetOfExprClass:
2407 case Expr::PredefinedExprClass:
2408 case Expr::ShuffleVectorExprClass:
2409 case Expr::StmtExprClass:
2410 case Expr::UnaryTypeTraitExprClass:
2411 case Expr::BinaryTypeTraitExprClass:
2412 case Expr::TypeTraitExprClass:
2413 case Expr::ArrayTypeTraitExprClass:
2414 case Expr::ExpressionTraitExprClass:
2415 case Expr::VAArgExprClass:
2416 case Expr::CXXUuidofExprClass:
2417 case Expr::CUDAKernelCallExprClass:
2418 case Expr::AsTypeExprClass:
2419 case Expr::PseudoObjectExprClass:
2420 case Expr::AtomicExprClass:
2421 {
2422 // As bad as this diagnostic is, it's better than crashing.
2423 DiagnosticsEngine &Diags = Context.getDiags();
2424 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2425 "cannot yet mangle expression type %0");
2426 Diags.Report(E->getExprLoc(), DiagID)
2427 << E->getStmtClassName() << E->getSourceRange();
2428 break;
2429 }
2430
2431 // Even gcc-4.5 doesn't mangle this.
2432 case Expr::BinaryConditionalOperatorClass: {
2433 DiagnosticsEngine &Diags = Context.getDiags();
2434 unsigned DiagID =
2435 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2436 "?: operator with omitted middle operand cannot be mangled");
2437 Diags.Report(E->getExprLoc(), DiagID)
2438 << E->getStmtClassName() << E->getSourceRange();
2439 break;
2440 }
2441
2442 // These are used for internal purposes and cannot be meaningfully mangled.
2443 case Expr::OpaqueValueExprClass:
2444 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2445
2446 case Expr::InitListExprClass: {
2447 // Proposal by Jason Merrill, 2012-01-03
2448 Out << "il";
2449 const InitListExpr *InitList = cast<InitListExpr>(E);
2450 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2451 mangleExpression(InitList->getInit(i));
2452 Out << "E";
2453 break;
2454 }
2455
2456 case Expr::CXXDefaultArgExprClass:
2457 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2458 break;
2459
2460 case Expr::SubstNonTypeTemplateParmExprClass:
2461 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2462 Arity);
2463 break;
2464
2465 case Expr::UserDefinedLiteralClass:
2466 // We follow g++'s approach of mangling a UDL as a call to the literal
2467 // operator.
2468 case Expr::CXXMemberCallExprClass: // fallthrough
2469 case Expr::CallExprClass: {
2470 const CallExpr *CE = cast<CallExpr>(E);
2471
2472 // <expression> ::= cp <simple-id> <expression>* E
2473 // We use this mangling only when the call would use ADL except
2474 // for being parenthesized. Per discussion with David
2475 // Vandervoorde, 2011.04.25.
2476 if (isParenthesizedADLCallee(CE)) {
2477 Out << "cp";
2478 // The callee here is a parenthesized UnresolvedLookupExpr with
2479 // no qualifier and should always get mangled as a <simple-id>
2480 // anyway.
2481
2482 // <expression> ::= cl <expression>* E
2483 } else {
2484 Out << "cl";
2485 }
2486
2487 mangleExpression(CE->getCallee(), CE->getNumArgs());
2488 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
2489 mangleExpression(CE->getArg(I));
2490 Out << 'E';
2491 break;
2492 }
2493
2494 case Expr::CXXNewExprClass: {
2495 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2496 if (New->isGlobalNew()) Out << "gs";
2497 Out << (New->isArray() ? "na" : "nw");
2498 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2499 E = New->placement_arg_end(); I != E; ++I)
2500 mangleExpression(*I);
2501 Out << '_';
2502 mangleType(New->getAllocatedType());
2503 if (New->hasInitializer()) {
2504 // Proposal by Jason Merrill, 2012-01-03
2505 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2506 Out << "il";
2507 else
2508 Out << "pi";
2509 const Expr *Init = New->getInitializer();
2510 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2511 // Directly inline the initializers.
2512 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2513 E = CCE->arg_end();
2514 I != E; ++I)
2515 mangleExpression(*I);
2516 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2517 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2518 mangleExpression(PLE->getExpr(i));
2519 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2520 isa<InitListExpr>(Init)) {
2521 // Only take InitListExprs apart for list-initialization.
2522 const InitListExpr *InitList = cast<InitListExpr>(Init);
2523 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2524 mangleExpression(InitList->getInit(i));
2525 } else
2526 mangleExpression(Init);
2527 }
2528 Out << 'E';
2529 break;
2530 }
2531
2532 case Expr::MemberExprClass: {
2533 const MemberExpr *ME = cast<MemberExpr>(E);
2534 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2535 ME->getQualifier(), 0, ME->getMemberDecl()->getDeclName(),
2536 Arity);
2537 break;
2538 }
2539
2540 case Expr::UnresolvedMemberExprClass: {
2541 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2542 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2543 ME->getQualifier(), 0, ME->getMemberName(),
2544 Arity);
2545 if (ME->hasExplicitTemplateArgs())
2546 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2547 break;
2548 }
2549
2550 case Expr::CXXDependentScopeMemberExprClass: {
2551 const CXXDependentScopeMemberExpr *ME
2552 = cast<CXXDependentScopeMemberExpr>(E);
2553 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2554 ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
2555 ME->getMember(), Arity);
2556 if (ME->hasExplicitTemplateArgs())
2557 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2558 break;
2559 }
2560
2561 case Expr::UnresolvedLookupExprClass: {
2562 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
2563 mangleUnresolvedName(ULE->getQualifier(), 0, ULE->getName(), Arity);
2564
2565 // All the <unresolved-name> productions end in a
2566 // base-unresolved-name, where <template-args> are just tacked
2567 // onto the end.
2568 if (ULE->hasExplicitTemplateArgs())
2569 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2570 break;
2571 }
2572
2573 case Expr::CXXUnresolvedConstructExprClass: {
2574 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2575 unsigned N = CE->arg_size();
2576
2577 Out << "cv";
2578 mangleType(CE->getType());
2579 if (N != 1) Out << '_';
2580 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2581 if (N != 1) Out << 'E';
2582 break;
2583 }
2584
2585 case Expr::CXXTemporaryObjectExprClass:
2586 case Expr::CXXConstructExprClass: {
2587 const CXXConstructExpr *CE = cast<CXXConstructExpr>(E);
2588 unsigned N = CE->getNumArgs();
2589
2590 // Proposal by Jason Merrill, 2012-01-03
2591 if (CE->isListInitialization())
2592 Out << "tl";
2593 else
2594 Out << "cv";
2595 mangleType(CE->getType());
2596 if (N != 1) Out << '_';
2597 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2598 if (N != 1) Out << 'E';
2599 break;
2600 }
2601
2602 case Expr::CXXScalarValueInitExprClass:
2603 Out <<"cv";
2604 mangleType(E->getType());
2605 Out <<"_E";
2606 break;
2607
2608 case Expr::CXXNoexceptExprClass:
2609 Out << "nx";
2610 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
2611 break;
2612
2613 case Expr::UnaryExprOrTypeTraitExprClass: {
2614 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
2615
2616 if (!SAE->isInstantiationDependent()) {
2617 // Itanium C++ ABI:
2618 // If the operand of a sizeof or alignof operator is not
2619 // instantiation-dependent it is encoded as an integer literal
2620 // reflecting the result of the operator.
2621 //
2622 // If the result of the operator is implicitly converted to a known
2623 // integer type, that type is used for the literal; otherwise, the type
2624 // of std::size_t or std::ptrdiff_t is used.
2625 QualType T = (ImplicitlyConvertedToType.isNull() ||
2626 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
2627 : ImplicitlyConvertedToType;
2628 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
2629 mangleIntegerLiteral(T, V);
2630 break;
2631 }
2632
2633 switch(SAE->getKind()) {
2634 case UETT_SizeOf:
2635 Out << 's';
2636 break;
2637 case UETT_AlignOf:
2638 Out << 'a';
2639 break;
2640 case UETT_VecStep:
2641 DiagnosticsEngine &Diags = Context.getDiags();
2642 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2643 "cannot yet mangle vec_step expression");
2644 Diags.Report(DiagID);
2645 return;
2646 }
2647 if (SAE->isArgumentType()) {
2648 Out << 't';
2649 mangleType(SAE->getArgumentType());
2650 } else {
2651 Out << 'z';
2652 mangleExpression(SAE->getArgumentExpr());
2653 }
2654 break;
2655 }
2656
2657 case Expr::CXXThrowExprClass: {
2658 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
2659
2660 // Proposal from David Vandervoorde, 2010.06.30
2661 if (TE->getSubExpr()) {
2662 Out << "tw";
2663 mangleExpression(TE->getSubExpr());
2664 } else {
2665 Out << "tr";
2666 }
2667 break;
2668 }
2669
2670 case Expr::CXXTypeidExprClass: {
2671 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
2672
2673 // Proposal from David Vandervoorde, 2010.06.30
2674 if (TIE->isTypeOperand()) {
2675 Out << "ti";
2676 mangleType(TIE->getTypeOperand());
2677 } else {
2678 Out << "te";
2679 mangleExpression(TIE->getExprOperand());
2680 }
2681 break;
2682 }
2683
2684 case Expr::CXXDeleteExprClass: {
2685 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
2686
2687 // Proposal from David Vandervoorde, 2010.06.30
2688 if (DE->isGlobalDelete()) Out << "gs";
2689 Out << (DE->isArrayForm() ? "da" : "dl");
2690 mangleExpression(DE->getArgument());
2691 break;
2692 }
2693
2694 case Expr::UnaryOperatorClass: {
2695 const UnaryOperator *UO = cast<UnaryOperator>(E);
2696 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
2697 /*Arity=*/1);
2698 mangleExpression(UO->getSubExpr());
2699 break;
2700 }
2701
2702 case Expr::ArraySubscriptExprClass: {
2703 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
2704
2705 // Array subscript is treated as a syntactically weird form of
2706 // binary operator.
2707 Out << "ix";
2708 mangleExpression(AE->getLHS());
2709 mangleExpression(AE->getRHS());
2710 break;
2711 }
2712
2713 case Expr::CompoundAssignOperatorClass: // fallthrough
2714 case Expr::BinaryOperatorClass: {
2715 const BinaryOperator *BO = cast<BinaryOperator>(E);
2716 if (BO->getOpcode() == BO_PtrMemD)
2717 Out << "ds";
2718 else
2719 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
2720 /*Arity=*/2);
2721 mangleExpression(BO->getLHS());
2722 mangleExpression(BO->getRHS());
2723 break;
2724 }
2725
2726 case Expr::ConditionalOperatorClass: {
2727 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
2728 mangleOperatorName(OO_Conditional, /*Arity=*/3);
2729 mangleExpression(CO->getCond());
2730 mangleExpression(CO->getLHS(), Arity);
2731 mangleExpression(CO->getRHS(), Arity);
2732 break;
2733 }
2734
2735 case Expr::ImplicitCastExprClass: {
2736 ImplicitlyConvertedToType = E->getType();
2737 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2738 goto recurse;
2739 }
2740
2741 case Expr::ObjCBridgedCastExprClass: {
2742 // Mangle ownership casts as a vendor extended operator __bridge,
2743 // __bridge_transfer, or __bridge_retain.
2744 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
2745 Out << "v1U" << Kind.size() << Kind;
2746 }
2747 // Fall through to mangle the cast itself.
2748
2749 case Expr::CStyleCastExprClass:
2750 case Expr::CXXStaticCastExprClass:
2751 case Expr::CXXDynamicCastExprClass:
2752 case Expr::CXXReinterpretCastExprClass:
2753 case Expr::CXXConstCastExprClass:
2754 case Expr::CXXFunctionalCastExprClass: {
2755 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2756 Out << "cv";
2757 mangleType(ECE->getType());
2758 mangleExpression(ECE->getSubExpr());
2759 break;
2760 }
2761
2762 case Expr::CXXOperatorCallExprClass: {
2763 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
2764 unsigned NumArgs = CE->getNumArgs();
2765 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
2766 // Mangle the arguments.
2767 for (unsigned i = 0; i != NumArgs; ++i)
2768 mangleExpression(CE->getArg(i));
2769 break;
2770 }
2771
2772 case Expr::ParenExprClass:
2773 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
2774 break;
2775
2776 case Expr::DeclRefExprClass: {
2777 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2778
2779 switch (D->getKind()) {
2780 default:
2781 // <expr-primary> ::= L <mangled-name> E # external name
2782 Out << 'L';
2783 mangle(D, "_Z");
2784 Out << 'E';
2785 break;
2786
2787 case Decl::ParmVar:
2788 mangleFunctionParam(cast<ParmVarDecl>(D));
2789 break;
2790
2791 case Decl::EnumConstant: {
2792 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
2793 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
2794 break;
2795 }
2796
2797 case Decl::NonTypeTemplateParm: {
2798 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
2799 mangleTemplateParameter(PD->getIndex());
2800 break;
2801 }
2802
2803 }
2804
2805 break;
2806 }
2807
2808 case Expr::SubstNonTypeTemplateParmPackExprClass:
2809 // FIXME: not clear how to mangle this!
2810 // template <unsigned N...> class A {
2811 // template <class U...> void foo(U (&x)[N]...);
2812 // };
2813 Out << "_SUBSTPACK_";
2814 break;
2815
2816 case Expr::FunctionParmPackExprClass: {
2817 // FIXME: not clear how to mangle this!
2818 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
2819 Out << "v110_SUBSTPACK";
2820 mangleFunctionParam(FPPE->getParameterPack());
2821 break;
2822 }
2823
2824 case Expr::DependentScopeDeclRefExprClass: {
2825 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
2826 mangleUnresolvedName(DRE->getQualifier(), 0, DRE->getDeclName(), Arity);
2827
2828 // All the <unresolved-name> productions end in a
2829 // base-unresolved-name, where <template-args> are just tacked
2830 // onto the end.
2831 if (DRE->hasExplicitTemplateArgs())
2832 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
2833 break;
2834 }
2835
2836 case Expr::CXXBindTemporaryExprClass:
2837 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
2838 break;
2839
2840 case Expr::ExprWithCleanupsClass:
2841 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
2842 break;
2843
2844 case Expr::FloatingLiteralClass: {
2845 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
2846 Out << 'L';
2847 mangleType(FL->getType());
2848 mangleFloat(FL->getValue());
2849 Out << 'E';
2850 break;
2851 }
2852
2853 case Expr::CharacterLiteralClass:
2854 Out << 'L';
2855 mangleType(E->getType());
2856 Out << cast<CharacterLiteral>(E)->getValue();
2857 Out << 'E';
2858 break;
2859
2860 // FIXME. __objc_yes/__objc_no are mangled same as true/false
2861 case Expr::ObjCBoolLiteralExprClass:
2862 Out << "Lb";
2863 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
2864 Out << 'E';
2865 break;
2866
2867 case Expr::CXXBoolLiteralExprClass:
2868 Out << "Lb";
2869 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
2870 Out << 'E';
2871 break;
2872
2873 case Expr::IntegerLiteralClass: {
2874 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
2875 if (E->getType()->isSignedIntegerType())
2876 Value.setIsSigned(true);
2877 mangleIntegerLiteral(E->getType(), Value);
2878 break;
2879 }
2880
2881 case Expr::ImaginaryLiteralClass: {
2882 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
2883 // Mangle as if a complex literal.
2884 // Proposal from David Vandevoorde, 2010.06.30.
2885 Out << 'L';
2886 mangleType(E->getType());
2887 if (const FloatingLiteral *Imag =
2888 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
2889 // Mangle a floating-point zero of the appropriate type.
2890 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
2891 Out << '_';
2892 mangleFloat(Imag->getValue());
2893 } else {
2894 Out << "0_";
2895 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
2896 if (IE->getSubExpr()->getType()->isSignedIntegerType())
2897 Value.setIsSigned(true);
2898 mangleNumber(Value);
2899 }
2900 Out << 'E';
2901 break;
2902 }
2903
2904 case Expr::StringLiteralClass: {
2905 // Revised proposal from David Vandervoorde, 2010.07.15.
2906 Out << 'L';
2907 assert(isa<ConstantArrayType>(E->getType()));
2908 mangleType(E->getType());
2909 Out << 'E';
2910 break;
2911 }
2912
2913 case Expr::GNUNullExprClass:
2914 // FIXME: should this really be mangled the same as nullptr?
2915 // fallthrough
2916
2917 case Expr::CXXNullPtrLiteralExprClass: {
2918 // Proposal from David Vandervoorde, 2010.06.30, as
2919 // modified by ABI list discussion.
2920 Out << "LDnE";
2921 break;
2922 }
2923
2924 case Expr::PackExpansionExprClass:
2925 Out << "sp";
2926 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
2927 break;
2928
2929 case Expr::SizeOfPackExprClass: {
2930 Out << "sZ";
2931 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
2932 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
2933 mangleTemplateParameter(TTP->getIndex());
2934 else if (const NonTypeTemplateParmDecl *NTTP
2935 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
2936 mangleTemplateParameter(NTTP->getIndex());
2937 else if (const TemplateTemplateParmDecl *TempTP
2938 = dyn_cast<TemplateTemplateParmDecl>(Pack))
2939 mangleTemplateParameter(TempTP->getIndex());
2940 else
2941 mangleFunctionParam(cast<ParmVarDecl>(Pack));
2942 break;
2943 }
2944
2945 case Expr::MaterializeTemporaryExprClass: {
2946 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
2947 break;
2948 }
2949
2950 case Expr::CXXThisExprClass:
2951 Out << "fpT";
2952 break;
2953 }
2954}
2955
2956/// Mangle an expression which refers to a parameter variable.
2957///
2958/// <expression> ::= <function-param>
2959/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
2960/// <function-param> ::= fp <top-level CV-qualifiers>
2961/// <parameter-2 non-negative number> _ # L == 0, I > 0
2962/// <function-param> ::= fL <L-1 non-negative number>
2963/// p <top-level CV-qualifiers> _ # L > 0, I == 0
2964/// <function-param> ::= fL <L-1 non-negative number>
2965/// p <top-level CV-qualifiers>
2966/// <I-1 non-negative number> _ # L > 0, I > 0
2967///
2968/// L is the nesting depth of the parameter, defined as 1 if the
2969/// parameter comes from the innermost function prototype scope
2970/// enclosing the current context, 2 if from the next enclosing
2971/// function prototype scope, and so on, with one special case: if
2972/// we've processed the full parameter clause for the innermost
2973/// function type, then L is one less. This definition conveniently
2974/// makes it irrelevant whether a function's result type was written
2975/// trailing or leading, but is otherwise overly complicated; the
2976/// numbering was first designed without considering references to
2977/// parameter in locations other than return types, and then the
2978/// mangling had to be generalized without changing the existing
2979/// manglings.
2980///
2981/// I is the zero-based index of the parameter within its parameter
2982/// declaration clause. Note that the original ABI document describes
2983/// this using 1-based ordinals.
2984void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
2985 unsigned parmDepth = parm->getFunctionScopeDepth();
2986 unsigned parmIndex = parm->getFunctionScopeIndex();
2987
2988 // Compute 'L'.
2989 // parmDepth does not include the declaring function prototype.
2990 // FunctionTypeDepth does account for that.
2991 assert(parmDepth < FunctionTypeDepth.getDepth());
2992 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
2993 if (FunctionTypeDepth.isInResultType())
2994 nestingDepth--;
2995
2996 if (nestingDepth == 0) {
2997 Out << "fp";
2998 } else {
2999 Out << "fL" << (nestingDepth - 1) << 'p';
3000 }
3001
3002 // Top-level qualifiers. We don't have to worry about arrays here,
3003 // because parameters declared as arrays should already have been
3004 // transformed to have pointer type. FIXME: apparently these don't
3005 // get mangled if used as an rvalue of a known non-class type?
3006 assert(!parm->getType()->isArrayType()
3007 && "parameter's type is still an array type?");
3008 mangleQualifiers(parm->getType().getQualifiers());
3009
3010 // Parameter index.
3011 if (parmIndex != 0) {
3012 Out << (parmIndex - 1);
3013 }
3014 Out << '_';
3015}
3016
3017void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3018 // <ctor-dtor-name> ::= C1 # complete object constructor
3019 // ::= C2 # base object constructor
3020 // ::= C3 # complete object allocating constructor
3021 //
3022 switch (T) {
3023 case Ctor_Complete:
3024 Out << "C1";
3025 break;
3026 case Ctor_Base:
3027 Out << "C2";
3028 break;
3029 case Ctor_CompleteAllocating:
3030 Out << "C3";
3031 break;
3032 }
3033}
3034
3035void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3036 // <ctor-dtor-name> ::= D0 # deleting destructor
3037 // ::= D1 # complete object destructor
3038 // ::= D2 # base object destructor
3039 //
3040 switch (T) {
3041 case Dtor_Deleting:
3042 Out << "D0";
3043 break;
3044 case Dtor_Complete:
3045 Out << "D1";
3046 break;
3047 case Dtor_Base:
3048 Out << "D2";
3049 break;
3050 }
3051}
3052
3053void CXXNameMangler::mangleTemplateArgs(
3054 const ASTTemplateArgumentListInfo &TemplateArgs) {
3055 // <template-args> ::= I <template-arg>+ E
3056 Out << 'I';
3057 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3058 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3059 Out << 'E';
3060}
3061
3062void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3063 // <template-args> ::= I <template-arg>+ E
3064 Out << 'I';
3065 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3066 mangleTemplateArg(AL[i]);
3067 Out << 'E';
3068}
3069
3070void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3071 unsigned NumTemplateArgs) {
3072 // <template-args> ::= I <template-arg>+ E
3073 Out << 'I';
3074 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3075 mangleTemplateArg(TemplateArgs[i]);
3076 Out << 'E';
3077}
3078
3079void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3080 // <template-arg> ::= <type> # type or template
3081 // ::= X <expression> E # expression
3082 // ::= <expr-primary> # simple expressions
3083 // ::= J <template-arg>* E # argument pack
3084 // ::= sp <expression> # pack expansion of (C++0x)
3085 if (!A.isInstantiationDependent() || A.isDependent())
3086 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3087
3088 switch (A.getKind()) {
3089 case TemplateArgument::Null:
3090 llvm_unreachable("Cannot mangle NULL template argument");
3091
3092 case TemplateArgument::Type:
3093 mangleType(A.getAsType());
3094 break;
3095 case TemplateArgument::Template:
3096 // This is mangled as <type>.
3097 mangleType(A.getAsTemplate());
3098 break;
3099 case TemplateArgument::TemplateExpansion:
3100 // <type> ::= Dp <type> # pack expansion (C++0x)
3101 Out << "Dp";
3102 mangleType(A.getAsTemplateOrTemplatePattern());
3103 break;
3104 case TemplateArgument::Expression: {
3105 // It's possible to end up with a DeclRefExpr here in certain
3106 // dependent cases, in which case we should mangle as a
3107 // declaration.
3108 const Expr *E = A.getAsExpr()->IgnoreParens();
3109 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3110 const ValueDecl *D = DRE->getDecl();
3111 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3112 Out << "L";
3113 mangle(D, "_Z");
3114 Out << 'E';
3115 break;
3116 }
3117 }
3118
3119 Out << 'X';
3120 mangleExpression(E);
3121 Out << 'E';
3122 break;
3123 }
3124 case TemplateArgument::Integral:
3125 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3126 break;
3127 case TemplateArgument::Declaration: {
3128 // <expr-primary> ::= L <mangled-name> E # external name
3129 // Clang produces AST's where pointer-to-member-function expressions
3130 // and pointer-to-function expressions are represented as a declaration not
3131 // an expression. We compensate for it here to produce the correct mangling.
3132 ValueDecl *D = A.getAsDecl();
3133 bool compensateMangling = !A.isDeclForReferenceParam();
3134 if (compensateMangling) {
3135 Out << 'X';
3136 mangleOperatorName(OO_Amp, 1);
3137 }
3138
3139 Out << 'L';
3140 // References to external entities use the mangled name; if the name would
3141 // not normally be manged then mangle it as unqualified.
3142 //
3143 // FIXME: The ABI specifies that external names here should have _Z, but
3144 // gcc leaves this off.
3145 if (compensateMangling)
3146 mangle(D, "_Z");
3147 else
3148 mangle(D, "Z");
3149 Out << 'E';
3150
3151 if (compensateMangling)
3152 Out << 'E';
3153
3154 break;
3155 }
3156 case TemplateArgument::NullPtr: {
3157 // <expr-primary> ::= L <type> 0 E
3158 Out << 'L';
3159 mangleType(A.getNullPtrType());
3160 Out << "0E";
3161 break;
3162 }
3163 case TemplateArgument::Pack: {
3164 // Note: proposal by Mike Herrick on 12/20/10
3165 Out << 'J';
3166 for (TemplateArgument::pack_iterator PA = A.pack_begin(),
3167 PAEnd = A.pack_end();
3168 PA != PAEnd; ++PA)
3169 mangleTemplateArg(*PA);
3170 Out << 'E';
3171 }
3172 }
3173}
3174
3175void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3176 // <template-param> ::= T_ # first template parameter
3177 // ::= T <parameter-2 non-negative number> _
3178 if (Index == 0)
3179 Out << "T_";
3180 else
3181 Out << 'T' << (Index - 1) << '_';
3182}
3183
3184void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3185 bool result = mangleSubstitution(type);
3186 assert(result && "no existing substitution for type");
3187 (void) result;
3188}
3189
3190void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3191 bool result = mangleSubstitution(tname);
3192 assert(result && "no existing substitution for template name");
3193 (void) result;
3194}
3195
3196// <substitution> ::= S <seq-id> _
3197// ::= S_
3198bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3199 // Try one of the standard substitutions first.
3200 if (mangleStandardSubstitution(ND))
3201 return true;
3202
3203 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3204 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3205}
3206
3207/// \brief Determine whether the given type has any qualifiers that are
3208/// relevant for substitutions.
3209static bool hasMangledSubstitutionQualifiers(QualType T) {
3210 Qualifiers Qs = T.getQualifiers();
3211 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3212}
3213
3214bool CXXNameMangler::mangleSubstitution(QualType T) {
3215 if (!hasMangledSubstitutionQualifiers(T)) {
3216 if (const RecordType *RT = T->getAs<RecordType>())
3217 return mangleSubstitution(RT->getDecl());
3218 }
3219
3220 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3221
3222 return mangleSubstitution(TypePtr);
3223}
3224
3225bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3226 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3227 return mangleSubstitution(TD);
3228
3229 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3230 return mangleSubstitution(
3231 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3232}
3233
3234bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3235 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3236 if (I == Substitutions.end())
3237 return false;
3238
3239 unsigned SeqID = I->second;
3240 if (SeqID == 0)
3241 Out << "S_";
3242 else {
3243 SeqID--;
3244
3245 // <seq-id> is encoded in base-36, using digits and upper case letters.
3246 char Buffer[10];
3247 char *BufferPtr = llvm::array_endof(Buffer);
3248
3249 if (SeqID == 0) *--BufferPtr = '0';
3250
3251 while (SeqID) {
3252 assert(BufferPtr > Buffer && "Buffer overflow!");
3253
3254 char c = static_cast<char>(SeqID % 36);
3255
3256 *--BufferPtr = (c < 10 ? '0' + c : 'A' + c - 10);
3257 SeqID /= 36;
3258 }
3259
3260 Out << 'S'
3261 << StringRef(BufferPtr, llvm::array_endof(Buffer)-BufferPtr)
3262 << '_';
3263 }
3264
3265 return true;
3266}
3267
3268static bool isCharType(QualType T) {
3269 if (T.isNull())
3270 return false;
3271
3272 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3273 T->isSpecificBuiltinType(BuiltinType::Char_U);
3274}
3275
3276/// isCharSpecialization - Returns whether a given type is a template
3277/// specialization of a given name with a single argument of type char.
3278static bool isCharSpecialization(QualType T, const char *Name) {
3279 if (T.isNull())
3280 return false;
3281
3282 const RecordType *RT = T->getAs<RecordType>();
3283 if (!RT)
3284 return false;
3285
3286 const ClassTemplateSpecializationDecl *SD =
3287 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3288 if (!SD)
3289 return false;
3290
3291 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3292 return false;
3293
3294 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3295 if (TemplateArgs.size() != 1)
3296 return false;
3297
3298 if (!isCharType(TemplateArgs[0].getAsType()))
3299 return false;
3300
3301 return SD->getIdentifier()->getName() == Name;
3302}
3303
3304template <std::size_t StrLen>
3305static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3306 const char (&Str)[StrLen]) {
3307 if (!SD->getIdentifier()->isStr(Str))
3308 return false;
3309
3310 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3311 if (TemplateArgs.size() != 2)
3312 return false;
3313
3314 if (!isCharType(TemplateArgs[0].getAsType()))
3315 return false;
3316
3317 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3318 return false;
3319
3320 return true;
3321}
3322
3323bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3324 // <substitution> ::= St # ::std::
3325 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3326 if (isStd(NS)) {
3327 Out << "St";
3328 return true;
3329 }
3330 }
3331
3332 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3333 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3334 return false;
3335
3336 // <substitution> ::= Sa # ::std::allocator
3337 if (TD->getIdentifier()->isStr("allocator")) {
3338 Out << "Sa";
3339 return true;
3340 }
3341
3342 // <<substitution> ::= Sb # ::std::basic_string
3343 if (TD->getIdentifier()->isStr("basic_string")) {
3344 Out << "Sb";
3345 return true;
3346 }
3347 }
3348
3349 if (const ClassTemplateSpecializationDecl *SD =
3350 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3351 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3352 return false;
3353
3354 // <substitution> ::= Ss # ::std::basic_string<char,
3355 // ::std::char_traits<char>,
3356 // ::std::allocator<char> >
3357 if (SD->getIdentifier()->isStr("basic_string")) {
3358 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3359
3360 if (TemplateArgs.size() != 3)
3361 return false;
3362
3363 if (!isCharType(TemplateArgs[0].getAsType()))
3364 return false;
3365
3366 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3367 return false;
3368
3369 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3370 return false;
3371
3372 Out << "Ss";
3373 return true;
3374 }
3375
3376 // <substitution> ::= Si # ::std::basic_istream<char,
3377 // ::std::char_traits<char> >
3378 if (isStreamCharSpecialization(SD, "basic_istream")) {
3379 Out << "Si";
3380 return true;
3381 }
3382
3383 // <substitution> ::= So # ::std::basic_ostream<char,
3384 // ::std::char_traits<char> >
3385 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3386 Out << "So";
3387 return true;
3388 }
3389
3390 // <substitution> ::= Sd # ::std::basic_iostream<char,
3391 // ::std::char_traits<char> >
3392 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3393 Out << "Sd";
3394 return true;
3395 }
3396 }
3397 return false;
3398}
3399
3400void CXXNameMangler::addSubstitution(QualType T) {
3401 if (!hasMangledSubstitutionQualifiers(T)) {
3402 if (const RecordType *RT = T->getAs<RecordType>()) {
3403 addSubstitution(RT->getDecl());
3404 return;
3405 }
3406 }
3407
3408 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3409 addSubstitution(TypePtr);
3410}
3411
3412void CXXNameMangler::addSubstitution(TemplateName Template) {
3413 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3414 return addSubstitution(TD);
3415
3416 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3417 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3418}
3419
3420void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3421 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3422 Substitutions[Ptr] = SeqID++;
3423}
3424
3425//
3426
3427/// \brief Mangles the name of the declaration D and emits that name to the
3428/// given output stream.
3429///
3430/// If the declaration D requires a mangled name, this routine will emit that
3431/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3432/// and this routine will return false. In this case, the caller should just
3433/// emit the identifier of the declaration (\c D->getIdentifier()) as its
3434/// name.
3435void ItaniumMangleContext::mangleName(const NamedDecl *D,
3436 raw_ostream &Out) {
3437 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3438 "Invalid mangleName() call, argument is not a variable or function!");
3439 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3440 "Invalid mangleName() call on 'structor decl!");
3441
3442 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3443 getASTContext().getSourceManager(),
3444 "Mangling declaration");
3445
3446 CXXNameMangler Mangler(*this, Out, D);
3447 return Mangler.mangle(D);
3448}
3449
3450void ItaniumMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
3451 CXXCtorType Type,
3452 raw_ostream &Out) {
3453 CXXNameMangler Mangler(*this, Out, D, Type);
3454 Mangler.mangle(D);
3455}
3456
3457void ItaniumMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
3458 CXXDtorType Type,
3459 raw_ostream &Out) {
3460 CXXNameMangler Mangler(*this, Out, D, Type);
3461 Mangler.mangle(D);
3462}
3463
3464void ItaniumMangleContext::mangleThunk(const CXXMethodDecl *MD,
3465 const ThunkInfo &Thunk,
3466 raw_ostream &Out) {
3467 // <special-name> ::= T <call-offset> <base encoding>
3468 // # base is the nominal target function of thunk
3469 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3470 // # base is the nominal target function of thunk
3471 // # first call-offset is 'this' adjustment
3472 // # second call-offset is result adjustment
3473
3474 assert(!isa<CXXDestructorDecl>(MD) &&
3475 "Use mangleCXXDtor for destructor decls!");
3476 CXXNameMangler Mangler(*this, Out);
3477 Mangler.getStream() << "_ZT";
3478 if (!Thunk.Return.isEmpty())
3479 Mangler.getStream() << 'c';
3480
3481 // Mangle the 'this' pointer adjustment.
3482 Mangler.mangleCallOffset(Thunk.This.NonVirtual, Thunk.This.VCallOffsetOffset);
3483
3484 // Mangle the return pointer adjustment if there is one.
3485 if (!Thunk.Return.isEmpty())
3486 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
3487 Thunk.Return.VBaseOffsetOffset);
3488
3489 Mangler.mangleFunctionEncoding(MD);
3490}
3491
3492void
3493ItaniumMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
3494 CXXDtorType Type,
3495 const ThisAdjustment &ThisAdjustment,
3496 raw_ostream &Out) {
3497 // <special-name> ::= T <call-offset> <base encoding>
3498 // # base is the nominal target function of thunk
3499 CXXNameMangler Mangler(*this, Out, DD, Type);
3500 Mangler.getStream() << "_ZT";
3501
3502 // Mangle the 'this' pointer adjustment.
3503 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
3504 ThisAdjustment.VCallOffsetOffset);
3505
3506 Mangler.mangleFunctionEncoding(DD);
3507}
3508
3509/// mangleGuardVariable - Returns the mangled name for a guard variable
3510/// for the passed in VarDecl.
3511void ItaniumMangleContext::mangleItaniumGuardVariable(const VarDecl *D,
3512 raw_ostream &Out) {
3513 // <special-name> ::= GV <object name> # Guard variable for one-time
3514 // # initialization
3515 CXXNameMangler Mangler(*this, Out);
3516 Mangler.getStream() << "_ZGV";
3517 Mangler.mangleName(D);
3518}
3519
3520void ItaniumMangleContext::mangleReferenceTemporary(const VarDecl *D,
3521 raw_ostream &Out) {
3522 // We match the GCC mangling here.
3523 // <special-name> ::= GR <object name>
3524 CXXNameMangler Mangler(*this, Out);
3525 Mangler.getStream() << "_ZGR";
3526 Mangler.mangleName(D);
3527}
3528
3529void ItaniumMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
3530 raw_ostream &Out) {
3531 // <special-name> ::= TV <type> # virtual table
3532 CXXNameMangler Mangler(*this, Out);
3533 Mangler.getStream() << "_ZTV";
3534 Mangler.mangleNameOrStandardSubstitution(RD);
3535}
3536
3537void ItaniumMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
3538 raw_ostream &Out) {
3539 // <special-name> ::= TT <type> # VTT structure
3540 CXXNameMangler Mangler(*this, Out);
3541 Mangler.getStream() << "_ZTT";
3542 Mangler.mangleNameOrStandardSubstitution(RD);
3543}
3544
3545void ItaniumMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
3546 int64_t Offset,
3547 const CXXRecordDecl *Type,
3548 raw_ostream &Out) {
3549 // <special-name> ::= TC <type> <offset number> _ <base type>
3550 CXXNameMangler Mangler(*this, Out);
3551 Mangler.getStream() << "_ZTC";
3552 Mangler.mangleNameOrStandardSubstitution(RD);
3553 Mangler.getStream() << Offset;
3554 Mangler.getStream() << '_';
3555 Mangler.mangleNameOrStandardSubstitution(Type);
3556}
3557
3558void ItaniumMangleContext::mangleCXXRTTI(QualType Ty,
3559 raw_ostream &Out) {
3560 // <special-name> ::= TI <type> # typeinfo structure
3561 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
3562 CXXNameMangler Mangler(*this, Out);
3563 Mangler.getStream() << "_ZTI";
3564 Mangler.mangleType(Ty);
3565}
3566
3567void ItaniumMangleContext::mangleCXXRTTIName(QualType Ty,
3568 raw_ostream &Out) {
3569 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
3570 CXXNameMangler Mangler(*this, Out);
3571 Mangler.getStream() << "_ZTS";
3572 Mangler.mangleType(Ty);
3573}
3574
3575MangleContext *clang::createItaniumMangleContext(ASTContext &Context,
3576 DiagnosticsEngine &Diags) {
3577 return new ItaniumMangleContext(Context, Diags);
3578}