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/Attr.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/Basic/ABI.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
34 #define MANGLE_CHECKER 0
40 using namespace clang;
44 /// \brief Retrieve the declaration context that should be used when mangling
45 /// the given declaration.
46 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
47 // The ABI assumes that lambda closure types that occur within
48 // default arguments live in the context of the function. However, due to
49 // the way in which Clang parses and creates function declarations, this is
50 // not the case: the lambda closure type ends up living in the context
51 // where the function itself resides, because the function declaration itself
52 // had not yet been created. Fix the context here.
53 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
55 if (ParmVarDecl *ContextParam
56 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
57 return ContextParam->getDeclContext();
60 // Perform the same check for block literals.
61 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
62 if (ParmVarDecl *ContextParam
63 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
64 return ContextParam->getDeclContext();
67 const DeclContext *DC = D->getDeclContext();
68 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
69 return getEffectiveDeclContext(CD);
74 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
75 return getEffectiveDeclContext(cast<Decl>(DC));
78 static bool isLocalContainerContext(const DeclContext *DC) {
79 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
82 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
83 const DeclContext *DC = getEffectiveDeclContext(D);
84 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
85 if (isLocalContainerContext(DC))
86 return dyn_cast<RecordDecl>(D);
88 DC = getEffectiveDeclContext(D);
93 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
94 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
95 return ftd->getTemplatedDecl();
100 static const NamedDecl *getStructor(const NamedDecl *decl) {
101 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
102 return (fn ? getStructor(fn) : decl);
105 static const unsigned UnknownArity = ~0U;
107 class ItaniumMangleContextImpl : public ItaniumMangleContext {
108 llvm::DenseMap<const TagDecl *, uint64_t> AnonStructIds;
109 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
110 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
111 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
114 explicit ItaniumMangleContextImpl(ASTContext &Context,
115 DiagnosticsEngine &Diags)
116 : ItaniumMangleContext(Context, Diags) {}
118 uint64_t getAnonymousStructId(const TagDecl *TD) {
119 std::pair<llvm::DenseMap<const TagDecl *,
120 uint64_t>::iterator, bool> Result =
121 AnonStructIds.insert(std::make_pair(TD, AnonStructIds.size()));
122 return Result.first->second;
125 /// @name Mangler Entry Points
128 bool shouldMangleCXXName(const NamedDecl *D);
129 void mangleCXXName(const NamedDecl *D, raw_ostream &);
130 void mangleThunk(const CXXMethodDecl *MD,
131 const ThunkInfo &Thunk,
133 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
134 const ThisAdjustment &ThisAdjustment,
136 void mangleReferenceTemporary(const VarDecl *D,
138 void mangleCXXVTable(const CXXRecordDecl *RD,
140 void mangleCXXVTT(const CXXRecordDecl *RD,
142 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
143 const CXXRecordDecl *Type,
145 void mangleCXXRTTI(QualType T, raw_ostream &);
146 void mangleCXXRTTIName(QualType T, raw_ostream &);
147 void mangleTypeName(QualType T, raw_ostream &);
148 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
150 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
153 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &);
154 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out);
155 void mangleDynamicAtExitDestructor(const VarDecl *D, raw_ostream &Out);
156 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &);
157 void mangleItaniumThreadLocalWrapper(const VarDecl *D, raw_ostream &);
159 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
160 // Lambda closure types are already numbered.
161 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND))
165 // Anonymous tags are already numbered.
166 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
167 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
171 // Use the canonical number for externally visible decls.
172 if (ND->isExternallyVisible()) {
173 unsigned discriminator = getASTContext().getManglingNumber(ND);
174 if (discriminator == 1)
176 disc = discriminator - 2;
180 // Make up a reasonable number for internal decls.
181 unsigned &discriminator = Uniquifier[ND];
182 if (!discriminator) {
183 const DeclContext *DC = getEffectiveDeclContext(ND);
184 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
186 if (discriminator == 1)
188 disc = discriminator-2;
194 /// CXXNameMangler - Manage the mangling of a single name.
195 class CXXNameMangler {
196 ItaniumMangleContextImpl &Context;
199 /// The "structor" is the top-level declaration being mangled, if
200 /// that's not a template specialization; otherwise it's the pattern
201 /// for that specialization.
202 const NamedDecl *Structor;
203 unsigned StructorType;
205 /// SeqID - The next subsitution sequence number.
208 class FunctionTypeDepthState {
211 enum { InResultTypeMask = 1 };
214 FunctionTypeDepthState() : Bits(0) {}
216 /// The number of function types we're inside.
217 unsigned getDepth() const {
221 /// True if we're in the return type of the innermost function type.
222 bool isInResultType() const {
223 return Bits & InResultTypeMask;
226 FunctionTypeDepthState push() {
227 FunctionTypeDepthState tmp = *this;
228 Bits = (Bits & ~InResultTypeMask) + 2;
232 void enterResultType() {
233 Bits |= InResultTypeMask;
236 void leaveResultType() {
237 Bits &= ~InResultTypeMask;
240 void pop(FunctionTypeDepthState saved) {
241 assert(getDepth() == saved.getDepth() + 1);
247 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
249 ASTContext &getASTContext() const { return Context.getASTContext(); }
252 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
253 const NamedDecl *D = 0)
254 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
256 // These can't be mangled without a ctor type or dtor type.
257 assert(!D || (!isa<CXXDestructorDecl>(D) &&
258 !isa<CXXConstructorDecl>(D)));
260 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
261 const CXXConstructorDecl *D, CXXCtorType Type)
262 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
264 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
265 const CXXDestructorDecl *D, CXXDtorType Type)
266 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
271 if (Out.str()[0] == '\01')
275 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
276 assert(status == 0 && "Could not demangle mangled name!");
280 raw_ostream &getStream() { return Out; }
282 void mangle(const NamedDecl *D, StringRef Prefix = "_Z");
283 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
284 void mangleNumber(const llvm::APSInt &I);
285 void mangleNumber(int64_t Number);
286 void mangleFloat(const llvm::APFloat &F);
287 void mangleFunctionEncoding(const FunctionDecl *FD);
288 void mangleName(const NamedDecl *ND);
289 void mangleType(QualType T);
290 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
293 bool mangleSubstitution(const NamedDecl *ND);
294 bool mangleSubstitution(QualType T);
295 bool mangleSubstitution(TemplateName Template);
296 bool mangleSubstitution(uintptr_t Ptr);
298 void mangleExistingSubstitution(QualType type);
299 void mangleExistingSubstitution(TemplateName name);
301 bool mangleStandardSubstitution(const NamedDecl *ND);
303 void addSubstitution(const NamedDecl *ND) {
304 ND = cast<NamedDecl>(ND->getCanonicalDecl());
306 addSubstitution(reinterpret_cast<uintptr_t>(ND));
308 void addSubstitution(QualType T);
309 void addSubstitution(TemplateName Template);
310 void addSubstitution(uintptr_t Ptr);
312 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
313 NamedDecl *firstQualifierLookup,
314 bool recursive = false);
315 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
316 NamedDecl *firstQualifierLookup,
317 DeclarationName name,
318 unsigned KnownArity = UnknownArity);
320 void mangleName(const TemplateDecl *TD,
321 const TemplateArgument *TemplateArgs,
322 unsigned NumTemplateArgs);
323 void mangleUnqualifiedName(const NamedDecl *ND) {
324 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
326 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
327 unsigned KnownArity);
328 void mangleUnscopedName(const NamedDecl *ND);
329 void mangleUnscopedTemplateName(const TemplateDecl *ND);
330 void mangleUnscopedTemplateName(TemplateName);
331 void mangleSourceName(const IdentifierInfo *II);
332 void mangleLocalName(const Decl *D);
333 void mangleBlockForPrefix(const BlockDecl *Block);
334 void mangleUnqualifiedBlock(const BlockDecl *Block);
335 void mangleLambda(const CXXRecordDecl *Lambda);
336 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
337 bool NoFunction=false);
338 void mangleNestedName(const TemplateDecl *TD,
339 const TemplateArgument *TemplateArgs,
340 unsigned NumTemplateArgs);
341 void manglePrefix(NestedNameSpecifier *qualifier);
342 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
343 void manglePrefix(QualType type);
344 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
345 void mangleTemplatePrefix(TemplateName Template);
346 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
347 void mangleQualifiers(Qualifiers Quals);
348 void mangleRefQualifier(RefQualifierKind RefQualifier);
350 void mangleObjCMethodName(const ObjCMethodDecl *MD);
352 // Declare manglers for every type class.
353 #define ABSTRACT_TYPE(CLASS, PARENT)
354 #define NON_CANONICAL_TYPE(CLASS, PARENT)
355 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
356 #include "clang/AST/TypeNodes.def"
358 void mangleType(const TagType*);
359 void mangleType(TemplateName);
360 void mangleBareFunctionType(const FunctionType *T,
361 bool MangleReturnType);
362 void mangleNeonVectorType(const VectorType *T);
363 void mangleAArch64NeonVectorType(const VectorType *T);
365 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
366 void mangleMemberExpr(const Expr *base, bool isArrow,
367 NestedNameSpecifier *qualifier,
368 NamedDecl *firstQualifierLookup,
369 DeclarationName name,
370 unsigned knownArity);
371 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
372 void mangleCXXCtorType(CXXCtorType T);
373 void mangleCXXDtorType(CXXDtorType T);
375 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
376 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
377 unsigned NumTemplateArgs);
378 void mangleTemplateArgs(const TemplateArgumentList &AL);
379 void mangleTemplateArg(TemplateArgument A);
381 void mangleTemplateParameter(unsigned Index);
383 void mangleFunctionParam(const ParmVarDecl *parm);
388 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
389 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
391 LanguageLinkage L = FD->getLanguageLinkage();
392 // Overloadable functions need mangling.
393 if (FD->hasAttr<OverloadableAttr>())
396 // "main" is not mangled.
400 // C++ functions and those whose names are not a simple identifier need
402 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
405 // C functions are not mangled.
406 if (L == CLanguageLinkage)
410 // Otherwise, no mangling is done outside C++ mode.
411 if (!getASTContext().getLangOpts().CPlusPlus)
414 const VarDecl *VD = dyn_cast<VarDecl>(D);
416 // C variables are not mangled.
420 // Variables at global scope with non-internal linkage are not mangled
421 const DeclContext *DC = getEffectiveDeclContext(D);
422 // Check for extern variable declared locally.
423 if (DC->isFunctionOrMethod() && D->hasLinkage())
424 while (!DC->isNamespace() && !DC->isTranslationUnit())
425 DC = getEffectiveParentContext(DC);
426 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
427 !isa<VarTemplateSpecializationDecl>(D))
434 void CXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
435 // <mangled-name> ::= _Z <encoding>
437 // ::= <special-name>
439 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
440 mangleFunctionEncoding(FD);
441 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
443 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
444 mangleName(IFD->getAnonField());
446 mangleName(cast<FieldDecl>(D));
449 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
450 // <encoding> ::= <function name> <bare-function-type>
453 // Don't mangle in the type if this isn't a decl we should typically mangle.
454 if (!Context.shouldMangleDeclName(FD))
457 // Whether the mangling of a function type includes the return type depends on
458 // the context and the nature of the function. The rules for deciding whether
459 // the return type is included are:
461 // 1. Template functions (names or types) have return types encoded, with
462 // the exceptions listed below.
463 // 2. Function types not appearing as part of a function name mangling,
464 // e.g. parameters, pointer types, etc., have return type encoded, with the
465 // exceptions listed below.
466 // 3. Non-template function names do not have return types encoded.
468 // The exceptions mentioned in (1) and (2) above, for which the return type is
469 // never included, are
472 // 3. Conversion operator functions, e.g. operator int.
473 bool MangleReturnType = false;
474 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
475 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
476 isa<CXXConversionDecl>(FD)))
477 MangleReturnType = true;
479 // Mangle the type of the primary template.
480 FD = PrimaryTemplate->getTemplatedDecl();
483 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
487 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
488 while (isa<LinkageSpecDecl>(DC)) {
489 DC = getEffectiveParentContext(DC);
495 /// isStd - Return whether a given namespace is the 'std' namespace.
496 static bool isStd(const NamespaceDecl *NS) {
497 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
498 ->isTranslationUnit())
501 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
502 return II && II->isStr("std");
505 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
507 static bool isStdNamespace(const DeclContext *DC) {
508 if (!DC->isNamespace())
511 return isStd(cast<NamespaceDecl>(DC));
514 static const TemplateDecl *
515 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
516 // Check if we have a function template.
517 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
518 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
519 TemplateArgs = FD->getTemplateSpecializationArgs();
524 // Check if we have a class template.
525 if (const ClassTemplateSpecializationDecl *Spec =
526 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
527 TemplateArgs = &Spec->getTemplateArgs();
528 return Spec->getSpecializedTemplate();
531 // Check if we have a variable template.
532 if (const VarTemplateSpecializationDecl *Spec =
533 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
534 TemplateArgs = &Spec->getTemplateArgs();
535 return Spec->getSpecializedTemplate();
541 static bool isLambda(const NamedDecl *ND) {
542 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
546 return Record->isLambda();
549 void CXXNameMangler::mangleName(const NamedDecl *ND) {
550 // <name> ::= <nested-name>
551 // ::= <unscoped-name>
552 // ::= <unscoped-template-name> <template-args>
555 const DeclContext *DC = getEffectiveDeclContext(ND);
557 // If this is an extern variable declared locally, the relevant DeclContext
558 // is that of the containing namespace, or the translation unit.
559 // FIXME: This is a hack; extern variables declared locally should have
560 // a proper semantic declaration context!
561 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
562 while (!DC->isNamespace() && !DC->isTranslationUnit())
563 DC = getEffectiveParentContext(DC);
564 else if (GetLocalClassDecl(ND)) {
569 DC = IgnoreLinkageSpecDecls(DC);
571 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
572 // Check if we have a template.
573 const TemplateArgumentList *TemplateArgs = 0;
574 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
575 mangleUnscopedTemplateName(TD);
576 mangleTemplateArgs(*TemplateArgs);
580 mangleUnscopedName(ND);
584 if (isLocalContainerContext(DC)) {
589 mangleNestedName(ND, DC);
591 void CXXNameMangler::mangleName(const TemplateDecl *TD,
592 const TemplateArgument *TemplateArgs,
593 unsigned NumTemplateArgs) {
594 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
596 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
597 mangleUnscopedTemplateName(TD);
598 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
600 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
604 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
605 // <unscoped-name> ::= <unqualified-name>
606 // ::= St <unqualified-name> # ::std::
608 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
611 mangleUnqualifiedName(ND);
614 void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
615 // <unscoped-template-name> ::= <unscoped-name>
616 // ::= <substitution>
617 if (mangleSubstitution(ND))
620 // <template-template-param> ::= <template-param>
621 if (const TemplateTemplateParmDecl *TTP
622 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
623 mangleTemplateParameter(TTP->getIndex());
627 mangleUnscopedName(ND->getTemplatedDecl());
631 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
632 // <unscoped-template-name> ::= <unscoped-name>
633 // ::= <substitution>
634 if (TemplateDecl *TD = Template.getAsTemplateDecl())
635 return mangleUnscopedTemplateName(TD);
637 if (mangleSubstitution(Template))
640 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
641 assert(Dependent && "Not a dependent template name?");
642 if (const IdentifierInfo *Id = Dependent->getIdentifier())
643 mangleSourceName(Id);
645 mangleOperatorName(Dependent->getOperator(), UnknownArity);
647 addSubstitution(Template);
650 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
652 // Floating-point literals are encoded using a fixed-length
653 // lowercase hexadecimal string corresponding to the internal
654 // representation (IEEE on Itanium), high-order bytes first,
655 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
657 // The 'without leading zeroes' thing seems to be an editorial
658 // mistake; see the discussion on cxx-abi-dev beginning on
661 // Our requirements here are just barely weird enough to justify
662 // using a custom algorithm instead of post-processing APInt::toString().
664 llvm::APInt valueBits = f.bitcastToAPInt();
665 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
666 assert(numCharacters != 0);
668 // Allocate a buffer of the right number of characters.
669 SmallVector<char, 20> buffer;
670 buffer.set_size(numCharacters);
672 // Fill the buffer left-to-right.
673 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
674 // The bit-index of the next hex digit.
675 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
677 // Project out 4 bits starting at 'digitIndex'.
678 llvm::integerPart hexDigit
679 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
680 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
683 // Map that over to a lowercase hex digit.
684 static const char charForHex[16] = {
685 '0', '1', '2', '3', '4', '5', '6', '7',
686 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
688 buffer[stringIndex] = charForHex[hexDigit];
691 Out.write(buffer.data(), numCharacters);
694 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
695 if (Value.isSigned() && Value.isNegative()) {
697 Value.abs().print(Out, /*signed*/ false);
699 Value.print(Out, /*signed*/ false);
703 void CXXNameMangler::mangleNumber(int64_t Number) {
704 // <number> ::= [n] <non-negative decimal integer>
713 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
714 // <call-offset> ::= h <nv-offset> _
715 // ::= v <v-offset> _
716 // <nv-offset> ::= <offset number> # non-virtual base override
717 // <v-offset> ::= <offset number> _ <virtual offset number>
718 // # virtual base override, with vcall offset
721 mangleNumber(NonVirtual);
727 mangleNumber(NonVirtual);
729 mangleNumber(Virtual);
733 void CXXNameMangler::manglePrefix(QualType type) {
734 if (const TemplateSpecializationType *TST =
735 type->getAs<TemplateSpecializationType>()) {
736 if (!mangleSubstitution(QualType(TST, 0))) {
737 mangleTemplatePrefix(TST->getTemplateName());
739 // FIXME: GCC does not appear to mangle the template arguments when
740 // the template in question is a dependent template name. Should we
741 // emulate that badness?
742 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
743 addSubstitution(QualType(TST, 0));
745 } else if (const DependentTemplateSpecializationType *DTST
746 = type->getAs<DependentTemplateSpecializationType>()) {
747 TemplateName Template
748 = getASTContext().getDependentTemplateName(DTST->getQualifier(),
749 DTST->getIdentifier());
750 mangleTemplatePrefix(Template);
752 // FIXME: GCC does not appear to mangle the template arguments when
753 // the template in question is a dependent template name. Should we
754 // emulate that badness?
755 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
757 // We use the QualType mangle type variant here because it handles
763 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
765 /// \param firstQualifierLookup - the entity found by unqualified lookup
766 /// for the first name in the qualifier, if this is for a member expression
767 /// \param recursive - true if this is being called recursively,
768 /// i.e. if there is more prefix "to the right".
769 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
770 NamedDecl *firstQualifierLookup,
774 // <unresolved-name> ::= [gs] <base-unresolved-name>
776 // T::x / decltype(p)::x
777 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
779 // T::N::x /decltype(p)::N::x
780 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
781 // <base-unresolved-name>
783 // A::x, N::y, A<T>::z; "gs" means leading "::"
784 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
785 // <base-unresolved-name>
787 switch (qualifier->getKind()) {
788 case NestedNameSpecifier::Global:
791 // We want an 'sr' unless this is the entire NNS.
795 // We never want an 'E' here.
798 case NestedNameSpecifier::Namespace:
799 if (qualifier->getPrefix())
800 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
804 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
806 case NestedNameSpecifier::NamespaceAlias:
807 if (qualifier->getPrefix())
808 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
812 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
815 case NestedNameSpecifier::TypeSpec:
816 case NestedNameSpecifier::TypeSpecWithTemplate: {
817 const Type *type = qualifier->getAsType();
819 // We only want to use an unresolved-type encoding if this is one of:
821 // - a template type parameter
822 // - a template template parameter with arguments
823 // In all of these cases, we should have no prefix.
824 if (qualifier->getPrefix()) {
825 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
828 // Otherwise, all the cases want this.
832 // Only certain other types are valid as prefixes; enumerate them.
833 switch (type->getTypeClass()) {
838 case Type::BlockPointer:
839 case Type::LValueReference:
840 case Type::RValueReference:
841 case Type::MemberPointer:
842 case Type::ConstantArray:
843 case Type::IncompleteArray:
844 case Type::VariableArray:
845 case Type::DependentSizedArray:
846 case Type::DependentSizedExtVector:
848 case Type::ExtVector:
849 case Type::FunctionProto:
850 case Type::FunctionNoProto:
853 case Type::Elaborated:
854 case Type::Attributed:
856 case Type::PackExpansion:
857 case Type::ObjCObject:
858 case Type::ObjCInterface:
859 case Type::ObjCObjectPointer:
861 llvm_unreachable("type is illegal as a nested name specifier");
863 case Type::SubstTemplateTypeParmPack:
864 // FIXME: not clear how to mangle this!
865 // template <class T...> class A {
866 // template <class U...> void foo(decltype(T::foo(U())) x...);
868 Out << "_SUBSTPACK_";
871 // <unresolved-type> ::= <template-param>
873 // ::= <template-template-param> <template-args>
874 // (this last is not official yet)
875 case Type::TypeOfExpr:
878 case Type::TemplateTypeParm:
879 case Type::UnaryTransform:
880 case Type::SubstTemplateTypeParm:
882 assert(!qualifier->getPrefix());
884 // We only get here recursively if we're followed by identifiers.
885 if (recursive) Out << 'N';
887 // This seems to do everything we want. It's not really
888 // sanctioned for a substituted template parameter, though.
889 mangleType(QualType(type, 0));
891 // We never want to print 'E' directly after an unresolved-type,
892 // so we return directly.
896 mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier());
899 case Type::UnresolvedUsing:
900 mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl()
905 mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier());
908 case Type::TemplateSpecialization: {
909 const TemplateSpecializationType *tst
910 = cast<TemplateSpecializationType>(type);
911 TemplateName name = tst->getTemplateName();
912 switch (name.getKind()) {
913 case TemplateName::Template:
914 case TemplateName::QualifiedTemplate: {
915 TemplateDecl *temp = name.getAsTemplateDecl();
917 // If the base is a template template parameter, this is an
919 assert(temp && "no template for template specialization type");
920 if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType;
922 mangleSourceName(temp->getIdentifier());
926 case TemplateName::OverloadedTemplate:
927 case TemplateName::DependentTemplate:
928 llvm_unreachable("invalid base for a template specialization type");
930 case TemplateName::SubstTemplateTemplateParm: {
931 SubstTemplateTemplateParmStorage *subst
932 = name.getAsSubstTemplateTemplateParm();
933 mangleExistingSubstitution(subst->getReplacement());
937 case TemplateName::SubstTemplateTemplateParmPack: {
938 // FIXME: not clear how to mangle this!
939 // template <template <class U> class T...> class A {
940 // template <class U...> void foo(decltype(T<U>::foo) x...);
942 Out << "_SUBSTPACK_";
947 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
951 case Type::InjectedClassName:
952 mangleSourceName(cast<InjectedClassNameType>(type)->getDecl()
956 case Type::DependentName:
957 mangleSourceName(cast<DependentNameType>(type)->getIdentifier());
960 case Type::DependentTemplateSpecialization: {
961 const DependentTemplateSpecializationType *tst
962 = cast<DependentTemplateSpecializationType>(type);
963 mangleSourceName(tst->getIdentifier());
964 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
971 case NestedNameSpecifier::Identifier:
972 // Member expressions can have these without prefixes.
973 if (qualifier->getPrefix()) {
974 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
976 } else if (firstQualifierLookup) {
978 // Try to make a proper qualifier out of the lookup result, and
979 // then just recurse on that.
980 NestedNameSpecifier *newQualifier;
981 if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) {
982 QualType type = getASTContext().getTypeDeclType(typeDecl);
984 // Pretend we had a different nested name specifier.
985 newQualifier = NestedNameSpecifier::Create(getASTContext(),
989 } else if (NamespaceDecl *nspace =
990 dyn_cast<NamespaceDecl>(firstQualifierLookup)) {
991 newQualifier = NestedNameSpecifier::Create(getASTContext(),
994 } else if (NamespaceAliasDecl *alias =
995 dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) {
996 newQualifier = NestedNameSpecifier::Create(getASTContext(),
1000 // No sensible mangling to do here.
1005 return mangleUnresolvedPrefix(newQualifier, /*lookup*/ 0, recursive);
1011 mangleSourceName(qualifier->getAsIdentifier());
1015 // If this was the innermost part of the NNS, and we fell out to
1016 // here, append an 'E'.
1021 /// Mangle an unresolved-name, which is generally used for names which
1022 /// weren't resolved to specific entities.
1023 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
1024 NamedDecl *firstQualifierLookup,
1025 DeclarationName name,
1026 unsigned knownArity) {
1027 if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup);
1028 mangleUnqualifiedName(0, name, knownArity);
1031 static const FieldDecl *FindFirstNamedDataMember(const RecordDecl *RD) {
1032 assert(RD->isAnonymousStructOrUnion() &&
1033 "Expected anonymous struct or union!");
1035 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1037 if (I->getIdentifier())
1040 if (const RecordType *RT = I->getType()->getAs<RecordType>())
1041 if (const FieldDecl *NamedDataMember =
1042 FindFirstNamedDataMember(RT->getDecl()))
1043 return NamedDataMember;
1046 // We didn't find a named data member.
1050 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1051 DeclarationName Name,
1052 unsigned KnownArity) {
1053 // <unqualified-name> ::= <operator-name>
1054 // ::= <ctor-dtor-name>
1055 // ::= <source-name>
1056 switch (Name.getNameKind()) {
1057 case DeclarationName::Identifier: {
1058 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
1059 // We must avoid conflicts between internally- and externally-
1060 // linked variable and function declaration names in the same TU:
1061 // void test() { extern void foo(); }
1062 // static void foo();
1063 // This naming convention is the same as that followed by GCC,
1064 // though it shouldn't actually matter.
1065 if (ND && ND->getFormalLinkage() == InternalLinkage &&
1066 getEffectiveDeclContext(ND)->isFileContext())
1069 mangleSourceName(II);
1073 // Otherwise, an anonymous entity. We must have a declaration.
1074 assert(ND && "mangling empty name without declaration");
1076 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1077 if (NS->isAnonymousNamespace()) {
1078 // This is how gcc mangles these names.
1079 Out << "12_GLOBAL__N_1";
1084 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1085 // We must have an anonymous union or struct declaration.
1086 const RecordDecl *RD =
1087 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
1089 // Itanium C++ ABI 5.1.2:
1091 // For the purposes of mangling, the name of an anonymous union is
1092 // considered to be the name of the first named data member found by a
1093 // pre-order, depth-first, declaration-order walk of the data members of
1094 // the anonymous union. If there is no such data member (i.e., if all of
1095 // the data members in the union are unnamed), then there is no way for
1096 // a program to refer to the anonymous union, and there is therefore no
1097 // need to mangle its name.
1098 const FieldDecl *FD = FindFirstNamedDataMember(RD);
1100 // It's actually possible for various reasons for us to get here
1101 // with an empty anonymous struct / union. Fortunately, it
1102 // doesn't really matter what name we generate.
1104 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1106 mangleSourceName(FD->getIdentifier());
1110 // Class extensions have no name as a category, and it's possible
1111 // for them to be the semantic parent of certain declarations
1112 // (primarily, tag decls defined within declarations). Such
1113 // declarations will always have internal linkage, so the name
1114 // doesn't really matter, but we shouldn't crash on them. For
1115 // safety, just handle all ObjC containers here.
1116 if (isa<ObjCContainerDecl>(ND))
1119 // We must have an anonymous struct.
1120 const TagDecl *TD = cast<TagDecl>(ND);
1121 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1122 assert(TD->getDeclContext() == D->getDeclContext() &&
1123 "Typedef should not be in another decl context!");
1124 assert(D->getDeclName().getAsIdentifierInfo() &&
1125 "Typedef was not named!");
1126 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1130 // <unnamed-type-name> ::= <closure-type-name>
1132 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1133 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1134 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1135 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1136 mangleLambda(Record);
1141 if (TD->isExternallyVisible()) {
1142 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1144 if (UnnamedMangle > 1)
1145 Out << llvm::utostr(UnnamedMangle - 2);
1150 // Get a unique id for the anonymous struct.
1151 uint64_t AnonStructId = Context.getAnonymousStructId(TD);
1153 // Mangle it as a source name in the form
1155 // where n is the length of the string.
1158 Str += llvm::utostr(AnonStructId);
1165 case DeclarationName::ObjCZeroArgSelector:
1166 case DeclarationName::ObjCOneArgSelector:
1167 case DeclarationName::ObjCMultiArgSelector:
1168 llvm_unreachable("Can't mangle Objective-C selector names here!");
1170 case DeclarationName::CXXConstructorName:
1172 // If the named decl is the C++ constructor we're mangling, use the type
1174 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1176 // Otherwise, use the complete constructor name. This is relevant if a
1177 // class with a constructor is declared within a constructor.
1178 mangleCXXCtorType(Ctor_Complete);
1181 case DeclarationName::CXXDestructorName:
1183 // If the named decl is the C++ destructor we're mangling, use the type we
1185 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1187 // Otherwise, use the complete destructor name. This is relevant if a
1188 // class with a destructor is declared within a destructor.
1189 mangleCXXDtorType(Dtor_Complete);
1192 case DeclarationName::CXXConversionFunctionName:
1193 // <operator-name> ::= cv <type> # (cast)
1195 mangleType(Name.getCXXNameType());
1198 case DeclarationName::CXXOperatorName: {
1201 Arity = cast<FunctionDecl>(ND)->getNumParams();
1203 // If we have a C++ member function, we need to include the 'this' pointer.
1204 // FIXME: This does not make sense for operators that are static, but their
1205 // names stay the same regardless of the arity (operator new for instance).
1206 if (isa<CXXMethodDecl>(ND))
1211 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1215 case DeclarationName::CXXLiteralOperatorName:
1216 // FIXME: This mangling is not yet official.
1218 mangleSourceName(Name.getCXXLiteralIdentifier());
1221 case DeclarationName::CXXUsingDirective:
1222 llvm_unreachable("Can't mangle a using directive name!");
1226 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1227 // <source-name> ::= <positive length number> <identifier>
1228 // <number> ::= [n] <non-negative decimal integer>
1229 // <identifier> ::= <unqualified source code identifier>
1230 Out << II->getLength() << II->getName();
1233 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1234 const DeclContext *DC,
1237 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1238 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1239 // <template-args> E
1242 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1243 Qualifiers MethodQuals =
1244 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1245 // We do not consider restrict a distinguishing attribute for overloading
1246 // purposes so we must not mangle it.
1247 MethodQuals.removeRestrict();
1248 mangleQualifiers(MethodQuals);
1249 mangleRefQualifier(Method->getRefQualifier());
1252 // Check if we have a template.
1253 const TemplateArgumentList *TemplateArgs = 0;
1254 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1255 mangleTemplatePrefix(TD, NoFunction);
1256 mangleTemplateArgs(*TemplateArgs);
1259 manglePrefix(DC, NoFunction);
1260 mangleUnqualifiedName(ND);
1265 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1266 const TemplateArgument *TemplateArgs,
1267 unsigned NumTemplateArgs) {
1268 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1272 mangleTemplatePrefix(TD);
1273 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1278 void CXXNameMangler::mangleLocalName(const Decl *D) {
1279 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1280 // := Z <function encoding> E s [<discriminator>]
1281 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1283 // <discriminator> := _ <non-negative number>
1284 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1285 const RecordDecl *RD = GetLocalClassDecl(D);
1286 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1290 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1291 mangleObjCMethodName(MD);
1292 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1293 mangleBlockForPrefix(BD);
1295 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1300 // The parameter number is omitted for the last parameter, 0 for the
1301 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1302 // <entity name> will of course contain a <closure-type-name>: Its
1303 // numbering will be local to the particular argument in which it appears
1304 // -- other default arguments do not affect its encoding.
1305 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1306 if (CXXRD->isLambda()) {
1307 if (const ParmVarDecl *Parm
1308 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1309 if (const FunctionDecl *Func
1310 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1312 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1314 mangleNumber(Num - 2);
1320 // Mangle the name relative to the closest enclosing function.
1321 // equality ok because RD derived from ND above
1323 mangleUnqualifiedName(RD);
1324 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1325 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1326 mangleUnqualifiedBlock(BD);
1328 const NamedDecl *ND = cast<NamedDecl>(D);
1329 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
1331 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1332 // Mangle a block in a default parameter; see above explanation for
1334 if (const ParmVarDecl *Parm
1335 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1336 if (const FunctionDecl *Func
1337 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1339 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1341 mangleNumber(Num - 2);
1346 mangleUnqualifiedBlock(BD);
1348 mangleUnqualifiedName(cast<NamedDecl>(D));
1351 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1353 if (Context.getNextDiscriminator(ND, disc)) {
1357 Out << "__" << disc << '_';
1362 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1363 if (GetLocalClassDecl(Block)) {
1364 mangleLocalName(Block);
1367 const DeclContext *DC = getEffectiveDeclContext(Block);
1368 if (isLocalContainerContext(DC)) {
1369 mangleLocalName(Block);
1372 manglePrefix(getEffectiveDeclContext(Block));
1373 mangleUnqualifiedBlock(Block);
1376 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1377 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1378 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1379 Context->getDeclContext()->isRecord()) {
1380 if (const IdentifierInfo *Name
1381 = cast<NamedDecl>(Context)->getIdentifier()) {
1382 mangleSourceName(Name);
1388 // If we have a block mangling number, use it.
1389 unsigned Number = Block->getBlockManglingNumber();
1390 // Otherwise, just make up a number. It doesn't matter what it is because
1391 // the symbol in question isn't externally visible.
1393 Number = Context.getBlockId(Block, false);
1400 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1401 // If the context of a closure type is an initializer for a class member
1402 // (static or nonstatic), it is encoded in a qualified name with a final
1403 // <prefix> of the form:
1405 // <data-member-prefix> := <member source-name> M
1407 // Technically, the data-member-prefix is part of the <prefix>. However,
1408 // since a closure type will always be mangled with a prefix, it's easier
1409 // to emit that last part of the prefix here.
1410 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1411 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1412 Context->getDeclContext()->isRecord()) {
1413 if (const IdentifierInfo *Name
1414 = cast<NamedDecl>(Context)->getIdentifier()) {
1415 mangleSourceName(Name);
1422 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1423 getAs<FunctionProtoType>();
1424 mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
1427 // The number is omitted for the first closure type with a given
1428 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1429 // (in lexical order) with that same <lambda-sig> and context.
1431 // The AST keeps track of the number for us.
1432 unsigned Number = Lambda->getLambdaManglingNumber();
1433 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1435 mangleNumber(Number - 2);
1439 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1440 switch (qualifier->getKind()) {
1441 case NestedNameSpecifier::Global:
1445 case NestedNameSpecifier::Namespace:
1446 mangleName(qualifier->getAsNamespace());
1449 case NestedNameSpecifier::NamespaceAlias:
1450 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1453 case NestedNameSpecifier::TypeSpec:
1454 case NestedNameSpecifier::TypeSpecWithTemplate:
1455 manglePrefix(QualType(qualifier->getAsType(), 0));
1458 case NestedNameSpecifier::Identifier:
1459 // Member expressions can have these without prefixes, but that
1460 // should end up in mangleUnresolvedPrefix instead.
1461 assert(qualifier->getPrefix());
1462 manglePrefix(qualifier->getPrefix());
1464 mangleSourceName(qualifier->getAsIdentifier());
1468 llvm_unreachable("unexpected nested name specifier");
1471 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1472 // <prefix> ::= <prefix> <unqualified-name>
1473 // ::= <template-prefix> <template-args>
1474 // ::= <template-param>
1476 // ::= <substitution>
1478 DC = IgnoreLinkageSpecDecls(DC);
1480 if (DC->isTranslationUnit())
1483 if (NoFunction && isLocalContainerContext(DC))
1486 assert(!isLocalContainerContext(DC));
1488 const NamedDecl *ND = cast<NamedDecl>(DC);
1489 if (mangleSubstitution(ND))
1492 // Check if we have a template.
1493 const TemplateArgumentList *TemplateArgs = 0;
1494 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1495 mangleTemplatePrefix(TD);
1496 mangleTemplateArgs(*TemplateArgs);
1498 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1499 mangleUnqualifiedName(ND);
1502 addSubstitution(ND);
1505 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1506 // <template-prefix> ::= <prefix> <template unqualified-name>
1507 // ::= <template-param>
1508 // ::= <substitution>
1509 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1510 return mangleTemplatePrefix(TD);
1512 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1513 manglePrefix(Qualified->getQualifier());
1515 if (OverloadedTemplateStorage *Overloaded
1516 = Template.getAsOverloadedTemplate()) {
1517 mangleUnqualifiedName(0, (*Overloaded->begin())->getDeclName(),
1522 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1523 assert(Dependent && "Unknown template name kind?");
1524 manglePrefix(Dependent->getQualifier());
1525 mangleUnscopedTemplateName(Template);
1528 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1530 // <template-prefix> ::= <prefix> <template unqualified-name>
1531 // ::= <template-param>
1532 // ::= <substitution>
1533 // <template-template-param> ::= <template-param>
1536 if (mangleSubstitution(ND))
1539 // <template-template-param> ::= <template-param>
1540 if (const TemplateTemplateParmDecl *TTP
1541 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1542 mangleTemplateParameter(TTP->getIndex());
1546 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1547 mangleUnqualifiedName(ND->getTemplatedDecl());
1548 addSubstitution(ND);
1551 /// Mangles a template name under the production <type>. Required for
1552 /// template template arguments.
1553 /// <type> ::= <class-enum-type>
1554 /// ::= <template-param>
1555 /// ::= <substitution>
1556 void CXXNameMangler::mangleType(TemplateName TN) {
1557 if (mangleSubstitution(TN))
1560 TemplateDecl *TD = 0;
1562 switch (TN.getKind()) {
1563 case TemplateName::QualifiedTemplate:
1564 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1567 case TemplateName::Template:
1568 TD = TN.getAsTemplateDecl();
1572 if (isa<TemplateTemplateParmDecl>(TD))
1573 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1578 case TemplateName::OverloadedTemplate:
1579 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1581 case TemplateName::DependentTemplate: {
1582 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1583 assert(Dependent->isIdentifier());
1585 // <class-enum-type> ::= <name>
1586 // <name> ::= <nested-name>
1587 mangleUnresolvedPrefix(Dependent->getQualifier(), 0);
1588 mangleSourceName(Dependent->getIdentifier());
1592 case TemplateName::SubstTemplateTemplateParm: {
1593 // Substituted template parameters are mangled as the substituted
1594 // template. This will check for the substitution twice, which is
1595 // fine, but we have to return early so that we don't try to *add*
1596 // the substitution twice.
1597 SubstTemplateTemplateParmStorage *subst
1598 = TN.getAsSubstTemplateTemplateParm();
1599 mangleType(subst->getReplacement());
1603 case TemplateName::SubstTemplateTemplateParmPack: {
1604 // FIXME: not clear how to mangle this!
1605 // template <template <class> class T...> class A {
1606 // template <template <class> class U...> void foo(B<T,U> x...);
1608 Out << "_SUBSTPACK_";
1613 addSubstitution(TN);
1617 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1619 // <operator-name> ::= nw # new
1620 case OO_New: Out << "nw"; break;
1622 case OO_Array_New: Out << "na"; break;
1624 case OO_Delete: Out << "dl"; break;
1625 // ::= da # delete[]
1626 case OO_Array_Delete: Out << "da"; break;
1627 // ::= ps # + (unary)
1628 // ::= pl # + (binary or unknown)
1630 Out << (Arity == 1? "ps" : "pl"); break;
1631 // ::= ng # - (unary)
1632 // ::= mi # - (binary or unknown)
1634 Out << (Arity == 1? "ng" : "mi"); break;
1635 // ::= ad # & (unary)
1636 // ::= an # & (binary or unknown)
1638 Out << (Arity == 1? "ad" : "an"); break;
1639 // ::= de # * (unary)
1640 // ::= ml # * (binary or unknown)
1642 // Use binary when unknown.
1643 Out << (Arity == 1? "de" : "ml"); break;
1645 case OO_Tilde: Out << "co"; break;
1647 case OO_Slash: Out << "dv"; break;
1649 case OO_Percent: Out << "rm"; break;
1651 case OO_Pipe: Out << "or"; break;
1653 case OO_Caret: Out << "eo"; break;
1655 case OO_Equal: Out << "aS"; break;
1657 case OO_PlusEqual: Out << "pL"; break;
1659 case OO_MinusEqual: Out << "mI"; break;
1661 case OO_StarEqual: Out << "mL"; break;
1663 case OO_SlashEqual: Out << "dV"; break;
1665 case OO_PercentEqual: Out << "rM"; break;
1667 case OO_AmpEqual: Out << "aN"; break;
1669 case OO_PipeEqual: Out << "oR"; break;
1671 case OO_CaretEqual: Out << "eO"; break;
1673 case OO_LessLess: Out << "ls"; break;
1675 case OO_GreaterGreater: Out << "rs"; break;
1677 case OO_LessLessEqual: Out << "lS"; break;
1679 case OO_GreaterGreaterEqual: Out << "rS"; break;
1681 case OO_EqualEqual: Out << "eq"; break;
1683 case OO_ExclaimEqual: Out << "ne"; break;
1685 case OO_Less: Out << "lt"; break;
1687 case OO_Greater: Out << "gt"; break;
1689 case OO_LessEqual: Out << "le"; break;
1691 case OO_GreaterEqual: Out << "ge"; break;
1693 case OO_Exclaim: Out << "nt"; break;
1695 case OO_AmpAmp: Out << "aa"; break;
1697 case OO_PipePipe: Out << "oo"; break;
1699 case OO_PlusPlus: Out << "pp"; break;
1701 case OO_MinusMinus: Out << "mm"; break;
1703 case OO_Comma: Out << "cm"; break;
1705 case OO_ArrowStar: Out << "pm"; break;
1707 case OO_Arrow: Out << "pt"; break;
1709 case OO_Call: Out << "cl"; break;
1711 case OO_Subscript: Out << "ix"; break;
1714 // The conditional operator can't be overloaded, but we still handle it when
1715 // mangling expressions.
1716 case OO_Conditional: Out << "qu"; break;
1719 case NUM_OVERLOADED_OPERATORS:
1720 llvm_unreachable("Not an overloaded operator");
1724 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1725 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1726 if (Quals.hasRestrict())
1728 if (Quals.hasVolatile())
1730 if (Quals.hasConst())
1733 if (Quals.hasAddressSpace()) {
1734 // Address space extension:
1736 // <type> ::= U <target-addrspace>
1737 // <type> ::= U <OpenCL-addrspace>
1738 // <type> ::= U <CUDA-addrspace>
1740 SmallString<64> ASString;
1741 unsigned AS = Quals.getAddressSpace();
1743 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1744 // <target-addrspace> ::= "AS" <address-space-number>
1745 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1746 ASString = "AS" + llvm::utostr_32(TargetAS);
1749 default: llvm_unreachable("Not a language specific address space");
1750 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1751 case LangAS::opencl_global: ASString = "CLglobal"; break;
1752 case LangAS::opencl_local: ASString = "CLlocal"; break;
1753 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1754 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1755 case LangAS::cuda_device: ASString = "CUdevice"; break;
1756 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1757 case LangAS::cuda_shared: ASString = "CUshared"; break;
1760 Out << 'U' << ASString.size() << ASString;
1763 StringRef LifetimeName;
1764 switch (Quals.getObjCLifetime()) {
1765 // Objective-C ARC Extension:
1767 // <type> ::= U "__strong"
1768 // <type> ::= U "__weak"
1769 // <type> ::= U "__autoreleasing"
1770 case Qualifiers::OCL_None:
1773 case Qualifiers::OCL_Weak:
1774 LifetimeName = "__weak";
1777 case Qualifiers::OCL_Strong:
1778 LifetimeName = "__strong";
1781 case Qualifiers::OCL_Autoreleasing:
1782 LifetimeName = "__autoreleasing";
1785 case Qualifiers::OCL_ExplicitNone:
1786 // The __unsafe_unretained qualifier is *not* mangled, so that
1787 // __unsafe_unretained types in ARC produce the same manglings as the
1788 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1789 // better ABI compatibility.
1791 // It's safe to do this because unqualified 'id' won't show up
1792 // in any type signatures that need to be mangled.
1795 if (!LifetimeName.empty())
1796 Out << 'U' << LifetimeName.size() << LifetimeName;
1799 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1800 // <ref-qualifier> ::= R # lvalue reference
1801 // ::= O # rvalue-reference
1802 switch (RefQualifier) {
1816 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1817 Context.mangleObjCMethodName(MD, Out);
1820 void CXXNameMangler::mangleType(QualType T) {
1821 // If our type is instantiation-dependent but not dependent, we mangle
1822 // it as it was written in the source, removing any top-level sugar.
1823 // Otherwise, use the canonical type.
1825 // FIXME: This is an approximation of the instantiation-dependent name
1826 // mangling rules, since we should really be using the type as written and
1827 // augmented via semantic analysis (i.e., with implicit conversions and
1828 // default template arguments) for any instantiation-dependent type.
1829 // Unfortunately, that requires several changes to our AST:
1830 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1831 // uniqued, so that we can handle substitutions properly
1832 // - Default template arguments will need to be represented in the
1833 // TemplateSpecializationType, since they need to be mangled even though
1834 // they aren't written.
1835 // - Conversions on non-type template arguments need to be expressed, since
1836 // they can affect the mangling of sizeof/alignof.
1837 if (!T->isInstantiationDependentType() || T->isDependentType())
1838 T = T.getCanonicalType();
1840 // Desugar any types that are purely sugar.
1842 // Don't desugar through template specialization types that aren't
1843 // type aliases. We need to mangle the template arguments as written.
1844 if (const TemplateSpecializationType *TST
1845 = dyn_cast<TemplateSpecializationType>(T))
1846 if (!TST->isTypeAlias())
1850 = T.getSingleStepDesugaredType(Context.getASTContext());
1857 SplitQualType split = T.split();
1858 Qualifiers quals = split.Quals;
1859 const Type *ty = split.Ty;
1861 bool isSubstitutable = quals || !isa<BuiltinType>(T);
1862 if (isSubstitutable && mangleSubstitution(T))
1865 // If we're mangling a qualified array type, push the qualifiers to
1866 // the element type.
1867 if (quals && isa<ArrayType>(T)) {
1868 ty = Context.getASTContext().getAsArrayType(T);
1869 quals = Qualifiers();
1871 // Note that we don't update T: we want to add the
1872 // substitution at the original type.
1876 mangleQualifiers(quals);
1877 // Recurse: even if the qualified type isn't yet substitutable,
1878 // the unqualified type might be.
1879 mangleType(QualType(ty, 0));
1881 switch (ty->getTypeClass()) {
1882 #define ABSTRACT_TYPE(CLASS, PARENT)
1883 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1885 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1887 #define TYPE(CLASS, PARENT) \
1889 mangleType(static_cast<const CLASS##Type*>(ty)); \
1891 #include "clang/AST/TypeNodes.def"
1895 // Add the substitution.
1896 if (isSubstitutable)
1900 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1901 if (!mangleStandardSubstitution(ND))
1905 void CXXNameMangler::mangleType(const BuiltinType *T) {
1906 // <type> ::= <builtin-type>
1907 // <builtin-type> ::= v # void
1911 // ::= a # signed char
1912 // ::= h # unsigned char
1914 // ::= t # unsigned short
1916 // ::= j # unsigned int
1918 // ::= m # unsigned long
1919 // ::= x # long long, __int64
1920 // ::= y # unsigned long long, __int64
1922 // UNSUPPORTED: ::= o # unsigned __int128
1925 // ::= e # long double, __float80
1926 // UNSUPPORTED: ::= g # __float128
1927 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1928 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1929 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1930 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1931 // ::= Di # char32_t
1932 // ::= Ds # char16_t
1933 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1934 // ::= u <source-name> # vendor extended type
1935 switch (T->getKind()) {
1936 case BuiltinType::Void: Out << 'v'; break;
1937 case BuiltinType::Bool: Out << 'b'; break;
1938 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
1939 case BuiltinType::UChar: Out << 'h'; break;
1940 case BuiltinType::UShort: Out << 't'; break;
1941 case BuiltinType::UInt: Out << 'j'; break;
1942 case BuiltinType::ULong: Out << 'm'; break;
1943 case BuiltinType::ULongLong: Out << 'y'; break;
1944 case BuiltinType::UInt128: Out << 'o'; break;
1945 case BuiltinType::SChar: Out << 'a'; break;
1946 case BuiltinType::WChar_S:
1947 case BuiltinType::WChar_U: Out << 'w'; break;
1948 case BuiltinType::Char16: Out << "Ds"; break;
1949 case BuiltinType::Char32: Out << "Di"; break;
1950 case BuiltinType::Short: Out << 's'; break;
1951 case BuiltinType::Int: Out << 'i'; break;
1952 case BuiltinType::Long: Out << 'l'; break;
1953 case BuiltinType::LongLong: Out << 'x'; break;
1954 case BuiltinType::Int128: Out << 'n'; break;
1955 case BuiltinType::Half: Out << "Dh"; break;
1956 case BuiltinType::Float: Out << 'f'; break;
1957 case BuiltinType::Double: Out << 'd'; break;
1958 case BuiltinType::LongDouble: Out << 'e'; break;
1959 case BuiltinType::NullPtr: Out << "Dn"; break;
1961 #define BUILTIN_TYPE(Id, SingletonId)
1962 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1963 case BuiltinType::Id:
1964 #include "clang/AST/BuiltinTypes.def"
1965 case BuiltinType::Dependent:
1966 llvm_unreachable("mangling a placeholder type");
1967 case BuiltinType::ObjCId: Out << "11objc_object"; break;
1968 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
1969 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
1970 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
1971 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
1972 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
1973 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
1974 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
1975 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
1976 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
1977 case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
1981 // <type> ::= <function-type>
1982 // <function-type> ::= [<CV-qualifiers>] F [Y]
1983 // <bare-function-type> [<ref-qualifier>] E
1984 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
1985 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
1986 // e.g. "const" in "int (A::*)() const".
1987 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
1991 // FIXME: We don't have enough information in the AST to produce the 'Y'
1992 // encoding for extern "C" function types.
1993 mangleBareFunctionType(T, /*MangleReturnType=*/true);
1995 // Mangle the ref-qualifier, if present.
1996 mangleRefQualifier(T->getRefQualifier());
2000 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2001 llvm_unreachable("Can't mangle K&R function prototypes");
2003 void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
2004 bool MangleReturnType) {
2005 // We should never be mangling something without a prototype.
2006 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2008 // Record that we're in a function type. See mangleFunctionParam
2009 // for details on what we're trying to achieve here.
2010 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2012 // <bare-function-type> ::= <signature type>+
2013 if (MangleReturnType) {
2014 FunctionTypeDepth.enterResultType();
2015 mangleType(Proto->getResultType());
2016 FunctionTypeDepth.leaveResultType();
2019 if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
2020 // <builtin-type> ::= v # void
2023 FunctionTypeDepth.pop(saved);
2027 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2028 ArgEnd = Proto->arg_type_end();
2029 Arg != ArgEnd; ++Arg)
2030 mangleType(Context.getASTContext().getSignatureParameterType(*Arg));
2032 FunctionTypeDepth.pop(saved);
2034 // <builtin-type> ::= z # ellipsis
2035 if (Proto->isVariadic())
2039 // <type> ::= <class-enum-type>
2040 // <class-enum-type> ::= <name>
2041 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2042 mangleName(T->getDecl());
2045 // <type> ::= <class-enum-type>
2046 // <class-enum-type> ::= <name>
2047 void CXXNameMangler::mangleType(const EnumType *T) {
2048 mangleType(static_cast<const TagType*>(T));
2050 void CXXNameMangler::mangleType(const RecordType *T) {
2051 mangleType(static_cast<const TagType*>(T));
2053 void CXXNameMangler::mangleType(const TagType *T) {
2054 mangleName(T->getDecl());
2057 // <type> ::= <array-type>
2058 // <array-type> ::= A <positive dimension number> _ <element type>
2059 // ::= A [<dimension expression>] _ <element type>
2060 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2061 Out << 'A' << T->getSize() << '_';
2062 mangleType(T->getElementType());
2064 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2066 // decayed vla types (size 0) will just be skipped.
2067 if (T->getSizeExpr())
2068 mangleExpression(T->getSizeExpr());
2070 mangleType(T->getElementType());
2072 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2074 mangleExpression(T->getSizeExpr());
2076 mangleType(T->getElementType());
2078 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2080 mangleType(T->getElementType());
2083 // <type> ::= <pointer-to-member-type>
2084 // <pointer-to-member-type> ::= M <class type> <member type>
2085 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2087 mangleType(QualType(T->getClass(), 0));
2088 QualType PointeeType = T->getPointeeType();
2089 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2092 // Itanium C++ ABI 5.1.8:
2094 // The type of a non-static member function is considered to be different,
2095 // for the purposes of substitution, from the type of a namespace-scope or
2096 // static member function whose type appears similar. The types of two
2097 // non-static member functions are considered to be different, for the
2098 // purposes of substitution, if the functions are members of different
2099 // classes. In other words, for the purposes of substitution, the class of
2100 // which the function is a member is considered part of the type of
2103 // Given that we already substitute member function pointers as a
2104 // whole, the net effect of this rule is just to unconditionally
2105 // suppress substitution on the function type in a member pointer.
2106 // We increment the SeqID here to emulate adding an entry to the
2107 // substitution table.
2110 mangleType(PointeeType);
2113 // <type> ::= <template-param>
2114 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2115 mangleTemplateParameter(T->getIndex());
2118 // <type> ::= <template-param>
2119 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2120 // FIXME: not clear how to mangle this!
2121 // template <class T...> class A {
2122 // template <class U...> void foo(T(*)(U) x...);
2124 Out << "_SUBSTPACK_";
2127 // <type> ::= P <type> # pointer-to
2128 void CXXNameMangler::mangleType(const PointerType *T) {
2130 mangleType(T->getPointeeType());
2132 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2134 mangleType(T->getPointeeType());
2137 // <type> ::= R <type> # reference-to
2138 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2140 mangleType(T->getPointeeType());
2143 // <type> ::= O <type> # rvalue reference-to (C++0x)
2144 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2146 mangleType(T->getPointeeType());
2149 // <type> ::= C <type> # complex pair (C 2000)
2150 void CXXNameMangler::mangleType(const ComplexType *T) {
2152 mangleType(T->getElementType());
2155 // ARM's ABI for Neon vector types specifies that they should be mangled as
2156 // if they are structs (to match ARM's initial implementation). The
2157 // vector type must be one of the special types predefined by ARM.
2158 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2159 QualType EltType = T->getElementType();
2160 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2161 const char *EltName = 0;
2162 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2163 switch (cast<BuiltinType>(EltType)->getKind()) {
2164 case BuiltinType::SChar: EltName = "poly8_t"; break;
2165 case BuiltinType::Short: EltName = "poly16_t"; break;
2166 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2169 switch (cast<BuiltinType>(EltType)->getKind()) {
2170 case BuiltinType::SChar: EltName = "int8_t"; break;
2171 case BuiltinType::UChar: EltName = "uint8_t"; break;
2172 case BuiltinType::Short: EltName = "int16_t"; break;
2173 case BuiltinType::UShort: EltName = "uint16_t"; break;
2174 case BuiltinType::Int: EltName = "int32_t"; break;
2175 case BuiltinType::UInt: EltName = "uint32_t"; break;
2176 case BuiltinType::LongLong: EltName = "int64_t"; break;
2177 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2178 case BuiltinType::Float: EltName = "float32_t"; break;
2179 case BuiltinType::Half: EltName = "float16_t";break;
2181 llvm_unreachable("unexpected Neon vector element type");
2184 const char *BaseName = 0;
2185 unsigned BitSize = (T->getNumElements() *
2186 getASTContext().getTypeSize(EltType));
2188 BaseName = "__simd64_";
2190 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2191 BaseName = "__simd128_";
2193 Out << strlen(BaseName) + strlen(EltName);
2194 Out << BaseName << EltName;
2197 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2198 switch (EltType->getKind()) {
2199 case BuiltinType::SChar:
2201 case BuiltinType::Short:
2203 case BuiltinType::Int:
2205 case BuiltinType::LongLong:
2207 case BuiltinType::UChar:
2209 case BuiltinType::UShort:
2211 case BuiltinType::UInt:
2213 case BuiltinType::ULongLong:
2215 case BuiltinType::Half:
2217 case BuiltinType::Float:
2219 case BuiltinType::Double:
2222 llvm_unreachable("Unexpected vector element base type");
2226 // AArch64's ABI for Neon vector types specifies that they should be mangled as
2227 // the equivalent internal name. The vector type must be one of the special
2228 // types predefined by ARM.
2229 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2230 QualType EltType = T->getElementType();
2231 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2233 (T->getNumElements() * getASTContext().getTypeSize(EltType));
2234 (void)BitSize; // Silence warning.
2236 assert((BitSize == 64 || BitSize == 128) &&
2237 "Neon vector type not 64 or 128 bits");
2240 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2241 switch (cast<BuiltinType>(EltType)->getKind()) {
2242 case BuiltinType::UChar:
2245 case BuiltinType::UShort:
2248 case BuiltinType::ULongLong:
2252 llvm_unreachable("unexpected Neon polynomial vector element type");
2255 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2257 std::string TypeName =
2258 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
2259 Out << TypeName.length() << TypeName;
2262 // GNU extension: vector types
2263 // <type> ::= <vector-type>
2264 // <vector-type> ::= Dv <positive dimension number> _
2265 // <extended element type>
2266 // ::= Dv [<dimension expression>] _ <element type>
2267 // <extended element type> ::= <element type>
2268 // ::= p # AltiVec vector pixel
2269 // ::= b # Altivec vector bool
2270 void CXXNameMangler::mangleType(const VectorType *T) {
2271 if ((T->getVectorKind() == VectorType::NeonVector ||
2272 T->getVectorKind() == VectorType::NeonPolyVector)) {
2273 if (getASTContext().getTargetInfo().getTriple().getArch() ==
2274 llvm::Triple::aarch64)
2275 mangleAArch64NeonVectorType(T);
2277 mangleNeonVectorType(T);
2280 Out << "Dv" << T->getNumElements() << '_';
2281 if (T->getVectorKind() == VectorType::AltiVecPixel)
2283 else if (T->getVectorKind() == VectorType::AltiVecBool)
2286 mangleType(T->getElementType());
2288 void CXXNameMangler::mangleType(const ExtVectorType *T) {
2289 mangleType(static_cast<const VectorType*>(T));
2291 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2293 mangleExpression(T->getSizeExpr());
2295 mangleType(T->getElementType());
2298 void CXXNameMangler::mangleType(const PackExpansionType *T) {
2299 // <type> ::= Dp <type> # pack expansion (C++0x)
2301 mangleType(T->getPattern());
2304 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2305 mangleSourceName(T->getDecl()->getIdentifier());
2308 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2309 if (!T->qual_empty()) {
2310 // Mangle protocol qualifiers.
2311 SmallString<64> QualStr;
2312 llvm::raw_svector_ostream QualOS(QualStr);
2313 QualOS << "objcproto";
2314 ObjCObjectType::qual_iterator i = T->qual_begin(), e = T->qual_end();
2315 for ( ; i != e; ++i) {
2316 StringRef name = (*i)->getName();
2317 QualOS << name.size() << name;
2320 Out << 'U' << QualStr.size() << QualStr;
2322 mangleType(T->getBaseType());
2325 void CXXNameMangler::mangleType(const BlockPointerType *T) {
2326 Out << "U13block_pointer";
2327 mangleType(T->getPointeeType());
2330 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2331 // Mangle injected class name types as if the user had written the
2332 // specialization out fully. It may not actually be possible to see
2333 // this mangling, though.
2334 mangleType(T->getInjectedSpecializationType());
2337 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2338 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2339 mangleName(TD, T->getArgs(), T->getNumArgs());
2341 if (mangleSubstitution(QualType(T, 0)))
2344 mangleTemplatePrefix(T->getTemplateName());
2346 // FIXME: GCC does not appear to mangle the template arguments when
2347 // the template in question is a dependent template name. Should we
2348 // emulate that badness?
2349 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2350 addSubstitution(QualType(T, 0));
2354 void CXXNameMangler::mangleType(const DependentNameType *T) {
2355 // Typename types are always nested
2357 manglePrefix(T->getQualifier());
2358 mangleSourceName(T->getIdentifier());
2362 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2363 // Dependently-scoped template types are nested if they have a prefix.
2366 // TODO: avoid making this TemplateName.
2367 TemplateName Prefix =
2368 getASTContext().getDependentTemplateName(T->getQualifier(),
2369 T->getIdentifier());
2370 mangleTemplatePrefix(Prefix);
2372 // FIXME: GCC does not appear to mangle the template arguments when
2373 // the template in question is a dependent template name. Should we
2374 // emulate that badness?
2375 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2379 void CXXNameMangler::mangleType(const TypeOfType *T) {
2380 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2381 // "extension with parameters" mangling.
2385 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2386 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2387 // "extension with parameters" mangling.
2391 void CXXNameMangler::mangleType(const DecltypeType *T) {
2392 Expr *E = T->getUnderlyingExpr();
2394 // type ::= Dt <expression> E # decltype of an id-expression
2395 // # or class member access
2396 // ::= DT <expression> E # decltype of an expression
2398 // This purports to be an exhaustive list of id-expressions and
2399 // class member accesses. Note that we do not ignore parentheses;
2400 // parentheses change the semantics of decltype for these
2401 // expressions (and cause the mangler to use the other form).
2402 if (isa<DeclRefExpr>(E) ||
2403 isa<MemberExpr>(E) ||
2404 isa<UnresolvedLookupExpr>(E) ||
2405 isa<DependentScopeDeclRefExpr>(E) ||
2406 isa<CXXDependentScopeMemberExpr>(E) ||
2407 isa<UnresolvedMemberExpr>(E))
2411 mangleExpression(E);
2415 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2416 // If this is dependent, we need to record that. If not, we simply
2417 // mangle it as the underlying type since they are equivalent.
2418 if (T->isDependentType()) {
2421 switch (T->getUTTKind()) {
2422 case UnaryTransformType::EnumUnderlyingType:
2428 mangleType(T->getUnderlyingType());
2431 void CXXNameMangler::mangleType(const AutoType *T) {
2432 QualType D = T->getDeducedType();
2433 // <builtin-type> ::= Da # dependent auto
2435 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
2440 void CXXNameMangler::mangleType(const AtomicType *T) {
2441 // <type> ::= U <source-name> <type> # vendor extended type qualifier
2442 // (Until there's a standardized mangling...)
2444 mangleType(T->getValueType());
2447 void CXXNameMangler::mangleIntegerLiteral(QualType T,
2448 const llvm::APSInt &Value) {
2449 // <expr-primary> ::= L <type> <value number> E # integer literal
2453 if (T->isBooleanType()) {
2454 // Boolean values are encoded as 0/1.
2455 Out << (Value.getBoolValue() ? '1' : '0');
2457 mangleNumber(Value);
2463 /// Mangles a member expression.
2464 void CXXNameMangler::mangleMemberExpr(const Expr *base,
2466 NestedNameSpecifier *qualifier,
2467 NamedDecl *firstQualifierLookup,
2468 DeclarationName member,
2470 // <expression> ::= dt <expression> <unresolved-name>
2471 // ::= pt <expression> <unresolved-name>
2473 if (base->isImplicitCXXThis()) {
2474 // Note: GCC mangles member expressions to the implicit 'this' as
2475 // *this., whereas we represent them as this->. The Itanium C++ ABI
2476 // does not specify anything here, so we follow GCC.
2479 Out << (isArrow ? "pt" : "dt");
2480 mangleExpression(base);
2483 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
2486 /// Look at the callee of the given call expression and determine if
2487 /// it's a parenthesized id-expression which would have triggered ADL
2489 static bool isParenthesizedADLCallee(const CallExpr *call) {
2490 const Expr *callee = call->getCallee();
2491 const Expr *fn = callee->IgnoreParens();
2493 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2494 // too, but for those to appear in the callee, it would have to be
2496 if (callee == fn) return false;
2498 // Must be an unresolved lookup.
2499 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2500 if (!lookup) return false;
2502 assert(!lookup->requiresADL());
2504 // Must be an unqualified lookup.
2505 if (lookup->getQualifier()) return false;
2507 // Must not have found a class member. Note that if one is a class
2508 // member, they're all class members.
2509 if (lookup->getNumDecls() > 0 &&
2510 (*lookup->decls_begin())->isCXXClassMember())
2513 // Otherwise, ADL would have been triggered.
2517 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2518 // <expression> ::= <unary operator-name> <expression>
2519 // ::= <binary operator-name> <expression> <expression>
2520 // ::= <trinary operator-name> <expression> <expression> <expression>
2521 // ::= cv <type> expression # conversion with one argument
2522 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2523 // ::= st <type> # sizeof (a type)
2524 // ::= at <type> # alignof (a type)
2525 // ::= <template-param>
2526 // ::= <function-param>
2527 // ::= sr <type> <unqualified-name> # dependent name
2528 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2529 // ::= ds <expression> <expression> # expr.*expr
2530 // ::= sZ <template-param> # size of a parameter pack
2531 // ::= sZ <function-param> # size of a function parameter pack
2532 // ::= <expr-primary>
2533 // <expr-primary> ::= L <type> <value number> E # integer literal
2534 // ::= L <type <value float> E # floating literal
2535 // ::= L <mangled-name> E # external name
2536 // ::= fpT # 'this' expression
2537 QualType ImplicitlyConvertedToType;
2540 switch (E->getStmtClass()) {
2541 case Expr::NoStmtClass:
2542 #define ABSTRACT_STMT(Type)
2543 #define EXPR(Type, Base)
2544 #define STMT(Type, Base) \
2545 case Expr::Type##Class:
2546 #include "clang/AST/StmtNodes.inc"
2549 // These all can only appear in local or variable-initialization
2550 // contexts and so should never appear in a mangling.
2551 case Expr::AddrLabelExprClass:
2552 case Expr::DesignatedInitExprClass:
2553 case Expr::ImplicitValueInitExprClass:
2554 case Expr::ParenListExprClass:
2555 case Expr::LambdaExprClass:
2556 case Expr::MSPropertyRefExprClass:
2557 llvm_unreachable("unexpected statement kind");
2559 // FIXME: invent manglings for all these.
2560 case Expr::BlockExprClass:
2561 case Expr::CXXPseudoDestructorExprClass:
2562 case Expr::ChooseExprClass:
2563 case Expr::CompoundLiteralExprClass:
2564 case Expr::ExtVectorElementExprClass:
2565 case Expr::GenericSelectionExprClass:
2566 case Expr::ObjCEncodeExprClass:
2567 case Expr::ObjCIsaExprClass:
2568 case Expr::ObjCIvarRefExprClass:
2569 case Expr::ObjCMessageExprClass:
2570 case Expr::ObjCPropertyRefExprClass:
2571 case Expr::ObjCProtocolExprClass:
2572 case Expr::ObjCSelectorExprClass:
2573 case Expr::ObjCStringLiteralClass:
2574 case Expr::ObjCBoxedExprClass:
2575 case Expr::ObjCArrayLiteralClass:
2576 case Expr::ObjCDictionaryLiteralClass:
2577 case Expr::ObjCSubscriptRefExprClass:
2578 case Expr::ObjCIndirectCopyRestoreExprClass:
2579 case Expr::OffsetOfExprClass:
2580 case Expr::PredefinedExprClass:
2581 case Expr::ShuffleVectorExprClass:
2582 case Expr::ConvertVectorExprClass:
2583 case Expr::StmtExprClass:
2584 case Expr::UnaryTypeTraitExprClass:
2585 case Expr::BinaryTypeTraitExprClass:
2586 case Expr::TypeTraitExprClass:
2587 case Expr::ArrayTypeTraitExprClass:
2588 case Expr::ExpressionTraitExprClass:
2589 case Expr::VAArgExprClass:
2590 case Expr::CXXUuidofExprClass:
2591 case Expr::CUDAKernelCallExprClass:
2592 case Expr::AsTypeExprClass:
2593 case Expr::PseudoObjectExprClass:
2594 case Expr::AtomicExprClass:
2596 // As bad as this diagnostic is, it's better than crashing.
2597 DiagnosticsEngine &Diags = Context.getDiags();
2598 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2599 "cannot yet mangle expression type %0");
2600 Diags.Report(E->getExprLoc(), DiagID)
2601 << E->getStmtClassName() << E->getSourceRange();
2605 // Even gcc-4.5 doesn't mangle this.
2606 case Expr::BinaryConditionalOperatorClass: {
2607 DiagnosticsEngine &Diags = Context.getDiags();
2609 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2610 "?: operator with omitted middle operand cannot be mangled");
2611 Diags.Report(E->getExprLoc(), DiagID)
2612 << E->getStmtClassName() << E->getSourceRange();
2616 // These are used for internal purposes and cannot be meaningfully mangled.
2617 case Expr::OpaqueValueExprClass:
2618 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2620 case Expr::InitListExprClass: {
2621 // Proposal by Jason Merrill, 2012-01-03
2623 const InitListExpr *InitList = cast<InitListExpr>(E);
2624 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2625 mangleExpression(InitList->getInit(i));
2630 case Expr::CXXDefaultArgExprClass:
2631 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2634 case Expr::CXXDefaultInitExprClass:
2635 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2638 case Expr::CXXStdInitializerListExprClass:
2639 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2642 case Expr::SubstNonTypeTemplateParmExprClass:
2643 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2647 case Expr::UserDefinedLiteralClass:
2648 // We follow g++'s approach of mangling a UDL as a call to the literal
2650 case Expr::CXXMemberCallExprClass: // fallthrough
2651 case Expr::CallExprClass: {
2652 const CallExpr *CE = cast<CallExpr>(E);
2654 // <expression> ::= cp <simple-id> <expression>* E
2655 // We use this mangling only when the call would use ADL except
2656 // for being parenthesized. Per discussion with David
2657 // Vandervoorde, 2011.04.25.
2658 if (isParenthesizedADLCallee(CE)) {
2660 // The callee here is a parenthesized UnresolvedLookupExpr with
2661 // no qualifier and should always get mangled as a <simple-id>
2664 // <expression> ::= cl <expression>* E
2669 mangleExpression(CE->getCallee(), CE->getNumArgs());
2670 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
2671 mangleExpression(CE->getArg(I));
2676 case Expr::CXXNewExprClass: {
2677 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2678 if (New->isGlobalNew()) Out << "gs";
2679 Out << (New->isArray() ? "na" : "nw");
2680 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2681 E = New->placement_arg_end(); I != E; ++I)
2682 mangleExpression(*I);
2684 mangleType(New->getAllocatedType());
2685 if (New->hasInitializer()) {
2686 // Proposal by Jason Merrill, 2012-01-03
2687 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2691 const Expr *Init = New->getInitializer();
2692 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2693 // Directly inline the initializers.
2694 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2697 mangleExpression(*I);
2698 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2699 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2700 mangleExpression(PLE->getExpr(i));
2701 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2702 isa<InitListExpr>(Init)) {
2703 // Only take InitListExprs apart for list-initialization.
2704 const InitListExpr *InitList = cast<InitListExpr>(Init);
2705 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2706 mangleExpression(InitList->getInit(i));
2708 mangleExpression(Init);
2714 case Expr::MemberExprClass: {
2715 const MemberExpr *ME = cast<MemberExpr>(E);
2716 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2717 ME->getQualifier(), 0, ME->getMemberDecl()->getDeclName(),
2722 case Expr::UnresolvedMemberExprClass: {
2723 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2724 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2725 ME->getQualifier(), 0, ME->getMemberName(),
2727 if (ME->hasExplicitTemplateArgs())
2728 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2732 case Expr::CXXDependentScopeMemberExprClass: {
2733 const CXXDependentScopeMemberExpr *ME
2734 = cast<CXXDependentScopeMemberExpr>(E);
2735 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2736 ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
2737 ME->getMember(), Arity);
2738 if (ME->hasExplicitTemplateArgs())
2739 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2743 case Expr::UnresolvedLookupExprClass: {
2744 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
2745 mangleUnresolvedName(ULE->getQualifier(), 0, ULE->getName(), Arity);
2747 // All the <unresolved-name> productions end in a
2748 // base-unresolved-name, where <template-args> are just tacked
2750 if (ULE->hasExplicitTemplateArgs())
2751 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2755 case Expr::CXXUnresolvedConstructExprClass: {
2756 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2757 unsigned N = CE->arg_size();
2760 mangleType(CE->getType());
2761 if (N != 1) Out << '_';
2762 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2763 if (N != 1) Out << 'E';
2767 case Expr::CXXTemporaryObjectExprClass:
2768 case Expr::CXXConstructExprClass: {
2769 const CXXConstructExpr *CE = cast<CXXConstructExpr>(E);
2770 unsigned N = CE->getNumArgs();
2772 // Proposal by Jason Merrill, 2012-01-03
2773 if (CE->isListInitialization())
2777 mangleType(CE->getType());
2778 if (N != 1) Out << '_';
2779 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2780 if (N != 1) Out << 'E';
2784 case Expr::CXXScalarValueInitExprClass:
2786 mangleType(E->getType());
2790 case Expr::CXXNoexceptExprClass:
2792 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
2795 case Expr::UnaryExprOrTypeTraitExprClass: {
2796 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
2798 if (!SAE->isInstantiationDependent()) {
2800 // If the operand of a sizeof or alignof operator is not
2801 // instantiation-dependent it is encoded as an integer literal
2802 // reflecting the result of the operator.
2804 // If the result of the operator is implicitly converted to a known
2805 // integer type, that type is used for the literal; otherwise, the type
2806 // of std::size_t or std::ptrdiff_t is used.
2807 QualType T = (ImplicitlyConvertedToType.isNull() ||
2808 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
2809 : ImplicitlyConvertedToType;
2810 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
2811 mangleIntegerLiteral(T, V);
2815 switch(SAE->getKind()) {
2823 DiagnosticsEngine &Diags = Context.getDiags();
2824 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2825 "cannot yet mangle vec_step expression");
2826 Diags.Report(DiagID);
2829 if (SAE->isArgumentType()) {
2831 mangleType(SAE->getArgumentType());
2834 mangleExpression(SAE->getArgumentExpr());
2839 case Expr::CXXThrowExprClass: {
2840 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
2841 // <expression> ::= tw <expression> # throw expression
2843 if (TE->getSubExpr()) {
2845 mangleExpression(TE->getSubExpr());
2852 case Expr::CXXTypeidExprClass: {
2853 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
2854 // <expression> ::= ti <type> # typeid (type)
2855 // ::= te <expression> # typeid (expression)
2856 if (TIE->isTypeOperand()) {
2858 mangleType(TIE->getTypeOperand(Context.getASTContext()));
2861 mangleExpression(TIE->getExprOperand());
2866 case Expr::CXXDeleteExprClass: {
2867 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
2868 // <expression> ::= [gs] dl <expression> # [::] delete expr
2869 // ::= [gs] da <expression> # [::] delete [] expr
2870 if (DE->isGlobalDelete()) Out << "gs";
2871 Out << (DE->isArrayForm() ? "da" : "dl");
2872 mangleExpression(DE->getArgument());
2876 case Expr::UnaryOperatorClass: {
2877 const UnaryOperator *UO = cast<UnaryOperator>(E);
2878 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
2880 mangleExpression(UO->getSubExpr());
2884 case Expr::ArraySubscriptExprClass: {
2885 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
2887 // Array subscript is treated as a syntactically weird form of
2890 mangleExpression(AE->getLHS());
2891 mangleExpression(AE->getRHS());
2895 case Expr::CompoundAssignOperatorClass: // fallthrough
2896 case Expr::BinaryOperatorClass: {
2897 const BinaryOperator *BO = cast<BinaryOperator>(E);
2898 if (BO->getOpcode() == BO_PtrMemD)
2901 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
2903 mangleExpression(BO->getLHS());
2904 mangleExpression(BO->getRHS());
2908 case Expr::ConditionalOperatorClass: {
2909 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
2910 mangleOperatorName(OO_Conditional, /*Arity=*/3);
2911 mangleExpression(CO->getCond());
2912 mangleExpression(CO->getLHS(), Arity);
2913 mangleExpression(CO->getRHS(), Arity);
2917 case Expr::ImplicitCastExprClass: {
2918 ImplicitlyConvertedToType = E->getType();
2919 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2923 case Expr::ObjCBridgedCastExprClass: {
2924 // Mangle ownership casts as a vendor extended operator __bridge,
2925 // __bridge_transfer, or __bridge_retain.
2926 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
2927 Out << "v1U" << Kind.size() << Kind;
2929 // Fall through to mangle the cast itself.
2931 case Expr::CStyleCastExprClass:
2932 case Expr::CXXStaticCastExprClass:
2933 case Expr::CXXDynamicCastExprClass:
2934 case Expr::CXXReinterpretCastExprClass:
2935 case Expr::CXXConstCastExprClass:
2936 case Expr::CXXFunctionalCastExprClass: {
2937 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2939 mangleType(ECE->getType());
2940 mangleExpression(ECE->getSubExpr());
2944 case Expr::CXXOperatorCallExprClass: {
2945 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
2946 unsigned NumArgs = CE->getNumArgs();
2947 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
2948 // Mangle the arguments.
2949 for (unsigned i = 0; i != NumArgs; ++i)
2950 mangleExpression(CE->getArg(i));
2954 case Expr::ParenExprClass:
2955 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
2958 case Expr::DeclRefExprClass: {
2959 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2961 switch (D->getKind()) {
2963 // <expr-primary> ::= L <mangled-name> E # external name
2970 mangleFunctionParam(cast<ParmVarDecl>(D));
2973 case Decl::EnumConstant: {
2974 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
2975 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
2979 case Decl::NonTypeTemplateParm: {
2980 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
2981 mangleTemplateParameter(PD->getIndex());
2990 case Expr::SubstNonTypeTemplateParmPackExprClass:
2991 // FIXME: not clear how to mangle this!
2992 // template <unsigned N...> class A {
2993 // template <class U...> void foo(U (&x)[N]...);
2995 Out << "_SUBSTPACK_";
2998 case Expr::FunctionParmPackExprClass: {
2999 // FIXME: not clear how to mangle this!
3000 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3001 Out << "v110_SUBSTPACK";
3002 mangleFunctionParam(FPPE->getParameterPack());
3006 case Expr::DependentScopeDeclRefExprClass: {
3007 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
3008 mangleUnresolvedName(DRE->getQualifier(), 0, DRE->getDeclName(), Arity);
3010 // All the <unresolved-name> productions end in a
3011 // base-unresolved-name, where <template-args> are just tacked
3013 if (DRE->hasExplicitTemplateArgs())
3014 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
3018 case Expr::CXXBindTemporaryExprClass:
3019 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3022 case Expr::ExprWithCleanupsClass:
3023 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3026 case Expr::FloatingLiteralClass: {
3027 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3029 mangleType(FL->getType());
3030 mangleFloat(FL->getValue());
3035 case Expr::CharacterLiteralClass:
3037 mangleType(E->getType());
3038 Out << cast<CharacterLiteral>(E)->getValue();
3042 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3043 case Expr::ObjCBoolLiteralExprClass:
3045 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3049 case Expr::CXXBoolLiteralExprClass:
3051 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3055 case Expr::IntegerLiteralClass: {
3056 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3057 if (E->getType()->isSignedIntegerType())
3058 Value.setIsSigned(true);
3059 mangleIntegerLiteral(E->getType(), Value);
3063 case Expr::ImaginaryLiteralClass: {
3064 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3065 // Mangle as if a complex literal.
3066 // Proposal from David Vandevoorde, 2010.06.30.
3068 mangleType(E->getType());
3069 if (const FloatingLiteral *Imag =
3070 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3071 // Mangle a floating-point zero of the appropriate type.
3072 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3074 mangleFloat(Imag->getValue());
3077 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3078 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3079 Value.setIsSigned(true);
3080 mangleNumber(Value);
3086 case Expr::StringLiteralClass: {
3087 // Revised proposal from David Vandervoorde, 2010.07.15.
3089 assert(isa<ConstantArrayType>(E->getType()));
3090 mangleType(E->getType());
3095 case Expr::GNUNullExprClass:
3096 // FIXME: should this really be mangled the same as nullptr?
3099 case Expr::CXXNullPtrLiteralExprClass: {
3104 case Expr::PackExpansionExprClass:
3106 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3109 case Expr::SizeOfPackExprClass: {
3111 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
3112 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3113 mangleTemplateParameter(TTP->getIndex());
3114 else if (const NonTypeTemplateParmDecl *NTTP
3115 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3116 mangleTemplateParameter(NTTP->getIndex());
3117 else if (const TemplateTemplateParmDecl *TempTP
3118 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3119 mangleTemplateParameter(TempTP->getIndex());
3121 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3125 case Expr::MaterializeTemporaryExprClass: {
3126 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3130 case Expr::CXXThisExprClass:
3136 /// Mangle an expression which refers to a parameter variable.
3138 /// <expression> ::= <function-param>
3139 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3140 /// <function-param> ::= fp <top-level CV-qualifiers>
3141 /// <parameter-2 non-negative number> _ # L == 0, I > 0
3142 /// <function-param> ::= fL <L-1 non-negative number>
3143 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
3144 /// <function-param> ::= fL <L-1 non-negative number>
3145 /// p <top-level CV-qualifiers>
3146 /// <I-1 non-negative number> _ # L > 0, I > 0
3148 /// L is the nesting depth of the parameter, defined as 1 if the
3149 /// parameter comes from the innermost function prototype scope
3150 /// enclosing the current context, 2 if from the next enclosing
3151 /// function prototype scope, and so on, with one special case: if
3152 /// we've processed the full parameter clause for the innermost
3153 /// function type, then L is one less. This definition conveniently
3154 /// makes it irrelevant whether a function's result type was written
3155 /// trailing or leading, but is otherwise overly complicated; the
3156 /// numbering was first designed without considering references to
3157 /// parameter in locations other than return types, and then the
3158 /// mangling had to be generalized without changing the existing
3161 /// I is the zero-based index of the parameter within its parameter
3162 /// declaration clause. Note that the original ABI document describes
3163 /// this using 1-based ordinals.
3164 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3165 unsigned parmDepth = parm->getFunctionScopeDepth();
3166 unsigned parmIndex = parm->getFunctionScopeIndex();
3169 // parmDepth does not include the declaring function prototype.
3170 // FunctionTypeDepth does account for that.
3171 assert(parmDepth < FunctionTypeDepth.getDepth());
3172 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3173 if (FunctionTypeDepth.isInResultType())
3176 if (nestingDepth == 0) {
3179 Out << "fL" << (nestingDepth - 1) << 'p';
3182 // Top-level qualifiers. We don't have to worry about arrays here,
3183 // because parameters declared as arrays should already have been
3184 // transformed to have pointer type. FIXME: apparently these don't
3185 // get mangled if used as an rvalue of a known non-class type?
3186 assert(!parm->getType()->isArrayType()
3187 && "parameter's type is still an array type?");
3188 mangleQualifiers(parm->getType().getQualifiers());
3191 if (parmIndex != 0) {
3192 Out << (parmIndex - 1);
3197 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3198 // <ctor-dtor-name> ::= C1 # complete object constructor
3199 // ::= C2 # base object constructor
3200 // ::= C3 # complete object allocating constructor
3209 case Ctor_CompleteAllocating:
3215 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3216 // <ctor-dtor-name> ::= D0 # deleting destructor
3217 // ::= D1 # complete object destructor
3218 // ::= D2 # base object destructor
3233 void CXXNameMangler::mangleTemplateArgs(
3234 const ASTTemplateArgumentListInfo &TemplateArgs) {
3235 // <template-args> ::= I <template-arg>+ E
3237 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3238 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3242 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3243 // <template-args> ::= I <template-arg>+ E
3245 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3246 mangleTemplateArg(AL[i]);
3250 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3251 unsigned NumTemplateArgs) {
3252 // <template-args> ::= I <template-arg>+ E
3254 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3255 mangleTemplateArg(TemplateArgs[i]);
3259 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3260 // <template-arg> ::= <type> # type or template
3261 // ::= X <expression> E # expression
3262 // ::= <expr-primary> # simple expressions
3263 // ::= J <template-arg>* E # argument pack
3264 if (!A.isInstantiationDependent() || A.isDependent())
3265 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3267 switch (A.getKind()) {
3268 case TemplateArgument::Null:
3269 llvm_unreachable("Cannot mangle NULL template argument");
3271 case TemplateArgument::Type:
3272 mangleType(A.getAsType());
3274 case TemplateArgument::Template:
3275 // This is mangled as <type>.
3276 mangleType(A.getAsTemplate());
3278 case TemplateArgument::TemplateExpansion:
3279 // <type> ::= Dp <type> # pack expansion (C++0x)
3281 mangleType(A.getAsTemplateOrTemplatePattern());
3283 case TemplateArgument::Expression: {
3284 // It's possible to end up with a DeclRefExpr here in certain
3285 // dependent cases, in which case we should mangle as a
3287 const Expr *E = A.getAsExpr()->IgnoreParens();
3288 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3289 const ValueDecl *D = DRE->getDecl();
3290 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3299 mangleExpression(E);
3303 case TemplateArgument::Integral:
3304 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3306 case TemplateArgument::Declaration: {
3307 // <expr-primary> ::= L <mangled-name> E # external name
3308 // Clang produces AST's where pointer-to-member-function expressions
3309 // and pointer-to-function expressions are represented as a declaration not
3310 // an expression. We compensate for it here to produce the correct mangling.
3311 ValueDecl *D = A.getAsDecl();
3312 bool compensateMangling = !A.isDeclForReferenceParam();
3313 if (compensateMangling) {
3315 mangleOperatorName(OO_Amp, 1);
3319 // References to external entities use the mangled name; if the name would
3320 // not normally be manged then mangle it as unqualified.
3322 // FIXME: The ABI specifies that external names here should have _Z, but
3323 // gcc leaves this off.
3324 if (compensateMangling)
3330 if (compensateMangling)
3335 case TemplateArgument::NullPtr: {
3336 // <expr-primary> ::= L <type> 0 E
3338 mangleType(A.getNullPtrType());
3342 case TemplateArgument::Pack: {
3343 // <template-arg> ::= J <template-arg>* E
3345 for (TemplateArgument::pack_iterator PA = A.pack_begin(),
3346 PAEnd = A.pack_end();
3348 mangleTemplateArg(*PA);
3354 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3355 // <template-param> ::= T_ # first template parameter
3356 // ::= T <parameter-2 non-negative number> _
3360 Out << 'T' << (Index - 1) << '_';
3363 void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3364 bool result = mangleSubstitution(type);
3365 assert(result && "no existing substitution for type");
3369 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3370 bool result = mangleSubstitution(tname);
3371 assert(result && "no existing substitution for template name");
3375 // <substitution> ::= S <seq-id> _
3377 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3378 // Try one of the standard substitutions first.
3379 if (mangleStandardSubstitution(ND))
3382 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3383 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3386 /// \brief Determine whether the given type has any qualifiers that are
3387 /// relevant for substitutions.
3388 static bool hasMangledSubstitutionQualifiers(QualType T) {
3389 Qualifiers Qs = T.getQualifiers();
3390 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3393 bool CXXNameMangler::mangleSubstitution(QualType T) {
3394 if (!hasMangledSubstitutionQualifiers(T)) {
3395 if (const RecordType *RT = T->getAs<RecordType>())
3396 return mangleSubstitution(RT->getDecl());
3399 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3401 return mangleSubstitution(TypePtr);
3404 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3405 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3406 return mangleSubstitution(TD);
3408 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3409 return mangleSubstitution(
3410 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3413 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3414 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3415 if (I == Substitutions.end())
3418 unsigned SeqID = I->second;
3424 // <seq-id> is encoded in base-36, using digits and upper case letters.
3426 char *BufferPtr = llvm::array_endof(Buffer);
3428 if (SeqID == 0) *--BufferPtr = '0';
3431 assert(BufferPtr > Buffer && "Buffer overflow!");
3433 char c = static_cast<char>(SeqID % 36);
3435 *--BufferPtr = (c < 10 ? '0' + c : 'A' + c - 10);
3440 << StringRef(BufferPtr, llvm::array_endof(Buffer)-BufferPtr)
3447 static bool isCharType(QualType T) {
3451 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3452 T->isSpecificBuiltinType(BuiltinType::Char_U);
3455 /// isCharSpecialization - Returns whether a given type is a template
3456 /// specialization of a given name with a single argument of type char.
3457 static bool isCharSpecialization(QualType T, const char *Name) {
3461 const RecordType *RT = T->getAs<RecordType>();
3465 const ClassTemplateSpecializationDecl *SD =
3466 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3470 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3473 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3474 if (TemplateArgs.size() != 1)
3477 if (!isCharType(TemplateArgs[0].getAsType()))
3480 return SD->getIdentifier()->getName() == Name;
3483 template <std::size_t StrLen>
3484 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3485 const char (&Str)[StrLen]) {
3486 if (!SD->getIdentifier()->isStr(Str))
3489 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3490 if (TemplateArgs.size() != 2)
3493 if (!isCharType(TemplateArgs[0].getAsType()))
3496 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3502 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3503 // <substitution> ::= St # ::std::
3504 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3511 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3512 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3515 // <substitution> ::= Sa # ::std::allocator
3516 if (TD->getIdentifier()->isStr("allocator")) {
3521 // <<substitution> ::= Sb # ::std::basic_string
3522 if (TD->getIdentifier()->isStr("basic_string")) {
3528 if (const ClassTemplateSpecializationDecl *SD =
3529 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3530 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3533 // <substitution> ::= Ss # ::std::basic_string<char,
3534 // ::std::char_traits<char>,
3535 // ::std::allocator<char> >
3536 if (SD->getIdentifier()->isStr("basic_string")) {
3537 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3539 if (TemplateArgs.size() != 3)
3542 if (!isCharType(TemplateArgs[0].getAsType()))
3545 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3548 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3555 // <substitution> ::= Si # ::std::basic_istream<char,
3556 // ::std::char_traits<char> >
3557 if (isStreamCharSpecialization(SD, "basic_istream")) {
3562 // <substitution> ::= So # ::std::basic_ostream<char,
3563 // ::std::char_traits<char> >
3564 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3569 // <substitution> ::= Sd # ::std::basic_iostream<char,
3570 // ::std::char_traits<char> >
3571 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3579 void CXXNameMangler::addSubstitution(QualType T) {
3580 if (!hasMangledSubstitutionQualifiers(T)) {
3581 if (const RecordType *RT = T->getAs<RecordType>()) {
3582 addSubstitution(RT->getDecl());
3587 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3588 addSubstitution(TypePtr);
3591 void CXXNameMangler::addSubstitution(TemplateName Template) {
3592 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3593 return addSubstitution(TD);
3595 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3596 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3599 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3600 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3601 Substitutions[Ptr] = SeqID++;
3606 /// \brief Mangles the name of the declaration D and emits that name to the
3607 /// given output stream.
3609 /// If the declaration D requires a mangled name, this routine will emit that
3610 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3611 /// and this routine will return false. In this case, the caller should just
3612 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
3614 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
3616 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3617 "Invalid mangleName() call, argument is not a variable or function!");
3618 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3619 "Invalid mangleName() call on 'structor decl!");
3621 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3622 getASTContext().getSourceManager(),
3623 "Mangling declaration");
3625 CXXNameMangler Mangler(*this, Out, D);
3626 return Mangler.mangle(D);
3629 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3632 CXXNameMangler Mangler(*this, Out, D, Type);
3636 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3639 CXXNameMangler Mangler(*this, Out, D, Type);
3643 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3644 const ThunkInfo &Thunk,
3646 // <special-name> ::= T <call-offset> <base encoding>
3647 // # base is the nominal target function of thunk
3648 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3649 // # base is the nominal target function of thunk
3650 // # first call-offset is 'this' adjustment
3651 // # second call-offset is result adjustment
3653 assert(!isa<CXXDestructorDecl>(MD) &&
3654 "Use mangleCXXDtor for destructor decls!");
3655 CXXNameMangler Mangler(*this, Out);
3656 Mangler.getStream() << "_ZT";
3657 if (!Thunk.Return.isEmpty())
3658 Mangler.getStream() << 'c';
3660 // Mangle the 'this' pointer adjustment.
3661 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
3662 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
3664 // Mangle the return pointer adjustment if there is one.
3665 if (!Thunk.Return.isEmpty())
3666 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
3667 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
3669 Mangler.mangleFunctionEncoding(MD);
3672 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
3673 const CXXDestructorDecl *DD, CXXDtorType Type,
3674 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
3675 // <special-name> ::= T <call-offset> <base encoding>
3676 // # base is the nominal target function of thunk
3677 CXXNameMangler Mangler(*this, Out, DD, Type);
3678 Mangler.getStream() << "_ZT";
3680 // Mangle the 'this' pointer adjustment.
3681 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
3682 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
3684 Mangler.mangleFunctionEncoding(DD);
3687 /// mangleGuardVariable - Returns the mangled name for a guard variable
3688 /// for the passed in VarDecl.
3689 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
3691 // <special-name> ::= GV <object name> # Guard variable for one-time
3693 CXXNameMangler Mangler(*this, Out);
3694 Mangler.getStream() << "_ZGV";
3695 Mangler.mangleName(D);
3698 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
3700 // These symbols are internal in the Itanium ABI, so the names don't matter.
3701 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
3702 // avoid duplicate symbols.
3703 Out << "__cxx_global_var_init";
3706 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3708 // Prefix the mangling of D with __dtor_.
3709 CXXNameMangler Mangler(*this, Out);
3710 Mangler.getStream() << "__dtor_";
3711 if (shouldMangleDeclName(D))
3714 Mangler.getStream() << D->getName();
3717 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
3719 // <special-name> ::= TH <object name>
3720 CXXNameMangler Mangler(*this, Out);
3721 Mangler.getStream() << "_ZTH";
3722 Mangler.mangleName(D);
3726 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
3728 // <special-name> ::= TW <object name>
3729 CXXNameMangler Mangler(*this, Out);
3730 Mangler.getStream() << "_ZTW";
3731 Mangler.mangleName(D);
3734 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
3736 // We match the GCC mangling here.
3737 // <special-name> ::= GR <object name>
3738 CXXNameMangler Mangler(*this, Out);
3739 Mangler.getStream() << "_ZGR";
3740 Mangler.mangleName(D);
3743 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
3745 // <special-name> ::= TV <type> # virtual table
3746 CXXNameMangler Mangler(*this, Out);
3747 Mangler.getStream() << "_ZTV";
3748 Mangler.mangleNameOrStandardSubstitution(RD);
3751 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
3753 // <special-name> ::= TT <type> # VTT structure
3754 CXXNameMangler Mangler(*this, Out);
3755 Mangler.getStream() << "_ZTT";
3756 Mangler.mangleNameOrStandardSubstitution(RD);
3759 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
3761 const CXXRecordDecl *Type,
3763 // <special-name> ::= TC <type> <offset number> _ <base type>
3764 CXXNameMangler Mangler(*this, Out);
3765 Mangler.getStream() << "_ZTC";
3766 Mangler.mangleNameOrStandardSubstitution(RD);
3767 Mangler.getStream() << Offset;
3768 Mangler.getStream() << '_';
3769 Mangler.mangleNameOrStandardSubstitution(Type);
3772 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
3773 // <special-name> ::= TI <type> # typeinfo structure
3774 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
3775 CXXNameMangler Mangler(*this, Out);
3776 Mangler.getStream() << "_ZTI";
3777 Mangler.mangleType(Ty);
3780 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
3782 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
3783 CXXNameMangler Mangler(*this, Out);
3784 Mangler.getStream() << "_ZTS";
3785 Mangler.mangleType(Ty);
3788 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
3789 mangleCXXRTTIName(Ty, Out);
3792 ItaniumMangleContext *
3793 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
3794 return new ItaniumMangleContextImpl(Context, Diags);