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