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