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