1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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):
14 // http://www.codesourcery.com/public/cxx-abi/abi.html
16 //===----------------------------------------------------------------------===//
17 #include "clang/AST/Mangle.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Basic/ABI.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/ErrorHandling.h"
33 #define MANGLE_CHECKER 0
39 using namespace clang;
43 static const CXXRecordDecl *GetLocalClassDecl(const NamedDecl *ND) {
44 const DeclContext *DC = dyn_cast<DeclContext>(ND);
46 DC = ND->getDeclContext();
47 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
48 if (isa<FunctionDecl>(DC->getParent()))
49 return dyn_cast<CXXRecordDecl>(DC);
55 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
56 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
57 return ftd->getTemplatedDecl();
62 static const NamedDecl *getStructor(const NamedDecl *decl) {
63 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
64 return (fn ? getStructor(fn) : decl);
67 static const unsigned UnknownArity = ~0U;
69 class ItaniumMangleContext : public MangleContext {
70 llvm::DenseMap<const TagDecl *, uint64_t> AnonStructIds;
71 unsigned Discriminator;
72 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
75 explicit ItaniumMangleContext(ASTContext &Context,
77 : MangleContext(Context, Diags) { }
79 uint64_t getAnonymousStructId(const TagDecl *TD) {
80 std::pair<llvm::DenseMap<const TagDecl *,
81 uint64_t>::iterator, bool> Result =
82 AnonStructIds.insert(std::make_pair(TD, AnonStructIds.size()));
83 return Result.first->second;
86 void startNewFunction() {
87 MangleContext::startNewFunction();
88 mangleInitDiscriminator();
91 /// @name Mangler Entry Points
94 bool shouldMangleDeclName(const NamedDecl *D);
95 void mangleName(const NamedDecl *D, llvm::raw_ostream &);
96 void mangleThunk(const CXXMethodDecl *MD,
97 const ThunkInfo &Thunk,
99 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
100 const ThisAdjustment &ThisAdjustment,
101 llvm::raw_ostream &);
102 void mangleReferenceTemporary(const VarDecl *D,
103 llvm::raw_ostream &);
104 void mangleCXXVTable(const CXXRecordDecl *RD,
105 llvm::raw_ostream &);
106 void mangleCXXVTT(const CXXRecordDecl *RD,
107 llvm::raw_ostream &);
108 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
109 const CXXRecordDecl *Type,
110 llvm::raw_ostream &);
111 void mangleCXXRTTI(QualType T, llvm::raw_ostream &);
112 void mangleCXXRTTIName(QualType T, llvm::raw_ostream &);
113 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
114 llvm::raw_ostream &);
115 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
116 llvm::raw_ostream &);
118 void mangleItaniumGuardVariable(const VarDecl *D, llvm::raw_ostream &);
120 void mangleInitDiscriminator() {
124 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
125 unsigned &discriminator = Uniquifier[ND];
127 discriminator = ++Discriminator;
128 if (discriminator == 1)
130 disc = discriminator-2;
136 /// CXXNameMangler - Manage the mangling of a single name.
137 class CXXNameMangler {
138 ItaniumMangleContext &Context;
139 llvm::raw_ostream &Out;
141 /// The "structor" is the top-level declaration being mangled, if
142 /// that's not a template specialization; otherwise it's the pattern
143 /// for that specialization.
144 const NamedDecl *Structor;
145 unsigned StructorType;
147 /// SeqID - The next subsitution sequence number.
150 class FunctionTypeDepthState {
153 enum { InResultTypeMask = 1 };
156 FunctionTypeDepthState() : Bits(0) {}
158 /// The number of function types we're inside.
159 unsigned getDepth() const {
163 /// True if we're in the return type of the innermost function type.
164 bool isInResultType() const {
165 return Bits & InResultTypeMask;
168 FunctionTypeDepthState push() {
169 FunctionTypeDepthState tmp = *this;
170 Bits = (Bits & ~InResultTypeMask) + 2;
174 void enterResultType() {
175 Bits |= InResultTypeMask;
178 void leaveResultType() {
179 Bits &= ~InResultTypeMask;
182 void pop(FunctionTypeDepthState saved) {
183 assert(getDepth() == saved.getDepth() + 1);
189 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
191 ASTContext &getASTContext() const { return Context.getASTContext(); }
194 CXXNameMangler(ItaniumMangleContext &C, llvm::raw_ostream &Out_,
195 const NamedDecl *D = 0)
196 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
198 // These can't be mangled without a ctor type or dtor type.
199 assert(!D || (!isa<CXXDestructorDecl>(D) &&
200 !isa<CXXConstructorDecl>(D)));
202 CXXNameMangler(ItaniumMangleContext &C, llvm::raw_ostream &Out_,
203 const CXXConstructorDecl *D, CXXCtorType Type)
204 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
206 CXXNameMangler(ItaniumMangleContext &C, llvm::raw_ostream &Out_,
207 const CXXDestructorDecl *D, CXXDtorType Type)
208 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
213 if (Out.str()[0] == '\01')
217 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
218 assert(status == 0 && "Could not demangle mangled name!");
222 llvm::raw_ostream &getStream() { return Out; }
224 void mangle(const NamedDecl *D, llvm::StringRef Prefix = "_Z");
225 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
226 void mangleNumber(const llvm::APSInt &I);
227 void mangleNumber(int64_t Number);
228 void mangleFloat(const llvm::APFloat &F);
229 void mangleFunctionEncoding(const FunctionDecl *FD);
230 void mangleName(const NamedDecl *ND);
231 void mangleType(QualType T);
232 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
235 bool mangleSubstitution(const NamedDecl *ND);
236 bool mangleSubstitution(QualType T);
237 bool mangleSubstitution(TemplateName Template);
238 bool mangleSubstitution(uintptr_t Ptr);
240 void mangleExistingSubstitution(QualType type);
241 void mangleExistingSubstitution(TemplateName name);
243 bool mangleStandardSubstitution(const NamedDecl *ND);
245 void addSubstitution(const NamedDecl *ND) {
246 ND = cast<NamedDecl>(ND->getCanonicalDecl());
248 addSubstitution(reinterpret_cast<uintptr_t>(ND));
250 void addSubstitution(QualType T);
251 void addSubstitution(TemplateName Template);
252 void addSubstitution(uintptr_t Ptr);
254 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
255 NamedDecl *firstQualifierLookup,
256 bool recursive = false);
257 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
258 NamedDecl *firstQualifierLookup,
259 DeclarationName name,
260 unsigned KnownArity = UnknownArity);
262 void mangleName(const TemplateDecl *TD,
263 const TemplateArgument *TemplateArgs,
264 unsigned NumTemplateArgs);
265 void mangleUnqualifiedName(const NamedDecl *ND) {
266 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
268 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
269 unsigned KnownArity);
270 void mangleUnscopedName(const NamedDecl *ND);
271 void mangleUnscopedTemplateName(const TemplateDecl *ND);
272 void mangleUnscopedTemplateName(TemplateName);
273 void mangleSourceName(const IdentifierInfo *II);
274 void mangleLocalName(const NamedDecl *ND);
275 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
276 bool NoFunction=false);
277 void mangleNestedName(const TemplateDecl *TD,
278 const TemplateArgument *TemplateArgs,
279 unsigned NumTemplateArgs);
280 void manglePrefix(NestedNameSpecifier *qualifier);
281 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
282 void manglePrefix(QualType type);
283 void mangleTemplatePrefix(const TemplateDecl *ND);
284 void mangleTemplatePrefix(TemplateName Template);
285 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
286 void mangleQualifiers(Qualifiers Quals);
287 void mangleRefQualifier(RefQualifierKind RefQualifier);
289 void mangleObjCMethodName(const ObjCMethodDecl *MD);
291 // Declare manglers for every type class.
292 #define ABSTRACT_TYPE(CLASS, PARENT)
293 #define NON_CANONICAL_TYPE(CLASS, PARENT)
294 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
295 #include "clang/AST/TypeNodes.def"
297 void mangleType(const TagType*);
298 void mangleType(TemplateName);
299 void mangleBareFunctionType(const FunctionType *T,
300 bool MangleReturnType);
301 void mangleNeonVectorType(const VectorType *T);
303 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
304 void mangleMemberExpr(const Expr *base, bool isArrow,
305 NestedNameSpecifier *qualifier,
306 NamedDecl *firstQualifierLookup,
307 DeclarationName name,
308 unsigned knownArity);
309 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
310 void mangleCXXCtorType(CXXCtorType T);
311 void mangleCXXDtorType(CXXDtorType T);
313 void mangleTemplateArgs(const ExplicitTemplateArgumentList &TemplateArgs);
314 void mangleTemplateArgs(TemplateName Template,
315 const TemplateArgument *TemplateArgs,
316 unsigned NumTemplateArgs);
317 void mangleTemplateArgs(const TemplateParameterList &PL,
318 const TemplateArgument *TemplateArgs,
319 unsigned NumTemplateArgs);
320 void mangleTemplateArgs(const TemplateParameterList &PL,
321 const TemplateArgumentList &AL);
322 void mangleTemplateArg(const NamedDecl *P, TemplateArgument A);
323 void mangleUnresolvedTemplateArgs(const TemplateArgument *args,
326 void mangleTemplateParameter(unsigned Index);
328 void mangleFunctionParam(const ParmVarDecl *parm);
333 static bool isInCLinkageSpecification(const Decl *D) {
334 D = D->getCanonicalDecl();
335 for (const DeclContext *DC = D->getDeclContext();
336 !DC->isTranslationUnit(); DC = DC->getParent()) {
337 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))
338 return Linkage->getLanguage() == LinkageSpecDecl::lang_c;
344 bool ItaniumMangleContext::shouldMangleDeclName(const NamedDecl *D) {
345 // In C, functions with no attributes never need to be mangled. Fastpath them.
346 if (!getASTContext().getLangOptions().CPlusPlus && !D->hasAttrs())
349 // Any decl can be declared with __asm("foo") on it, and this takes precedence
350 // over all other naming in the .o file.
351 if (D->hasAttr<AsmLabelAttr>())
354 // Clang's "overloadable" attribute extension to C/C++ implies name mangling
355 // (always) as does passing a C++ member function and a function
356 // whose name is not a simple identifier.
357 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
358 if (FD && (FD->hasAttr<OverloadableAttr>() || isa<CXXMethodDecl>(FD) ||
359 !FD->getDeclName().isIdentifier()))
362 // Otherwise, no mangling is done outside C++ mode.
363 if (!getASTContext().getLangOptions().CPlusPlus)
366 // Variables at global scope with non-internal linkage are not mangled
368 const DeclContext *DC = D->getDeclContext();
369 // Check for extern variable declared locally.
370 if (DC->isFunctionOrMethod() && D->hasLinkage())
371 while (!DC->isNamespace() && !DC->isTranslationUnit())
372 DC = DC->getParent();
373 if (DC->isTranslationUnit() && D->getLinkage() != InternalLinkage)
377 // Class members are always mangled.
378 if (D->getDeclContext()->isRecord())
381 // C functions and "main" are not mangled.
382 if ((FD && FD->isMain()) || isInCLinkageSpecification(D))
388 void CXXNameMangler::mangle(const NamedDecl *D, llvm::StringRef Prefix) {
389 // Any decl can be declared with __asm("foo") on it, and this takes precedence
390 // over all other naming in the .o file.
391 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
392 // If we have an asm name, then we use it as the mangling.
394 // Adding the prefix can cause problems when one file has a "foo" and
395 // another has a "\01foo". That is known to happen on ELF with the
396 // tricks normally used for producing aliases (PR9177). Fortunately the
397 // llvm mangler on ELF is a nop, so we can just avoid adding the \01
398 // marker. We also avoid adding the marker if this is an alias for an
400 llvm::StringRef UserLabelPrefix =
401 getASTContext().Target.getUserLabelPrefix();
402 if (!UserLabelPrefix.empty() && !ALA->getLabel().startswith("llvm."))
403 Out << '\01'; // LLVM IR Marker for __asm("foo")
405 Out << ALA->getLabel();
409 // <mangled-name> ::= _Z <encoding>
411 // ::= <special-name>
413 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
414 mangleFunctionEncoding(FD);
415 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
418 mangleName(cast<FieldDecl>(D));
421 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
422 // <encoding> ::= <function name> <bare-function-type>
425 // Don't mangle in the type if this isn't a decl we should typically mangle.
426 if (!Context.shouldMangleDeclName(FD))
429 // Whether the mangling of a function type includes the return type depends on
430 // the context and the nature of the function. The rules for deciding whether
431 // the return type is included are:
433 // 1. Template functions (names or types) have return types encoded, with
434 // the exceptions listed below.
435 // 2. Function types not appearing as part of a function name mangling,
436 // e.g. parameters, pointer types, etc., have return type encoded, with the
437 // exceptions listed below.
438 // 3. Non-template function names do not have return types encoded.
440 // The exceptions mentioned in (1) and (2) above, for which the return type is
441 // never included, are
444 // 3. Conversion operator functions, e.g. operator int.
445 bool MangleReturnType = false;
446 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
447 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
448 isa<CXXConversionDecl>(FD)))
449 MangleReturnType = true;
451 // Mangle the type of the primary template.
452 FD = PrimaryTemplate->getTemplatedDecl();
455 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
459 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
460 while (isa<LinkageSpecDecl>(DC)) {
461 DC = DC->getParent();
467 /// isStd - Return whether a given namespace is the 'std' namespace.
468 static bool isStd(const NamespaceDecl *NS) {
469 if (!IgnoreLinkageSpecDecls(NS->getParent())->isTranslationUnit())
472 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
473 return II && II->isStr("std");
476 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
478 static bool isStdNamespace(const DeclContext *DC) {
479 if (!DC->isNamespace())
482 return isStd(cast<NamespaceDecl>(DC));
485 static const TemplateDecl *
486 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
487 // Check if we have a function template.
488 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
489 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
490 TemplateArgs = FD->getTemplateSpecializationArgs();
495 // Check if we have a class template.
496 if (const ClassTemplateSpecializationDecl *Spec =
497 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
498 TemplateArgs = &Spec->getTemplateArgs();
499 return Spec->getSpecializedTemplate();
505 void CXXNameMangler::mangleName(const NamedDecl *ND) {
506 // <name> ::= <nested-name>
507 // ::= <unscoped-name>
508 // ::= <unscoped-template-name> <template-args>
511 const DeclContext *DC = ND->getDeclContext();
513 // If this is an extern variable declared locally, the relevant DeclContext
514 // is that of the containing namespace, or the translation unit.
515 if (isa<FunctionDecl>(DC) && ND->hasLinkage())
516 while (!DC->isNamespace() && !DC->isTranslationUnit())
517 DC = DC->getParent();
518 else if (GetLocalClassDecl(ND)) {
523 while (isa<LinkageSpecDecl>(DC))
524 DC = DC->getParent();
526 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
527 // Check if we have a template.
528 const TemplateArgumentList *TemplateArgs = 0;
529 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
530 mangleUnscopedTemplateName(TD);
531 TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
532 mangleTemplateArgs(*TemplateParameters, *TemplateArgs);
536 mangleUnscopedName(ND);
540 if (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)) {
545 mangleNestedName(ND, DC);
547 void CXXNameMangler::mangleName(const TemplateDecl *TD,
548 const TemplateArgument *TemplateArgs,
549 unsigned NumTemplateArgs) {
550 const DeclContext *DC = IgnoreLinkageSpecDecls(TD->getDeclContext());
552 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
553 mangleUnscopedTemplateName(TD);
554 TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
555 mangleTemplateArgs(*TemplateParameters, TemplateArgs, NumTemplateArgs);
557 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
561 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
562 // <unscoped-name> ::= <unqualified-name>
563 // ::= St <unqualified-name> # ::std::
564 if (isStdNamespace(ND->getDeclContext()))
567 mangleUnqualifiedName(ND);
570 void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
571 // <unscoped-template-name> ::= <unscoped-name>
572 // ::= <substitution>
573 if (mangleSubstitution(ND))
576 // <template-template-param> ::= <template-param>
577 if (const TemplateTemplateParmDecl *TTP
578 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
579 mangleTemplateParameter(TTP->getIndex());
583 mangleUnscopedName(ND->getTemplatedDecl());
587 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
588 // <unscoped-template-name> ::= <unscoped-name>
589 // ::= <substitution>
590 if (TemplateDecl *TD = Template.getAsTemplateDecl())
591 return mangleUnscopedTemplateName(TD);
593 if (mangleSubstitution(Template))
596 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
597 assert(Dependent && "Not a dependent template name?");
598 if (const IdentifierInfo *Id = Dependent->getIdentifier())
599 mangleSourceName(Id);
601 mangleOperatorName(Dependent->getOperator(), UnknownArity);
603 addSubstitution(Template);
606 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
608 // Floating-point literals are encoded using a fixed-length
609 // lowercase hexadecimal string corresponding to the internal
610 // representation (IEEE on Itanium), high-order bytes first,
611 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
613 // APInt::toString uses uppercase hexadecimal, and it's not really
614 // worth embellishing that interface for this use case, so we just
615 // do a second pass to lowercase things.
616 typedef llvm::SmallString<20> buffer_t;
618 f.bitcastToAPInt().toString(buffer, 16, false);
620 for (buffer_t::iterator i = buffer.begin(), e = buffer.end(); i != e; ++i)
621 if (isupper(*i)) *i = tolower(*i);
623 Out.write(buffer.data(), buffer.size());
626 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
627 if (Value.isSigned() && Value.isNegative()) {
629 Value.abs().print(Out, true);
631 Value.print(Out, Value.isSigned());
634 void CXXNameMangler::mangleNumber(int64_t Number) {
635 // <number> ::= [n] <non-negative decimal integer>
644 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
645 // <call-offset> ::= h <nv-offset> _
646 // ::= v <v-offset> _
647 // <nv-offset> ::= <offset number> # non-virtual base override
648 // <v-offset> ::= <offset number> _ <virtual offset number>
649 // # virtual base override, with vcall offset
652 mangleNumber(NonVirtual);
658 mangleNumber(NonVirtual);
660 mangleNumber(Virtual);
664 void CXXNameMangler::manglePrefix(QualType type) {
665 if (const TemplateSpecializationType *TST =
666 type->getAs<TemplateSpecializationType>()) {
667 if (!mangleSubstitution(QualType(TST, 0))) {
668 mangleTemplatePrefix(TST->getTemplateName());
670 // FIXME: GCC does not appear to mangle the template arguments when
671 // the template in question is a dependent template name. Should we
672 // emulate that badness?
673 mangleTemplateArgs(TST->getTemplateName(), TST->getArgs(),
675 addSubstitution(QualType(TST, 0));
677 } else if (const DependentTemplateSpecializationType *DTST
678 = type->getAs<DependentTemplateSpecializationType>()) {
679 TemplateName Template
680 = getASTContext().getDependentTemplateName(DTST->getQualifier(),
681 DTST->getIdentifier());
682 mangleTemplatePrefix(Template);
684 // FIXME: GCC does not appear to mangle the template arguments when
685 // the template in question is a dependent template name. Should we
686 // emulate that badness?
687 mangleTemplateArgs(Template, DTST->getArgs(), DTST->getNumArgs());
689 // We use the QualType mangle type variant here because it handles
695 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
697 /// \param firstQualifierLookup - the entity found by unqualified lookup
698 /// for the first name in the qualifier, if this is for a member expression
699 /// \param recursive - true if this is being called recursively,
700 /// i.e. if there is more prefix "to the right".
701 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
702 NamedDecl *firstQualifierLookup,
706 // <unresolved-name> ::= [gs] <base-unresolved-name>
708 // T::x / decltype(p)::x
709 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
711 // T::N::x /decltype(p)::N::x
712 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
713 // <base-unresolved-name>
715 // A::x, N::y, A<T>::z; "gs" means leading "::"
716 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
717 // <base-unresolved-name>
719 switch (qualifier->getKind()) {
720 case NestedNameSpecifier::Global:
723 // We want an 'sr' unless this is the entire NNS.
727 // We never want an 'E' here.
730 case NestedNameSpecifier::Namespace:
731 if (qualifier->getPrefix())
732 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
736 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
738 case NestedNameSpecifier::NamespaceAlias:
739 if (qualifier->getPrefix())
740 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
744 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
747 case NestedNameSpecifier::TypeSpec:
748 case NestedNameSpecifier::TypeSpecWithTemplate: {
749 const Type *type = qualifier->getAsType();
751 // We only want to use an unresolved-type encoding if this is one of:
753 // - a template type parameter
754 // - a template template parameter with arguments
755 // In all of these cases, we should have no prefix.
756 if (qualifier->getPrefix()) {
757 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
760 // Otherwise, all the cases want this.
764 // Only certain other types are valid as prefixes; enumerate them.
765 switch (type->getTypeClass()) {
769 case Type::BlockPointer:
770 case Type::LValueReference:
771 case Type::RValueReference:
772 case Type::MemberPointer:
773 case Type::ConstantArray:
774 case Type::IncompleteArray:
775 case Type::VariableArray:
776 case Type::DependentSizedArray:
777 case Type::DependentSizedExtVector:
779 case Type::ExtVector:
780 case Type::FunctionProto:
781 case Type::FunctionNoProto:
784 case Type::Elaborated:
785 case Type::Attributed:
787 case Type::PackExpansion:
788 case Type::ObjCObject:
789 case Type::ObjCInterface:
790 case Type::ObjCObjectPointer:
791 llvm_unreachable("type is illegal as a nested name specifier");
793 case Type::SubstTemplateTypeParmPack:
794 // FIXME: not clear how to mangle this!
795 // template <class T...> class A {
796 // template <class U...> void foo(decltype(T::foo(U())) x...);
798 Out << "_SUBSTPACK_";
801 // <unresolved-type> ::= <template-param>
803 // ::= <template-template-param> <template-args>
804 // (this last is not official yet)
805 case Type::TypeOfExpr:
808 case Type::TemplateTypeParm:
809 case Type::UnaryTransform:
810 case Type::SubstTemplateTypeParm:
812 assert(!qualifier->getPrefix());
814 // We only get here recursively if we're followed by identifiers.
815 if (recursive) Out << 'N';
817 // This seems to do everything we want. It's not really
818 // sanctioned for a substituted template parameter, though.
819 mangleType(QualType(type, 0));
821 // We never want to print 'E' directly after an unresolved-type,
822 // so we return directly.
826 mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier());
829 case Type::UnresolvedUsing:
830 mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl()
835 mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier());
838 case Type::TemplateSpecialization: {
839 const TemplateSpecializationType *tst
840 = cast<TemplateSpecializationType>(type);
841 TemplateName name = tst->getTemplateName();
842 switch (name.getKind()) {
843 case TemplateName::Template:
844 case TemplateName::QualifiedTemplate: {
845 TemplateDecl *temp = name.getAsTemplateDecl();
847 // If the base is a template template parameter, this is an
849 assert(temp && "no template for template specialization type");
850 if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType;
852 mangleSourceName(temp->getIdentifier());
856 case TemplateName::OverloadedTemplate:
857 case TemplateName::DependentTemplate:
858 llvm_unreachable("invalid base for a template specialization type");
860 case TemplateName::SubstTemplateTemplateParm: {
861 SubstTemplateTemplateParmStorage *subst
862 = name.getAsSubstTemplateTemplateParm();
863 mangleExistingSubstitution(subst->getReplacement());
867 case TemplateName::SubstTemplateTemplateParmPack: {
868 // FIXME: not clear how to mangle this!
869 // template <template <class U> class T...> class A {
870 // template <class U...> void foo(decltype(T<U>::foo) x...);
872 Out << "_SUBSTPACK_";
877 mangleUnresolvedTemplateArgs(tst->getArgs(), tst->getNumArgs());
881 case Type::InjectedClassName:
882 mangleSourceName(cast<InjectedClassNameType>(type)->getDecl()
886 case Type::DependentName:
887 mangleSourceName(cast<DependentNameType>(type)->getIdentifier());
890 case Type::DependentTemplateSpecialization: {
891 const DependentTemplateSpecializationType *tst
892 = cast<DependentTemplateSpecializationType>(type);
893 mangleSourceName(tst->getIdentifier());
894 mangleUnresolvedTemplateArgs(tst->getArgs(), tst->getNumArgs());
901 case NestedNameSpecifier::Identifier:
902 // Member expressions can have these without prefixes.
903 if (qualifier->getPrefix()) {
904 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
906 } else if (firstQualifierLookup) {
908 // Try to make a proper qualifier out of the lookup result, and
909 // then just recurse on that.
910 NestedNameSpecifier *newQualifier;
911 if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) {
912 QualType type = getASTContext().getTypeDeclType(typeDecl);
914 // Pretend we had a different nested name specifier.
915 newQualifier = NestedNameSpecifier::Create(getASTContext(),
919 } else if (NamespaceDecl *nspace =
920 dyn_cast<NamespaceDecl>(firstQualifierLookup)) {
921 newQualifier = NestedNameSpecifier::Create(getASTContext(),
924 } else if (NamespaceAliasDecl *alias =
925 dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) {
926 newQualifier = NestedNameSpecifier::Create(getASTContext(),
930 // No sensible mangling to do here.
935 return mangleUnresolvedPrefix(newQualifier, /*lookup*/ 0, recursive);
941 mangleSourceName(qualifier->getAsIdentifier());
945 // If this was the innermost part of the NNS, and we fell out to
946 // here, append an 'E'.
951 /// Mangle an unresolved-name, which is generally used for names which
952 /// weren't resolved to specific entities.
953 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
954 NamedDecl *firstQualifierLookup,
955 DeclarationName name,
956 unsigned knownArity) {
957 if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup);
958 mangleUnqualifiedName(0, name, knownArity);
961 static const FieldDecl *FindFirstNamedDataMember(const RecordDecl *RD) {
962 assert(RD->isAnonymousStructOrUnion() &&
963 "Expected anonymous struct or union!");
965 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
967 const FieldDecl *FD = *I;
969 if (FD->getIdentifier())
972 if (const RecordType *RT = FD->getType()->getAs<RecordType>()) {
973 if (const FieldDecl *NamedDataMember =
974 FindFirstNamedDataMember(RT->getDecl()))
975 return NamedDataMember;
979 // We didn't find a named data member.
983 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
984 DeclarationName Name,
985 unsigned KnownArity) {
986 // <unqualified-name> ::= <operator-name>
987 // ::= <ctor-dtor-name>
989 switch (Name.getNameKind()) {
990 case DeclarationName::Identifier: {
991 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
992 // We must avoid conflicts between internally- and externally-
993 // linked variable and function declaration names in the same TU:
994 // void test() { extern void foo(); }
995 // static void foo();
996 // This naming convention is the same as that followed by GCC,
997 // though it shouldn't actually matter.
998 if (ND && ND->getLinkage() == InternalLinkage &&
999 ND->getDeclContext()->isFileContext())
1002 mangleSourceName(II);
1006 // Otherwise, an anonymous entity. We must have a declaration.
1007 assert(ND && "mangling empty name without declaration");
1009 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1010 if (NS->isAnonymousNamespace()) {
1011 // This is how gcc mangles these names.
1012 Out << "12_GLOBAL__N_1";
1017 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1018 // We must have an anonymous union or struct declaration.
1019 const RecordDecl *RD =
1020 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
1022 // Itanium C++ ABI 5.1.2:
1024 // For the purposes of mangling, the name of an anonymous union is
1025 // considered to be the name of the first named data member found by a
1026 // pre-order, depth-first, declaration-order walk of the data members of
1027 // the anonymous union. If there is no such data member (i.e., if all of
1028 // the data members in the union are unnamed), then there is no way for
1029 // a program to refer to the anonymous union, and there is therefore no
1030 // need to mangle its name.
1031 const FieldDecl *FD = FindFirstNamedDataMember(RD);
1033 // It's actually possible for various reasons for us to get here
1034 // with an empty anonymous struct / union. Fortunately, it
1035 // doesn't really matter what name we generate.
1037 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1039 mangleSourceName(FD->getIdentifier());
1043 // We must have an anonymous struct.
1044 const TagDecl *TD = cast<TagDecl>(ND);
1045 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1046 assert(TD->getDeclContext() == D->getDeclContext() &&
1047 "Typedef should not be in another decl context!");
1048 assert(D->getDeclName().getAsIdentifierInfo() &&
1049 "Typedef was not named!");
1050 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1054 // Get a unique id for the anonymous struct.
1055 uint64_t AnonStructId = Context.getAnonymousStructId(TD);
1057 // Mangle it as a source name in the form
1059 // where n is the length of the string.
1060 llvm::SmallString<8> Str;
1062 Str += llvm::utostr(AnonStructId);
1069 case DeclarationName::ObjCZeroArgSelector:
1070 case DeclarationName::ObjCOneArgSelector:
1071 case DeclarationName::ObjCMultiArgSelector:
1072 assert(false && "Can't mangle Objective-C selector names here!");
1075 case DeclarationName::CXXConstructorName:
1077 // If the named decl is the C++ constructor we're mangling, use the type
1079 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1081 // Otherwise, use the complete constructor name. This is relevant if a
1082 // class with a constructor is declared within a constructor.
1083 mangleCXXCtorType(Ctor_Complete);
1086 case DeclarationName::CXXDestructorName:
1088 // If the named decl is the C++ destructor we're mangling, use the type we
1090 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1092 // Otherwise, use the complete destructor name. This is relevant if a
1093 // class with a destructor is declared within a destructor.
1094 mangleCXXDtorType(Dtor_Complete);
1097 case DeclarationName::CXXConversionFunctionName:
1098 // <operator-name> ::= cv <type> # (cast)
1100 mangleType(Name.getCXXNameType());
1103 case DeclarationName::CXXOperatorName: {
1106 Arity = cast<FunctionDecl>(ND)->getNumParams();
1108 // If we have a C++ member function, we need to include the 'this' pointer.
1109 // FIXME: This does not make sense for operators that are static, but their
1110 // names stay the same regardless of the arity (operator new for instance).
1111 if (isa<CXXMethodDecl>(ND))
1116 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1120 case DeclarationName::CXXLiteralOperatorName:
1121 // FIXME: This mangling is not yet official.
1123 mangleSourceName(Name.getCXXLiteralIdentifier());
1126 case DeclarationName::CXXUsingDirective:
1127 assert(false && "Can't mangle a using directive name!");
1132 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1133 // <source-name> ::= <positive length number> <identifier>
1134 // <number> ::= [n] <non-negative decimal integer>
1135 // <identifier> ::= <unqualified source code identifier>
1136 Out << II->getLength() << II->getName();
1139 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1140 const DeclContext *DC,
1143 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1144 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1145 // <template-args> E
1148 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1149 mangleQualifiers(Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
1150 mangleRefQualifier(Method->getRefQualifier());
1153 // Check if we have a template.
1154 const TemplateArgumentList *TemplateArgs = 0;
1155 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1156 mangleTemplatePrefix(TD);
1157 TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
1158 mangleTemplateArgs(*TemplateParameters, *TemplateArgs);
1161 manglePrefix(DC, NoFunction);
1162 mangleUnqualifiedName(ND);
1167 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1168 const TemplateArgument *TemplateArgs,
1169 unsigned NumTemplateArgs) {
1170 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1174 mangleTemplatePrefix(TD);
1175 TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
1176 mangleTemplateArgs(*TemplateParameters, TemplateArgs, NumTemplateArgs);
1181 void CXXNameMangler::mangleLocalName(const NamedDecl *ND) {
1182 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1183 // := Z <function encoding> E s [<discriminator>]
1184 // <discriminator> := _ <non-negative number>
1185 const DeclContext *DC = ND->getDeclContext();
1186 if (isa<ObjCMethodDecl>(DC) && isa<FunctionDecl>(ND)) {
1187 // Don't add objc method name mangling to locally declared function
1188 mangleUnqualifiedName(ND);
1194 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC)) {
1195 mangleObjCMethodName(MD);
1196 } else if (const CXXRecordDecl *RD = GetLocalClassDecl(ND)) {
1197 mangleFunctionEncoding(cast<FunctionDecl>(RD->getDeclContext()));
1200 // Mangle the name relative to the closest enclosing function.
1201 if (ND == RD) // equality ok because RD derived from ND above
1202 mangleUnqualifiedName(ND);
1204 mangleNestedName(ND, DC, true /*NoFunction*/);
1207 if (Context.getNextDiscriminator(RD, disc)) {
1211 Out << "__" << disc << '_';
1217 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1220 mangleUnqualifiedName(ND);
1223 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1224 switch (qualifier->getKind()) {
1225 case NestedNameSpecifier::Global:
1229 case NestedNameSpecifier::Namespace:
1230 mangleName(qualifier->getAsNamespace());
1233 case NestedNameSpecifier::NamespaceAlias:
1234 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1237 case NestedNameSpecifier::TypeSpec:
1238 case NestedNameSpecifier::TypeSpecWithTemplate:
1239 manglePrefix(QualType(qualifier->getAsType(), 0));
1242 case NestedNameSpecifier::Identifier:
1243 // Member expressions can have these without prefixes, but that
1244 // should end up in mangleUnresolvedPrefix instead.
1245 assert(qualifier->getPrefix());
1246 manglePrefix(qualifier->getPrefix());
1248 mangleSourceName(qualifier->getAsIdentifier());
1252 llvm_unreachable("unexpected nested name specifier");
1255 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1256 // <prefix> ::= <prefix> <unqualified-name>
1257 // ::= <template-prefix> <template-args>
1258 // ::= <template-param>
1260 // ::= <substitution>
1262 while (isa<LinkageSpecDecl>(DC))
1263 DC = DC->getParent();
1265 if (DC->isTranslationUnit())
1268 if (const BlockDecl *Block = dyn_cast<BlockDecl>(DC)) {
1269 manglePrefix(DC->getParent(), NoFunction);
1270 llvm::SmallString<64> Name;
1271 llvm::raw_svector_ostream NameStream(Name);
1272 Context.mangleBlock(Block, NameStream);
1274 Out << Name.size() << Name;
1278 if (mangleSubstitution(cast<NamedDecl>(DC)))
1281 // Check if we have a template.
1282 const TemplateArgumentList *TemplateArgs = 0;
1283 if (const TemplateDecl *TD = isTemplate(cast<NamedDecl>(DC), TemplateArgs)) {
1284 mangleTemplatePrefix(TD);
1285 TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
1286 mangleTemplateArgs(*TemplateParameters, *TemplateArgs);
1288 else if(NoFunction && (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)))
1290 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC))
1291 mangleObjCMethodName(Method);
1293 manglePrefix(DC->getParent(), NoFunction);
1294 mangleUnqualifiedName(cast<NamedDecl>(DC));
1297 addSubstitution(cast<NamedDecl>(DC));
1300 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1301 // <template-prefix> ::= <prefix> <template unqualified-name>
1302 // ::= <template-param>
1303 // ::= <substitution>
1304 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1305 return mangleTemplatePrefix(TD);
1307 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1308 manglePrefix(Qualified->getQualifier());
1310 if (OverloadedTemplateStorage *Overloaded
1311 = Template.getAsOverloadedTemplate()) {
1312 mangleUnqualifiedName(0, (*Overloaded->begin())->getDeclName(),
1317 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1318 assert(Dependent && "Unknown template name kind?");
1319 manglePrefix(Dependent->getQualifier());
1320 mangleUnscopedTemplateName(Template);
1323 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND) {
1324 // <template-prefix> ::= <prefix> <template unqualified-name>
1325 // ::= <template-param>
1326 // ::= <substitution>
1327 // <template-template-param> ::= <template-param>
1330 if (mangleSubstitution(ND))
1333 // <template-template-param> ::= <template-param>
1334 if (const TemplateTemplateParmDecl *TTP
1335 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1336 mangleTemplateParameter(TTP->getIndex());
1340 manglePrefix(ND->getDeclContext());
1341 mangleUnqualifiedName(ND->getTemplatedDecl());
1342 addSubstitution(ND);
1345 /// Mangles a template name under the production <type>. Required for
1346 /// template template arguments.
1347 /// <type> ::= <class-enum-type>
1348 /// ::= <template-param>
1349 /// ::= <substitution>
1350 void CXXNameMangler::mangleType(TemplateName TN) {
1351 if (mangleSubstitution(TN))
1354 TemplateDecl *TD = 0;
1356 switch (TN.getKind()) {
1357 case TemplateName::QualifiedTemplate:
1358 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1361 case TemplateName::Template:
1362 TD = TN.getAsTemplateDecl();
1366 if (isa<TemplateTemplateParmDecl>(TD))
1367 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1372 case TemplateName::OverloadedTemplate:
1373 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1376 case TemplateName::DependentTemplate: {
1377 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1378 assert(Dependent->isIdentifier());
1380 // <class-enum-type> ::= <name>
1381 // <name> ::= <nested-name>
1382 mangleUnresolvedPrefix(Dependent->getQualifier(), 0);
1383 mangleSourceName(Dependent->getIdentifier());
1387 case TemplateName::SubstTemplateTemplateParm: {
1388 // Substituted template parameters are mangled as the substituted
1389 // template. This will check for the substitution twice, which is
1390 // fine, but we have to return early so that we don't try to *add*
1391 // the substitution twice.
1392 SubstTemplateTemplateParmStorage *subst
1393 = TN.getAsSubstTemplateTemplateParm();
1394 mangleType(subst->getReplacement());
1398 case TemplateName::SubstTemplateTemplateParmPack: {
1399 // FIXME: not clear how to mangle this!
1400 // template <template <class> class T...> class A {
1401 // template <template <class> class U...> void foo(B<T,U> x...);
1403 Out << "_SUBSTPACK_";
1408 addSubstitution(TN);
1412 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1414 // <operator-name> ::= nw # new
1415 case OO_New: Out << "nw"; break;
1417 case OO_Array_New: Out << "na"; break;
1419 case OO_Delete: Out << "dl"; break;
1420 // ::= da # delete[]
1421 case OO_Array_Delete: Out << "da"; break;
1422 // ::= ps # + (unary)
1423 // ::= pl # + (binary or unknown)
1425 Out << (Arity == 1? "ps" : "pl"); break;
1426 // ::= ng # - (unary)
1427 // ::= mi # - (binary or unknown)
1429 Out << (Arity == 1? "ng" : "mi"); break;
1430 // ::= ad # & (unary)
1431 // ::= an # & (binary or unknown)
1433 Out << (Arity == 1? "ad" : "an"); break;
1434 // ::= de # * (unary)
1435 // ::= ml # * (binary or unknown)
1437 // Use binary when unknown.
1438 Out << (Arity == 1? "de" : "ml"); break;
1440 case OO_Tilde: Out << "co"; break;
1442 case OO_Slash: Out << "dv"; break;
1444 case OO_Percent: Out << "rm"; break;
1446 case OO_Pipe: Out << "or"; break;
1448 case OO_Caret: Out << "eo"; break;
1450 case OO_Equal: Out << "aS"; break;
1452 case OO_PlusEqual: Out << "pL"; break;
1454 case OO_MinusEqual: Out << "mI"; break;
1456 case OO_StarEqual: Out << "mL"; break;
1458 case OO_SlashEqual: Out << "dV"; break;
1460 case OO_PercentEqual: Out << "rM"; break;
1462 case OO_AmpEqual: Out << "aN"; break;
1464 case OO_PipeEqual: Out << "oR"; break;
1466 case OO_CaretEqual: Out << "eO"; break;
1468 case OO_LessLess: Out << "ls"; break;
1470 case OO_GreaterGreater: Out << "rs"; break;
1472 case OO_LessLessEqual: Out << "lS"; break;
1474 case OO_GreaterGreaterEqual: Out << "rS"; break;
1476 case OO_EqualEqual: Out << "eq"; break;
1478 case OO_ExclaimEqual: Out << "ne"; break;
1480 case OO_Less: Out << "lt"; break;
1482 case OO_Greater: Out << "gt"; break;
1484 case OO_LessEqual: Out << "le"; break;
1486 case OO_GreaterEqual: Out << "ge"; break;
1488 case OO_Exclaim: Out << "nt"; break;
1490 case OO_AmpAmp: Out << "aa"; break;
1492 case OO_PipePipe: Out << "oo"; break;
1494 case OO_PlusPlus: Out << "pp"; break;
1496 case OO_MinusMinus: Out << "mm"; break;
1498 case OO_Comma: Out << "cm"; break;
1500 case OO_ArrowStar: Out << "pm"; break;
1502 case OO_Arrow: Out << "pt"; break;
1504 case OO_Call: Out << "cl"; break;
1506 case OO_Subscript: Out << "ix"; break;
1509 // The conditional operator can't be overloaded, but we still handle it when
1510 // mangling expressions.
1511 case OO_Conditional: Out << "qu"; break;
1514 case NUM_OVERLOADED_OPERATORS:
1515 assert(false && "Not an overloaded operator");
1520 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1521 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1522 if (Quals.hasRestrict())
1524 if (Quals.hasVolatile())
1526 if (Quals.hasConst())
1529 if (Quals.hasAddressSpace()) {
1532 // <type> ::= U <address-space-number>
1534 // where <address-space-number> is a source name consisting of 'AS'
1535 // followed by the address space <number>.
1536 llvm::SmallString<64> ASString;
1537 ASString = "AS" + llvm::utostr_32(Quals.getAddressSpace());
1538 Out << 'U' << ASString.size() << ASString;
1541 llvm::StringRef LifetimeName;
1542 switch (Quals.getObjCLifetime()) {
1543 // Objective-C ARC Extension:
1545 // <type> ::= U "__strong"
1546 // <type> ::= U "__weak"
1547 // <type> ::= U "__autoreleasing"
1548 case Qualifiers::OCL_None:
1551 case Qualifiers::OCL_Weak:
1552 LifetimeName = "__weak";
1555 case Qualifiers::OCL_Strong:
1556 LifetimeName = "__strong";
1559 case Qualifiers::OCL_Autoreleasing:
1560 LifetimeName = "__autoreleasing";
1563 case Qualifiers::OCL_ExplicitNone:
1564 // The __unsafe_unretained qualifier is *not* mangled, so that
1565 // __unsafe_unretained types in ARC produce the same manglings as the
1566 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1567 // better ABI compatibility.
1569 // It's safe to do this because unqualified 'id' won't show up
1570 // in any type signatures that need to be mangled.
1573 if (!LifetimeName.empty())
1574 Out << 'U' << LifetimeName.size() << LifetimeName;
1577 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1578 // <ref-qualifier> ::= R # lvalue reference
1579 // ::= O # rvalue-reference
1580 // Proposal to Itanium C++ ABI list on 1/26/11
1581 switch (RefQualifier) {
1595 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1596 Context.mangleObjCMethodName(MD, Out);
1599 void CXXNameMangler::mangleType(QualType T) {
1600 // If our type is instantiation-dependent but not dependent, we mangle
1601 // it as it was written in the source, removing any top-level sugar.
1602 // Otherwise, use the canonical type.
1604 // FIXME: This is an approximation of the instantiation-dependent name
1605 // mangling rules, since we should really be using the type as written and
1606 // augmented via semantic analysis (i.e., with implicit conversions and
1607 // default template arguments) for any instantiation-dependent type.
1608 // Unfortunately, that requires several changes to our AST:
1609 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1610 // uniqued, so that we can handle substitutions properly
1611 // - Default template arguments will need to be represented in the
1612 // TemplateSpecializationType, since they need to be mangled even though
1613 // they aren't written.
1614 // - Conversions on non-type template arguments need to be expressed, since
1615 // they can affect the mangling of sizeof/alignof.
1616 if (!T->isInstantiationDependentType() || T->isDependentType())
1617 T = T.getCanonicalType();
1619 // Desugar any types that are purely sugar.
1621 // Don't desugar through template specialization types that aren't
1622 // type aliases. We need to mangle the template arguments as written.
1623 if (const TemplateSpecializationType *TST
1624 = dyn_cast<TemplateSpecializationType>(T))
1625 if (!TST->isTypeAlias())
1629 = T.getSingleStepDesugaredType(Context.getASTContext());
1636 SplitQualType split = T.split();
1637 Qualifiers quals = split.second;
1638 const Type *ty = split.first;
1640 bool isSubstitutable = quals || !isa<BuiltinType>(T);
1641 if (isSubstitutable && mangleSubstitution(T))
1644 // If we're mangling a qualified array type, push the qualifiers to
1645 // the element type.
1646 if (quals && isa<ArrayType>(T)) {
1647 ty = Context.getASTContext().getAsArrayType(T);
1648 quals = Qualifiers();
1650 // Note that we don't update T: we want to add the
1651 // substitution at the original type.
1655 mangleQualifiers(quals);
1656 // Recurse: even if the qualified type isn't yet substitutable,
1657 // the unqualified type might be.
1658 mangleType(QualType(ty, 0));
1660 switch (ty->getTypeClass()) {
1661 #define ABSTRACT_TYPE(CLASS, PARENT)
1662 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1664 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1666 #define TYPE(CLASS, PARENT) \
1668 mangleType(static_cast<const CLASS##Type*>(ty)); \
1670 #include "clang/AST/TypeNodes.def"
1674 // Add the substitution.
1675 if (isSubstitutable)
1679 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1680 if (!mangleStandardSubstitution(ND))
1684 void CXXNameMangler::mangleType(const BuiltinType *T) {
1685 // <type> ::= <builtin-type>
1686 // <builtin-type> ::= v # void
1690 // ::= a # signed char
1691 // ::= h # unsigned char
1693 // ::= t # unsigned short
1695 // ::= j # unsigned int
1697 // ::= m # unsigned long
1698 // ::= x # long long, __int64
1699 // ::= y # unsigned long long, __int64
1701 // UNSUPPORTED: ::= o # unsigned __int128
1704 // ::= e # long double, __float80
1705 // UNSUPPORTED: ::= g # __float128
1706 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1707 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1708 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1709 // UNSUPPORTED: ::= Dh # IEEE 754r half-precision floating point (16 bits)
1710 // ::= Di # char32_t
1711 // ::= Ds # char16_t
1712 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1713 // ::= u <source-name> # vendor extended type
1714 switch (T->getKind()) {
1715 case BuiltinType::Void: Out << 'v'; break;
1716 case BuiltinType::Bool: Out << 'b'; break;
1717 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
1718 case BuiltinType::UChar: Out << 'h'; break;
1719 case BuiltinType::UShort: Out << 't'; break;
1720 case BuiltinType::UInt: Out << 'j'; break;
1721 case BuiltinType::ULong: Out << 'm'; break;
1722 case BuiltinType::ULongLong: Out << 'y'; break;
1723 case BuiltinType::UInt128: Out << 'o'; break;
1724 case BuiltinType::SChar: Out << 'a'; break;
1725 case BuiltinType::WChar_S:
1726 case BuiltinType::WChar_U: Out << 'w'; break;
1727 case BuiltinType::Char16: Out << "Ds"; break;
1728 case BuiltinType::Char32: Out << "Di"; break;
1729 case BuiltinType::Short: Out << 's'; break;
1730 case BuiltinType::Int: Out << 'i'; break;
1731 case BuiltinType::Long: Out << 'l'; break;
1732 case BuiltinType::LongLong: Out << 'x'; break;
1733 case BuiltinType::Int128: Out << 'n'; break;
1734 case BuiltinType::Float: Out << 'f'; break;
1735 case BuiltinType::Double: Out << 'd'; break;
1736 case BuiltinType::LongDouble: Out << 'e'; break;
1737 case BuiltinType::NullPtr: Out << "Dn"; break;
1739 case BuiltinType::Overload:
1740 case BuiltinType::Dependent:
1741 case BuiltinType::BoundMember:
1742 case BuiltinType::UnknownAny:
1743 llvm_unreachable("mangling a placeholder type");
1745 case BuiltinType::ObjCId: Out << "11objc_object"; break;
1746 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
1747 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
1751 // <type> ::= <function-type>
1752 // <function-type> ::= F [Y] <bare-function-type> E
1753 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
1755 // FIXME: We don't have enough information in the AST to produce the 'Y'
1756 // encoding for extern "C" function types.
1757 mangleBareFunctionType(T, /*MangleReturnType=*/true);
1760 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
1761 llvm_unreachable("Can't mangle K&R function prototypes");
1763 void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
1764 bool MangleReturnType) {
1765 // We should never be mangling something without a prototype.
1766 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1768 // Record that we're in a function type. See mangleFunctionParam
1769 // for details on what we're trying to achieve here.
1770 FunctionTypeDepthState saved = FunctionTypeDepth.push();
1772 // <bare-function-type> ::= <signature type>+
1773 if (MangleReturnType) {
1774 FunctionTypeDepth.enterResultType();
1775 mangleType(Proto->getResultType());
1776 FunctionTypeDepth.leaveResultType();
1779 if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
1780 // <builtin-type> ::= v # void
1783 FunctionTypeDepth.pop(saved);
1787 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1788 ArgEnd = Proto->arg_type_end();
1789 Arg != ArgEnd; ++Arg)
1790 mangleType(Context.getASTContext().getSignatureParameterType(*Arg));
1792 FunctionTypeDepth.pop(saved);
1794 // <builtin-type> ::= z # ellipsis
1795 if (Proto->isVariadic())
1799 // <type> ::= <class-enum-type>
1800 // <class-enum-type> ::= <name>
1801 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
1802 mangleName(T->getDecl());
1805 // <type> ::= <class-enum-type>
1806 // <class-enum-type> ::= <name>
1807 void CXXNameMangler::mangleType(const EnumType *T) {
1808 mangleType(static_cast<const TagType*>(T));
1810 void CXXNameMangler::mangleType(const RecordType *T) {
1811 mangleType(static_cast<const TagType*>(T));
1813 void CXXNameMangler::mangleType(const TagType *T) {
1814 mangleName(T->getDecl());
1817 // <type> ::= <array-type>
1818 // <array-type> ::= A <positive dimension number> _ <element type>
1819 // ::= A [<dimension expression>] _ <element type>
1820 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
1821 Out << 'A' << T->getSize() << '_';
1822 mangleType(T->getElementType());
1824 void CXXNameMangler::mangleType(const VariableArrayType *T) {
1826 // decayed vla types (size 0) will just be skipped.
1827 if (T->getSizeExpr())
1828 mangleExpression(T->getSizeExpr());
1830 mangleType(T->getElementType());
1832 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
1834 mangleExpression(T->getSizeExpr());
1836 mangleType(T->getElementType());
1838 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
1840 mangleType(T->getElementType());
1843 // <type> ::= <pointer-to-member-type>
1844 // <pointer-to-member-type> ::= M <class type> <member type>
1845 void CXXNameMangler::mangleType(const MemberPointerType *T) {
1847 mangleType(QualType(T->getClass(), 0));
1848 QualType PointeeType = T->getPointeeType();
1849 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
1850 mangleQualifiers(Qualifiers::fromCVRMask(FPT->getTypeQuals()));
1851 mangleRefQualifier(FPT->getRefQualifier());
1854 // Itanium C++ ABI 5.1.8:
1856 // The type of a non-static member function is considered to be different,
1857 // for the purposes of substitution, from the type of a namespace-scope or
1858 // static member function whose type appears similar. The types of two
1859 // non-static member functions are considered to be different, for the
1860 // purposes of substitution, if the functions are members of different
1861 // classes. In other words, for the purposes of substitution, the class of
1862 // which the function is a member is considered part of the type of
1865 // We increment the SeqID here to emulate adding an entry to the
1866 // substitution table. We can't actually add it because we don't want this
1867 // particular function type to be substituted.
1870 mangleType(PointeeType);
1873 // <type> ::= <template-param>
1874 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
1875 mangleTemplateParameter(T->getIndex());
1878 // <type> ::= <template-param>
1879 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
1880 // FIXME: not clear how to mangle this!
1881 // template <class T...> class A {
1882 // template <class U...> void foo(T(*)(U) x...);
1884 Out << "_SUBSTPACK_";
1887 // <type> ::= P <type> # pointer-to
1888 void CXXNameMangler::mangleType(const PointerType *T) {
1890 mangleType(T->getPointeeType());
1892 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
1894 mangleType(T->getPointeeType());
1897 // <type> ::= R <type> # reference-to
1898 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
1900 mangleType(T->getPointeeType());
1903 // <type> ::= O <type> # rvalue reference-to (C++0x)
1904 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
1906 mangleType(T->getPointeeType());
1909 // <type> ::= C <type> # complex pair (C 2000)
1910 void CXXNameMangler::mangleType(const ComplexType *T) {
1912 mangleType(T->getElementType());
1915 // ARM's ABI for Neon vector types specifies that they should be mangled as
1916 // if they are structs (to match ARM's initial implementation). The
1917 // vector type must be one of the special types predefined by ARM.
1918 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
1919 QualType EltType = T->getElementType();
1920 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
1921 const char *EltName = 0;
1922 if (T->getVectorKind() == VectorType::NeonPolyVector) {
1923 switch (cast<BuiltinType>(EltType)->getKind()) {
1924 case BuiltinType::SChar: EltName = "poly8_t"; break;
1925 case BuiltinType::Short: EltName = "poly16_t"; break;
1926 default: llvm_unreachable("unexpected Neon polynomial vector element type");
1929 switch (cast<BuiltinType>(EltType)->getKind()) {
1930 case BuiltinType::SChar: EltName = "int8_t"; break;
1931 case BuiltinType::UChar: EltName = "uint8_t"; break;
1932 case BuiltinType::Short: EltName = "int16_t"; break;
1933 case BuiltinType::UShort: EltName = "uint16_t"; break;
1934 case BuiltinType::Int: EltName = "int32_t"; break;
1935 case BuiltinType::UInt: EltName = "uint32_t"; break;
1936 case BuiltinType::LongLong: EltName = "int64_t"; break;
1937 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
1938 case BuiltinType::Float: EltName = "float32_t"; break;
1939 default: llvm_unreachable("unexpected Neon vector element type");
1942 const char *BaseName = 0;
1943 unsigned BitSize = (T->getNumElements() *
1944 getASTContext().getTypeSize(EltType));
1946 BaseName = "__simd64_";
1948 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
1949 BaseName = "__simd128_";
1951 Out << strlen(BaseName) + strlen(EltName);
1952 Out << BaseName << EltName;
1955 // GNU extension: vector types
1956 // <type> ::= <vector-type>
1957 // <vector-type> ::= Dv <positive dimension number> _
1958 // <extended element type>
1959 // ::= Dv [<dimension expression>] _ <element type>
1960 // <extended element type> ::= <element type>
1961 // ::= p # AltiVec vector pixel
1962 void CXXNameMangler::mangleType(const VectorType *T) {
1963 if ((T->getVectorKind() == VectorType::NeonVector ||
1964 T->getVectorKind() == VectorType::NeonPolyVector)) {
1965 mangleNeonVectorType(T);
1968 Out << "Dv" << T->getNumElements() << '_';
1969 if (T->getVectorKind() == VectorType::AltiVecPixel)
1971 else if (T->getVectorKind() == VectorType::AltiVecBool)
1974 mangleType(T->getElementType());
1976 void CXXNameMangler::mangleType(const ExtVectorType *T) {
1977 mangleType(static_cast<const VectorType*>(T));
1979 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
1981 mangleExpression(T->getSizeExpr());
1983 mangleType(T->getElementType());
1986 void CXXNameMangler::mangleType(const PackExpansionType *T) {
1987 // <type> ::= Dp <type> # pack expansion (C++0x)
1989 mangleType(T->getPattern());
1992 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
1993 mangleSourceName(T->getDecl()->getIdentifier());
1996 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
1997 // We don't allow overloading by different protocol qualification,
1998 // so mangling them isn't necessary.
1999 mangleType(T->getBaseType());
2002 void CXXNameMangler::mangleType(const BlockPointerType *T) {
2003 Out << "U13block_pointer";
2004 mangleType(T->getPointeeType());
2007 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2008 // Mangle injected class name types as if the user had written the
2009 // specialization out fully. It may not actually be possible to see
2010 // this mangling, though.
2011 mangleType(T->getInjectedSpecializationType());
2014 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2015 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2016 mangleName(TD, T->getArgs(), T->getNumArgs());
2018 if (mangleSubstitution(QualType(T, 0)))
2021 mangleTemplatePrefix(T->getTemplateName());
2023 // FIXME: GCC does not appear to mangle the template arguments when
2024 // the template in question is a dependent template name. Should we
2025 // emulate that badness?
2026 mangleTemplateArgs(T->getTemplateName(), T->getArgs(), T->getNumArgs());
2027 addSubstitution(QualType(T, 0));
2031 void CXXNameMangler::mangleType(const DependentNameType *T) {
2032 // Typename types are always nested
2034 manglePrefix(T->getQualifier());
2035 mangleSourceName(T->getIdentifier());
2039 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2040 // Dependently-scoped template types are nested if they have a prefix.
2043 // TODO: avoid making this TemplateName.
2044 TemplateName Prefix =
2045 getASTContext().getDependentTemplateName(T->getQualifier(),
2046 T->getIdentifier());
2047 mangleTemplatePrefix(Prefix);
2049 // FIXME: GCC does not appear to mangle the template arguments when
2050 // the template in question is a dependent template name. Should we
2051 // emulate that badness?
2052 mangleTemplateArgs(Prefix, T->getArgs(), T->getNumArgs());
2056 void CXXNameMangler::mangleType(const TypeOfType *T) {
2057 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2058 // "extension with parameters" mangling.
2062 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2063 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2064 // "extension with parameters" mangling.
2068 void CXXNameMangler::mangleType(const DecltypeType *T) {
2069 Expr *E = T->getUnderlyingExpr();
2071 // type ::= Dt <expression> E # decltype of an id-expression
2072 // # or class member access
2073 // ::= DT <expression> E # decltype of an expression
2075 // This purports to be an exhaustive list of id-expressions and
2076 // class member accesses. Note that we do not ignore parentheses;
2077 // parentheses change the semantics of decltype for these
2078 // expressions (and cause the mangler to use the other form).
2079 if (isa<DeclRefExpr>(E) ||
2080 isa<MemberExpr>(E) ||
2081 isa<UnresolvedLookupExpr>(E) ||
2082 isa<DependentScopeDeclRefExpr>(E) ||
2083 isa<CXXDependentScopeMemberExpr>(E) ||
2084 isa<UnresolvedMemberExpr>(E))
2088 mangleExpression(E);
2092 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2093 // If this is dependent, we need to record that. If not, we simply
2094 // mangle it as the underlying type since they are equivalent.
2095 if (T->isDependentType()) {
2098 switch (T->getUTTKind()) {
2099 case UnaryTransformType::EnumUnderlyingType:
2105 mangleType(T->getUnderlyingType());
2108 void CXXNameMangler::mangleType(const AutoType *T) {
2109 QualType D = T->getDeducedType();
2110 // <builtin-type> ::= Da # dependent auto
2117 void CXXNameMangler::mangleIntegerLiteral(QualType T,
2118 const llvm::APSInt &Value) {
2119 // <expr-primary> ::= L <type> <value number> E # integer literal
2123 if (T->isBooleanType()) {
2124 // Boolean values are encoded as 0/1.
2125 Out << (Value.getBoolValue() ? '1' : '0');
2127 mangleNumber(Value);
2133 /// Mangles a member expression. Implicit accesses are not handled,
2134 /// but that should be okay, because you shouldn't be able to
2135 /// make an implicit access in a function template declaration.
2136 void CXXNameMangler::mangleMemberExpr(const Expr *base,
2138 NestedNameSpecifier *qualifier,
2139 NamedDecl *firstQualifierLookup,
2140 DeclarationName member,
2142 // <expression> ::= dt <expression> <unresolved-name>
2143 // ::= pt <expression> <unresolved-name>
2144 Out << (isArrow ? "pt" : "dt");
2145 mangleExpression(base);
2146 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
2149 /// Look at the callee of the given call expression and determine if
2150 /// it's a parenthesized id-expression which would have triggered ADL
2152 static bool isParenthesizedADLCallee(const CallExpr *call) {
2153 const Expr *callee = call->getCallee();
2154 const Expr *fn = callee->IgnoreParens();
2156 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2157 // too, but for those to appear in the callee, it would have to be
2159 if (callee == fn) return false;
2161 // Must be an unresolved lookup.
2162 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2163 if (!lookup) return false;
2165 assert(!lookup->requiresADL());
2167 // Must be an unqualified lookup.
2168 if (lookup->getQualifier()) return false;
2170 // Must not have found a class member. Note that if one is a class
2171 // member, they're all class members.
2172 if (lookup->getNumDecls() > 0 &&
2173 (*lookup->decls_begin())->isCXXClassMember())
2176 // Otherwise, ADL would have been triggered.
2180 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2181 // <expression> ::= <unary operator-name> <expression>
2182 // ::= <binary operator-name> <expression> <expression>
2183 // ::= <trinary operator-name> <expression> <expression> <expression>
2184 // ::= cv <type> expression # conversion with one argument
2185 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2186 // ::= st <type> # sizeof (a type)
2187 // ::= at <type> # alignof (a type)
2188 // ::= <template-param>
2189 // ::= <function-param>
2190 // ::= sr <type> <unqualified-name> # dependent name
2191 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2192 // ::= ds <expression> <expression> # expr.*expr
2193 // ::= sZ <template-param> # size of a parameter pack
2194 // ::= sZ <function-param> # size of a function parameter pack
2195 // ::= <expr-primary>
2196 // <expr-primary> ::= L <type> <value number> E # integer literal
2197 // ::= L <type <value float> E # floating literal
2198 // ::= L <mangled-name> E # external name
2199 QualType ImplicitlyConvertedToType;
2202 switch (E->getStmtClass()) {
2203 case Expr::NoStmtClass:
2204 #define ABSTRACT_STMT(Type)
2205 #define EXPR(Type, Base)
2206 #define STMT(Type, Base) \
2207 case Expr::Type##Class:
2208 #include "clang/AST/StmtNodes.inc"
2211 // These all can only appear in local or variable-initialization
2212 // contexts and so should never appear in a mangling.
2213 case Expr::AddrLabelExprClass:
2214 case Expr::BlockDeclRefExprClass:
2215 case Expr::CXXThisExprClass:
2216 case Expr::DesignatedInitExprClass:
2217 case Expr::ImplicitValueInitExprClass:
2218 case Expr::InitListExprClass:
2219 case Expr::ParenListExprClass:
2220 case Expr::CXXScalarValueInitExprClass:
2221 llvm_unreachable("unexpected statement kind");
2224 // FIXME: invent manglings for all these.
2225 case Expr::BlockExprClass:
2226 case Expr::CXXPseudoDestructorExprClass:
2227 case Expr::ChooseExprClass:
2228 case Expr::CompoundLiteralExprClass:
2229 case Expr::ExtVectorElementExprClass:
2230 case Expr::GenericSelectionExprClass:
2231 case Expr::ObjCEncodeExprClass:
2232 case Expr::ObjCIsaExprClass:
2233 case Expr::ObjCIvarRefExprClass:
2234 case Expr::ObjCMessageExprClass:
2235 case Expr::ObjCPropertyRefExprClass:
2236 case Expr::ObjCProtocolExprClass:
2237 case Expr::ObjCSelectorExprClass:
2238 case Expr::ObjCStringLiteralClass:
2239 case Expr::ObjCIndirectCopyRestoreExprClass:
2240 case Expr::OffsetOfExprClass:
2241 case Expr::PredefinedExprClass:
2242 case Expr::ShuffleVectorExprClass:
2243 case Expr::StmtExprClass:
2244 case Expr::UnaryTypeTraitExprClass:
2245 case Expr::BinaryTypeTraitExprClass:
2246 case Expr::ArrayTypeTraitExprClass:
2247 case Expr::ExpressionTraitExprClass:
2248 case Expr::VAArgExprClass:
2249 case Expr::CXXUuidofExprClass:
2250 case Expr::CXXNoexceptExprClass:
2251 case Expr::CUDAKernelCallExprClass:
2252 case Expr::AsTypeExprClass:
2254 // As bad as this diagnostic is, it's better than crashing.
2255 Diagnostic &Diags = Context.getDiags();
2256 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
2257 "cannot yet mangle expression type %0");
2258 Diags.Report(E->getExprLoc(), DiagID)
2259 << E->getStmtClassName() << E->getSourceRange();
2263 // Even gcc-4.5 doesn't mangle this.
2264 case Expr::BinaryConditionalOperatorClass: {
2265 Diagnostic &Diags = Context.getDiags();
2267 Diags.getCustomDiagID(Diagnostic::Error,
2268 "?: operator with omitted middle operand cannot be mangled");
2269 Diags.Report(E->getExprLoc(), DiagID)
2270 << E->getStmtClassName() << E->getSourceRange();
2274 // These are used for internal purposes and cannot be meaningfully mangled.
2275 case Expr::OpaqueValueExprClass:
2276 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2278 case Expr::CXXDefaultArgExprClass:
2279 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2282 case Expr::SubstNonTypeTemplateParmExprClass:
2283 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2287 case Expr::CXXMemberCallExprClass: // fallthrough
2288 case Expr::CallExprClass: {
2289 const CallExpr *CE = cast<CallExpr>(E);
2291 // <expression> ::= cp <simple-id> <expression>* E
2292 // We use this mangling only when the call would use ADL except
2293 // for being parenthesized. Per discussion with David
2294 // Vandervoorde, 2011.04.25.
2295 if (isParenthesizedADLCallee(CE)) {
2297 // The callee here is a parenthesized UnresolvedLookupExpr with
2298 // no qualifier and should always get mangled as a <simple-id>
2301 // <expression> ::= cl <expression>* E
2306 mangleExpression(CE->getCallee(), CE->getNumArgs());
2307 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
2308 mangleExpression(CE->getArg(I));
2313 case Expr::CXXNewExprClass: {
2314 // Proposal from David Vandervoorde, 2010.06.30
2315 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2316 if (New->isGlobalNew()) Out << "gs";
2317 Out << (New->isArray() ? "na" : "nw");
2318 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2319 E = New->placement_arg_end(); I != E; ++I)
2320 mangleExpression(*I);
2322 mangleType(New->getAllocatedType());
2323 if (New->hasInitializer()) {
2325 for (CXXNewExpr::const_arg_iterator I = New->constructor_arg_begin(),
2326 E = New->constructor_arg_end(); I != E; ++I)
2327 mangleExpression(*I);
2333 case Expr::MemberExprClass: {
2334 const MemberExpr *ME = cast<MemberExpr>(E);
2335 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2336 ME->getQualifier(), 0, ME->getMemberDecl()->getDeclName(),
2341 case Expr::UnresolvedMemberExprClass: {
2342 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2343 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2344 ME->getQualifier(), 0, ME->getMemberName(),
2346 if (ME->hasExplicitTemplateArgs())
2347 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2351 case Expr::CXXDependentScopeMemberExprClass: {
2352 const CXXDependentScopeMemberExpr *ME
2353 = cast<CXXDependentScopeMemberExpr>(E);
2354 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2355 ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
2356 ME->getMember(), Arity);
2357 if (ME->hasExplicitTemplateArgs())
2358 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2362 case Expr::UnresolvedLookupExprClass: {
2363 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
2364 mangleUnresolvedName(ULE->getQualifier(), 0, ULE->getName(), Arity);
2366 // All the <unresolved-name> productions end in a
2367 // base-unresolved-name, where <template-args> are just tacked
2369 if (ULE->hasExplicitTemplateArgs())
2370 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2374 case Expr::CXXUnresolvedConstructExprClass: {
2375 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2376 unsigned N = CE->arg_size();
2379 mangleType(CE->getType());
2380 if (N != 1) Out << '_';
2381 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2382 if (N != 1) Out << 'E';
2386 case Expr::CXXTemporaryObjectExprClass:
2387 case Expr::CXXConstructExprClass: {
2388 const CXXConstructExpr *CE = cast<CXXConstructExpr>(E);
2389 unsigned N = CE->getNumArgs();
2392 mangleType(CE->getType());
2393 if (N != 1) Out << '_';
2394 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2395 if (N != 1) Out << 'E';
2399 case Expr::UnaryExprOrTypeTraitExprClass: {
2400 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
2402 if (!SAE->isInstantiationDependent()) {
2404 // If the operand of a sizeof or alignof operator is not
2405 // instantiation-dependent it is encoded as an integer literal
2406 // reflecting the result of the operator.
2408 // If the result of the operator is implicitly converted to a known
2409 // integer type, that type is used for the literal; otherwise, the type
2410 // of std::size_t or std::ptrdiff_t is used.
2411 QualType T = (ImplicitlyConvertedToType.isNull() ||
2412 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
2413 : ImplicitlyConvertedToType;
2414 mangleIntegerLiteral(T, SAE->EvaluateAsInt(Context.getASTContext()));
2418 switch(SAE->getKind()) {
2426 Diagnostic &Diags = Context.getDiags();
2427 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
2428 "cannot yet mangle vec_step expression");
2429 Diags.Report(DiagID);
2432 if (SAE->isArgumentType()) {
2434 mangleType(SAE->getArgumentType());
2437 mangleExpression(SAE->getArgumentExpr());
2442 case Expr::CXXThrowExprClass: {
2443 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
2445 // Proposal from David Vandervoorde, 2010.06.30
2446 if (TE->getSubExpr()) {
2448 mangleExpression(TE->getSubExpr());
2455 case Expr::CXXTypeidExprClass: {
2456 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
2458 // Proposal from David Vandervoorde, 2010.06.30
2459 if (TIE->isTypeOperand()) {
2461 mangleType(TIE->getTypeOperand());
2464 mangleExpression(TIE->getExprOperand());
2469 case Expr::CXXDeleteExprClass: {
2470 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
2472 // Proposal from David Vandervoorde, 2010.06.30
2473 if (DE->isGlobalDelete()) Out << "gs";
2474 Out << (DE->isArrayForm() ? "da" : "dl");
2475 mangleExpression(DE->getArgument());
2479 case Expr::UnaryOperatorClass: {
2480 const UnaryOperator *UO = cast<UnaryOperator>(E);
2481 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
2483 mangleExpression(UO->getSubExpr());
2487 case Expr::ArraySubscriptExprClass: {
2488 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
2490 // Array subscript is treated as a syntactically weird form of
2493 mangleExpression(AE->getLHS());
2494 mangleExpression(AE->getRHS());
2498 case Expr::CompoundAssignOperatorClass: // fallthrough
2499 case Expr::BinaryOperatorClass: {
2500 const BinaryOperator *BO = cast<BinaryOperator>(E);
2501 if (BO->getOpcode() == BO_PtrMemD)
2504 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
2506 mangleExpression(BO->getLHS());
2507 mangleExpression(BO->getRHS());
2511 case Expr::ConditionalOperatorClass: {
2512 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
2513 mangleOperatorName(OO_Conditional, /*Arity=*/3);
2514 mangleExpression(CO->getCond());
2515 mangleExpression(CO->getLHS(), Arity);
2516 mangleExpression(CO->getRHS(), Arity);
2520 case Expr::ImplicitCastExprClass: {
2521 ImplicitlyConvertedToType = E->getType();
2522 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2526 case Expr::ObjCBridgedCastExprClass: {
2527 // Mangle ownership casts as a vendor extended operator __bridge,
2528 // __bridge_transfer, or __bridge_retain.
2529 llvm::StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
2530 Out << "v1U" << Kind.size() << Kind;
2532 // Fall through to mangle the cast itself.
2534 case Expr::CStyleCastExprClass:
2535 case Expr::CXXStaticCastExprClass:
2536 case Expr::CXXDynamicCastExprClass:
2537 case Expr::CXXReinterpretCastExprClass:
2538 case Expr::CXXConstCastExprClass:
2539 case Expr::CXXFunctionalCastExprClass: {
2540 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2542 mangleType(ECE->getType());
2543 mangleExpression(ECE->getSubExpr());
2547 case Expr::CXXOperatorCallExprClass: {
2548 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
2549 unsigned NumArgs = CE->getNumArgs();
2550 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
2551 // Mangle the arguments.
2552 for (unsigned i = 0; i != NumArgs; ++i)
2553 mangleExpression(CE->getArg(i));
2557 case Expr::ParenExprClass:
2558 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
2561 case Expr::DeclRefExprClass: {
2562 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2564 switch (D->getKind()) {
2566 // <expr-primary> ::= L <mangled-name> E # external name
2573 mangleFunctionParam(cast<ParmVarDecl>(D));
2576 case Decl::EnumConstant: {
2577 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
2578 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
2582 case Decl::NonTypeTemplateParm: {
2583 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
2584 mangleTemplateParameter(PD->getIndex());
2593 case Expr::SubstNonTypeTemplateParmPackExprClass:
2594 // FIXME: not clear how to mangle this!
2595 // template <unsigned N...> class A {
2596 // template <class U...> void foo(U (&x)[N]...);
2598 Out << "_SUBSTPACK_";
2601 case Expr::DependentScopeDeclRefExprClass: {
2602 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
2603 mangleUnresolvedName(DRE->getQualifier(), 0, DRE->getDeclName(), Arity);
2605 // All the <unresolved-name> productions end in a
2606 // base-unresolved-name, where <template-args> are just tacked
2608 if (DRE->hasExplicitTemplateArgs())
2609 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
2613 case Expr::CXXBindTemporaryExprClass:
2614 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
2617 case Expr::ExprWithCleanupsClass:
2618 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
2621 case Expr::FloatingLiteralClass: {
2622 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
2624 mangleType(FL->getType());
2625 mangleFloat(FL->getValue());
2630 case Expr::CharacterLiteralClass:
2632 mangleType(E->getType());
2633 Out << cast<CharacterLiteral>(E)->getValue();
2637 case Expr::CXXBoolLiteralExprClass:
2639 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
2643 case Expr::IntegerLiteralClass: {
2644 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
2645 if (E->getType()->isSignedIntegerType())
2646 Value.setIsSigned(true);
2647 mangleIntegerLiteral(E->getType(), Value);
2651 case Expr::ImaginaryLiteralClass: {
2652 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
2653 // Mangle as if a complex literal.
2654 // Proposal from David Vandevoorde, 2010.06.30.
2656 mangleType(E->getType());
2657 if (const FloatingLiteral *Imag =
2658 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
2659 // Mangle a floating-point zero of the appropriate type.
2660 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
2662 mangleFloat(Imag->getValue());
2665 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
2666 if (IE->getSubExpr()->getType()->isSignedIntegerType())
2667 Value.setIsSigned(true);
2668 mangleNumber(Value);
2674 case Expr::StringLiteralClass: {
2675 // Revised proposal from David Vandervoorde, 2010.07.15.
2677 assert(isa<ConstantArrayType>(E->getType()));
2678 mangleType(E->getType());
2683 case Expr::GNUNullExprClass:
2684 // FIXME: should this really be mangled the same as nullptr?
2687 case Expr::CXXNullPtrLiteralExprClass: {
2688 // Proposal from David Vandervoorde, 2010.06.30, as
2689 // modified by ABI list discussion.
2694 case Expr::PackExpansionExprClass:
2696 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
2699 case Expr::SizeOfPackExprClass: {
2701 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
2702 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
2703 mangleTemplateParameter(TTP->getIndex());
2704 else if (const NonTypeTemplateParmDecl *NTTP
2705 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
2706 mangleTemplateParameter(NTTP->getIndex());
2707 else if (const TemplateTemplateParmDecl *TempTP
2708 = dyn_cast<TemplateTemplateParmDecl>(Pack))
2709 mangleTemplateParameter(TempTP->getIndex());
2711 mangleFunctionParam(cast<ParmVarDecl>(Pack));
2715 case Expr::MaterializeTemporaryExprClass: {
2716 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
2722 /// Mangle an expression which refers to a parameter variable.
2724 /// <expression> ::= <function-param>
2725 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
2726 /// <function-param> ::= fp <top-level CV-qualifiers>
2727 /// <parameter-2 non-negative number> _ # L == 0, I > 0
2728 /// <function-param> ::= fL <L-1 non-negative number>
2729 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
2730 /// <function-param> ::= fL <L-1 non-negative number>
2731 /// p <top-level CV-qualifiers>
2732 /// <I-1 non-negative number> _ # L > 0, I > 0
2734 /// L is the nesting depth of the parameter, defined as 1 if the
2735 /// parameter comes from the innermost function prototype scope
2736 /// enclosing the current context, 2 if from the next enclosing
2737 /// function prototype scope, and so on, with one special case: if
2738 /// we've processed the full parameter clause for the innermost
2739 /// function type, then L is one less. This definition conveniently
2740 /// makes it irrelevant whether a function's result type was written
2741 /// trailing or leading, but is otherwise overly complicated; the
2742 /// numbering was first designed without considering references to
2743 /// parameter in locations other than return types, and then the
2744 /// mangling had to be generalized without changing the existing
2747 /// I is the zero-based index of the parameter within its parameter
2748 /// declaration clause. Note that the original ABI document describes
2749 /// this using 1-based ordinals.
2750 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
2751 unsigned parmDepth = parm->getFunctionScopeDepth();
2752 unsigned parmIndex = parm->getFunctionScopeIndex();
2755 // parmDepth does not include the declaring function prototype.
2756 // FunctionTypeDepth does account for that.
2757 assert(parmDepth < FunctionTypeDepth.getDepth());
2758 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
2759 if (FunctionTypeDepth.isInResultType())
2762 if (nestingDepth == 0) {
2765 Out << "fL" << (nestingDepth - 1) << 'p';
2768 // Top-level qualifiers. We don't have to worry about arrays here,
2769 // because parameters declared as arrays should already have been
2770 // tranformed to have pointer type. FIXME: apparently these don't
2771 // get mangled if used as an rvalue of a known non-class type?
2772 assert(!parm->getType()->isArrayType()
2773 && "parameter's type is still an array type?");
2774 mangleQualifiers(parm->getType().getQualifiers());
2777 if (parmIndex != 0) {
2778 Out << (parmIndex - 1);
2783 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
2784 // <ctor-dtor-name> ::= C1 # complete object constructor
2785 // ::= C2 # base object constructor
2786 // ::= C3 # complete object allocating constructor
2795 case Ctor_CompleteAllocating:
2801 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
2802 // <ctor-dtor-name> ::= D0 # deleting destructor
2803 // ::= D1 # complete object destructor
2804 // ::= D2 # base object destructor
2819 void CXXNameMangler::mangleTemplateArgs(
2820 const ExplicitTemplateArgumentList &TemplateArgs) {
2821 // <template-args> ::= I <template-arg>+ E
2823 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
2824 mangleTemplateArg(0, TemplateArgs.getTemplateArgs()[i].getArgument());
2828 void CXXNameMangler::mangleTemplateArgs(TemplateName Template,
2829 const TemplateArgument *TemplateArgs,
2830 unsigned NumTemplateArgs) {
2831 if (TemplateDecl *TD = Template.getAsTemplateDecl())
2832 return mangleTemplateArgs(*TD->getTemplateParameters(), TemplateArgs,
2835 mangleUnresolvedTemplateArgs(TemplateArgs, NumTemplateArgs);
2838 void CXXNameMangler::mangleUnresolvedTemplateArgs(const TemplateArgument *args,
2840 // <template-args> ::= I <template-arg>+ E
2842 for (unsigned i = 0; i != numArgs; ++i)
2843 mangleTemplateArg(0, args[i]);
2847 void CXXNameMangler::mangleTemplateArgs(const TemplateParameterList &PL,
2848 const TemplateArgumentList &AL) {
2849 // <template-args> ::= I <template-arg>+ E
2851 for (unsigned i = 0, e = AL.size(); i != e; ++i)
2852 mangleTemplateArg(PL.getParam(i), AL[i]);
2856 void CXXNameMangler::mangleTemplateArgs(const TemplateParameterList &PL,
2857 const TemplateArgument *TemplateArgs,
2858 unsigned NumTemplateArgs) {
2859 // <template-args> ::= I <template-arg>+ E
2861 for (unsigned i = 0; i != NumTemplateArgs; ++i)
2862 mangleTemplateArg(PL.getParam(i), TemplateArgs[i]);
2866 void CXXNameMangler::mangleTemplateArg(const NamedDecl *P,
2867 TemplateArgument A) {
2868 // <template-arg> ::= <type> # type or template
2869 // ::= X <expression> E # expression
2870 // ::= <expr-primary> # simple expressions
2871 // ::= J <template-arg>* E # argument pack
2872 // ::= sp <expression> # pack expansion of (C++0x)
2873 if (!A.isInstantiationDependent() || A.isDependent())
2874 A = Context.getASTContext().getCanonicalTemplateArgument(A);
2876 switch (A.getKind()) {
2877 case TemplateArgument::Null:
2878 llvm_unreachable("Cannot mangle NULL template argument");
2880 case TemplateArgument::Type:
2881 mangleType(A.getAsType());
2883 case TemplateArgument::Template:
2884 // This is mangled as <type>.
2885 mangleType(A.getAsTemplate());
2887 case TemplateArgument::TemplateExpansion:
2888 // <type> ::= Dp <type> # pack expansion (C++0x)
2890 mangleType(A.getAsTemplateOrTemplatePattern());
2892 case TemplateArgument::Expression:
2894 mangleExpression(A.getAsExpr());
2897 case TemplateArgument::Integral:
2898 mangleIntegerLiteral(A.getIntegralType(), *A.getAsIntegral());
2900 case TemplateArgument::Declaration: {
2901 assert(P && "Missing template parameter for declaration argument");
2902 // <expr-primary> ::= L <mangled-name> E # external name
2904 // Clang produces AST's where pointer-to-member-function expressions
2905 // and pointer-to-function expressions are represented as a declaration not
2906 // an expression. We compensate for it here to produce the correct mangling.
2907 NamedDecl *D = cast<NamedDecl>(A.getAsDecl());
2908 const NonTypeTemplateParmDecl *Parameter = cast<NonTypeTemplateParmDecl>(P);
2909 bool compensateMangling = !Parameter->getType()->isReferenceType();
2910 if (compensateMangling) {
2912 mangleOperatorName(OO_Amp, 1);
2916 // References to external entities use the mangled name; if the name would
2917 // not normally be manged then mangle it as unqualified.
2919 // FIXME: The ABI specifies that external names here should have _Z, but
2920 // gcc leaves this off.
2921 if (compensateMangling)
2927 if (compensateMangling)
2933 case TemplateArgument::Pack: {
2934 // Note: proposal by Mike Herrick on 12/20/10
2936 for (TemplateArgument::pack_iterator PA = A.pack_begin(),
2937 PAEnd = A.pack_end();
2939 mangleTemplateArg(P, *PA);
2945 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
2946 // <template-param> ::= T_ # first template parameter
2947 // ::= T <parameter-2 non-negative number> _
2951 Out << 'T' << (Index - 1) << '_';
2954 void CXXNameMangler::mangleExistingSubstitution(QualType type) {
2955 bool result = mangleSubstitution(type);
2956 assert(result && "no existing substitution for type");
2960 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
2961 bool result = mangleSubstitution(tname);
2962 assert(result && "no existing substitution for template name");
2966 // <substitution> ::= S <seq-id> _
2968 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
2969 // Try one of the standard substitutions first.
2970 if (mangleStandardSubstitution(ND))
2973 ND = cast<NamedDecl>(ND->getCanonicalDecl());
2974 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
2977 bool CXXNameMangler::mangleSubstitution(QualType T) {
2978 if (!T.getCVRQualifiers()) {
2979 if (const RecordType *RT = T->getAs<RecordType>())
2980 return mangleSubstitution(RT->getDecl());
2983 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
2985 return mangleSubstitution(TypePtr);
2988 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
2989 if (TemplateDecl *TD = Template.getAsTemplateDecl())
2990 return mangleSubstitution(TD);
2992 Template = Context.getASTContext().getCanonicalTemplateName(Template);
2993 return mangleSubstitution(
2994 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
2997 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
2998 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
2999 if (I == Substitutions.end())
3002 unsigned SeqID = I->second;
3008 // <seq-id> is encoded in base-36, using digits and upper case letters.
3010 char *BufferPtr = llvm::array_endof(Buffer);
3012 if (SeqID == 0) *--BufferPtr = '0';
3015 assert(BufferPtr > Buffer && "Buffer overflow!");
3017 char c = static_cast<char>(SeqID % 36);
3019 *--BufferPtr = (c < 10 ? '0' + c : 'A' + c - 10);
3024 << llvm::StringRef(BufferPtr, llvm::array_endof(Buffer)-BufferPtr)
3031 static bool isCharType(QualType T) {
3035 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3036 T->isSpecificBuiltinType(BuiltinType::Char_U);
3039 /// isCharSpecialization - Returns whether a given type is a template
3040 /// specialization of a given name with a single argument of type char.
3041 static bool isCharSpecialization(QualType T, const char *Name) {
3045 const RecordType *RT = T->getAs<RecordType>();
3049 const ClassTemplateSpecializationDecl *SD =
3050 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3054 if (!isStdNamespace(SD->getDeclContext()))
3057 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3058 if (TemplateArgs.size() != 1)
3061 if (!isCharType(TemplateArgs[0].getAsType()))
3064 return SD->getIdentifier()->getName() == Name;
3067 template <std::size_t StrLen>
3068 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3069 const char (&Str)[StrLen]) {
3070 if (!SD->getIdentifier()->isStr(Str))
3073 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3074 if (TemplateArgs.size() != 2)
3077 if (!isCharType(TemplateArgs[0].getAsType()))
3080 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3086 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3087 // <substitution> ::= St # ::std::
3088 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3095 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3096 if (!isStdNamespace(TD->getDeclContext()))
3099 // <substitution> ::= Sa # ::std::allocator
3100 if (TD->getIdentifier()->isStr("allocator")) {
3105 // <<substitution> ::= Sb # ::std::basic_string
3106 if (TD->getIdentifier()->isStr("basic_string")) {
3112 if (const ClassTemplateSpecializationDecl *SD =
3113 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3114 if (!isStdNamespace(SD->getDeclContext()))
3117 // <substitution> ::= Ss # ::std::basic_string<char,
3118 // ::std::char_traits<char>,
3119 // ::std::allocator<char> >
3120 if (SD->getIdentifier()->isStr("basic_string")) {
3121 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3123 if (TemplateArgs.size() != 3)
3126 if (!isCharType(TemplateArgs[0].getAsType()))
3129 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3132 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3139 // <substitution> ::= Si # ::std::basic_istream<char,
3140 // ::std::char_traits<char> >
3141 if (isStreamCharSpecialization(SD, "basic_istream")) {
3146 // <substitution> ::= So # ::std::basic_ostream<char,
3147 // ::std::char_traits<char> >
3148 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3153 // <substitution> ::= Sd # ::std::basic_iostream<char,
3154 // ::std::char_traits<char> >
3155 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3163 void CXXNameMangler::addSubstitution(QualType T) {
3164 if (!T.getCVRQualifiers()) {
3165 if (const RecordType *RT = T->getAs<RecordType>()) {
3166 addSubstitution(RT->getDecl());
3171 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3172 addSubstitution(TypePtr);
3175 void CXXNameMangler::addSubstitution(TemplateName Template) {
3176 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3177 return addSubstitution(TD);
3179 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3180 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3183 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3184 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3185 Substitutions[Ptr] = SeqID++;
3190 /// \brief Mangles the name of the declaration D and emits that name to the
3191 /// given output stream.
3193 /// If the declaration D requires a mangled name, this routine will emit that
3194 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3195 /// and this routine will return false. In this case, the caller should just
3196 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
3198 void ItaniumMangleContext::mangleName(const NamedDecl *D,
3199 llvm::raw_ostream &Out) {
3200 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3201 "Invalid mangleName() call, argument is not a variable or function!");
3202 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3203 "Invalid mangleName() call on 'structor decl!");
3205 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3206 getASTContext().getSourceManager(),
3207 "Mangling declaration");
3209 CXXNameMangler Mangler(*this, Out, D);
3210 return Mangler.mangle(D);
3213 void ItaniumMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
3215 llvm::raw_ostream &Out) {
3216 CXXNameMangler Mangler(*this, Out, D, Type);
3220 void ItaniumMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
3222 llvm::raw_ostream &Out) {
3223 CXXNameMangler Mangler(*this, Out, D, Type);
3227 void ItaniumMangleContext::mangleThunk(const CXXMethodDecl *MD,
3228 const ThunkInfo &Thunk,
3229 llvm::raw_ostream &Out) {
3230 // <special-name> ::= T <call-offset> <base encoding>
3231 // # base is the nominal target function of thunk
3232 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3233 // # base is the nominal target function of thunk
3234 // # first call-offset is 'this' adjustment
3235 // # second call-offset is result adjustment
3237 assert(!isa<CXXDestructorDecl>(MD) &&
3238 "Use mangleCXXDtor for destructor decls!");
3239 CXXNameMangler Mangler(*this, Out);
3240 Mangler.getStream() << "_ZT";
3241 if (!Thunk.Return.isEmpty())
3242 Mangler.getStream() << 'c';
3244 // Mangle the 'this' pointer adjustment.
3245 Mangler.mangleCallOffset(Thunk.This.NonVirtual, Thunk.This.VCallOffsetOffset);
3247 // Mangle the return pointer adjustment if there is one.
3248 if (!Thunk.Return.isEmpty())
3249 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
3250 Thunk.Return.VBaseOffsetOffset);
3252 Mangler.mangleFunctionEncoding(MD);
3256 ItaniumMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
3258 const ThisAdjustment &ThisAdjustment,
3259 llvm::raw_ostream &Out) {
3260 // <special-name> ::= T <call-offset> <base encoding>
3261 // # base is the nominal target function of thunk
3262 CXXNameMangler Mangler(*this, Out, DD, Type);
3263 Mangler.getStream() << "_ZT";
3265 // Mangle the 'this' pointer adjustment.
3266 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
3267 ThisAdjustment.VCallOffsetOffset);
3269 Mangler.mangleFunctionEncoding(DD);
3272 /// mangleGuardVariable - Returns the mangled name for a guard variable
3273 /// for the passed in VarDecl.
3274 void ItaniumMangleContext::mangleItaniumGuardVariable(const VarDecl *D,
3275 llvm::raw_ostream &Out) {
3276 // <special-name> ::= GV <object name> # Guard variable for one-time
3278 CXXNameMangler Mangler(*this, Out);
3279 Mangler.getStream() << "_ZGV";
3280 Mangler.mangleName(D);
3283 void ItaniumMangleContext::mangleReferenceTemporary(const VarDecl *D,
3284 llvm::raw_ostream &Out) {
3285 // We match the GCC mangling here.
3286 // <special-name> ::= GR <object name>
3287 CXXNameMangler Mangler(*this, Out);
3288 Mangler.getStream() << "_ZGR";
3289 Mangler.mangleName(D);
3292 void ItaniumMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
3293 llvm::raw_ostream &Out) {
3294 // <special-name> ::= TV <type> # virtual table
3295 CXXNameMangler Mangler(*this, Out);
3296 Mangler.getStream() << "_ZTV";
3297 Mangler.mangleNameOrStandardSubstitution(RD);
3300 void ItaniumMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
3301 llvm::raw_ostream &Out) {
3302 // <special-name> ::= TT <type> # VTT structure
3303 CXXNameMangler Mangler(*this, Out);
3304 Mangler.getStream() << "_ZTT";
3305 Mangler.mangleNameOrStandardSubstitution(RD);
3308 void ItaniumMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
3310 const CXXRecordDecl *Type,
3311 llvm::raw_ostream &Out) {
3312 // <special-name> ::= TC <type> <offset number> _ <base type>
3313 CXXNameMangler Mangler(*this, Out);
3314 Mangler.getStream() << "_ZTC";
3315 Mangler.mangleNameOrStandardSubstitution(RD);
3316 Mangler.getStream() << Offset;
3317 Mangler.getStream() << '_';
3318 Mangler.mangleNameOrStandardSubstitution(Type);
3321 void ItaniumMangleContext::mangleCXXRTTI(QualType Ty,
3322 llvm::raw_ostream &Out) {
3323 // <special-name> ::= TI <type> # typeinfo structure
3324 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
3325 CXXNameMangler Mangler(*this, Out);
3326 Mangler.getStream() << "_ZTI";
3327 Mangler.mangleType(Ty);
3330 void ItaniumMangleContext::mangleCXXRTTIName(QualType Ty,
3331 llvm::raw_ostream &Out) {
3332 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
3333 CXXNameMangler Mangler(*this, Out);
3334 Mangler.getStream() << "_ZTS";
3335 Mangler.mangleType(Ty);
3338 MangleContext *clang::createItaniumMangleContext(ASTContext &Context,
3339 Diagnostic &Diags) {
3340 return new ItaniumMangleContext(Context, Diags);