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