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