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