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