blob: 419cb32e45a968ccba2a9615a3d6dd7e35d6b362 [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);
329 void mangleTemplatePrefix(const TemplateDecl *ND);
330 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)) {
1253 mangleTemplatePrefix(TD);
1254 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
1516void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND) {
1517 // <template-prefix> ::= <prefix> <template unqualified-name>
1518 // ::= <template-param>
1519 // ::= <substitution>
1520 // <template-template-param> ::= <template-param>
1521 // <substitution>
1522
1523 if (mangleSubstitution(ND))
1524 return;
1525
1526 // <template-template-param> ::= <template-param>
1527 if (const TemplateTemplateParmDecl *TTP
1528 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1529 mangleTemplateParameter(TTP->getIndex());
1530 return;
1531 }
1532
1533 manglePrefix(getEffectiveDeclContext(ND));
1534 mangleUnqualifiedName(ND->getTemplatedDecl());
1535 addSubstitution(ND);
1536}
1537
1538/// Mangles a template name under the production <type>. Required for
1539/// template template arguments.
1540/// <type> ::= <class-enum-type>
1541/// ::= <template-param>
1542/// ::= <substitution>
1543void CXXNameMangler::mangleType(TemplateName TN) {
1544 if (mangleSubstitution(TN))
1545 return;
1546
1547 TemplateDecl *TD = 0;
1548
1549 switch (TN.getKind()) {
1550 case TemplateName::QualifiedTemplate:
1551 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1552 goto HaveDecl;
1553
1554 case TemplateName::Template:
1555 TD = TN.getAsTemplateDecl();
1556 goto HaveDecl;
1557
1558 HaveDecl:
1559 if (isa<TemplateTemplateParmDecl>(TD))
1560 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1561 else
1562 mangleName(TD);
1563 break;
1564
1565 case TemplateName::OverloadedTemplate:
1566 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1567
1568 case TemplateName::DependentTemplate: {
1569 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1570 assert(Dependent->isIdentifier());
1571
1572 // <class-enum-type> ::= <name>
1573 // <name> ::= <nested-name>
1574 mangleUnresolvedPrefix(Dependent->getQualifier(), 0);
1575 mangleSourceName(Dependent->getIdentifier());
1576 break;
1577 }
1578
1579 case TemplateName::SubstTemplateTemplateParm: {
1580 // Substituted template parameters are mangled as the substituted
1581 // template. This will check for the substitution twice, which is
1582 // fine, but we have to return early so that we don't try to *add*
1583 // the substitution twice.
1584 SubstTemplateTemplateParmStorage *subst
1585 = TN.getAsSubstTemplateTemplateParm();
1586 mangleType(subst->getReplacement());
1587 return;
1588 }
1589
1590 case TemplateName::SubstTemplateTemplateParmPack: {
1591 // FIXME: not clear how to mangle this!
1592 // template <template <class> class T...> class A {
1593 // template <template <class> class U...> void foo(B<T,U> x...);
1594 // };
1595 Out << "_SUBSTPACK_";
1596 break;
1597 }
1598 }
1599
1600 addSubstitution(TN);
1601}
1602
1603void
1604CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1605 switch (OO) {
1606 // <operator-name> ::= nw # new
1607 case OO_New: Out << "nw"; break;
1608 // ::= na # new[]
1609 case OO_Array_New: Out << "na"; break;
1610 // ::= dl # delete
1611 case OO_Delete: Out << "dl"; break;
1612 // ::= da # delete[]
1613 case OO_Array_Delete: Out << "da"; break;
1614 // ::= ps # + (unary)
1615 // ::= pl # + (binary or unknown)
1616 case OO_Plus:
1617 Out << (Arity == 1? "ps" : "pl"); break;
1618 // ::= ng # - (unary)
1619 // ::= mi # - (binary or unknown)
1620 case OO_Minus:
1621 Out << (Arity == 1? "ng" : "mi"); break;
1622 // ::= ad # & (unary)
1623 // ::= an # & (binary or unknown)
1624 case OO_Amp:
1625 Out << (Arity == 1? "ad" : "an"); break;
1626 // ::= de # * (unary)
1627 // ::= ml # * (binary or unknown)
1628 case OO_Star:
1629 // Use binary when unknown.
1630 Out << (Arity == 1? "de" : "ml"); break;
1631 // ::= co # ~
1632 case OO_Tilde: Out << "co"; break;
1633 // ::= dv # /
1634 case OO_Slash: Out << "dv"; break;
1635 // ::= rm # %
1636 case OO_Percent: Out << "rm"; break;
1637 // ::= or # |
1638 case OO_Pipe: Out << "or"; break;
1639 // ::= eo # ^
1640 case OO_Caret: Out << "eo"; break;
1641 // ::= aS # =
1642 case OO_Equal: Out << "aS"; break;
1643 // ::= pL # +=
1644 case OO_PlusEqual: Out << "pL"; break;
1645 // ::= mI # -=
1646 case OO_MinusEqual: Out << "mI"; break;
1647 // ::= mL # *=
1648 case OO_StarEqual: Out << "mL"; break;
1649 // ::= dV # /=
1650 case OO_SlashEqual: Out << "dV"; break;
1651 // ::= rM # %=
1652 case OO_PercentEqual: Out << "rM"; break;
1653 // ::= aN # &=
1654 case OO_AmpEqual: Out << "aN"; break;
1655 // ::= oR # |=
1656 case OO_PipeEqual: Out << "oR"; break;
1657 // ::= eO # ^=
1658 case OO_CaretEqual: Out << "eO"; break;
1659 // ::= ls # <<
1660 case OO_LessLess: Out << "ls"; break;
1661 // ::= rs # >>
1662 case OO_GreaterGreater: Out << "rs"; break;
1663 // ::= lS # <<=
1664 case OO_LessLessEqual: Out << "lS"; break;
1665 // ::= rS # >>=
1666 case OO_GreaterGreaterEqual: Out << "rS"; break;
1667 // ::= eq # ==
1668 case OO_EqualEqual: Out << "eq"; break;
1669 // ::= ne # !=
1670 case OO_ExclaimEqual: Out << "ne"; break;
1671 // ::= lt # <
1672 case OO_Less: Out << "lt"; break;
1673 // ::= gt # >
1674 case OO_Greater: Out << "gt"; break;
1675 // ::= le # <=
1676 case OO_LessEqual: Out << "le"; break;
1677 // ::= ge # >=
1678 case OO_GreaterEqual: Out << "ge"; break;
1679 // ::= nt # !
1680 case OO_Exclaim: Out << "nt"; break;
1681 // ::= aa # &&
1682 case OO_AmpAmp: Out << "aa"; break;
1683 // ::= oo # ||
1684 case OO_PipePipe: Out << "oo"; break;
1685 // ::= pp # ++
1686 case OO_PlusPlus: Out << "pp"; break;
1687 // ::= mm # --
1688 case OO_MinusMinus: Out << "mm"; break;
1689 // ::= cm # ,
1690 case OO_Comma: Out << "cm"; break;
1691 // ::= pm # ->*
1692 case OO_ArrowStar: Out << "pm"; break;
1693 // ::= pt # ->
1694 case OO_Arrow: Out << "pt"; break;
1695 // ::= cl # ()
1696 case OO_Call: Out << "cl"; break;
1697 // ::= ix # []
1698 case OO_Subscript: Out << "ix"; break;
1699
1700 // ::= qu # ?
1701 // The conditional operator can't be overloaded, but we still handle it when
1702 // mangling expressions.
1703 case OO_Conditional: Out << "qu"; break;
1704
1705 case OO_None:
1706 case NUM_OVERLOADED_OPERATORS:
1707 llvm_unreachable("Not an overloaded operator");
1708 }
1709}
1710
1711void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1712 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1713 if (Quals.hasRestrict())
1714 Out << 'r';
1715 if (Quals.hasVolatile())
1716 Out << 'V';
1717 if (Quals.hasConst())
1718 Out << 'K';
1719
1720 if (Quals.hasAddressSpace()) {
1721 // Extension:
1722 //
1723 // <type> ::= U <address-space-number>
1724 //
1725 // where <address-space-number> is a source name consisting of 'AS'
1726 // followed by the address space <number>.
1727 SmallString<64> ASString;
Tanya Lattnerf21107b2013-02-08 01:07:32 +00001728 ASString = "AS" + llvm::utostr_32(
1729 Context.getASTContext().getTargetAddressSpace(Quals.getAddressSpace()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001730 Out << 'U' << ASString.size() << ASString;
1731 }
1732
1733 StringRef LifetimeName;
1734 switch (Quals.getObjCLifetime()) {
1735 // Objective-C ARC Extension:
1736 //
1737 // <type> ::= U "__strong"
1738 // <type> ::= U "__weak"
1739 // <type> ::= U "__autoreleasing"
1740 case Qualifiers::OCL_None:
1741 break;
1742
1743 case Qualifiers::OCL_Weak:
1744 LifetimeName = "__weak";
1745 break;
1746
1747 case Qualifiers::OCL_Strong:
1748 LifetimeName = "__strong";
1749 break;
1750
1751 case Qualifiers::OCL_Autoreleasing:
1752 LifetimeName = "__autoreleasing";
1753 break;
1754
1755 case Qualifiers::OCL_ExplicitNone:
1756 // The __unsafe_unretained qualifier is *not* mangled, so that
1757 // __unsafe_unretained types in ARC produce the same manglings as the
1758 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1759 // better ABI compatibility.
1760 //
1761 // It's safe to do this because unqualified 'id' won't show up
1762 // in any type signatures that need to be mangled.
1763 break;
1764 }
1765 if (!LifetimeName.empty())
1766 Out << 'U' << LifetimeName.size() << LifetimeName;
1767}
1768
1769void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1770 // <ref-qualifier> ::= R # lvalue reference
1771 // ::= O # rvalue-reference
1772 // Proposal to Itanium C++ ABI list on 1/26/11
1773 switch (RefQualifier) {
1774 case RQ_None:
1775 break;
1776
1777 case RQ_LValue:
1778 Out << 'R';
1779 break;
1780
1781 case RQ_RValue:
1782 Out << 'O';
1783 break;
1784 }
1785}
1786
1787void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1788 Context.mangleObjCMethodName(MD, Out);
1789}
1790
1791void CXXNameMangler::mangleType(QualType T) {
1792 // If our type is instantiation-dependent but not dependent, we mangle
1793 // it as it was written in the source, removing any top-level sugar.
1794 // Otherwise, use the canonical type.
1795 //
1796 // FIXME: This is an approximation of the instantiation-dependent name
1797 // mangling rules, since we should really be using the type as written and
1798 // augmented via semantic analysis (i.e., with implicit conversions and
1799 // default template arguments) for any instantiation-dependent type.
1800 // Unfortunately, that requires several changes to our AST:
1801 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1802 // uniqued, so that we can handle substitutions properly
1803 // - Default template arguments will need to be represented in the
1804 // TemplateSpecializationType, since they need to be mangled even though
1805 // they aren't written.
1806 // - Conversions on non-type template arguments need to be expressed, since
1807 // they can affect the mangling of sizeof/alignof.
1808 if (!T->isInstantiationDependentType() || T->isDependentType())
1809 T = T.getCanonicalType();
1810 else {
1811 // Desugar any types that are purely sugar.
1812 do {
1813 // Don't desugar through template specialization types that aren't
1814 // type aliases. We need to mangle the template arguments as written.
1815 if (const TemplateSpecializationType *TST
1816 = dyn_cast<TemplateSpecializationType>(T))
1817 if (!TST->isTypeAlias())
1818 break;
1819
1820 QualType Desugared
1821 = T.getSingleStepDesugaredType(Context.getASTContext());
1822 if (Desugared == T)
1823 break;
1824
1825 T = Desugared;
1826 } while (true);
1827 }
1828 SplitQualType split = T.split();
1829 Qualifiers quals = split.Quals;
1830 const Type *ty = split.Ty;
1831
1832 bool isSubstitutable = quals || !isa<BuiltinType>(T);
1833 if (isSubstitutable && mangleSubstitution(T))
1834 return;
1835
1836 // If we're mangling a qualified array type, push the qualifiers to
1837 // the element type.
1838 if (quals && isa<ArrayType>(T)) {
1839 ty = Context.getASTContext().getAsArrayType(T);
1840 quals = Qualifiers();
1841
1842 // Note that we don't update T: we want to add the
1843 // substitution at the original type.
1844 }
1845
1846 if (quals) {
1847 mangleQualifiers(quals);
1848 // Recurse: even if the qualified type isn't yet substitutable,
1849 // the unqualified type might be.
1850 mangleType(QualType(ty, 0));
1851 } else {
1852 switch (ty->getTypeClass()) {
1853#define ABSTRACT_TYPE(CLASS, PARENT)
1854#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1855 case Type::CLASS: \
1856 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1857 return;
1858#define TYPE(CLASS, PARENT) \
1859 case Type::CLASS: \
1860 mangleType(static_cast<const CLASS##Type*>(ty)); \
1861 break;
1862#include "clang/AST/TypeNodes.def"
1863 }
1864 }
1865
1866 // Add the substitution.
1867 if (isSubstitutable)
1868 addSubstitution(T);
1869}
1870
1871void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1872 if (!mangleStandardSubstitution(ND))
1873 mangleName(ND);
1874}
1875
1876void CXXNameMangler::mangleType(const BuiltinType *T) {
1877 // <type> ::= <builtin-type>
1878 // <builtin-type> ::= v # void
1879 // ::= w # wchar_t
1880 // ::= b # bool
1881 // ::= c # char
1882 // ::= a # signed char
1883 // ::= h # unsigned char
1884 // ::= s # short
1885 // ::= t # unsigned short
1886 // ::= i # int
1887 // ::= j # unsigned int
1888 // ::= l # long
1889 // ::= m # unsigned long
1890 // ::= x # long long, __int64
1891 // ::= y # unsigned long long, __int64
1892 // ::= n # __int128
1893 // UNSUPPORTED: ::= o # unsigned __int128
1894 // ::= f # float
1895 // ::= d # double
1896 // ::= e # long double, __float80
1897 // UNSUPPORTED: ::= g # __float128
1898 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1899 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1900 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1901 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1902 // ::= Di # char32_t
1903 // ::= Ds # char16_t
1904 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1905 // ::= u <source-name> # vendor extended type
1906 switch (T->getKind()) {
1907 case BuiltinType::Void: Out << 'v'; break;
1908 case BuiltinType::Bool: Out << 'b'; break;
1909 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
1910 case BuiltinType::UChar: Out << 'h'; break;
1911 case BuiltinType::UShort: Out << 't'; break;
1912 case BuiltinType::UInt: Out << 'j'; break;
1913 case BuiltinType::ULong: Out << 'm'; break;
1914 case BuiltinType::ULongLong: Out << 'y'; break;
1915 case BuiltinType::UInt128: Out << 'o'; break;
1916 case BuiltinType::SChar: Out << 'a'; break;
1917 case BuiltinType::WChar_S:
1918 case BuiltinType::WChar_U: Out << 'w'; break;
1919 case BuiltinType::Char16: Out << "Ds"; break;
1920 case BuiltinType::Char32: Out << "Di"; break;
1921 case BuiltinType::Short: Out << 's'; break;
1922 case BuiltinType::Int: Out << 'i'; break;
1923 case BuiltinType::Long: Out << 'l'; break;
1924 case BuiltinType::LongLong: Out << 'x'; break;
1925 case BuiltinType::Int128: Out << 'n'; break;
1926 case BuiltinType::Half: Out << "Dh"; break;
1927 case BuiltinType::Float: Out << 'f'; break;
1928 case BuiltinType::Double: Out << 'd'; break;
1929 case BuiltinType::LongDouble: Out << 'e'; break;
1930 case BuiltinType::NullPtr: Out << "Dn"; break;
1931
1932#define BUILTIN_TYPE(Id, SingletonId)
1933#define PLACEHOLDER_TYPE(Id, SingletonId) \
1934 case BuiltinType::Id:
1935#include "clang/AST/BuiltinTypes.def"
1936 case BuiltinType::Dependent:
1937 llvm_unreachable("mangling a placeholder type");
1938 case BuiltinType::ObjCId: Out << "11objc_object"; break;
1939 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
1940 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
Guy Benyeib13621d2012-12-18 14:38:23 +00001941 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
1942 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
1943 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
1944 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
1945 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
1946 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001947 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001948 case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001949 }
1950}
1951
1952// <type> ::= <function-type>
1953// <function-type> ::= [<CV-qualifiers>] F [Y]
1954// <bare-function-type> [<ref-qualifier>] E
1955// (Proposal to cxx-abi-dev, 2012-05-11)
1956void CXXNameMangler::mangleType(const FunctionProtoType *T) {
1957 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
1958 // e.g. "const" in "int (A::*)() const".
1959 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
1960
1961 Out << 'F';
1962
1963 // FIXME: We don't have enough information in the AST to produce the 'Y'
1964 // encoding for extern "C" function types.
1965 mangleBareFunctionType(T, /*MangleReturnType=*/true);
1966
1967 // Mangle the ref-qualifier, if present.
1968 mangleRefQualifier(T->getRefQualifier());
1969
1970 Out << 'E';
1971}
1972void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
1973 llvm_unreachable("Can't mangle K&R function prototypes");
1974}
1975void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
1976 bool MangleReturnType) {
1977 // We should never be mangling something without a prototype.
1978 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1979
1980 // Record that we're in a function type. See mangleFunctionParam
1981 // for details on what we're trying to achieve here.
1982 FunctionTypeDepthState saved = FunctionTypeDepth.push();
1983
1984 // <bare-function-type> ::= <signature type>+
1985 if (MangleReturnType) {
1986 FunctionTypeDepth.enterResultType();
1987 mangleType(Proto->getResultType());
1988 FunctionTypeDepth.leaveResultType();
1989 }
1990
1991 if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
1992 // <builtin-type> ::= v # void
1993 Out << 'v';
1994
1995 FunctionTypeDepth.pop(saved);
1996 return;
1997 }
1998
1999 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2000 ArgEnd = Proto->arg_type_end();
2001 Arg != ArgEnd; ++Arg)
2002 mangleType(Context.getASTContext().getSignatureParameterType(*Arg));
2003
2004 FunctionTypeDepth.pop(saved);
2005
2006 // <builtin-type> ::= z # ellipsis
2007 if (Proto->isVariadic())
2008 Out << 'z';
2009}
2010
2011// <type> ::= <class-enum-type>
2012// <class-enum-type> ::= <name>
2013void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2014 mangleName(T->getDecl());
2015}
2016
2017// <type> ::= <class-enum-type>
2018// <class-enum-type> ::= <name>
2019void CXXNameMangler::mangleType(const EnumType *T) {
2020 mangleType(static_cast<const TagType*>(T));
2021}
2022void CXXNameMangler::mangleType(const RecordType *T) {
2023 mangleType(static_cast<const TagType*>(T));
2024}
2025void CXXNameMangler::mangleType(const TagType *T) {
2026 mangleName(T->getDecl());
2027}
2028
2029// <type> ::= <array-type>
2030// <array-type> ::= A <positive dimension number> _ <element type>
2031// ::= A [<dimension expression>] _ <element type>
2032void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2033 Out << 'A' << T->getSize() << '_';
2034 mangleType(T->getElementType());
2035}
2036void CXXNameMangler::mangleType(const VariableArrayType *T) {
2037 Out << 'A';
2038 // decayed vla types (size 0) will just be skipped.
2039 if (T->getSizeExpr())
2040 mangleExpression(T->getSizeExpr());
2041 Out << '_';
2042 mangleType(T->getElementType());
2043}
2044void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2045 Out << 'A';
2046 mangleExpression(T->getSizeExpr());
2047 Out << '_';
2048 mangleType(T->getElementType());
2049}
2050void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2051 Out << "A_";
2052 mangleType(T->getElementType());
2053}
2054
2055// <type> ::= <pointer-to-member-type>
2056// <pointer-to-member-type> ::= M <class type> <member type>
2057void CXXNameMangler::mangleType(const MemberPointerType *T) {
2058 Out << 'M';
2059 mangleType(QualType(T->getClass(), 0));
2060 QualType PointeeType = T->getPointeeType();
2061 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2062 mangleType(FPT);
2063
2064 // Itanium C++ ABI 5.1.8:
2065 //
2066 // The type of a non-static member function is considered to be different,
2067 // for the purposes of substitution, from the type of a namespace-scope or
2068 // static member function whose type appears similar. The types of two
2069 // non-static member functions are considered to be different, for the
2070 // purposes of substitution, if the functions are members of different
2071 // classes. In other words, for the purposes of substitution, the class of
2072 // which the function is a member is considered part of the type of
2073 // function.
2074
2075 // Given that we already substitute member function pointers as a
2076 // whole, the net effect of this rule is just to unconditionally
2077 // suppress substitution on the function type in a member pointer.
2078 // We increment the SeqID here to emulate adding an entry to the
2079 // substitution table.
2080 ++SeqID;
2081 } else
2082 mangleType(PointeeType);
2083}
2084
2085// <type> ::= <template-param>
2086void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2087 mangleTemplateParameter(T->getIndex());
2088}
2089
2090// <type> ::= <template-param>
2091void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2092 // FIXME: not clear how to mangle this!
2093 // template <class T...> class A {
2094 // template <class U...> void foo(T(*)(U) x...);
2095 // };
2096 Out << "_SUBSTPACK_";
2097}
2098
2099// <type> ::= P <type> # pointer-to
2100void CXXNameMangler::mangleType(const PointerType *T) {
2101 Out << 'P';
2102 mangleType(T->getPointeeType());
2103}
2104void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2105 Out << 'P';
2106 mangleType(T->getPointeeType());
2107}
2108
2109// <type> ::= R <type> # reference-to
2110void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2111 Out << 'R';
2112 mangleType(T->getPointeeType());
2113}
2114
2115// <type> ::= O <type> # rvalue reference-to (C++0x)
2116void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2117 Out << 'O';
2118 mangleType(T->getPointeeType());
2119}
2120
2121// <type> ::= C <type> # complex pair (C 2000)
2122void CXXNameMangler::mangleType(const ComplexType *T) {
2123 Out << 'C';
2124 mangleType(T->getElementType());
2125}
2126
2127// ARM's ABI for Neon vector types specifies that they should be mangled as
2128// if they are structs (to match ARM's initial implementation). The
2129// vector type must be one of the special types predefined by ARM.
2130void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2131 QualType EltType = T->getElementType();
2132 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2133 const char *EltName = 0;
2134 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2135 switch (cast<BuiltinType>(EltType)->getKind()) {
2136 case BuiltinType::SChar: EltName = "poly8_t"; break;
2137 case BuiltinType::Short: EltName = "poly16_t"; break;
2138 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2139 }
2140 } else {
2141 switch (cast<BuiltinType>(EltType)->getKind()) {
2142 case BuiltinType::SChar: EltName = "int8_t"; break;
2143 case BuiltinType::UChar: EltName = "uint8_t"; break;
2144 case BuiltinType::Short: EltName = "int16_t"; break;
2145 case BuiltinType::UShort: EltName = "uint16_t"; break;
2146 case BuiltinType::Int: EltName = "int32_t"; break;
2147 case BuiltinType::UInt: EltName = "uint32_t"; break;
2148 case BuiltinType::LongLong: EltName = "int64_t"; break;
2149 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2150 case BuiltinType::Float: EltName = "float32_t"; break;
2151 default: llvm_unreachable("unexpected Neon vector element type");
2152 }
2153 }
2154 const char *BaseName = 0;
2155 unsigned BitSize = (T->getNumElements() *
2156 getASTContext().getTypeSize(EltType));
2157 if (BitSize == 64)
2158 BaseName = "__simd64_";
2159 else {
2160 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2161 BaseName = "__simd128_";
2162 }
2163 Out << strlen(BaseName) + strlen(EltName);
2164 Out << BaseName << EltName;
2165}
2166
2167// GNU extension: vector types
2168// <type> ::= <vector-type>
2169// <vector-type> ::= Dv <positive dimension number> _
2170// <extended element type>
2171// ::= Dv [<dimension expression>] _ <element type>
2172// <extended element type> ::= <element type>
2173// ::= p # AltiVec vector pixel
2174// ::= b # Altivec vector bool
2175void CXXNameMangler::mangleType(const VectorType *T) {
2176 if ((T->getVectorKind() == VectorType::NeonVector ||
2177 T->getVectorKind() == VectorType::NeonPolyVector)) {
2178 mangleNeonVectorType(T);
2179 return;
2180 }
2181 Out << "Dv" << T->getNumElements() << '_';
2182 if (T->getVectorKind() == VectorType::AltiVecPixel)
2183 Out << 'p';
2184 else if (T->getVectorKind() == VectorType::AltiVecBool)
2185 Out << 'b';
2186 else
2187 mangleType(T->getElementType());
2188}
2189void CXXNameMangler::mangleType(const ExtVectorType *T) {
2190 mangleType(static_cast<const VectorType*>(T));
2191}
2192void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2193 Out << "Dv";
2194 mangleExpression(T->getSizeExpr());
2195 Out << '_';
2196 mangleType(T->getElementType());
2197}
2198
2199void CXXNameMangler::mangleType(const PackExpansionType *T) {
2200 // <type> ::= Dp <type> # pack expansion (C++0x)
2201 Out << "Dp";
2202 mangleType(T->getPattern());
2203}
2204
2205void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2206 mangleSourceName(T->getDecl()->getIdentifier());
2207}
2208
2209void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Eli Friedman06017002013-06-18 22:41:37 +00002210 if (!T->qual_empty()) {
2211 // Mangle protocol qualifiers.
2212 SmallString<64> QualStr;
2213 llvm::raw_svector_ostream QualOS(QualStr);
2214 QualOS << "objcproto";
2215 ObjCObjectType::qual_iterator i = T->qual_begin(), e = T->qual_end();
2216 for ( ; i != e; ++i) {
2217 StringRef name = (*i)->getName();
2218 QualOS << name.size() << name;
2219 }
2220 QualOS.flush();
2221 Out << 'U' << QualStr.size() << QualStr;
2222 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002223 mangleType(T->getBaseType());
2224}
2225
2226void CXXNameMangler::mangleType(const BlockPointerType *T) {
2227 Out << "U13block_pointer";
2228 mangleType(T->getPointeeType());
2229}
2230
2231void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2232 // Mangle injected class name types as if the user had written the
2233 // specialization out fully. It may not actually be possible to see
2234 // this mangling, though.
2235 mangleType(T->getInjectedSpecializationType());
2236}
2237
2238void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2239 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2240 mangleName(TD, T->getArgs(), T->getNumArgs());
2241 } else {
2242 if (mangleSubstitution(QualType(T, 0)))
2243 return;
2244
2245 mangleTemplatePrefix(T->getTemplateName());
2246
2247 // FIXME: GCC does not appear to mangle the template arguments when
2248 // the template in question is a dependent template name. Should we
2249 // emulate that badness?
2250 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2251 addSubstitution(QualType(T, 0));
2252 }
2253}
2254
2255void CXXNameMangler::mangleType(const DependentNameType *T) {
2256 // Typename types are always nested
2257 Out << 'N';
2258 manglePrefix(T->getQualifier());
2259 mangleSourceName(T->getIdentifier());
2260 Out << 'E';
2261}
2262
2263void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2264 // Dependently-scoped template types are nested if they have a prefix.
2265 Out << 'N';
2266
2267 // TODO: avoid making this TemplateName.
2268 TemplateName Prefix =
2269 getASTContext().getDependentTemplateName(T->getQualifier(),
2270 T->getIdentifier());
2271 mangleTemplatePrefix(Prefix);
2272
2273 // FIXME: GCC does not appear to mangle the template arguments when
2274 // the template in question is a dependent template name. Should we
2275 // emulate that badness?
2276 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2277 Out << 'E';
2278}
2279
2280void CXXNameMangler::mangleType(const TypeOfType *T) {
2281 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2282 // "extension with parameters" mangling.
2283 Out << "u6typeof";
2284}
2285
2286void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2287 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2288 // "extension with parameters" mangling.
2289 Out << "u6typeof";
2290}
2291
2292void CXXNameMangler::mangleType(const DecltypeType *T) {
2293 Expr *E = T->getUnderlyingExpr();
2294
2295 // type ::= Dt <expression> E # decltype of an id-expression
2296 // # or class member access
2297 // ::= DT <expression> E # decltype of an expression
2298
2299 // This purports to be an exhaustive list of id-expressions and
2300 // class member accesses. Note that we do not ignore parentheses;
2301 // parentheses change the semantics of decltype for these
2302 // expressions (and cause the mangler to use the other form).
2303 if (isa<DeclRefExpr>(E) ||
2304 isa<MemberExpr>(E) ||
2305 isa<UnresolvedLookupExpr>(E) ||
2306 isa<DependentScopeDeclRefExpr>(E) ||
2307 isa<CXXDependentScopeMemberExpr>(E) ||
2308 isa<UnresolvedMemberExpr>(E))
2309 Out << "Dt";
2310 else
2311 Out << "DT";
2312 mangleExpression(E);
2313 Out << 'E';
2314}
2315
2316void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2317 // If this is dependent, we need to record that. If not, we simply
2318 // mangle it as the underlying type since they are equivalent.
2319 if (T->isDependentType()) {
2320 Out << 'U';
2321
2322 switch (T->getUTTKind()) {
2323 case UnaryTransformType::EnumUnderlyingType:
2324 Out << "3eut";
2325 break;
2326 }
2327 }
2328
2329 mangleType(T->getUnderlyingType());
2330}
2331
2332void CXXNameMangler::mangleType(const AutoType *T) {
2333 QualType D = T->getDeducedType();
2334 // <builtin-type> ::= Da # dependent auto
2335 if (D.isNull())
Richard Smitha2c36462013-04-26 16:15:35 +00002336 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002337 else
2338 mangleType(D);
2339}
2340
2341void CXXNameMangler::mangleType(const AtomicType *T) {
2342 // <type> ::= U <source-name> <type> # vendor extended type qualifier
2343 // (Until there's a standardized mangling...)
2344 Out << "U7_Atomic";
2345 mangleType(T->getValueType());
2346}
2347
2348void CXXNameMangler::mangleIntegerLiteral(QualType T,
2349 const llvm::APSInt &Value) {
2350 // <expr-primary> ::= L <type> <value number> E # integer literal
2351 Out << 'L';
2352
2353 mangleType(T);
2354 if (T->isBooleanType()) {
2355 // Boolean values are encoded as 0/1.
2356 Out << (Value.getBoolValue() ? '1' : '0');
2357 } else {
2358 mangleNumber(Value);
2359 }
2360 Out << 'E';
2361
2362}
2363
2364/// Mangles a member expression.
2365void CXXNameMangler::mangleMemberExpr(const Expr *base,
2366 bool isArrow,
2367 NestedNameSpecifier *qualifier,
2368 NamedDecl *firstQualifierLookup,
2369 DeclarationName member,
2370 unsigned arity) {
2371 // <expression> ::= dt <expression> <unresolved-name>
2372 // ::= pt <expression> <unresolved-name>
2373 if (base) {
2374 if (base->isImplicitCXXThis()) {
2375 // Note: GCC mangles member expressions to the implicit 'this' as
2376 // *this., whereas we represent them as this->. The Itanium C++ ABI
2377 // does not specify anything here, so we follow GCC.
2378 Out << "dtdefpT";
2379 } else {
2380 Out << (isArrow ? "pt" : "dt");
2381 mangleExpression(base);
2382 }
2383 }
2384 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
2385}
2386
2387/// Look at the callee of the given call expression and determine if
2388/// it's a parenthesized id-expression which would have triggered ADL
2389/// otherwise.
2390static bool isParenthesizedADLCallee(const CallExpr *call) {
2391 const Expr *callee = call->getCallee();
2392 const Expr *fn = callee->IgnoreParens();
2393
2394 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2395 // too, but for those to appear in the callee, it would have to be
2396 // parenthesized.
2397 if (callee == fn) return false;
2398
2399 // Must be an unresolved lookup.
2400 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2401 if (!lookup) return false;
2402
2403 assert(!lookup->requiresADL());
2404
2405 // Must be an unqualified lookup.
2406 if (lookup->getQualifier()) return false;
2407
2408 // Must not have found a class member. Note that if one is a class
2409 // member, they're all class members.
2410 if (lookup->getNumDecls() > 0 &&
2411 (*lookup->decls_begin())->isCXXClassMember())
2412 return false;
2413
2414 // Otherwise, ADL would have been triggered.
2415 return true;
2416}
2417
2418void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2419 // <expression> ::= <unary operator-name> <expression>
2420 // ::= <binary operator-name> <expression> <expression>
2421 // ::= <trinary operator-name> <expression> <expression> <expression>
2422 // ::= cv <type> expression # conversion with one argument
2423 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2424 // ::= st <type> # sizeof (a type)
2425 // ::= at <type> # alignof (a type)
2426 // ::= <template-param>
2427 // ::= <function-param>
2428 // ::= sr <type> <unqualified-name> # dependent name
2429 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2430 // ::= ds <expression> <expression> # expr.*expr
2431 // ::= sZ <template-param> # size of a parameter pack
2432 // ::= sZ <function-param> # size of a function parameter pack
2433 // ::= <expr-primary>
2434 // <expr-primary> ::= L <type> <value number> E # integer literal
2435 // ::= L <type <value float> E # floating literal
2436 // ::= L <mangled-name> E # external name
2437 // ::= fpT # 'this' expression
2438 QualType ImplicitlyConvertedToType;
2439
2440recurse:
2441 switch (E->getStmtClass()) {
2442 case Expr::NoStmtClass:
2443#define ABSTRACT_STMT(Type)
2444#define EXPR(Type, Base)
2445#define STMT(Type, Base) \
2446 case Expr::Type##Class:
2447#include "clang/AST/StmtNodes.inc"
2448 // fallthrough
2449
2450 // These all can only appear in local or variable-initialization
2451 // contexts and so should never appear in a mangling.
2452 case Expr::AddrLabelExprClass:
2453 case Expr::DesignatedInitExprClass:
2454 case Expr::ImplicitValueInitExprClass:
2455 case Expr::ParenListExprClass:
2456 case Expr::LambdaExprClass:
John McCall76da55d2013-04-16 07:28:30 +00002457 case Expr::MSPropertyRefExprClass:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002458 llvm_unreachable("unexpected statement kind");
2459
2460 // FIXME: invent manglings for all these.
2461 case Expr::BlockExprClass:
2462 case Expr::CXXPseudoDestructorExprClass:
2463 case Expr::ChooseExprClass:
2464 case Expr::CompoundLiteralExprClass:
2465 case Expr::ExtVectorElementExprClass:
2466 case Expr::GenericSelectionExprClass:
2467 case Expr::ObjCEncodeExprClass:
2468 case Expr::ObjCIsaExprClass:
2469 case Expr::ObjCIvarRefExprClass:
2470 case Expr::ObjCMessageExprClass:
2471 case Expr::ObjCPropertyRefExprClass:
2472 case Expr::ObjCProtocolExprClass:
2473 case Expr::ObjCSelectorExprClass:
2474 case Expr::ObjCStringLiteralClass:
2475 case Expr::ObjCBoxedExprClass:
2476 case Expr::ObjCArrayLiteralClass:
2477 case Expr::ObjCDictionaryLiteralClass:
2478 case Expr::ObjCSubscriptRefExprClass:
2479 case Expr::ObjCIndirectCopyRestoreExprClass:
2480 case Expr::OffsetOfExprClass:
2481 case Expr::PredefinedExprClass:
2482 case Expr::ShuffleVectorExprClass:
2483 case Expr::StmtExprClass:
2484 case Expr::UnaryTypeTraitExprClass:
2485 case Expr::BinaryTypeTraitExprClass:
2486 case Expr::TypeTraitExprClass:
2487 case Expr::ArrayTypeTraitExprClass:
2488 case Expr::ExpressionTraitExprClass:
2489 case Expr::VAArgExprClass:
2490 case Expr::CXXUuidofExprClass:
2491 case Expr::CUDAKernelCallExprClass:
2492 case Expr::AsTypeExprClass:
2493 case Expr::PseudoObjectExprClass:
2494 case Expr::AtomicExprClass:
2495 {
2496 // As bad as this diagnostic is, it's better than crashing.
2497 DiagnosticsEngine &Diags = Context.getDiags();
2498 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2499 "cannot yet mangle expression type %0");
2500 Diags.Report(E->getExprLoc(), DiagID)
2501 << E->getStmtClassName() << E->getSourceRange();
2502 break;
2503 }
2504
2505 // Even gcc-4.5 doesn't mangle this.
2506 case Expr::BinaryConditionalOperatorClass: {
2507 DiagnosticsEngine &Diags = Context.getDiags();
2508 unsigned DiagID =
2509 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2510 "?: operator with omitted middle operand cannot be mangled");
2511 Diags.Report(E->getExprLoc(), DiagID)
2512 << E->getStmtClassName() << E->getSourceRange();
2513 break;
2514 }
2515
2516 // These are used for internal purposes and cannot be meaningfully mangled.
2517 case Expr::OpaqueValueExprClass:
2518 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2519
2520 case Expr::InitListExprClass: {
2521 // Proposal by Jason Merrill, 2012-01-03
2522 Out << "il";
2523 const InitListExpr *InitList = cast<InitListExpr>(E);
2524 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2525 mangleExpression(InitList->getInit(i));
2526 Out << "E";
2527 break;
2528 }
2529
2530 case Expr::CXXDefaultArgExprClass:
2531 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2532 break;
2533
Richard Smithc3bf52c2013-04-20 22:23:05 +00002534 case Expr::CXXDefaultInitExprClass:
2535 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2536 break;
2537
Richard Smith7c3e6152013-06-12 22:31:48 +00002538 case Expr::CXXStdInitializerListExprClass:
2539 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2540 break;
2541
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002542 case Expr::SubstNonTypeTemplateParmExprClass:
2543 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2544 Arity);
2545 break;
2546
2547 case Expr::UserDefinedLiteralClass:
2548 // We follow g++'s approach of mangling a UDL as a call to the literal
2549 // operator.
2550 case Expr::CXXMemberCallExprClass: // fallthrough
2551 case Expr::CallExprClass: {
2552 const CallExpr *CE = cast<CallExpr>(E);
2553
2554 // <expression> ::= cp <simple-id> <expression>* E
2555 // We use this mangling only when the call would use ADL except
2556 // for being parenthesized. Per discussion with David
2557 // Vandervoorde, 2011.04.25.
2558 if (isParenthesizedADLCallee(CE)) {
2559 Out << "cp";
2560 // The callee here is a parenthesized UnresolvedLookupExpr with
2561 // no qualifier and should always get mangled as a <simple-id>
2562 // anyway.
2563
2564 // <expression> ::= cl <expression>* E
2565 } else {
2566 Out << "cl";
2567 }
2568
2569 mangleExpression(CE->getCallee(), CE->getNumArgs());
2570 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
2571 mangleExpression(CE->getArg(I));
2572 Out << 'E';
2573 break;
2574 }
2575
2576 case Expr::CXXNewExprClass: {
2577 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2578 if (New->isGlobalNew()) Out << "gs";
2579 Out << (New->isArray() ? "na" : "nw");
2580 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2581 E = New->placement_arg_end(); I != E; ++I)
2582 mangleExpression(*I);
2583 Out << '_';
2584 mangleType(New->getAllocatedType());
2585 if (New->hasInitializer()) {
2586 // Proposal by Jason Merrill, 2012-01-03
2587 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2588 Out << "il";
2589 else
2590 Out << "pi";
2591 const Expr *Init = New->getInitializer();
2592 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2593 // Directly inline the initializers.
2594 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2595 E = CCE->arg_end();
2596 I != E; ++I)
2597 mangleExpression(*I);
2598 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2599 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2600 mangleExpression(PLE->getExpr(i));
2601 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2602 isa<InitListExpr>(Init)) {
2603 // Only take InitListExprs apart for list-initialization.
2604 const InitListExpr *InitList = cast<InitListExpr>(Init);
2605 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2606 mangleExpression(InitList->getInit(i));
2607 } else
2608 mangleExpression(Init);
2609 }
2610 Out << 'E';
2611 break;
2612 }
2613
2614 case Expr::MemberExprClass: {
2615 const MemberExpr *ME = cast<MemberExpr>(E);
2616 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2617 ME->getQualifier(), 0, ME->getMemberDecl()->getDeclName(),
2618 Arity);
2619 break;
2620 }
2621
2622 case Expr::UnresolvedMemberExprClass: {
2623 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2624 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2625 ME->getQualifier(), 0, ME->getMemberName(),
2626 Arity);
2627 if (ME->hasExplicitTemplateArgs())
2628 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2629 break;
2630 }
2631
2632 case Expr::CXXDependentScopeMemberExprClass: {
2633 const CXXDependentScopeMemberExpr *ME
2634 = cast<CXXDependentScopeMemberExpr>(E);
2635 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2636 ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
2637 ME->getMember(), Arity);
2638 if (ME->hasExplicitTemplateArgs())
2639 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2640 break;
2641 }
2642
2643 case Expr::UnresolvedLookupExprClass: {
2644 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
2645 mangleUnresolvedName(ULE->getQualifier(), 0, ULE->getName(), Arity);
2646
2647 // All the <unresolved-name> productions end in a
2648 // base-unresolved-name, where <template-args> are just tacked
2649 // onto the end.
2650 if (ULE->hasExplicitTemplateArgs())
2651 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2652 break;
2653 }
2654
2655 case Expr::CXXUnresolvedConstructExprClass: {
2656 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2657 unsigned N = CE->arg_size();
2658
2659 Out << "cv";
2660 mangleType(CE->getType());
2661 if (N != 1) Out << '_';
2662 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2663 if (N != 1) Out << 'E';
2664 break;
2665 }
2666
2667 case Expr::CXXTemporaryObjectExprClass:
2668 case Expr::CXXConstructExprClass: {
2669 const CXXConstructExpr *CE = cast<CXXConstructExpr>(E);
2670 unsigned N = CE->getNumArgs();
2671
2672 // Proposal by Jason Merrill, 2012-01-03
2673 if (CE->isListInitialization())
2674 Out << "tl";
2675 else
2676 Out << "cv";
2677 mangleType(CE->getType());
2678 if (N != 1) Out << '_';
2679 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2680 if (N != 1) Out << 'E';
2681 break;
2682 }
2683
2684 case Expr::CXXScalarValueInitExprClass:
2685 Out <<"cv";
2686 mangleType(E->getType());
2687 Out <<"_E";
2688 break;
2689
2690 case Expr::CXXNoexceptExprClass:
2691 Out << "nx";
2692 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
2693 break;
2694
2695 case Expr::UnaryExprOrTypeTraitExprClass: {
2696 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
2697
2698 if (!SAE->isInstantiationDependent()) {
2699 // Itanium C++ ABI:
2700 // If the operand of a sizeof or alignof operator is not
2701 // instantiation-dependent it is encoded as an integer literal
2702 // reflecting the result of the operator.
2703 //
2704 // If the result of the operator is implicitly converted to a known
2705 // integer type, that type is used for the literal; otherwise, the type
2706 // of std::size_t or std::ptrdiff_t is used.
2707 QualType T = (ImplicitlyConvertedToType.isNull() ||
2708 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
2709 : ImplicitlyConvertedToType;
2710 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
2711 mangleIntegerLiteral(T, V);
2712 break;
2713 }
2714
2715 switch(SAE->getKind()) {
2716 case UETT_SizeOf:
2717 Out << 's';
2718 break;
2719 case UETT_AlignOf:
2720 Out << 'a';
2721 break;
2722 case UETT_VecStep:
2723 DiagnosticsEngine &Diags = Context.getDiags();
2724 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2725 "cannot yet mangle vec_step expression");
2726 Diags.Report(DiagID);
2727 return;
2728 }
2729 if (SAE->isArgumentType()) {
2730 Out << 't';
2731 mangleType(SAE->getArgumentType());
2732 } else {
2733 Out << 'z';
2734 mangleExpression(SAE->getArgumentExpr());
2735 }
2736 break;
2737 }
2738
2739 case Expr::CXXThrowExprClass: {
2740 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
2741
2742 // Proposal from David Vandervoorde, 2010.06.30
2743 if (TE->getSubExpr()) {
2744 Out << "tw";
2745 mangleExpression(TE->getSubExpr());
2746 } else {
2747 Out << "tr";
2748 }
2749 break;
2750 }
2751
2752 case Expr::CXXTypeidExprClass: {
2753 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
2754
2755 // Proposal from David Vandervoorde, 2010.06.30
2756 if (TIE->isTypeOperand()) {
2757 Out << "ti";
2758 mangleType(TIE->getTypeOperand());
2759 } else {
2760 Out << "te";
2761 mangleExpression(TIE->getExprOperand());
2762 }
2763 break;
2764 }
2765
2766 case Expr::CXXDeleteExprClass: {
2767 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
2768
2769 // Proposal from David Vandervoorde, 2010.06.30
2770 if (DE->isGlobalDelete()) Out << "gs";
2771 Out << (DE->isArrayForm() ? "da" : "dl");
2772 mangleExpression(DE->getArgument());
2773 break;
2774 }
2775
2776 case Expr::UnaryOperatorClass: {
2777 const UnaryOperator *UO = cast<UnaryOperator>(E);
2778 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
2779 /*Arity=*/1);
2780 mangleExpression(UO->getSubExpr());
2781 break;
2782 }
2783
2784 case Expr::ArraySubscriptExprClass: {
2785 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
2786
2787 // Array subscript is treated as a syntactically weird form of
2788 // binary operator.
2789 Out << "ix";
2790 mangleExpression(AE->getLHS());
2791 mangleExpression(AE->getRHS());
2792 break;
2793 }
2794
2795 case Expr::CompoundAssignOperatorClass: // fallthrough
2796 case Expr::BinaryOperatorClass: {
2797 const BinaryOperator *BO = cast<BinaryOperator>(E);
2798 if (BO->getOpcode() == BO_PtrMemD)
2799 Out << "ds";
2800 else
2801 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
2802 /*Arity=*/2);
2803 mangleExpression(BO->getLHS());
2804 mangleExpression(BO->getRHS());
2805 break;
2806 }
2807
2808 case Expr::ConditionalOperatorClass: {
2809 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
2810 mangleOperatorName(OO_Conditional, /*Arity=*/3);
2811 mangleExpression(CO->getCond());
2812 mangleExpression(CO->getLHS(), Arity);
2813 mangleExpression(CO->getRHS(), Arity);
2814 break;
2815 }
2816
2817 case Expr::ImplicitCastExprClass: {
2818 ImplicitlyConvertedToType = E->getType();
2819 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2820 goto recurse;
2821 }
2822
2823 case Expr::ObjCBridgedCastExprClass: {
2824 // Mangle ownership casts as a vendor extended operator __bridge,
2825 // __bridge_transfer, or __bridge_retain.
2826 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
2827 Out << "v1U" << Kind.size() << Kind;
2828 }
2829 // Fall through to mangle the cast itself.
2830
2831 case Expr::CStyleCastExprClass:
2832 case Expr::CXXStaticCastExprClass:
2833 case Expr::CXXDynamicCastExprClass:
2834 case Expr::CXXReinterpretCastExprClass:
2835 case Expr::CXXConstCastExprClass:
2836 case Expr::CXXFunctionalCastExprClass: {
2837 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2838 Out << "cv";
2839 mangleType(ECE->getType());
2840 mangleExpression(ECE->getSubExpr());
2841 break;
2842 }
2843
2844 case Expr::CXXOperatorCallExprClass: {
2845 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
2846 unsigned NumArgs = CE->getNumArgs();
2847 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
2848 // Mangle the arguments.
2849 for (unsigned i = 0; i != NumArgs; ++i)
2850 mangleExpression(CE->getArg(i));
2851 break;
2852 }
2853
2854 case Expr::ParenExprClass:
2855 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
2856 break;
2857
2858 case Expr::DeclRefExprClass: {
2859 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2860
2861 switch (D->getKind()) {
2862 default:
2863 // <expr-primary> ::= L <mangled-name> E # external name
2864 Out << 'L';
2865 mangle(D, "_Z");
2866 Out << 'E';
2867 break;
2868
2869 case Decl::ParmVar:
2870 mangleFunctionParam(cast<ParmVarDecl>(D));
2871 break;
2872
2873 case Decl::EnumConstant: {
2874 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
2875 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
2876 break;
2877 }
2878
2879 case Decl::NonTypeTemplateParm: {
2880 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
2881 mangleTemplateParameter(PD->getIndex());
2882 break;
2883 }
2884
2885 }
2886
2887 break;
2888 }
2889
2890 case Expr::SubstNonTypeTemplateParmPackExprClass:
2891 // FIXME: not clear how to mangle this!
2892 // template <unsigned N...> class A {
2893 // template <class U...> void foo(U (&x)[N]...);
2894 // };
2895 Out << "_SUBSTPACK_";
2896 break;
2897
2898 case Expr::FunctionParmPackExprClass: {
2899 // FIXME: not clear how to mangle this!
2900 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
2901 Out << "v110_SUBSTPACK";
2902 mangleFunctionParam(FPPE->getParameterPack());
2903 break;
2904 }
2905
2906 case Expr::DependentScopeDeclRefExprClass: {
2907 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
2908 mangleUnresolvedName(DRE->getQualifier(), 0, DRE->getDeclName(), Arity);
2909
2910 // All the <unresolved-name> productions end in a
2911 // base-unresolved-name, where <template-args> are just tacked
2912 // onto the end.
2913 if (DRE->hasExplicitTemplateArgs())
2914 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
2915 break;
2916 }
2917
2918 case Expr::CXXBindTemporaryExprClass:
2919 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
2920 break;
2921
2922 case Expr::ExprWithCleanupsClass:
2923 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
2924 break;
2925
2926 case Expr::FloatingLiteralClass: {
2927 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
2928 Out << 'L';
2929 mangleType(FL->getType());
2930 mangleFloat(FL->getValue());
2931 Out << 'E';
2932 break;
2933 }
2934
2935 case Expr::CharacterLiteralClass:
2936 Out << 'L';
2937 mangleType(E->getType());
2938 Out << cast<CharacterLiteral>(E)->getValue();
2939 Out << 'E';
2940 break;
2941
2942 // FIXME. __objc_yes/__objc_no are mangled same as true/false
2943 case Expr::ObjCBoolLiteralExprClass:
2944 Out << "Lb";
2945 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
2946 Out << 'E';
2947 break;
2948
2949 case Expr::CXXBoolLiteralExprClass:
2950 Out << "Lb";
2951 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
2952 Out << 'E';
2953 break;
2954
2955 case Expr::IntegerLiteralClass: {
2956 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
2957 if (E->getType()->isSignedIntegerType())
2958 Value.setIsSigned(true);
2959 mangleIntegerLiteral(E->getType(), Value);
2960 break;
2961 }
2962
2963 case Expr::ImaginaryLiteralClass: {
2964 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
2965 // Mangle as if a complex literal.
2966 // Proposal from David Vandevoorde, 2010.06.30.
2967 Out << 'L';
2968 mangleType(E->getType());
2969 if (const FloatingLiteral *Imag =
2970 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
2971 // Mangle a floating-point zero of the appropriate type.
2972 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
2973 Out << '_';
2974 mangleFloat(Imag->getValue());
2975 } else {
2976 Out << "0_";
2977 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
2978 if (IE->getSubExpr()->getType()->isSignedIntegerType())
2979 Value.setIsSigned(true);
2980 mangleNumber(Value);
2981 }
2982 Out << 'E';
2983 break;
2984 }
2985
2986 case Expr::StringLiteralClass: {
2987 // Revised proposal from David Vandervoorde, 2010.07.15.
2988 Out << 'L';
2989 assert(isa<ConstantArrayType>(E->getType()));
2990 mangleType(E->getType());
2991 Out << 'E';
2992 break;
2993 }
2994
2995 case Expr::GNUNullExprClass:
2996 // FIXME: should this really be mangled the same as nullptr?
2997 // fallthrough
2998
2999 case Expr::CXXNullPtrLiteralExprClass: {
3000 // Proposal from David Vandervoorde, 2010.06.30, as
3001 // modified by ABI list discussion.
3002 Out << "LDnE";
3003 break;
3004 }
3005
3006 case Expr::PackExpansionExprClass:
3007 Out << "sp";
3008 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3009 break;
3010
3011 case Expr::SizeOfPackExprClass: {
3012 Out << "sZ";
3013 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
3014 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3015 mangleTemplateParameter(TTP->getIndex());
3016 else if (const NonTypeTemplateParmDecl *NTTP
3017 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3018 mangleTemplateParameter(NTTP->getIndex());
3019 else if (const TemplateTemplateParmDecl *TempTP
3020 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3021 mangleTemplateParameter(TempTP->getIndex());
3022 else
3023 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3024 break;
3025 }
3026
3027 case Expr::MaterializeTemporaryExprClass: {
3028 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3029 break;
3030 }
3031
3032 case Expr::CXXThisExprClass:
3033 Out << "fpT";
3034 break;
3035 }
3036}
3037
3038/// Mangle an expression which refers to a parameter variable.
3039///
3040/// <expression> ::= <function-param>
3041/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3042/// <function-param> ::= fp <top-level CV-qualifiers>
3043/// <parameter-2 non-negative number> _ # L == 0, I > 0
3044/// <function-param> ::= fL <L-1 non-negative number>
3045/// p <top-level CV-qualifiers> _ # L > 0, I == 0
3046/// <function-param> ::= fL <L-1 non-negative number>
3047/// p <top-level CV-qualifiers>
3048/// <I-1 non-negative number> _ # L > 0, I > 0
3049///
3050/// L is the nesting depth of the parameter, defined as 1 if the
3051/// parameter comes from the innermost function prototype scope
3052/// enclosing the current context, 2 if from the next enclosing
3053/// function prototype scope, and so on, with one special case: if
3054/// we've processed the full parameter clause for the innermost
3055/// function type, then L is one less. This definition conveniently
3056/// makes it irrelevant whether a function's result type was written
3057/// trailing or leading, but is otherwise overly complicated; the
3058/// numbering was first designed without considering references to
3059/// parameter in locations other than return types, and then the
3060/// mangling had to be generalized without changing the existing
3061/// manglings.
3062///
3063/// I is the zero-based index of the parameter within its parameter
3064/// declaration clause. Note that the original ABI document describes
3065/// this using 1-based ordinals.
3066void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3067 unsigned parmDepth = parm->getFunctionScopeDepth();
3068 unsigned parmIndex = parm->getFunctionScopeIndex();
3069
3070 // Compute 'L'.
3071 // parmDepth does not include the declaring function prototype.
3072 // FunctionTypeDepth does account for that.
3073 assert(parmDepth < FunctionTypeDepth.getDepth());
3074 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3075 if (FunctionTypeDepth.isInResultType())
3076 nestingDepth--;
3077
3078 if (nestingDepth == 0) {
3079 Out << "fp";
3080 } else {
3081 Out << "fL" << (nestingDepth - 1) << 'p';
3082 }
3083
3084 // Top-level qualifiers. We don't have to worry about arrays here,
3085 // because parameters declared as arrays should already have been
3086 // transformed to have pointer type. FIXME: apparently these don't
3087 // get mangled if used as an rvalue of a known non-class type?
3088 assert(!parm->getType()->isArrayType()
3089 && "parameter's type is still an array type?");
3090 mangleQualifiers(parm->getType().getQualifiers());
3091
3092 // Parameter index.
3093 if (parmIndex != 0) {
3094 Out << (parmIndex - 1);
3095 }
3096 Out << '_';
3097}
3098
3099void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3100 // <ctor-dtor-name> ::= C1 # complete object constructor
3101 // ::= C2 # base object constructor
3102 // ::= C3 # complete object allocating constructor
3103 //
3104 switch (T) {
3105 case Ctor_Complete:
3106 Out << "C1";
3107 break;
3108 case Ctor_Base:
3109 Out << "C2";
3110 break;
3111 case Ctor_CompleteAllocating:
3112 Out << "C3";
3113 break;
3114 }
3115}
3116
3117void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3118 // <ctor-dtor-name> ::= D0 # deleting destructor
3119 // ::= D1 # complete object destructor
3120 // ::= D2 # base object destructor
3121 //
3122 switch (T) {
3123 case Dtor_Deleting:
3124 Out << "D0";
3125 break;
3126 case Dtor_Complete:
3127 Out << "D1";
3128 break;
3129 case Dtor_Base:
3130 Out << "D2";
3131 break;
3132 }
3133}
3134
3135void CXXNameMangler::mangleTemplateArgs(
3136 const ASTTemplateArgumentListInfo &TemplateArgs) {
3137 // <template-args> ::= I <template-arg>+ E
3138 Out << 'I';
3139 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3140 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3141 Out << 'E';
3142}
3143
3144void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3145 // <template-args> ::= I <template-arg>+ E
3146 Out << 'I';
3147 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3148 mangleTemplateArg(AL[i]);
3149 Out << 'E';
3150}
3151
3152void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3153 unsigned NumTemplateArgs) {
3154 // <template-args> ::= I <template-arg>+ E
3155 Out << 'I';
3156 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3157 mangleTemplateArg(TemplateArgs[i]);
3158 Out << 'E';
3159}
3160
3161void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3162 // <template-arg> ::= <type> # type or template
3163 // ::= X <expression> E # expression
3164 // ::= <expr-primary> # simple expressions
3165 // ::= J <template-arg>* E # argument pack
3166 // ::= sp <expression> # pack expansion of (C++0x)
3167 if (!A.isInstantiationDependent() || A.isDependent())
3168 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3169
3170 switch (A.getKind()) {
3171 case TemplateArgument::Null:
3172 llvm_unreachable("Cannot mangle NULL template argument");
3173
3174 case TemplateArgument::Type:
3175 mangleType(A.getAsType());
3176 break;
3177 case TemplateArgument::Template:
3178 // This is mangled as <type>.
3179 mangleType(A.getAsTemplate());
3180 break;
3181 case TemplateArgument::TemplateExpansion:
3182 // <type> ::= Dp <type> # pack expansion (C++0x)
3183 Out << "Dp";
3184 mangleType(A.getAsTemplateOrTemplatePattern());
3185 break;
3186 case TemplateArgument::Expression: {
3187 // It's possible to end up with a DeclRefExpr here in certain
3188 // dependent cases, in which case we should mangle as a
3189 // declaration.
3190 const Expr *E = A.getAsExpr()->IgnoreParens();
3191 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3192 const ValueDecl *D = DRE->getDecl();
3193 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3194 Out << "L";
3195 mangle(D, "_Z");
3196 Out << 'E';
3197 break;
3198 }
3199 }
3200
3201 Out << 'X';
3202 mangleExpression(E);
3203 Out << 'E';
3204 break;
3205 }
3206 case TemplateArgument::Integral:
3207 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3208 break;
3209 case TemplateArgument::Declaration: {
3210 // <expr-primary> ::= L <mangled-name> E # external name
3211 // Clang produces AST's where pointer-to-member-function expressions
3212 // and pointer-to-function expressions are represented as a declaration not
3213 // an expression. We compensate for it here to produce the correct mangling.
3214 ValueDecl *D = A.getAsDecl();
3215 bool compensateMangling = !A.isDeclForReferenceParam();
3216 if (compensateMangling) {
3217 Out << 'X';
3218 mangleOperatorName(OO_Amp, 1);
3219 }
3220
3221 Out << 'L';
3222 // References to external entities use the mangled name; if the name would
3223 // not normally be manged then mangle it as unqualified.
3224 //
3225 // FIXME: The ABI specifies that external names here should have _Z, but
3226 // gcc leaves this off.
3227 if (compensateMangling)
3228 mangle(D, "_Z");
3229 else
3230 mangle(D, "Z");
3231 Out << 'E';
3232
3233 if (compensateMangling)
3234 Out << 'E';
3235
3236 break;
3237 }
3238 case TemplateArgument::NullPtr: {
3239 // <expr-primary> ::= L <type> 0 E
3240 Out << 'L';
3241 mangleType(A.getNullPtrType());
3242 Out << "0E";
3243 break;
3244 }
3245 case TemplateArgument::Pack: {
3246 // Note: proposal by Mike Herrick on 12/20/10
3247 Out << 'J';
3248 for (TemplateArgument::pack_iterator PA = A.pack_begin(),
3249 PAEnd = A.pack_end();
3250 PA != PAEnd; ++PA)
3251 mangleTemplateArg(*PA);
3252 Out << 'E';
3253 }
3254 }
3255}
3256
3257void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3258 // <template-param> ::= T_ # first template parameter
3259 // ::= T <parameter-2 non-negative number> _
3260 if (Index == 0)
3261 Out << "T_";
3262 else
3263 Out << 'T' << (Index - 1) << '_';
3264}
3265
3266void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3267 bool result = mangleSubstitution(type);
3268 assert(result && "no existing substitution for type");
3269 (void) result;
3270}
3271
3272void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3273 bool result = mangleSubstitution(tname);
3274 assert(result && "no existing substitution for template name");
3275 (void) result;
3276}
3277
3278// <substitution> ::= S <seq-id> _
3279// ::= S_
3280bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3281 // Try one of the standard substitutions first.
3282 if (mangleStandardSubstitution(ND))
3283 return true;
3284
3285 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3286 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3287}
3288
3289/// \brief Determine whether the given type has any qualifiers that are
3290/// relevant for substitutions.
3291static bool hasMangledSubstitutionQualifiers(QualType T) {
3292 Qualifiers Qs = T.getQualifiers();
3293 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3294}
3295
3296bool CXXNameMangler::mangleSubstitution(QualType T) {
3297 if (!hasMangledSubstitutionQualifiers(T)) {
3298 if (const RecordType *RT = T->getAs<RecordType>())
3299 return mangleSubstitution(RT->getDecl());
3300 }
3301
3302 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3303
3304 return mangleSubstitution(TypePtr);
3305}
3306
3307bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3308 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3309 return mangleSubstitution(TD);
3310
3311 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3312 return mangleSubstitution(
3313 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3314}
3315
3316bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3317 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3318 if (I == Substitutions.end())
3319 return false;
3320
3321 unsigned SeqID = I->second;
3322 if (SeqID == 0)
3323 Out << "S_";
3324 else {
3325 SeqID--;
3326
3327 // <seq-id> is encoded in base-36, using digits and upper case letters.
3328 char Buffer[10];
3329 char *BufferPtr = llvm::array_endof(Buffer);
3330
3331 if (SeqID == 0) *--BufferPtr = '0';
3332
3333 while (SeqID) {
3334 assert(BufferPtr > Buffer && "Buffer overflow!");
3335
3336 char c = static_cast<char>(SeqID % 36);
3337
3338 *--BufferPtr = (c < 10 ? '0' + c : 'A' + c - 10);
3339 SeqID /= 36;
3340 }
3341
3342 Out << 'S'
3343 << StringRef(BufferPtr, llvm::array_endof(Buffer)-BufferPtr)
3344 << '_';
3345 }
3346
3347 return true;
3348}
3349
3350static bool isCharType(QualType T) {
3351 if (T.isNull())
3352 return false;
3353
3354 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3355 T->isSpecificBuiltinType(BuiltinType::Char_U);
3356}
3357
3358/// isCharSpecialization - Returns whether a given type is a template
3359/// specialization of a given name with a single argument of type char.
3360static bool isCharSpecialization(QualType T, const char *Name) {
3361 if (T.isNull())
3362 return false;
3363
3364 const RecordType *RT = T->getAs<RecordType>();
3365 if (!RT)
3366 return false;
3367
3368 const ClassTemplateSpecializationDecl *SD =
3369 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3370 if (!SD)
3371 return false;
3372
3373 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3374 return false;
3375
3376 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3377 if (TemplateArgs.size() != 1)
3378 return false;
3379
3380 if (!isCharType(TemplateArgs[0].getAsType()))
3381 return false;
3382
3383 return SD->getIdentifier()->getName() == Name;
3384}
3385
3386template <std::size_t StrLen>
3387static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3388 const char (&Str)[StrLen]) {
3389 if (!SD->getIdentifier()->isStr(Str))
3390 return false;
3391
3392 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3393 if (TemplateArgs.size() != 2)
3394 return false;
3395
3396 if (!isCharType(TemplateArgs[0].getAsType()))
3397 return false;
3398
3399 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3400 return false;
3401
3402 return true;
3403}
3404
3405bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3406 // <substitution> ::= St # ::std::
3407 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3408 if (isStd(NS)) {
3409 Out << "St";
3410 return true;
3411 }
3412 }
3413
3414 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3415 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3416 return false;
3417
3418 // <substitution> ::= Sa # ::std::allocator
3419 if (TD->getIdentifier()->isStr("allocator")) {
3420 Out << "Sa";
3421 return true;
3422 }
3423
3424 // <<substitution> ::= Sb # ::std::basic_string
3425 if (TD->getIdentifier()->isStr("basic_string")) {
3426 Out << "Sb";
3427 return true;
3428 }
3429 }
3430
3431 if (const ClassTemplateSpecializationDecl *SD =
3432 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3433 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3434 return false;
3435
3436 // <substitution> ::= Ss # ::std::basic_string<char,
3437 // ::std::char_traits<char>,
3438 // ::std::allocator<char> >
3439 if (SD->getIdentifier()->isStr("basic_string")) {
3440 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3441
3442 if (TemplateArgs.size() != 3)
3443 return false;
3444
3445 if (!isCharType(TemplateArgs[0].getAsType()))
3446 return false;
3447
3448 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3449 return false;
3450
3451 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3452 return false;
3453
3454 Out << "Ss";
3455 return true;
3456 }
3457
3458 // <substitution> ::= Si # ::std::basic_istream<char,
3459 // ::std::char_traits<char> >
3460 if (isStreamCharSpecialization(SD, "basic_istream")) {
3461 Out << "Si";
3462 return true;
3463 }
3464
3465 // <substitution> ::= So # ::std::basic_ostream<char,
3466 // ::std::char_traits<char> >
3467 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3468 Out << "So";
3469 return true;
3470 }
3471
3472 // <substitution> ::= Sd # ::std::basic_iostream<char,
3473 // ::std::char_traits<char> >
3474 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3475 Out << "Sd";
3476 return true;
3477 }
3478 }
3479 return false;
3480}
3481
3482void CXXNameMangler::addSubstitution(QualType T) {
3483 if (!hasMangledSubstitutionQualifiers(T)) {
3484 if (const RecordType *RT = T->getAs<RecordType>()) {
3485 addSubstitution(RT->getDecl());
3486 return;
3487 }
3488 }
3489
3490 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3491 addSubstitution(TypePtr);
3492}
3493
3494void CXXNameMangler::addSubstitution(TemplateName Template) {
3495 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3496 return addSubstitution(TD);
3497
3498 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3499 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3500}
3501
3502void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3503 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3504 Substitutions[Ptr] = SeqID++;
3505}
3506
3507//
3508
3509/// \brief Mangles the name of the declaration D and emits that name to the
3510/// given output stream.
3511///
3512/// If the declaration D requires a mangled name, this routine will emit that
3513/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3514/// and this routine will return false. In this case, the caller should just
3515/// emit the identifier of the declaration (\c D->getIdentifier()) as its
3516/// name.
3517void ItaniumMangleContext::mangleName(const NamedDecl *D,
3518 raw_ostream &Out) {
3519 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3520 "Invalid mangleName() call, argument is not a variable or function!");
3521 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3522 "Invalid mangleName() call on 'structor decl!");
3523
3524 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3525 getASTContext().getSourceManager(),
3526 "Mangling declaration");
3527
3528 CXXNameMangler Mangler(*this, Out, D);
3529 return Mangler.mangle(D);
3530}
3531
3532void ItaniumMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
3533 CXXCtorType Type,
3534 raw_ostream &Out) {
3535 CXXNameMangler Mangler(*this, Out, D, Type);
3536 Mangler.mangle(D);
3537}
3538
3539void ItaniumMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
3540 CXXDtorType Type,
3541 raw_ostream &Out) {
3542 CXXNameMangler Mangler(*this, Out, D, Type);
3543 Mangler.mangle(D);
3544}
3545
3546void ItaniumMangleContext::mangleThunk(const CXXMethodDecl *MD,
3547 const ThunkInfo &Thunk,
3548 raw_ostream &Out) {
3549 // <special-name> ::= T <call-offset> <base encoding>
3550 // # base is the nominal target function of thunk
3551 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3552 // # base is the nominal target function of thunk
3553 // # first call-offset is 'this' adjustment
3554 // # second call-offset is result adjustment
3555
3556 assert(!isa<CXXDestructorDecl>(MD) &&
3557 "Use mangleCXXDtor for destructor decls!");
3558 CXXNameMangler Mangler(*this, Out);
3559 Mangler.getStream() << "_ZT";
3560 if (!Thunk.Return.isEmpty())
3561 Mangler.getStream() << 'c';
3562
3563 // Mangle the 'this' pointer adjustment.
3564 Mangler.mangleCallOffset(Thunk.This.NonVirtual, Thunk.This.VCallOffsetOffset);
3565
3566 // Mangle the return pointer adjustment if there is one.
3567 if (!Thunk.Return.isEmpty())
3568 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
3569 Thunk.Return.VBaseOffsetOffset);
3570
3571 Mangler.mangleFunctionEncoding(MD);
3572}
3573
3574void
3575ItaniumMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
3576 CXXDtorType Type,
3577 const ThisAdjustment &ThisAdjustment,
3578 raw_ostream &Out) {
3579 // <special-name> ::= T <call-offset> <base encoding>
3580 // # base is the nominal target function of thunk
3581 CXXNameMangler Mangler(*this, Out, DD, Type);
3582 Mangler.getStream() << "_ZT";
3583
3584 // Mangle the 'this' pointer adjustment.
3585 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
3586 ThisAdjustment.VCallOffsetOffset);
3587
3588 Mangler.mangleFunctionEncoding(DD);
3589}
3590
3591/// mangleGuardVariable - Returns the mangled name for a guard variable
3592/// for the passed in VarDecl.
3593void ItaniumMangleContext::mangleItaniumGuardVariable(const VarDecl *D,
3594 raw_ostream &Out) {
3595 // <special-name> ::= GV <object name> # Guard variable for one-time
3596 // # initialization
3597 CXXNameMangler Mangler(*this, Out);
3598 Mangler.getStream() << "_ZGV";
3599 Mangler.mangleName(D);
3600}
3601
Richard Smithb80a16e2013-04-19 16:42:07 +00003602void ItaniumMangleContext::mangleItaniumThreadLocalInit(const VarDecl *D,
3603 raw_ostream &Out) {
3604 // <special-name> ::= TH <object name>
3605 CXXNameMangler Mangler(*this, Out);
3606 Mangler.getStream() << "_ZTH";
3607 Mangler.mangleName(D);
3608}
3609
3610void ItaniumMangleContext::mangleItaniumThreadLocalWrapper(const VarDecl *D,
3611 raw_ostream &Out) {
3612 // <special-name> ::= TW <object name>
3613 CXXNameMangler Mangler(*this, Out);
3614 Mangler.getStream() << "_ZTW";
3615 Mangler.mangleName(D);
3616}
3617
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003618void ItaniumMangleContext::mangleReferenceTemporary(const VarDecl *D,
3619 raw_ostream &Out) {
3620 // We match the GCC mangling here.
3621 // <special-name> ::= GR <object name>
3622 CXXNameMangler Mangler(*this, Out);
3623 Mangler.getStream() << "_ZGR";
3624 Mangler.mangleName(D);
3625}
3626
3627void ItaniumMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
3628 raw_ostream &Out) {
3629 // <special-name> ::= TV <type> # virtual table
3630 CXXNameMangler Mangler(*this, Out);
3631 Mangler.getStream() << "_ZTV";
3632 Mangler.mangleNameOrStandardSubstitution(RD);
3633}
3634
3635void ItaniumMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
3636 raw_ostream &Out) {
3637 // <special-name> ::= TT <type> # VTT structure
3638 CXXNameMangler Mangler(*this, Out);
3639 Mangler.getStream() << "_ZTT";
3640 Mangler.mangleNameOrStandardSubstitution(RD);
3641}
3642
Reid Kleckner90633022013-06-19 15:20:38 +00003643void
3644ItaniumMangleContext::mangleCXXVBTable(const CXXRecordDecl *Derived,
3645 ArrayRef<const CXXRecordDecl *> BasePath,
3646 raw_ostream &Out) {
3647 llvm_unreachable("The Itanium C++ ABI does not have virtual base tables!");
3648}
3649
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003650void ItaniumMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
3651 int64_t Offset,
3652 const CXXRecordDecl *Type,
3653 raw_ostream &Out) {
3654 // <special-name> ::= TC <type> <offset number> _ <base type>
3655 CXXNameMangler Mangler(*this, Out);
3656 Mangler.getStream() << "_ZTC";
3657 Mangler.mangleNameOrStandardSubstitution(RD);
3658 Mangler.getStream() << Offset;
3659 Mangler.getStream() << '_';
3660 Mangler.mangleNameOrStandardSubstitution(Type);
3661}
3662
3663void ItaniumMangleContext::mangleCXXRTTI(QualType Ty,
3664 raw_ostream &Out) {
3665 // <special-name> ::= TI <type> # typeinfo structure
3666 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
3667 CXXNameMangler Mangler(*this, Out);
3668 Mangler.getStream() << "_ZTI";
3669 Mangler.mangleType(Ty);
3670}
3671
3672void ItaniumMangleContext::mangleCXXRTTIName(QualType Ty,
3673 raw_ostream &Out) {
3674 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
3675 CXXNameMangler Mangler(*this, Out);
3676 Mangler.getStream() << "_ZTS";
3677 Mangler.mangleType(Ty);
3678}
3679
3680MangleContext *clang::createItaniumMangleContext(ASTContext &Context,
3681 DiagnosticsEngine &Diags) {
3682 return new ItaniumMangleContext(Context, Diags);
3683}