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://mentorembedded.github.io/cxx-abi/abi.html#mangling
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/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/ABI.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
35 #define MANGLE_CHECKER 0
41 using namespace clang;
45 /// Retrieve the declaration context that should be used when mangling the given
47 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
48 // The ABI assumes that lambda closure types that occur within
49 // default arguments live in the context of the function. However, due to
50 // the way in which Clang parses and creates function declarations, this is
51 // not the case: the lambda closure type ends up living in the context
52 // where the function itself resides, because the function declaration itself
53 // had not yet been created. Fix the context here.
54 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
56 if (ParmVarDecl *ContextParam
57 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
58 return ContextParam->getDeclContext();
61 // Perform the same check for block literals.
62 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
63 if (ParmVarDecl *ContextParam
64 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
65 return ContextParam->getDeclContext();
68 const DeclContext *DC = D->getDeclContext();
69 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
70 return getEffectiveDeclContext(CD);
72 if (const auto *VD = dyn_cast<VarDecl>(D))
74 return VD->getASTContext().getTranslationUnitDecl();
76 if (const auto *FD = dyn_cast<FunctionDecl>(D))
78 return FD->getASTContext().getTranslationUnitDecl();
83 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
84 return getEffectiveDeclContext(cast<Decl>(DC));
87 static bool isLocalContainerContext(const DeclContext *DC) {
88 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
91 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
92 const DeclContext *DC = getEffectiveDeclContext(D);
93 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
94 if (isLocalContainerContext(DC))
95 return dyn_cast<RecordDecl>(D);
97 DC = getEffectiveDeclContext(D);
102 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
103 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
104 return ftd->getTemplatedDecl();
109 static const NamedDecl *getStructor(const NamedDecl *decl) {
110 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
111 return (fn ? getStructor(fn) : decl);
114 static bool isLambda(const NamedDecl *ND) {
115 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
119 return Record->isLambda();
122 static const unsigned UnknownArity = ~0U;
124 class ItaniumMangleContextImpl : public ItaniumMangleContext {
125 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
126 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
127 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
130 explicit ItaniumMangleContextImpl(ASTContext &Context,
131 DiagnosticsEngine &Diags)
132 : ItaniumMangleContext(Context, Diags) {}
134 /// @name Mangler Entry Points
137 bool shouldMangleCXXName(const NamedDecl *D) override;
138 bool shouldMangleStringLiteral(const StringLiteral *) override {
141 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
142 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
143 raw_ostream &) override;
144 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
145 const ThisAdjustment &ThisAdjustment,
146 raw_ostream &) override;
147 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
148 raw_ostream &) override;
149 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
150 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
151 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
152 const CXXRecordDecl *Type, raw_ostream &) override;
153 void mangleCXXRTTI(QualType T, raw_ostream &) override;
154 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
155 void mangleTypeName(QualType T, raw_ostream &) override;
156 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
157 raw_ostream &) override;
158 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
159 raw_ostream &) override;
161 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
162 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
163 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
164 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
165 void mangleDynamicAtExitDestructor(const VarDecl *D,
166 raw_ostream &Out) override;
167 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
168 raw_ostream &Out) override;
169 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
170 raw_ostream &Out) override;
171 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
172 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
173 raw_ostream &) override;
175 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
177 void mangleCXXVTableBitSet(const CXXRecordDecl *RD, raw_ostream &) override;
179 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
180 // Lambda closure types are already numbered.
184 // Anonymous tags are already numbered.
185 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
186 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
190 // Use the canonical number for externally visible decls.
191 if (ND->isExternallyVisible()) {
192 unsigned discriminator = getASTContext().getManglingNumber(ND);
193 if (discriminator == 1)
195 disc = discriminator - 2;
199 // Make up a reasonable number for internal decls.
200 unsigned &discriminator = Uniquifier[ND];
201 if (!discriminator) {
202 const DeclContext *DC = getEffectiveDeclContext(ND);
203 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
205 if (discriminator == 1)
207 disc = discriminator-2;
213 /// Manage the mangling of a single name.
214 class CXXNameMangler {
215 ItaniumMangleContextImpl &Context;
218 /// The "structor" is the top-level declaration being mangled, if
219 /// that's not a template specialization; otherwise it's the pattern
220 /// for that specialization.
221 const NamedDecl *Structor;
222 unsigned StructorType;
224 /// The next substitution sequence number.
227 class FunctionTypeDepthState {
230 enum { InResultTypeMask = 1 };
233 FunctionTypeDepthState() : Bits(0) {}
235 /// The number of function types we're inside.
236 unsigned getDepth() const {
240 /// True if we're in the return type of the innermost function type.
241 bool isInResultType() const {
242 return Bits & InResultTypeMask;
245 FunctionTypeDepthState push() {
246 FunctionTypeDepthState tmp = *this;
247 Bits = (Bits & ~InResultTypeMask) + 2;
251 void enterResultType() {
252 Bits |= InResultTypeMask;
255 void leaveResultType() {
256 Bits &= ~InResultTypeMask;
259 void pop(FunctionTypeDepthState saved) {
260 assert(getDepth() == saved.getDepth() + 1);
266 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
268 ASTContext &getASTContext() const { return Context.getASTContext(); }
271 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
272 const NamedDecl *D = nullptr)
273 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
275 // These can't be mangled without a ctor type or dtor type.
276 assert(!D || (!isa<CXXDestructorDecl>(D) &&
277 !isa<CXXConstructorDecl>(D)));
279 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
280 const CXXConstructorDecl *D, CXXCtorType Type)
281 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
283 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
284 const CXXDestructorDecl *D, CXXDtorType Type)
285 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
290 if (Out.str()[0] == '\01')
294 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
295 assert(status == 0 && "Could not demangle mangled name!");
299 raw_ostream &getStream() { return Out; }
301 void mangle(const NamedDecl *D);
302 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
303 void mangleNumber(const llvm::APSInt &I);
304 void mangleNumber(int64_t Number);
305 void mangleFloat(const llvm::APFloat &F);
306 void mangleFunctionEncoding(const FunctionDecl *FD);
307 void mangleSeqID(unsigned SeqID);
308 void mangleName(const NamedDecl *ND);
309 void mangleType(QualType T);
310 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
314 bool mangleSubstitution(const NamedDecl *ND);
315 bool mangleSubstitution(QualType T);
316 bool mangleSubstitution(TemplateName Template);
317 bool mangleSubstitution(uintptr_t Ptr);
319 void mangleExistingSubstitution(QualType type);
320 void mangleExistingSubstitution(TemplateName name);
322 bool mangleStandardSubstitution(const NamedDecl *ND);
324 void addSubstitution(const NamedDecl *ND) {
325 ND = cast<NamedDecl>(ND->getCanonicalDecl());
327 addSubstitution(reinterpret_cast<uintptr_t>(ND));
329 void addSubstitution(QualType T);
330 void addSubstitution(TemplateName Template);
331 void addSubstitution(uintptr_t Ptr);
333 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
334 bool recursive = false);
335 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
336 DeclarationName name,
337 unsigned KnownArity = UnknownArity);
339 void mangleName(const TemplateDecl *TD,
340 const TemplateArgument *TemplateArgs,
341 unsigned NumTemplateArgs);
342 void mangleUnqualifiedName(const NamedDecl *ND) {
343 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
345 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
346 unsigned KnownArity);
347 void mangleUnscopedName(const NamedDecl *ND);
348 void mangleUnscopedTemplateName(const TemplateDecl *ND);
349 void mangleUnscopedTemplateName(TemplateName);
350 void mangleSourceName(const IdentifierInfo *II);
351 void mangleLocalName(const Decl *D);
352 void mangleBlockForPrefix(const BlockDecl *Block);
353 void mangleUnqualifiedBlock(const BlockDecl *Block);
354 void mangleLambda(const CXXRecordDecl *Lambda);
355 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
356 bool NoFunction=false);
357 void mangleNestedName(const TemplateDecl *TD,
358 const TemplateArgument *TemplateArgs,
359 unsigned NumTemplateArgs);
360 void manglePrefix(NestedNameSpecifier *qualifier);
361 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
362 void manglePrefix(QualType type);
363 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
364 void mangleTemplatePrefix(TemplateName Template);
365 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
366 StringRef Prefix = "");
367 void mangleOperatorName(DeclarationName Name, unsigned Arity);
368 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
369 void mangleQualifiers(Qualifiers Quals);
370 void mangleRefQualifier(RefQualifierKind RefQualifier);
372 void mangleObjCMethodName(const ObjCMethodDecl *MD);
374 // Declare manglers for every type class.
375 #define ABSTRACT_TYPE(CLASS, PARENT)
376 #define NON_CANONICAL_TYPE(CLASS, PARENT)
377 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
378 #include "clang/AST/TypeNodes.def"
380 void mangleType(const TagType*);
381 void mangleType(TemplateName);
382 void mangleBareFunctionType(const FunctionType *T,
383 bool MangleReturnType);
384 void mangleNeonVectorType(const VectorType *T);
385 void mangleAArch64NeonVectorType(const VectorType *T);
387 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
388 void mangleMemberExprBase(const Expr *base, bool isArrow);
389 void mangleMemberExpr(const Expr *base, bool isArrow,
390 NestedNameSpecifier *qualifier,
391 NamedDecl *firstQualifierLookup,
392 DeclarationName name,
393 unsigned knownArity);
394 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
395 void mangleInitListElements(const InitListExpr *InitList);
396 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
397 void mangleCXXCtorType(CXXCtorType T);
398 void mangleCXXDtorType(CXXDtorType T);
400 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
401 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
402 unsigned NumTemplateArgs);
403 void mangleTemplateArgs(const TemplateArgumentList &AL);
404 void mangleTemplateArg(TemplateArgument A);
406 void mangleTemplateParameter(unsigned Index);
408 void mangleFunctionParam(const ParmVarDecl *parm);
413 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
414 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
416 LanguageLinkage L = FD->getLanguageLinkage();
417 // Overloadable functions need mangling.
418 if (FD->hasAttr<OverloadableAttr>())
421 // "main" is not mangled.
425 // C++ functions and those whose names are not a simple identifier need
427 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
430 // C functions are not mangled.
431 if (L == CLanguageLinkage)
435 // Otherwise, no mangling is done outside C++ mode.
436 if (!getASTContext().getLangOpts().CPlusPlus)
439 const VarDecl *VD = dyn_cast<VarDecl>(D);
441 // C variables are not mangled.
445 // Variables at global scope with non-internal linkage are not mangled
446 const DeclContext *DC = getEffectiveDeclContext(D);
447 // Check for extern variable declared locally.
448 if (DC->isFunctionOrMethod() && D->hasLinkage())
449 while (!DC->isNamespace() && !DC->isTranslationUnit())
450 DC = getEffectiveParentContext(DC);
451 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
452 !isa<VarTemplateSpecializationDecl>(D))
459 void CXXNameMangler::mangle(const NamedDecl *D) {
460 // <mangled-name> ::= _Z <encoding>
462 // ::= <special-name>
464 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
465 mangleFunctionEncoding(FD);
466 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
468 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
469 mangleName(IFD->getAnonField());
471 mangleName(cast<FieldDecl>(D));
474 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
475 // <encoding> ::= <function name> <bare-function-type>
478 // Don't mangle in the type if this isn't a decl we should typically mangle.
479 if (!Context.shouldMangleDeclName(FD))
482 if (FD->hasAttr<EnableIfAttr>()) {
483 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
484 Out << "Ua9enable_ifI";
485 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
487 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
488 E = FD->getAttrs().rend();
490 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
494 mangleExpression(EIA->getCond());
498 FunctionTypeDepth.pop(Saved);
501 // Whether the mangling of a function type includes the return type depends on
502 // the context and the nature of the function. The rules for deciding whether
503 // the return type is included are:
505 // 1. Template functions (names or types) have return types encoded, with
506 // the exceptions listed below.
507 // 2. Function types not appearing as part of a function name mangling,
508 // e.g. parameters, pointer types, etc., have return type encoded, with the
509 // exceptions listed below.
510 // 3. Non-template function names do not have return types encoded.
512 // The exceptions mentioned in (1) and (2) above, for which the return type is
513 // never included, are
516 // 3. Conversion operator functions, e.g. operator int.
517 bool MangleReturnType = false;
518 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
519 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
520 isa<CXXConversionDecl>(FD)))
521 MangleReturnType = true;
523 // Mangle the type of the primary template.
524 FD = PrimaryTemplate->getTemplatedDecl();
527 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
531 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
532 while (isa<LinkageSpecDecl>(DC)) {
533 DC = getEffectiveParentContext(DC);
539 /// Return whether a given namespace is the 'std' namespace.
540 static bool isStd(const NamespaceDecl *NS) {
541 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
542 ->isTranslationUnit())
545 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
546 return II && II->isStr("std");
549 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
551 static bool isStdNamespace(const DeclContext *DC) {
552 if (!DC->isNamespace())
555 return isStd(cast<NamespaceDecl>(DC));
558 static const TemplateDecl *
559 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
560 // Check if we have a function template.
561 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
562 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
563 TemplateArgs = FD->getTemplateSpecializationArgs();
568 // Check if we have a class template.
569 if (const ClassTemplateSpecializationDecl *Spec =
570 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
571 TemplateArgs = &Spec->getTemplateArgs();
572 return Spec->getSpecializedTemplate();
575 // Check if we have a variable template.
576 if (const VarTemplateSpecializationDecl *Spec =
577 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
578 TemplateArgs = &Spec->getTemplateArgs();
579 return Spec->getSpecializedTemplate();
585 void CXXNameMangler::mangleName(const NamedDecl *ND) {
586 // <name> ::= <nested-name>
587 // ::= <unscoped-name>
588 // ::= <unscoped-template-name> <template-args>
591 const DeclContext *DC = getEffectiveDeclContext(ND);
593 // If this is an extern variable declared locally, the relevant DeclContext
594 // is that of the containing namespace, or the translation unit.
595 // FIXME: This is a hack; extern variables declared locally should have
596 // a proper semantic declaration context!
597 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
598 while (!DC->isNamespace() && !DC->isTranslationUnit())
599 DC = getEffectiveParentContext(DC);
600 else if (GetLocalClassDecl(ND)) {
605 DC = IgnoreLinkageSpecDecls(DC);
607 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
608 // Check if we have a template.
609 const TemplateArgumentList *TemplateArgs = nullptr;
610 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
611 mangleUnscopedTemplateName(TD);
612 mangleTemplateArgs(*TemplateArgs);
616 mangleUnscopedName(ND);
620 if (isLocalContainerContext(DC)) {
625 mangleNestedName(ND, DC);
627 void CXXNameMangler::mangleName(const TemplateDecl *TD,
628 const TemplateArgument *TemplateArgs,
629 unsigned NumTemplateArgs) {
630 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
632 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
633 mangleUnscopedTemplateName(TD);
634 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
636 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
640 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
641 // <unscoped-name> ::= <unqualified-name>
642 // ::= St <unqualified-name> # ::std::
644 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
647 mangleUnqualifiedName(ND);
650 void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
651 // <unscoped-template-name> ::= <unscoped-name>
652 // ::= <substitution>
653 if (mangleSubstitution(ND))
656 // <template-template-param> ::= <template-param>
657 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
658 mangleTemplateParameter(TTP->getIndex());
660 mangleUnscopedName(ND->getTemplatedDecl());
665 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
666 // <unscoped-template-name> ::= <unscoped-name>
667 // ::= <substitution>
668 if (TemplateDecl *TD = Template.getAsTemplateDecl())
669 return mangleUnscopedTemplateName(TD);
671 if (mangleSubstitution(Template))
674 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
675 assert(Dependent && "Not a dependent template name?");
676 if (const IdentifierInfo *Id = Dependent->getIdentifier())
677 mangleSourceName(Id);
679 mangleOperatorName(Dependent->getOperator(), UnknownArity);
681 addSubstitution(Template);
684 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
686 // Floating-point literals are encoded using a fixed-length
687 // lowercase hexadecimal string corresponding to the internal
688 // representation (IEEE on Itanium), high-order bytes first,
689 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
691 // The 'without leading zeroes' thing seems to be an editorial
692 // mistake; see the discussion on cxx-abi-dev beginning on
695 // Our requirements here are just barely weird enough to justify
696 // using a custom algorithm instead of post-processing APInt::toString().
698 llvm::APInt valueBits = f.bitcastToAPInt();
699 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
700 assert(numCharacters != 0);
702 // Allocate a buffer of the right number of characters.
703 SmallVector<char, 20> buffer;
704 buffer.set_size(numCharacters);
706 // Fill the buffer left-to-right.
707 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
708 // The bit-index of the next hex digit.
709 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
711 // Project out 4 bits starting at 'digitIndex'.
712 llvm::integerPart hexDigit
713 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
714 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
717 // Map that over to a lowercase hex digit.
718 static const char charForHex[16] = {
719 '0', '1', '2', '3', '4', '5', '6', '7',
720 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
722 buffer[stringIndex] = charForHex[hexDigit];
725 Out.write(buffer.data(), numCharacters);
728 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
729 if (Value.isSigned() && Value.isNegative()) {
731 Value.abs().print(Out, /*signed*/ false);
733 Value.print(Out, /*signed*/ false);
737 void CXXNameMangler::mangleNumber(int64_t Number) {
738 // <number> ::= [n] <non-negative decimal integer>
747 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
748 // <call-offset> ::= h <nv-offset> _
749 // ::= v <v-offset> _
750 // <nv-offset> ::= <offset number> # non-virtual base override
751 // <v-offset> ::= <offset number> _ <virtual offset number>
752 // # virtual base override, with vcall offset
755 mangleNumber(NonVirtual);
761 mangleNumber(NonVirtual);
763 mangleNumber(Virtual);
767 void CXXNameMangler::manglePrefix(QualType type) {
768 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
769 if (!mangleSubstitution(QualType(TST, 0))) {
770 mangleTemplatePrefix(TST->getTemplateName());
772 // FIXME: GCC does not appear to mangle the template arguments when
773 // the template in question is a dependent template name. Should we
774 // emulate that badness?
775 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
776 addSubstitution(QualType(TST, 0));
778 } else if (const auto *DTST =
779 type->getAs<DependentTemplateSpecializationType>()) {
780 if (!mangleSubstitution(QualType(DTST, 0))) {
781 TemplateName Template = getASTContext().getDependentTemplateName(
782 DTST->getQualifier(), DTST->getIdentifier());
783 mangleTemplatePrefix(Template);
785 // FIXME: GCC does not appear to mangle the template arguments when
786 // the template in question is a dependent template name. Should we
787 // emulate that badness?
788 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
789 addSubstitution(QualType(DTST, 0));
792 // We use the QualType mangle type variant here because it handles
798 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
800 /// \param recursive - true if this is being called recursively,
801 /// i.e. if there is more prefix "to the right".
802 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
806 // <unresolved-name> ::= [gs] <base-unresolved-name>
808 // T::x / decltype(p)::x
809 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
811 // T::N::x /decltype(p)::N::x
812 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
813 // <base-unresolved-name>
815 // A::x, N::y, A<T>::z; "gs" means leading "::"
816 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
817 // <base-unresolved-name>
819 switch (qualifier->getKind()) {
820 case NestedNameSpecifier::Global:
823 // We want an 'sr' unless this is the entire NNS.
827 // We never want an 'E' here.
830 case NestedNameSpecifier::Super:
831 llvm_unreachable("Can't mangle __super specifier");
833 case NestedNameSpecifier::Namespace:
834 if (qualifier->getPrefix())
835 mangleUnresolvedPrefix(qualifier->getPrefix(),
839 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
841 case NestedNameSpecifier::NamespaceAlias:
842 if (qualifier->getPrefix())
843 mangleUnresolvedPrefix(qualifier->getPrefix(),
847 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
850 case NestedNameSpecifier::TypeSpec:
851 case NestedNameSpecifier::TypeSpecWithTemplate: {
852 const Type *type = qualifier->getAsType();
854 // We only want to use an unresolved-type encoding if this is one of:
856 // - a template type parameter
857 // - a template template parameter with arguments
858 // In all of these cases, we should have no prefix.
859 if (qualifier->getPrefix()) {
860 mangleUnresolvedPrefix(qualifier->getPrefix(),
863 // Otherwise, all the cases want this.
867 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
873 case NestedNameSpecifier::Identifier:
874 // Member expressions can have these without prefixes.
875 if (qualifier->getPrefix())
876 mangleUnresolvedPrefix(qualifier->getPrefix(),
881 mangleSourceName(qualifier->getAsIdentifier());
885 // If this was the innermost part of the NNS, and we fell out to
886 // here, append an 'E'.
891 /// Mangle an unresolved-name, which is generally used for names which
892 /// weren't resolved to specific entities.
893 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
894 DeclarationName name,
895 unsigned knownArity) {
896 if (qualifier) mangleUnresolvedPrefix(qualifier);
897 switch (name.getNameKind()) {
898 // <base-unresolved-name> ::= <simple-id>
899 case DeclarationName::Identifier:
900 mangleSourceName(name.getAsIdentifierInfo());
902 // <base-unresolved-name> ::= dn <destructor-name>
903 case DeclarationName::CXXDestructorName:
905 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
907 // <base-unresolved-name> ::= on <operator-name>
908 case DeclarationName::CXXConversionFunctionName:
909 case DeclarationName::CXXLiteralOperatorName:
910 case DeclarationName::CXXOperatorName:
912 mangleOperatorName(name, knownArity);
914 case DeclarationName::CXXConstructorName:
915 llvm_unreachable("Can't mangle a constructor name!");
916 case DeclarationName::CXXUsingDirective:
917 llvm_unreachable("Can't mangle a using directive name!");
918 case DeclarationName::ObjCMultiArgSelector:
919 case DeclarationName::ObjCOneArgSelector:
920 case DeclarationName::ObjCZeroArgSelector:
921 llvm_unreachable("Can't mangle Objective-C selector names here!");
925 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
926 DeclarationName Name,
927 unsigned KnownArity) {
928 unsigned Arity = KnownArity;
929 // <unqualified-name> ::= <operator-name>
930 // ::= <ctor-dtor-name>
932 switch (Name.getNameKind()) {
933 case DeclarationName::Identifier: {
934 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
935 // We must avoid conflicts between internally- and externally-
936 // linked variable and function declaration names in the same TU:
937 // void test() { extern void foo(); }
938 // static void foo();
939 // This naming convention is the same as that followed by GCC,
940 // though it shouldn't actually matter.
941 if (ND && ND->getFormalLinkage() == InternalLinkage &&
942 getEffectiveDeclContext(ND)->isFileContext())
945 mangleSourceName(II);
949 // Otherwise, an anonymous entity. We must have a declaration.
950 assert(ND && "mangling empty name without declaration");
952 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
953 if (NS->isAnonymousNamespace()) {
954 // This is how gcc mangles these names.
955 Out << "12_GLOBAL__N_1";
960 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
961 // We must have an anonymous union or struct declaration.
962 const RecordDecl *RD =
963 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
965 // Itanium C++ ABI 5.1.2:
967 // For the purposes of mangling, the name of an anonymous union is
968 // considered to be the name of the first named data member found by a
969 // pre-order, depth-first, declaration-order walk of the data members of
970 // the anonymous union. If there is no such data member (i.e., if all of
971 // the data members in the union are unnamed), then there is no way for
972 // a program to refer to the anonymous union, and there is therefore no
973 // need to mangle its name.
974 assert(RD->isAnonymousStructOrUnion()
975 && "Expected anonymous struct or union!");
976 const FieldDecl *FD = RD->findFirstNamedDataMember();
978 // It's actually possible for various reasons for us to get here
979 // with an empty anonymous struct / union. Fortunately, it
980 // doesn't really matter what name we generate.
982 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
984 mangleSourceName(FD->getIdentifier());
988 // Class extensions have no name as a category, and it's possible
989 // for them to be the semantic parent of certain declarations
990 // (primarily, tag decls defined within declarations). Such
991 // declarations will always have internal linkage, so the name
992 // doesn't really matter, but we shouldn't crash on them. For
993 // safety, just handle all ObjC containers here.
994 if (isa<ObjCContainerDecl>(ND))
997 // We must have an anonymous struct.
998 const TagDecl *TD = cast<TagDecl>(ND);
999 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1000 assert(TD->getDeclContext() == D->getDeclContext() &&
1001 "Typedef should not be in another decl context!");
1002 assert(D->getDeclName().getAsIdentifierInfo() &&
1003 "Typedef was not named!");
1004 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1008 // <unnamed-type-name> ::= <closure-type-name>
1010 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1011 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1012 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1013 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1014 mangleLambda(Record);
1019 if (TD->isExternallyVisible()) {
1020 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1022 if (UnnamedMangle > 1)
1023 Out << llvm::utostr(UnnamedMangle - 2);
1028 // Get a unique id for the anonymous struct.
1029 unsigned AnonStructId = Context.getAnonymousStructId(TD);
1031 // Mangle it as a source name in the form
1033 // where n is the length of the string.
1036 Str += llvm::utostr(AnonStructId);
1043 case DeclarationName::ObjCZeroArgSelector:
1044 case DeclarationName::ObjCOneArgSelector:
1045 case DeclarationName::ObjCMultiArgSelector:
1046 llvm_unreachable("Can't mangle Objective-C selector names here!");
1048 case DeclarationName::CXXConstructorName:
1050 // If the named decl is the C++ constructor we're mangling, use the type
1052 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1054 // Otherwise, use the complete constructor name. This is relevant if a
1055 // class with a constructor is declared within a constructor.
1056 mangleCXXCtorType(Ctor_Complete);
1059 case DeclarationName::CXXDestructorName:
1061 // If the named decl is the C++ destructor we're mangling, use the type we
1063 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1065 // Otherwise, use the complete destructor name. This is relevant if a
1066 // class with a destructor is declared within a destructor.
1067 mangleCXXDtorType(Dtor_Complete);
1070 case DeclarationName::CXXOperatorName:
1071 if (ND && Arity == UnknownArity) {
1072 Arity = cast<FunctionDecl>(ND)->getNumParams();
1074 // If we have a member function, we need to include the 'this' pointer.
1075 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1076 if (!MD->isStatic())
1080 case DeclarationName::CXXConversionFunctionName:
1081 case DeclarationName::CXXLiteralOperatorName:
1082 mangleOperatorName(Name, Arity);
1085 case DeclarationName::CXXUsingDirective:
1086 llvm_unreachable("Can't mangle a using directive name!");
1090 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1091 // <source-name> ::= <positive length number> <identifier>
1092 // <number> ::= [n] <non-negative decimal integer>
1093 // <identifier> ::= <unqualified source code identifier>
1094 Out << II->getLength() << II->getName();
1097 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1098 const DeclContext *DC,
1101 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1102 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1103 // <template-args> E
1106 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1107 Qualifiers MethodQuals =
1108 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1109 // We do not consider restrict a distinguishing attribute for overloading
1110 // purposes so we must not mangle it.
1111 MethodQuals.removeRestrict();
1112 mangleQualifiers(MethodQuals);
1113 mangleRefQualifier(Method->getRefQualifier());
1116 // Check if we have a template.
1117 const TemplateArgumentList *TemplateArgs = nullptr;
1118 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1119 mangleTemplatePrefix(TD, NoFunction);
1120 mangleTemplateArgs(*TemplateArgs);
1123 manglePrefix(DC, NoFunction);
1124 mangleUnqualifiedName(ND);
1129 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1130 const TemplateArgument *TemplateArgs,
1131 unsigned NumTemplateArgs) {
1132 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1136 mangleTemplatePrefix(TD);
1137 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1142 void CXXNameMangler::mangleLocalName(const Decl *D) {
1143 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1144 // := Z <function encoding> E s [<discriminator>]
1145 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1147 // <discriminator> := _ <non-negative number>
1148 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1149 const RecordDecl *RD = GetLocalClassDecl(D);
1150 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1154 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1155 mangleObjCMethodName(MD);
1156 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1157 mangleBlockForPrefix(BD);
1159 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1164 // The parameter number is omitted for the last parameter, 0 for the
1165 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1166 // <entity name> will of course contain a <closure-type-name>: Its
1167 // numbering will be local to the particular argument in which it appears
1168 // -- other default arguments do not affect its encoding.
1169 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1170 if (CXXRD->isLambda()) {
1171 if (const ParmVarDecl *Parm
1172 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1173 if (const FunctionDecl *Func
1174 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1176 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1178 mangleNumber(Num - 2);
1184 // Mangle the name relative to the closest enclosing function.
1185 // equality ok because RD derived from ND above
1187 mangleUnqualifiedName(RD);
1188 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1189 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1190 mangleUnqualifiedBlock(BD);
1192 const NamedDecl *ND = cast<NamedDecl>(D);
1193 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
1195 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1196 // Mangle a block in a default parameter; see above explanation for
1198 if (const ParmVarDecl *Parm
1199 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1200 if (const FunctionDecl *Func
1201 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1203 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1205 mangleNumber(Num - 2);
1210 mangleUnqualifiedBlock(BD);
1212 mangleUnqualifiedName(cast<NamedDecl>(D));
1215 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1217 if (Context.getNextDiscriminator(ND, disc)) {
1221 Out << "__" << disc << '_';
1226 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1227 if (GetLocalClassDecl(Block)) {
1228 mangleLocalName(Block);
1231 const DeclContext *DC = getEffectiveDeclContext(Block);
1232 if (isLocalContainerContext(DC)) {
1233 mangleLocalName(Block);
1236 manglePrefix(getEffectiveDeclContext(Block));
1237 mangleUnqualifiedBlock(Block);
1240 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1241 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1242 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1243 Context->getDeclContext()->isRecord()) {
1244 if (const IdentifierInfo *Name
1245 = cast<NamedDecl>(Context)->getIdentifier()) {
1246 mangleSourceName(Name);
1252 // If we have a block mangling number, use it.
1253 unsigned Number = Block->getBlockManglingNumber();
1254 // Otherwise, just make up a number. It doesn't matter what it is because
1255 // the symbol in question isn't externally visible.
1257 Number = Context.getBlockId(Block, false);
1264 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1265 // If the context of a closure type is an initializer for a class member
1266 // (static or nonstatic), it is encoded in a qualified name with a final
1267 // <prefix> of the form:
1269 // <data-member-prefix> := <member source-name> M
1271 // Technically, the data-member-prefix is part of the <prefix>. However,
1272 // since a closure type will always be mangled with a prefix, it's easier
1273 // to emit that last part of the prefix here.
1274 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1275 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1276 Context->getDeclContext()->isRecord()) {
1277 if (const IdentifierInfo *Name
1278 = cast<NamedDecl>(Context)->getIdentifier()) {
1279 mangleSourceName(Name);
1286 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1287 getAs<FunctionProtoType>();
1288 mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
1291 // The number is omitted for the first closure type with a given
1292 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1293 // (in lexical order) with that same <lambda-sig> and context.
1295 // The AST keeps track of the number for us.
1296 unsigned Number = Lambda->getLambdaManglingNumber();
1297 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1299 mangleNumber(Number - 2);
1303 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1304 switch (qualifier->getKind()) {
1305 case NestedNameSpecifier::Global:
1309 case NestedNameSpecifier::Super:
1310 llvm_unreachable("Can't mangle __super specifier");
1312 case NestedNameSpecifier::Namespace:
1313 mangleName(qualifier->getAsNamespace());
1316 case NestedNameSpecifier::NamespaceAlias:
1317 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1320 case NestedNameSpecifier::TypeSpec:
1321 case NestedNameSpecifier::TypeSpecWithTemplate:
1322 manglePrefix(QualType(qualifier->getAsType(), 0));
1325 case NestedNameSpecifier::Identifier:
1326 // Member expressions can have these without prefixes, but that
1327 // should end up in mangleUnresolvedPrefix instead.
1328 assert(qualifier->getPrefix());
1329 manglePrefix(qualifier->getPrefix());
1331 mangleSourceName(qualifier->getAsIdentifier());
1335 llvm_unreachable("unexpected nested name specifier");
1338 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1339 // <prefix> ::= <prefix> <unqualified-name>
1340 // ::= <template-prefix> <template-args>
1341 // ::= <template-param>
1343 // ::= <substitution>
1345 DC = IgnoreLinkageSpecDecls(DC);
1347 if (DC->isTranslationUnit())
1350 if (NoFunction && isLocalContainerContext(DC))
1353 assert(!isLocalContainerContext(DC));
1355 const NamedDecl *ND = cast<NamedDecl>(DC);
1356 if (mangleSubstitution(ND))
1359 // Check if we have a template.
1360 const TemplateArgumentList *TemplateArgs = nullptr;
1361 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1362 mangleTemplatePrefix(TD);
1363 mangleTemplateArgs(*TemplateArgs);
1365 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1366 mangleUnqualifiedName(ND);
1369 addSubstitution(ND);
1372 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1373 // <template-prefix> ::= <prefix> <template unqualified-name>
1374 // ::= <template-param>
1375 // ::= <substitution>
1376 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1377 return mangleTemplatePrefix(TD);
1379 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1380 manglePrefix(Qualified->getQualifier());
1382 if (OverloadedTemplateStorage *Overloaded
1383 = Template.getAsOverloadedTemplate()) {
1384 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
1389 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1390 assert(Dependent && "Unknown template name kind?");
1391 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1392 manglePrefix(Qualifier);
1393 mangleUnscopedTemplateName(Template);
1396 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1398 // <template-prefix> ::= <prefix> <template unqualified-name>
1399 // ::= <template-param>
1400 // ::= <substitution>
1401 // <template-template-param> ::= <template-param>
1404 if (mangleSubstitution(ND))
1407 // <template-template-param> ::= <template-param>
1408 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1409 mangleTemplateParameter(TTP->getIndex());
1411 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1412 mangleUnqualifiedName(ND->getTemplatedDecl());
1415 addSubstitution(ND);
1418 /// Mangles a template name under the production <type>. Required for
1419 /// template template arguments.
1420 /// <type> ::= <class-enum-type>
1421 /// ::= <template-param>
1422 /// ::= <substitution>
1423 void CXXNameMangler::mangleType(TemplateName TN) {
1424 if (mangleSubstitution(TN))
1427 TemplateDecl *TD = nullptr;
1429 switch (TN.getKind()) {
1430 case TemplateName::QualifiedTemplate:
1431 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1434 case TemplateName::Template:
1435 TD = TN.getAsTemplateDecl();
1439 if (isa<TemplateTemplateParmDecl>(TD))
1440 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1445 case TemplateName::OverloadedTemplate:
1446 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1448 case TemplateName::DependentTemplate: {
1449 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1450 assert(Dependent->isIdentifier());
1452 // <class-enum-type> ::= <name>
1453 // <name> ::= <nested-name>
1454 mangleUnresolvedPrefix(Dependent->getQualifier());
1455 mangleSourceName(Dependent->getIdentifier());
1459 case TemplateName::SubstTemplateTemplateParm: {
1460 // Substituted template parameters are mangled as the substituted
1461 // template. This will check for the substitution twice, which is
1462 // fine, but we have to return early so that we don't try to *add*
1463 // the substitution twice.
1464 SubstTemplateTemplateParmStorage *subst
1465 = TN.getAsSubstTemplateTemplateParm();
1466 mangleType(subst->getReplacement());
1470 case TemplateName::SubstTemplateTemplateParmPack: {
1471 // FIXME: not clear how to mangle this!
1472 // template <template <class> class T...> class A {
1473 // template <template <class> class U...> void foo(B<T,U> x...);
1475 Out << "_SUBSTPACK_";
1480 addSubstitution(TN);
1483 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1485 // Only certain other types are valid as prefixes; enumerate them.
1486 switch (Ty->getTypeClass()) {
1489 case Type::Adjusted:
1492 case Type::BlockPointer:
1493 case Type::LValueReference:
1494 case Type::RValueReference:
1495 case Type::MemberPointer:
1496 case Type::ConstantArray:
1497 case Type::IncompleteArray:
1498 case Type::VariableArray:
1499 case Type::DependentSizedArray:
1500 case Type::DependentSizedExtVector:
1502 case Type::ExtVector:
1503 case Type::FunctionProto:
1504 case Type::FunctionNoProto:
1506 case Type::Attributed:
1508 case Type::PackExpansion:
1509 case Type::ObjCObject:
1510 case Type::ObjCInterface:
1511 case Type::ObjCObjectPointer:
1513 llvm_unreachable("type is illegal as a nested name specifier");
1515 case Type::SubstTemplateTypeParmPack:
1516 // FIXME: not clear how to mangle this!
1517 // template <class T...> class A {
1518 // template <class U...> void foo(decltype(T::foo(U())) x...);
1520 Out << "_SUBSTPACK_";
1523 // <unresolved-type> ::= <template-param>
1525 // ::= <template-template-param> <template-args>
1526 // (this last is not official yet)
1527 case Type::TypeOfExpr:
1529 case Type::Decltype:
1530 case Type::TemplateTypeParm:
1531 case Type::UnaryTransform:
1532 case Type::SubstTemplateTypeParm:
1534 // Some callers want a prefix before the mangled type.
1537 // This seems to do everything we want. It's not really
1538 // sanctioned for a substituted template parameter, though.
1541 // We never want to print 'E' directly after an unresolved-type,
1542 // so we return directly.
1546 mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
1549 case Type::UnresolvedUsing:
1551 cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
1556 mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
1559 case Type::TemplateSpecialization: {
1560 const TemplateSpecializationType *TST =
1561 cast<TemplateSpecializationType>(Ty);
1562 TemplateName TN = TST->getTemplateName();
1563 switch (TN.getKind()) {
1564 case TemplateName::Template:
1565 case TemplateName::QualifiedTemplate: {
1566 TemplateDecl *TD = TN.getAsTemplateDecl();
1568 // If the base is a template template parameter, this is an
1570 assert(TD && "no template for template specialization type");
1571 if (isa<TemplateTemplateParmDecl>(TD))
1572 goto unresolvedType;
1574 mangleSourceName(TD->getIdentifier());
1578 case TemplateName::OverloadedTemplate:
1579 case TemplateName::DependentTemplate:
1580 llvm_unreachable("invalid base for a template specialization type");
1582 case TemplateName::SubstTemplateTemplateParm: {
1583 SubstTemplateTemplateParmStorage *subst =
1584 TN.getAsSubstTemplateTemplateParm();
1585 mangleExistingSubstitution(subst->getReplacement());
1589 case TemplateName::SubstTemplateTemplateParmPack: {
1590 // FIXME: not clear how to mangle this!
1591 // template <template <class U> class T...> class A {
1592 // template <class U...> void foo(decltype(T<U>::foo) x...);
1594 Out << "_SUBSTPACK_";
1599 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1603 case Type::InjectedClassName:
1605 cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
1608 case Type::DependentName:
1609 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1612 case Type::DependentTemplateSpecialization: {
1613 const DependentTemplateSpecializationType *DTST =
1614 cast<DependentTemplateSpecializationType>(Ty);
1615 mangleSourceName(DTST->getIdentifier());
1616 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1620 case Type::Elaborated:
1621 return mangleUnresolvedTypeOrSimpleId(
1622 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1628 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1629 switch (Name.getNameKind()) {
1630 case DeclarationName::CXXConstructorName:
1631 case DeclarationName::CXXDestructorName:
1632 case DeclarationName::CXXUsingDirective:
1633 case DeclarationName::Identifier:
1634 case DeclarationName::ObjCMultiArgSelector:
1635 case DeclarationName::ObjCOneArgSelector:
1636 case DeclarationName::ObjCZeroArgSelector:
1637 llvm_unreachable("Not an operator name");
1639 case DeclarationName::CXXConversionFunctionName:
1640 // <operator-name> ::= cv <type> # (cast)
1642 mangleType(Name.getCXXNameType());
1645 case DeclarationName::CXXLiteralOperatorName:
1647 mangleSourceName(Name.getCXXLiteralIdentifier());
1650 case DeclarationName::CXXOperatorName:
1651 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1659 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1661 // <operator-name> ::= nw # new
1662 case OO_New: Out << "nw"; break;
1664 case OO_Array_New: Out << "na"; break;
1666 case OO_Delete: Out << "dl"; break;
1667 // ::= da # delete[]
1668 case OO_Array_Delete: Out << "da"; break;
1669 // ::= ps # + (unary)
1670 // ::= pl # + (binary or unknown)
1672 Out << (Arity == 1? "ps" : "pl"); break;
1673 // ::= ng # - (unary)
1674 // ::= mi # - (binary or unknown)
1676 Out << (Arity == 1? "ng" : "mi"); break;
1677 // ::= ad # & (unary)
1678 // ::= an # & (binary or unknown)
1680 Out << (Arity == 1? "ad" : "an"); break;
1681 // ::= de # * (unary)
1682 // ::= ml # * (binary or unknown)
1684 // Use binary when unknown.
1685 Out << (Arity == 1? "de" : "ml"); break;
1687 case OO_Tilde: Out << "co"; break;
1689 case OO_Slash: Out << "dv"; break;
1691 case OO_Percent: Out << "rm"; break;
1693 case OO_Pipe: Out << "or"; break;
1695 case OO_Caret: Out << "eo"; break;
1697 case OO_Equal: Out << "aS"; break;
1699 case OO_PlusEqual: Out << "pL"; break;
1701 case OO_MinusEqual: Out << "mI"; break;
1703 case OO_StarEqual: Out << "mL"; break;
1705 case OO_SlashEqual: Out << "dV"; break;
1707 case OO_PercentEqual: Out << "rM"; break;
1709 case OO_AmpEqual: Out << "aN"; break;
1711 case OO_PipeEqual: Out << "oR"; break;
1713 case OO_CaretEqual: Out << "eO"; break;
1715 case OO_LessLess: Out << "ls"; break;
1717 case OO_GreaterGreater: Out << "rs"; break;
1719 case OO_LessLessEqual: Out << "lS"; break;
1721 case OO_GreaterGreaterEqual: Out << "rS"; break;
1723 case OO_EqualEqual: Out << "eq"; break;
1725 case OO_ExclaimEqual: Out << "ne"; break;
1727 case OO_Less: Out << "lt"; break;
1729 case OO_Greater: Out << "gt"; break;
1731 case OO_LessEqual: Out << "le"; break;
1733 case OO_GreaterEqual: Out << "ge"; break;
1735 case OO_Exclaim: Out << "nt"; break;
1737 case OO_AmpAmp: Out << "aa"; break;
1739 case OO_PipePipe: Out << "oo"; break;
1741 case OO_PlusPlus: Out << "pp"; break;
1743 case OO_MinusMinus: Out << "mm"; break;
1745 case OO_Comma: Out << "cm"; break;
1747 case OO_ArrowStar: Out << "pm"; break;
1749 case OO_Arrow: Out << "pt"; break;
1751 case OO_Call: Out << "cl"; break;
1753 case OO_Subscript: Out << "ix"; break;
1756 // The conditional operator can't be overloaded, but we still handle it when
1757 // mangling expressions.
1758 case OO_Conditional: Out << "qu"; break;
1761 case NUM_OVERLOADED_OPERATORS:
1762 llvm_unreachable("Not an overloaded operator");
1766 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1767 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1768 if (Quals.hasRestrict())
1770 if (Quals.hasVolatile())
1772 if (Quals.hasConst())
1775 if (Quals.hasAddressSpace()) {
1776 // Address space extension:
1778 // <type> ::= U <target-addrspace>
1779 // <type> ::= U <OpenCL-addrspace>
1780 // <type> ::= U <CUDA-addrspace>
1782 SmallString<64> ASString;
1783 unsigned AS = Quals.getAddressSpace();
1785 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1786 // <target-addrspace> ::= "AS" <address-space-number>
1787 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1788 ASString = "AS" + llvm::utostr_32(TargetAS);
1791 default: llvm_unreachable("Not a language specific address space");
1792 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1793 case LangAS::opencl_global: ASString = "CLglobal"; break;
1794 case LangAS::opencl_local: ASString = "CLlocal"; break;
1795 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1796 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1797 case LangAS::cuda_device: ASString = "CUdevice"; break;
1798 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1799 case LangAS::cuda_shared: ASString = "CUshared"; break;
1802 Out << 'U' << ASString.size() << ASString;
1805 StringRef LifetimeName;
1806 switch (Quals.getObjCLifetime()) {
1807 // Objective-C ARC Extension:
1809 // <type> ::= U "__strong"
1810 // <type> ::= U "__weak"
1811 // <type> ::= U "__autoreleasing"
1812 case Qualifiers::OCL_None:
1815 case Qualifiers::OCL_Weak:
1816 LifetimeName = "__weak";
1819 case Qualifiers::OCL_Strong:
1820 LifetimeName = "__strong";
1823 case Qualifiers::OCL_Autoreleasing:
1824 LifetimeName = "__autoreleasing";
1827 case Qualifiers::OCL_ExplicitNone:
1828 // The __unsafe_unretained qualifier is *not* mangled, so that
1829 // __unsafe_unretained types in ARC produce the same manglings as the
1830 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1831 // better ABI compatibility.
1833 // It's safe to do this because unqualified 'id' won't show up
1834 // in any type signatures that need to be mangled.
1837 if (!LifetimeName.empty())
1838 Out << 'U' << LifetimeName.size() << LifetimeName;
1841 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1842 // <ref-qualifier> ::= R # lvalue reference
1843 // ::= O # rvalue-reference
1844 switch (RefQualifier) {
1858 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1859 Context.mangleObjCMethodName(MD, Out);
1862 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1865 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1867 if (Ty->isOpenCLSpecificType())
1869 if (Ty->isBuiltinType())
1875 void CXXNameMangler::mangleType(QualType T) {
1876 // If our type is instantiation-dependent but not dependent, we mangle
1877 // it as it was written in the source, removing any top-level sugar.
1878 // Otherwise, use the canonical type.
1880 // FIXME: This is an approximation of the instantiation-dependent name
1881 // mangling rules, since we should really be using the type as written and
1882 // augmented via semantic analysis (i.e., with implicit conversions and
1883 // default template arguments) for any instantiation-dependent type.
1884 // Unfortunately, that requires several changes to our AST:
1885 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1886 // uniqued, so that we can handle substitutions properly
1887 // - Default template arguments will need to be represented in the
1888 // TemplateSpecializationType, since they need to be mangled even though
1889 // they aren't written.
1890 // - Conversions on non-type template arguments need to be expressed, since
1891 // they can affect the mangling of sizeof/alignof.
1892 if (!T->isInstantiationDependentType() || T->isDependentType())
1893 T = T.getCanonicalType();
1895 // Desugar any types that are purely sugar.
1897 // Don't desugar through template specialization types that aren't
1898 // type aliases. We need to mangle the template arguments as written.
1899 if (const TemplateSpecializationType *TST
1900 = dyn_cast<TemplateSpecializationType>(T))
1901 if (!TST->isTypeAlias())
1905 = T.getSingleStepDesugaredType(Context.getASTContext());
1912 SplitQualType split = T.split();
1913 Qualifiers quals = split.Quals;
1914 const Type *ty = split.Ty;
1916 bool isSubstitutable = isTypeSubstitutable(quals, ty);
1917 if (isSubstitutable && mangleSubstitution(T))
1920 // If we're mangling a qualified array type, push the qualifiers to
1921 // the element type.
1922 if (quals && isa<ArrayType>(T)) {
1923 ty = Context.getASTContext().getAsArrayType(T);
1924 quals = Qualifiers();
1926 // Note that we don't update T: we want to add the
1927 // substitution at the original type.
1931 mangleQualifiers(quals);
1932 // Recurse: even if the qualified type isn't yet substitutable,
1933 // the unqualified type might be.
1934 mangleType(QualType(ty, 0));
1936 switch (ty->getTypeClass()) {
1937 #define ABSTRACT_TYPE(CLASS, PARENT)
1938 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1940 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1942 #define TYPE(CLASS, PARENT) \
1944 mangleType(static_cast<const CLASS##Type*>(ty)); \
1946 #include "clang/AST/TypeNodes.def"
1950 // Add the substitution.
1951 if (isSubstitutable)
1955 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1956 if (!mangleStandardSubstitution(ND))
1960 void CXXNameMangler::mangleType(const BuiltinType *T) {
1961 // <type> ::= <builtin-type>
1962 // <builtin-type> ::= v # void
1966 // ::= a # signed char
1967 // ::= h # unsigned char
1969 // ::= t # unsigned short
1971 // ::= j # unsigned int
1973 // ::= m # unsigned long
1974 // ::= x # long long, __int64
1975 // ::= y # unsigned long long, __int64
1977 // ::= o # unsigned __int128
1980 // ::= e # long double, __float80
1981 // UNSUPPORTED: ::= g # __float128
1982 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1983 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1984 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1985 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1986 // ::= Di # char32_t
1987 // ::= Ds # char16_t
1988 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1989 // ::= u <source-name> # vendor extended type
1990 switch (T->getKind()) {
1991 case BuiltinType::Void: Out << 'v'; break;
1992 case BuiltinType::Bool: Out << 'b'; break;
1993 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
1994 case BuiltinType::UChar: Out << 'h'; break;
1995 case BuiltinType::UShort: Out << 't'; break;
1996 case BuiltinType::UInt: Out << 'j'; break;
1997 case BuiltinType::ULong: Out << 'm'; break;
1998 case BuiltinType::ULongLong: Out << 'y'; break;
1999 case BuiltinType::UInt128: Out << 'o'; break;
2000 case BuiltinType::SChar: Out << 'a'; break;
2001 case BuiltinType::WChar_S:
2002 case BuiltinType::WChar_U: Out << 'w'; break;
2003 case BuiltinType::Char16: Out << "Ds"; break;
2004 case BuiltinType::Char32: Out << "Di"; break;
2005 case BuiltinType::Short: Out << 's'; break;
2006 case BuiltinType::Int: Out << 'i'; break;
2007 case BuiltinType::Long: Out << 'l'; break;
2008 case BuiltinType::LongLong: Out << 'x'; break;
2009 case BuiltinType::Int128: Out << 'n'; break;
2010 case BuiltinType::Half: Out << "Dh"; break;
2011 case BuiltinType::Float: Out << 'f'; break;
2012 case BuiltinType::Double: Out << 'd'; break;
2013 case BuiltinType::LongDouble:
2014 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2018 case BuiltinType::NullPtr: Out << "Dn"; break;
2020 #define BUILTIN_TYPE(Id, SingletonId)
2021 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2022 case BuiltinType::Id:
2023 #include "clang/AST/BuiltinTypes.def"
2024 case BuiltinType::Dependent:
2025 llvm_unreachable("mangling a placeholder type");
2026 case BuiltinType::ObjCId: Out << "11objc_object"; break;
2027 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
2028 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
2029 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
2030 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
2031 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
2032 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
2033 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
2034 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
2035 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
2036 case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
2040 // <type> ::= <function-type>
2041 // <function-type> ::= [<CV-qualifiers>] F [Y]
2042 // <bare-function-type> [<ref-qualifier>] E
2043 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2044 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2045 // e.g. "const" in "int (A::*)() const".
2046 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2050 // FIXME: We don't have enough information in the AST to produce the 'Y'
2051 // encoding for extern "C" function types.
2052 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2054 // Mangle the ref-qualifier, if present.
2055 mangleRefQualifier(T->getRefQualifier());
2059 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2060 llvm_unreachable("Can't mangle K&R function prototypes");
2062 void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
2063 bool MangleReturnType) {
2064 // We should never be mangling something without a prototype.
2065 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2067 // Record that we're in a function type. See mangleFunctionParam
2068 // for details on what we're trying to achieve here.
2069 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2071 // <bare-function-type> ::= <signature type>+
2072 if (MangleReturnType) {
2073 FunctionTypeDepth.enterResultType();
2074 mangleType(Proto->getReturnType());
2075 FunctionTypeDepth.leaveResultType();
2078 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2079 // <builtin-type> ::= v # void
2082 FunctionTypeDepth.pop(saved);
2086 for (const auto &Arg : Proto->param_types())
2087 mangleType(Context.getASTContext().getSignatureParameterType(Arg));
2089 FunctionTypeDepth.pop(saved);
2091 // <builtin-type> ::= z # ellipsis
2092 if (Proto->isVariadic())
2096 // <type> ::= <class-enum-type>
2097 // <class-enum-type> ::= <name>
2098 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2099 mangleName(T->getDecl());
2102 // <type> ::= <class-enum-type>
2103 // <class-enum-type> ::= <name>
2104 void CXXNameMangler::mangleType(const EnumType *T) {
2105 mangleType(static_cast<const TagType*>(T));
2107 void CXXNameMangler::mangleType(const RecordType *T) {
2108 mangleType(static_cast<const TagType*>(T));
2110 void CXXNameMangler::mangleType(const TagType *T) {
2111 mangleName(T->getDecl());
2114 // <type> ::= <array-type>
2115 // <array-type> ::= A <positive dimension number> _ <element type>
2116 // ::= A [<dimension expression>] _ <element type>
2117 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2118 Out << 'A' << T->getSize() << '_';
2119 mangleType(T->getElementType());
2121 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2123 // decayed vla types (size 0) will just be skipped.
2124 if (T->getSizeExpr())
2125 mangleExpression(T->getSizeExpr());
2127 mangleType(T->getElementType());
2129 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2131 mangleExpression(T->getSizeExpr());
2133 mangleType(T->getElementType());
2135 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2137 mangleType(T->getElementType());
2140 // <type> ::= <pointer-to-member-type>
2141 // <pointer-to-member-type> ::= M <class type> <member type>
2142 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2144 mangleType(QualType(T->getClass(), 0));
2145 QualType PointeeType = T->getPointeeType();
2146 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2149 // Itanium C++ ABI 5.1.8:
2151 // The type of a non-static member function is considered to be different,
2152 // for the purposes of substitution, from the type of a namespace-scope or
2153 // static member function whose type appears similar. The types of two
2154 // non-static member functions are considered to be different, for the
2155 // purposes of substitution, if the functions are members of different
2156 // classes. In other words, for the purposes of substitution, the class of
2157 // which the function is a member is considered part of the type of
2160 // Given that we already substitute member function pointers as a
2161 // whole, the net effect of this rule is just to unconditionally
2162 // suppress substitution on the function type in a member pointer.
2163 // We increment the SeqID here to emulate adding an entry to the
2164 // substitution table.
2167 mangleType(PointeeType);
2170 // <type> ::= <template-param>
2171 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2172 mangleTemplateParameter(T->getIndex());
2175 // <type> ::= <template-param>
2176 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2177 // FIXME: not clear how to mangle this!
2178 // template <class T...> class A {
2179 // template <class U...> void foo(T(*)(U) x...);
2181 Out << "_SUBSTPACK_";
2184 // <type> ::= P <type> # pointer-to
2185 void CXXNameMangler::mangleType(const PointerType *T) {
2187 mangleType(T->getPointeeType());
2189 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2191 mangleType(T->getPointeeType());
2194 // <type> ::= R <type> # reference-to
2195 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2197 mangleType(T->getPointeeType());
2200 // <type> ::= O <type> # rvalue reference-to (C++0x)
2201 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2203 mangleType(T->getPointeeType());
2206 // <type> ::= C <type> # complex pair (C 2000)
2207 void CXXNameMangler::mangleType(const ComplexType *T) {
2209 mangleType(T->getElementType());
2212 // ARM's ABI for Neon vector types specifies that they should be mangled as
2213 // if they are structs (to match ARM's initial implementation). The
2214 // vector type must be one of the special types predefined by ARM.
2215 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2216 QualType EltType = T->getElementType();
2217 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2218 const char *EltName = nullptr;
2219 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2220 switch (cast<BuiltinType>(EltType)->getKind()) {
2221 case BuiltinType::SChar:
2222 case BuiltinType::UChar:
2223 EltName = "poly8_t";
2225 case BuiltinType::Short:
2226 case BuiltinType::UShort:
2227 EltName = "poly16_t";
2229 case BuiltinType::ULongLong:
2230 EltName = "poly64_t";
2232 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2235 switch (cast<BuiltinType>(EltType)->getKind()) {
2236 case BuiltinType::SChar: EltName = "int8_t"; break;
2237 case BuiltinType::UChar: EltName = "uint8_t"; break;
2238 case BuiltinType::Short: EltName = "int16_t"; break;
2239 case BuiltinType::UShort: EltName = "uint16_t"; break;
2240 case BuiltinType::Int: EltName = "int32_t"; break;
2241 case BuiltinType::UInt: EltName = "uint32_t"; break;
2242 case BuiltinType::LongLong: EltName = "int64_t"; break;
2243 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2244 case BuiltinType::Double: EltName = "float64_t"; break;
2245 case BuiltinType::Float: EltName = "float32_t"; break;
2246 case BuiltinType::Half: EltName = "float16_t";break;
2248 llvm_unreachable("unexpected Neon vector element type");
2251 const char *BaseName = nullptr;
2252 unsigned BitSize = (T->getNumElements() *
2253 getASTContext().getTypeSize(EltType));
2255 BaseName = "__simd64_";
2257 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2258 BaseName = "__simd128_";
2260 Out << strlen(BaseName) + strlen(EltName);
2261 Out << BaseName << EltName;
2264 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2265 switch (EltType->getKind()) {
2266 case BuiltinType::SChar:
2268 case BuiltinType::Short:
2270 case BuiltinType::Int:
2272 case BuiltinType::Long:
2273 case BuiltinType::LongLong:
2275 case BuiltinType::UChar:
2277 case BuiltinType::UShort:
2279 case BuiltinType::UInt:
2281 case BuiltinType::ULong:
2282 case BuiltinType::ULongLong:
2284 case BuiltinType::Half:
2286 case BuiltinType::Float:
2288 case BuiltinType::Double:
2291 llvm_unreachable("Unexpected vector element base type");
2295 // AArch64's ABI for Neon vector types specifies that they should be mangled as
2296 // the equivalent internal name. The vector type must be one of the special
2297 // types predefined by ARM.
2298 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2299 QualType EltType = T->getElementType();
2300 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2302 (T->getNumElements() * getASTContext().getTypeSize(EltType));
2303 (void)BitSize; // Silence warning.
2305 assert((BitSize == 64 || BitSize == 128) &&
2306 "Neon vector type not 64 or 128 bits");
2309 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2310 switch (cast<BuiltinType>(EltType)->getKind()) {
2311 case BuiltinType::UChar:
2314 case BuiltinType::UShort:
2317 case BuiltinType::ULong:
2318 case BuiltinType::ULongLong:
2322 llvm_unreachable("unexpected Neon polynomial vector element type");
2325 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2327 std::string TypeName =
2328 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
2329 Out << TypeName.length() << TypeName;
2332 // GNU extension: vector types
2333 // <type> ::= <vector-type>
2334 // <vector-type> ::= Dv <positive dimension number> _
2335 // <extended element type>
2336 // ::= Dv [<dimension expression>] _ <element type>
2337 // <extended element type> ::= <element type>
2338 // ::= p # AltiVec vector pixel
2339 // ::= b # Altivec vector bool
2340 void CXXNameMangler::mangleType(const VectorType *T) {
2341 if ((T->getVectorKind() == VectorType::NeonVector ||
2342 T->getVectorKind() == VectorType::NeonPolyVector)) {
2343 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
2344 llvm::Triple::ArchType Arch =
2345 getASTContext().getTargetInfo().getTriple().getArch();
2346 if ((Arch == llvm::Triple::aarch64 ||
2347 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
2348 mangleAArch64NeonVectorType(T);
2350 mangleNeonVectorType(T);
2353 Out << "Dv" << T->getNumElements() << '_';
2354 if (T->getVectorKind() == VectorType::AltiVecPixel)
2356 else if (T->getVectorKind() == VectorType::AltiVecBool)
2359 mangleType(T->getElementType());
2361 void CXXNameMangler::mangleType(const ExtVectorType *T) {
2362 mangleType(static_cast<const VectorType*>(T));
2364 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2366 mangleExpression(T->getSizeExpr());
2368 mangleType(T->getElementType());
2371 void CXXNameMangler::mangleType(const PackExpansionType *T) {
2372 // <type> ::= Dp <type> # pack expansion (C++0x)
2374 mangleType(T->getPattern());
2377 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2378 mangleSourceName(T->getDecl()->getIdentifier());
2381 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2382 // Treat __kindof as a vendor extended type qualifier.
2383 if (T->isKindOfType())
2384 Out << "U8__kindof";
2386 if (!T->qual_empty()) {
2387 // Mangle protocol qualifiers.
2388 SmallString<64> QualStr;
2389 llvm::raw_svector_ostream QualOS(QualStr);
2390 QualOS << "objcproto";
2391 for (const auto *I : T->quals()) {
2392 StringRef name = I->getName();
2393 QualOS << name.size() << name;
2396 Out << 'U' << QualStr.size() << QualStr;
2399 mangleType(T->getBaseType());
2401 if (T->isSpecialized()) {
2402 // Mangle type arguments as I <type>+ E
2404 for (auto typeArg : T->getTypeArgs())
2405 mangleType(typeArg);
2410 void CXXNameMangler::mangleType(const BlockPointerType *T) {
2411 Out << "U13block_pointer";
2412 mangleType(T->getPointeeType());
2415 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2416 // Mangle injected class name types as if the user had written the
2417 // specialization out fully. It may not actually be possible to see
2418 // this mangling, though.
2419 mangleType(T->getInjectedSpecializationType());
2422 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2423 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2424 mangleName(TD, T->getArgs(), T->getNumArgs());
2426 if (mangleSubstitution(QualType(T, 0)))
2429 mangleTemplatePrefix(T->getTemplateName());
2431 // FIXME: GCC does not appear to mangle the template arguments when
2432 // the template in question is a dependent template name. Should we
2433 // emulate that badness?
2434 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2435 addSubstitution(QualType(T, 0));
2439 void CXXNameMangler::mangleType(const DependentNameType *T) {
2440 // Proposal by cxx-abi-dev, 2014-03-26
2441 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2442 // # dependent elaborated type specifier using
2444 // ::= Ts <name> # dependent elaborated type specifier using
2445 // # 'struct' or 'class'
2446 // ::= Tu <name> # dependent elaborated type specifier using
2448 // ::= Te <name> # dependent elaborated type specifier using
2450 switch (T->getKeyword()) {
2465 llvm_unreachable("unexpected keyword for dependent type name");
2467 // Typename types are always nested
2469 manglePrefix(T->getQualifier());
2470 mangleSourceName(T->getIdentifier());
2474 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2475 // Dependently-scoped template types are nested if they have a prefix.
2478 // TODO: avoid making this TemplateName.
2479 TemplateName Prefix =
2480 getASTContext().getDependentTemplateName(T->getQualifier(),
2481 T->getIdentifier());
2482 mangleTemplatePrefix(Prefix);
2484 // FIXME: GCC does not appear to mangle the template arguments when
2485 // the template in question is a dependent template name. Should we
2486 // emulate that badness?
2487 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2491 void CXXNameMangler::mangleType(const TypeOfType *T) {
2492 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2493 // "extension with parameters" mangling.
2497 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2498 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2499 // "extension with parameters" mangling.
2503 void CXXNameMangler::mangleType(const DecltypeType *T) {
2504 Expr *E = T->getUnderlyingExpr();
2506 // type ::= Dt <expression> E # decltype of an id-expression
2507 // # or class member access
2508 // ::= DT <expression> E # decltype of an expression
2510 // This purports to be an exhaustive list of id-expressions and
2511 // class member accesses. Note that we do not ignore parentheses;
2512 // parentheses change the semantics of decltype for these
2513 // expressions (and cause the mangler to use the other form).
2514 if (isa<DeclRefExpr>(E) ||
2515 isa<MemberExpr>(E) ||
2516 isa<UnresolvedLookupExpr>(E) ||
2517 isa<DependentScopeDeclRefExpr>(E) ||
2518 isa<CXXDependentScopeMemberExpr>(E) ||
2519 isa<UnresolvedMemberExpr>(E))
2523 mangleExpression(E);
2527 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2528 // If this is dependent, we need to record that. If not, we simply
2529 // mangle it as the underlying type since they are equivalent.
2530 if (T->isDependentType()) {
2533 switch (T->getUTTKind()) {
2534 case UnaryTransformType::EnumUnderlyingType:
2540 mangleType(T->getUnderlyingType());
2543 void CXXNameMangler::mangleType(const AutoType *T) {
2544 QualType D = T->getDeducedType();
2545 // <builtin-type> ::= Da # dependent auto
2547 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
2552 void CXXNameMangler::mangleType(const AtomicType *T) {
2553 // <type> ::= U <source-name> <type> # vendor extended type qualifier
2554 // (Until there's a standardized mangling...)
2556 mangleType(T->getValueType());
2559 void CXXNameMangler::mangleIntegerLiteral(QualType T,
2560 const llvm::APSInt &Value) {
2561 // <expr-primary> ::= L <type> <value number> E # integer literal
2565 if (T->isBooleanType()) {
2566 // Boolean values are encoded as 0/1.
2567 Out << (Value.getBoolValue() ? '1' : '0');
2569 mangleNumber(Value);
2575 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2576 // Ignore member expressions involving anonymous unions.
2577 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2578 if (!RT->getDecl()->isAnonymousStructOrUnion())
2580 const auto *ME = dyn_cast<MemberExpr>(Base);
2583 Base = ME->getBase();
2584 IsArrow = ME->isArrow();
2587 if (Base->isImplicitCXXThis()) {
2588 // Note: GCC mangles member expressions to the implicit 'this' as
2589 // *this., whereas we represent them as this->. The Itanium C++ ABI
2590 // does not specify anything here, so we follow GCC.
2593 Out << (IsArrow ? "pt" : "dt");
2594 mangleExpression(Base);
2598 /// Mangles a member expression.
2599 void CXXNameMangler::mangleMemberExpr(const Expr *base,
2601 NestedNameSpecifier *qualifier,
2602 NamedDecl *firstQualifierLookup,
2603 DeclarationName member,
2605 // <expression> ::= dt <expression> <unresolved-name>
2606 // ::= pt <expression> <unresolved-name>
2608 mangleMemberExprBase(base, isArrow);
2609 mangleUnresolvedName(qualifier, member, arity);
2612 /// Look at the callee of the given call expression and determine if
2613 /// it's a parenthesized id-expression which would have triggered ADL
2615 static bool isParenthesizedADLCallee(const CallExpr *call) {
2616 const Expr *callee = call->getCallee();
2617 const Expr *fn = callee->IgnoreParens();
2619 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2620 // too, but for those to appear in the callee, it would have to be
2622 if (callee == fn) return false;
2624 // Must be an unresolved lookup.
2625 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2626 if (!lookup) return false;
2628 assert(!lookup->requiresADL());
2630 // Must be an unqualified lookup.
2631 if (lookup->getQualifier()) return false;
2633 // Must not have found a class member. Note that if one is a class
2634 // member, they're all class members.
2635 if (lookup->getNumDecls() > 0 &&
2636 (*lookup->decls_begin())->isCXXClassMember())
2639 // Otherwise, ADL would have been triggered.
2643 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2644 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2645 Out << CastEncoding;
2646 mangleType(ECE->getType());
2647 mangleExpression(ECE->getSubExpr());
2650 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2651 if (auto *Syntactic = InitList->getSyntacticForm())
2652 InitList = Syntactic;
2653 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2654 mangleExpression(InitList->getInit(i));
2657 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2658 // <expression> ::= <unary operator-name> <expression>
2659 // ::= <binary operator-name> <expression> <expression>
2660 // ::= <trinary operator-name> <expression> <expression> <expression>
2661 // ::= cv <type> expression # conversion with one argument
2662 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2663 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2664 // ::= sc <type> <expression> # static_cast<type> (expression)
2665 // ::= cc <type> <expression> # const_cast<type> (expression)
2666 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
2667 // ::= st <type> # sizeof (a type)
2668 // ::= at <type> # alignof (a type)
2669 // ::= <template-param>
2670 // ::= <function-param>
2671 // ::= sr <type> <unqualified-name> # dependent name
2672 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2673 // ::= ds <expression> <expression> # expr.*expr
2674 // ::= sZ <template-param> # size of a parameter pack
2675 // ::= sZ <function-param> # size of a function parameter pack
2676 // ::= <expr-primary>
2677 // <expr-primary> ::= L <type> <value number> E # integer literal
2678 // ::= L <type <value float> E # floating literal
2679 // ::= L <mangled-name> E # external name
2680 // ::= fpT # 'this' expression
2681 QualType ImplicitlyConvertedToType;
2684 switch (E->getStmtClass()) {
2685 case Expr::NoStmtClass:
2686 #define ABSTRACT_STMT(Type)
2687 #define EXPR(Type, Base)
2688 #define STMT(Type, Base) \
2689 case Expr::Type##Class:
2690 #include "clang/AST/StmtNodes.inc"
2693 // These all can only appear in local or variable-initialization
2694 // contexts and so should never appear in a mangling.
2695 case Expr::AddrLabelExprClass:
2696 case Expr::DesignatedInitUpdateExprClass:
2697 case Expr::ImplicitValueInitExprClass:
2698 case Expr::NoInitExprClass:
2699 case Expr::ParenListExprClass:
2700 case Expr::LambdaExprClass:
2701 case Expr::MSPropertyRefExprClass:
2702 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
2703 llvm_unreachable("unexpected statement kind");
2705 // FIXME: invent manglings for all these.
2706 case Expr::BlockExprClass:
2707 case Expr::ChooseExprClass:
2708 case Expr::CompoundLiteralExprClass:
2709 case Expr::DesignatedInitExprClass:
2710 case Expr::ExtVectorElementExprClass:
2711 case Expr::GenericSelectionExprClass:
2712 case Expr::ObjCEncodeExprClass:
2713 case Expr::ObjCIsaExprClass:
2714 case Expr::ObjCIvarRefExprClass:
2715 case Expr::ObjCMessageExprClass:
2716 case Expr::ObjCPropertyRefExprClass:
2717 case Expr::ObjCProtocolExprClass:
2718 case Expr::ObjCSelectorExprClass:
2719 case Expr::ObjCStringLiteralClass:
2720 case Expr::ObjCBoxedExprClass:
2721 case Expr::ObjCArrayLiteralClass:
2722 case Expr::ObjCDictionaryLiteralClass:
2723 case Expr::ObjCSubscriptRefExprClass:
2724 case Expr::ObjCIndirectCopyRestoreExprClass:
2725 case Expr::OffsetOfExprClass:
2726 case Expr::PredefinedExprClass:
2727 case Expr::ShuffleVectorExprClass:
2728 case Expr::ConvertVectorExprClass:
2729 case Expr::StmtExprClass:
2730 case Expr::TypeTraitExprClass:
2731 case Expr::ArrayTypeTraitExprClass:
2732 case Expr::ExpressionTraitExprClass:
2733 case Expr::VAArgExprClass:
2734 case Expr::CUDAKernelCallExprClass:
2735 case Expr::AsTypeExprClass:
2736 case Expr::PseudoObjectExprClass:
2737 case Expr::AtomicExprClass:
2739 // As bad as this diagnostic is, it's better than crashing.
2740 DiagnosticsEngine &Diags = Context.getDiags();
2741 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2742 "cannot yet mangle expression type %0");
2743 Diags.Report(E->getExprLoc(), DiagID)
2744 << E->getStmtClassName() << E->getSourceRange();
2748 case Expr::CXXUuidofExprClass: {
2749 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2750 if (UE->isTypeOperand()) {
2751 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2752 Out << "u8__uuidoft";
2755 Expr *UuidExp = UE->getExprOperand();
2756 Out << "u8__uuidofz";
2757 mangleExpression(UuidExp, Arity);
2762 // Even gcc-4.5 doesn't mangle this.
2763 case Expr::BinaryConditionalOperatorClass: {
2764 DiagnosticsEngine &Diags = Context.getDiags();
2766 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2767 "?: operator with omitted middle operand cannot be mangled");
2768 Diags.Report(E->getExprLoc(), DiagID)
2769 << E->getStmtClassName() << E->getSourceRange();
2773 // These are used for internal purposes and cannot be meaningfully mangled.
2774 case Expr::OpaqueValueExprClass:
2775 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2777 case Expr::InitListExprClass: {
2779 mangleInitListElements(cast<InitListExpr>(E));
2784 case Expr::CXXDefaultArgExprClass:
2785 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2788 case Expr::CXXDefaultInitExprClass:
2789 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2792 case Expr::CXXStdInitializerListExprClass:
2793 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2796 case Expr::SubstNonTypeTemplateParmExprClass:
2797 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2801 case Expr::UserDefinedLiteralClass:
2802 // We follow g++'s approach of mangling a UDL as a call to the literal
2804 case Expr::CXXMemberCallExprClass: // fallthrough
2805 case Expr::CallExprClass: {
2806 const CallExpr *CE = cast<CallExpr>(E);
2808 // <expression> ::= cp <simple-id> <expression>* E
2809 // We use this mangling only when the call would use ADL except
2810 // for being parenthesized. Per discussion with David
2811 // Vandervoorde, 2011.04.25.
2812 if (isParenthesizedADLCallee(CE)) {
2814 // The callee here is a parenthesized UnresolvedLookupExpr with
2815 // no qualifier and should always get mangled as a <simple-id>
2818 // <expression> ::= cl <expression>* E
2823 unsigned CallArity = CE->getNumArgs();
2824 for (const Expr *Arg : CE->arguments())
2825 if (isa<PackExpansionExpr>(Arg))
2826 CallArity = UnknownArity;
2828 mangleExpression(CE->getCallee(), CallArity);
2829 for (const Expr *Arg : CE->arguments())
2830 mangleExpression(Arg);
2835 case Expr::CXXNewExprClass: {
2836 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2837 if (New->isGlobalNew()) Out << "gs";
2838 Out << (New->isArray() ? "na" : "nw");
2839 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2840 E = New->placement_arg_end(); I != E; ++I)
2841 mangleExpression(*I);
2843 mangleType(New->getAllocatedType());
2844 if (New->hasInitializer()) {
2845 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2849 const Expr *Init = New->getInitializer();
2850 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2851 // Directly inline the initializers.
2852 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2855 mangleExpression(*I);
2856 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2857 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2858 mangleExpression(PLE->getExpr(i));
2859 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2860 isa<InitListExpr>(Init)) {
2861 // Only take InitListExprs apart for list-initialization.
2862 mangleInitListElements(cast<InitListExpr>(Init));
2864 mangleExpression(Init);
2870 case Expr::CXXPseudoDestructorExprClass: {
2871 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
2872 if (const Expr *Base = PDE->getBase())
2873 mangleMemberExprBase(Base, PDE->isArrow());
2874 NestedNameSpecifier *Qualifier = PDE->getQualifier();
2876 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
2878 mangleUnresolvedPrefix(Qualifier,
2879 /*Recursive=*/true);
2880 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
2884 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
2887 } else if (Qualifier) {
2888 mangleUnresolvedPrefix(Qualifier);
2890 // <base-unresolved-name> ::= dn <destructor-name>
2892 QualType DestroyedType = PDE->getDestroyedType();
2893 mangleUnresolvedTypeOrSimpleId(DestroyedType);
2897 case Expr::MemberExprClass: {
2898 const MemberExpr *ME = cast<MemberExpr>(E);
2899 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2900 ME->getQualifier(), nullptr,
2901 ME->getMemberDecl()->getDeclName(), Arity);
2905 case Expr::UnresolvedMemberExprClass: {
2906 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2907 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
2908 ME->isArrow(), ME->getQualifier(), nullptr,
2909 ME->getMemberName(), Arity);
2910 if (ME->hasExplicitTemplateArgs())
2911 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2915 case Expr::CXXDependentScopeMemberExprClass: {
2916 const CXXDependentScopeMemberExpr *ME
2917 = cast<CXXDependentScopeMemberExpr>(E);
2918 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
2919 ME->isArrow(), ME->getQualifier(),
2920 ME->getFirstQualifierFoundInScope(),
2921 ME->getMember(), Arity);
2922 if (ME->hasExplicitTemplateArgs())
2923 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2927 case Expr::UnresolvedLookupExprClass: {
2928 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
2929 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
2931 // All the <unresolved-name> productions end in a
2932 // base-unresolved-name, where <template-args> are just tacked
2934 if (ULE->hasExplicitTemplateArgs())
2935 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2939 case Expr::CXXUnresolvedConstructExprClass: {
2940 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2941 unsigned N = CE->arg_size();
2944 mangleType(CE->getType());
2945 if (N != 1) Out << '_';
2946 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2947 if (N != 1) Out << 'E';
2951 case Expr::CXXConstructExprClass: {
2952 const auto *CE = cast<CXXConstructExpr>(E);
2953 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
2955 CE->getNumArgs() >= 1 &&
2956 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
2957 "implicit CXXConstructExpr must have one argument");
2958 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
2961 for (auto *E : CE->arguments())
2962 mangleExpression(E);
2967 case Expr::CXXTemporaryObjectExprClass: {
2968 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
2969 unsigned N = CE->getNumArgs();
2970 bool List = CE->isListInitialization();
2976 mangleType(CE->getType());
2977 if (!List && N != 1)
2979 if (CE->isStdInitListInitialization()) {
2980 // We implicitly created a std::initializer_list<T> for the first argument
2981 // of a constructor of type U in an expression of the form U{a, b, c}.
2982 // Strip all the semantic gunk off the initializer list.
2984 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
2985 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
2986 mangleInitListElements(ILE);
2988 for (auto *E : CE->arguments())
2989 mangleExpression(E);
2996 case Expr::CXXScalarValueInitExprClass:
2998 mangleType(E->getType());
3002 case Expr::CXXNoexceptExprClass:
3004 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3007 case Expr::UnaryExprOrTypeTraitExprClass: {
3008 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3010 if (!SAE->isInstantiationDependent()) {
3012 // If the operand of a sizeof or alignof operator is not
3013 // instantiation-dependent it is encoded as an integer literal
3014 // reflecting the result of the operator.
3016 // If the result of the operator is implicitly converted to a known
3017 // integer type, that type is used for the literal; otherwise, the type
3018 // of std::size_t or std::ptrdiff_t is used.
3019 QualType T = (ImplicitlyConvertedToType.isNull() ||
3020 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3021 : ImplicitlyConvertedToType;
3022 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3023 mangleIntegerLiteral(T, V);
3027 switch(SAE->getKind()) {
3034 case UETT_VecStep: {
3035 DiagnosticsEngine &Diags = Context.getDiags();
3036 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3037 "cannot yet mangle vec_step expression");
3038 Diags.Report(DiagID);
3041 case UETT_OpenMPRequiredSimdAlign:
3042 DiagnosticsEngine &Diags = Context.getDiags();
3043 unsigned DiagID = Diags.getCustomDiagID(
3044 DiagnosticsEngine::Error,
3045 "cannot yet mangle __builtin_omp_required_simd_align expression");
3046 Diags.Report(DiagID);
3049 if (SAE->isArgumentType()) {
3051 mangleType(SAE->getArgumentType());
3054 mangleExpression(SAE->getArgumentExpr());
3059 case Expr::CXXThrowExprClass: {
3060 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
3061 // <expression> ::= tw <expression> # throw expression
3063 if (TE->getSubExpr()) {
3065 mangleExpression(TE->getSubExpr());
3072 case Expr::CXXTypeidExprClass: {
3073 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
3074 // <expression> ::= ti <type> # typeid (type)
3075 // ::= te <expression> # typeid (expression)
3076 if (TIE->isTypeOperand()) {
3078 mangleType(TIE->getTypeOperand(Context.getASTContext()));
3081 mangleExpression(TIE->getExprOperand());
3086 case Expr::CXXDeleteExprClass: {
3087 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
3088 // <expression> ::= [gs] dl <expression> # [::] delete expr
3089 // ::= [gs] da <expression> # [::] delete [] expr
3090 if (DE->isGlobalDelete()) Out << "gs";
3091 Out << (DE->isArrayForm() ? "da" : "dl");
3092 mangleExpression(DE->getArgument());
3096 case Expr::UnaryOperatorClass: {
3097 const UnaryOperator *UO = cast<UnaryOperator>(E);
3098 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3100 mangleExpression(UO->getSubExpr());
3104 case Expr::ArraySubscriptExprClass: {
3105 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3107 // Array subscript is treated as a syntactically weird form of
3110 mangleExpression(AE->getLHS());
3111 mangleExpression(AE->getRHS());
3115 case Expr::CompoundAssignOperatorClass: // fallthrough
3116 case Expr::BinaryOperatorClass: {
3117 const BinaryOperator *BO = cast<BinaryOperator>(E);
3118 if (BO->getOpcode() == BO_PtrMemD)
3121 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3123 mangleExpression(BO->getLHS());
3124 mangleExpression(BO->getRHS());
3128 case Expr::ConditionalOperatorClass: {
3129 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3130 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3131 mangleExpression(CO->getCond());
3132 mangleExpression(CO->getLHS(), Arity);
3133 mangleExpression(CO->getRHS(), Arity);
3137 case Expr::ImplicitCastExprClass: {
3138 ImplicitlyConvertedToType = E->getType();
3139 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3143 case Expr::ObjCBridgedCastExprClass: {
3144 // Mangle ownership casts as a vendor extended operator __bridge,
3145 // __bridge_transfer, or __bridge_retain.
3146 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3147 Out << "v1U" << Kind.size() << Kind;
3149 // Fall through to mangle the cast itself.
3151 case Expr::CStyleCastExprClass:
3152 mangleCastExpression(E, "cv");
3155 case Expr::CXXFunctionalCastExprClass: {
3156 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3157 // FIXME: Add isImplicit to CXXConstructExpr.
3158 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3159 if (CCE->getParenOrBraceRange().isInvalid())
3160 Sub = CCE->getArg(0)->IgnoreImplicit();
3161 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3162 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3163 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3165 mangleType(E->getType());
3166 mangleInitListElements(IL);
3169 mangleCastExpression(E, "cv");
3174 case Expr::CXXStaticCastExprClass:
3175 mangleCastExpression(E, "sc");
3177 case Expr::CXXDynamicCastExprClass:
3178 mangleCastExpression(E, "dc");
3180 case Expr::CXXReinterpretCastExprClass:
3181 mangleCastExpression(E, "rc");
3183 case Expr::CXXConstCastExprClass:
3184 mangleCastExpression(E, "cc");
3187 case Expr::CXXOperatorCallExprClass: {
3188 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3189 unsigned NumArgs = CE->getNumArgs();
3190 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3191 // Mangle the arguments.
3192 for (unsigned i = 0; i != NumArgs; ++i)
3193 mangleExpression(CE->getArg(i));
3197 case Expr::ParenExprClass:
3198 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3201 case Expr::DeclRefExprClass: {
3202 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3204 switch (D->getKind()) {
3206 // <expr-primary> ::= L <mangled-name> E # external name
3213 mangleFunctionParam(cast<ParmVarDecl>(D));
3216 case Decl::EnumConstant: {
3217 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3218 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3222 case Decl::NonTypeTemplateParm: {
3223 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3224 mangleTemplateParameter(PD->getIndex());
3233 case Expr::SubstNonTypeTemplateParmPackExprClass:
3234 // FIXME: not clear how to mangle this!
3235 // template <unsigned N...> class A {
3236 // template <class U...> void foo(U (&x)[N]...);
3238 Out << "_SUBSTPACK_";
3241 case Expr::FunctionParmPackExprClass: {
3242 // FIXME: not clear how to mangle this!
3243 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3244 Out << "v110_SUBSTPACK";
3245 mangleFunctionParam(FPPE->getParameterPack());
3249 case Expr::DependentScopeDeclRefExprClass: {
3250 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
3251 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
3253 // All the <unresolved-name> productions end in a
3254 // base-unresolved-name, where <template-args> are just tacked
3256 if (DRE->hasExplicitTemplateArgs())
3257 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
3261 case Expr::CXXBindTemporaryExprClass:
3262 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3265 case Expr::ExprWithCleanupsClass:
3266 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3269 case Expr::FloatingLiteralClass: {
3270 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3272 mangleType(FL->getType());
3273 mangleFloat(FL->getValue());
3278 case Expr::CharacterLiteralClass:
3280 mangleType(E->getType());
3281 Out << cast<CharacterLiteral>(E)->getValue();
3285 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3286 case Expr::ObjCBoolLiteralExprClass:
3288 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3292 case Expr::CXXBoolLiteralExprClass:
3294 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3298 case Expr::IntegerLiteralClass: {
3299 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3300 if (E->getType()->isSignedIntegerType())
3301 Value.setIsSigned(true);
3302 mangleIntegerLiteral(E->getType(), Value);
3306 case Expr::ImaginaryLiteralClass: {
3307 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3308 // Mangle as if a complex literal.
3309 // Proposal from David Vandevoorde, 2010.06.30.
3311 mangleType(E->getType());
3312 if (const FloatingLiteral *Imag =
3313 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3314 // Mangle a floating-point zero of the appropriate type.
3315 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3317 mangleFloat(Imag->getValue());
3320 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3321 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3322 Value.setIsSigned(true);
3323 mangleNumber(Value);
3329 case Expr::StringLiteralClass: {
3330 // Revised proposal from David Vandervoorde, 2010.07.15.
3332 assert(isa<ConstantArrayType>(E->getType()));
3333 mangleType(E->getType());
3338 case Expr::GNUNullExprClass:
3339 // FIXME: should this really be mangled the same as nullptr?
3342 case Expr::CXXNullPtrLiteralExprClass: {
3347 case Expr::PackExpansionExprClass:
3349 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3352 case Expr::SizeOfPackExprClass: {
3354 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
3355 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3356 mangleTemplateParameter(TTP->getIndex());
3357 else if (const NonTypeTemplateParmDecl *NTTP
3358 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3359 mangleTemplateParameter(NTTP->getIndex());
3360 else if (const TemplateTemplateParmDecl *TempTP
3361 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3362 mangleTemplateParameter(TempTP->getIndex());
3364 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3368 case Expr::MaterializeTemporaryExprClass: {
3369 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3373 case Expr::CXXFoldExprClass: {
3374 auto *FE = cast<CXXFoldExpr>(E);
3375 if (FE->isLeftFold())
3376 Out << (FE->getInit() ? "fL" : "fl");
3378 Out << (FE->getInit() ? "fR" : "fr");
3380 if (FE->getOperator() == BO_PtrMemD)
3384 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3388 mangleExpression(FE->getLHS());
3390 mangleExpression(FE->getRHS());
3394 case Expr::CXXThisExprClass:
3400 /// Mangle an expression which refers to a parameter variable.
3402 /// <expression> ::= <function-param>
3403 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3404 /// <function-param> ::= fp <top-level CV-qualifiers>
3405 /// <parameter-2 non-negative number> _ # L == 0, I > 0
3406 /// <function-param> ::= fL <L-1 non-negative number>
3407 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
3408 /// <function-param> ::= fL <L-1 non-negative number>
3409 /// p <top-level CV-qualifiers>
3410 /// <I-1 non-negative number> _ # L > 0, I > 0
3412 /// L is the nesting depth of the parameter, defined as 1 if the
3413 /// parameter comes from the innermost function prototype scope
3414 /// enclosing the current context, 2 if from the next enclosing
3415 /// function prototype scope, and so on, with one special case: if
3416 /// we've processed the full parameter clause for the innermost
3417 /// function type, then L is one less. This definition conveniently
3418 /// makes it irrelevant whether a function's result type was written
3419 /// trailing or leading, but is otherwise overly complicated; the
3420 /// numbering was first designed without considering references to
3421 /// parameter in locations other than return types, and then the
3422 /// mangling had to be generalized without changing the existing
3425 /// I is the zero-based index of the parameter within its parameter
3426 /// declaration clause. Note that the original ABI document describes
3427 /// this using 1-based ordinals.
3428 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3429 unsigned parmDepth = parm->getFunctionScopeDepth();
3430 unsigned parmIndex = parm->getFunctionScopeIndex();
3433 // parmDepth does not include the declaring function prototype.
3434 // FunctionTypeDepth does account for that.
3435 assert(parmDepth < FunctionTypeDepth.getDepth());
3436 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3437 if (FunctionTypeDepth.isInResultType())
3440 if (nestingDepth == 0) {
3443 Out << "fL" << (nestingDepth - 1) << 'p';
3446 // Top-level qualifiers. We don't have to worry about arrays here,
3447 // because parameters declared as arrays should already have been
3448 // transformed to have pointer type. FIXME: apparently these don't
3449 // get mangled if used as an rvalue of a known non-class type?
3450 assert(!parm->getType()->isArrayType()
3451 && "parameter's type is still an array type?");
3452 mangleQualifiers(parm->getType().getQualifiers());
3455 if (parmIndex != 0) {
3456 Out << (parmIndex - 1);
3461 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3462 // <ctor-dtor-name> ::= C1 # complete object constructor
3463 // ::= C2 # base object constructor
3465 // In addition, C5 is a comdat name with C1 and C2 in it.
3476 case Ctor_DefaultClosure:
3477 case Ctor_CopyingClosure:
3478 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
3482 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3483 // <ctor-dtor-name> ::= D0 # deleting destructor
3484 // ::= D1 # complete object destructor
3485 // ::= D2 # base object destructor
3487 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
3504 void CXXNameMangler::mangleTemplateArgs(
3505 const ASTTemplateArgumentListInfo &TemplateArgs) {
3506 // <template-args> ::= I <template-arg>+ E
3508 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3509 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3513 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3514 // <template-args> ::= I <template-arg>+ E
3516 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3517 mangleTemplateArg(AL[i]);
3521 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3522 unsigned NumTemplateArgs) {
3523 // <template-args> ::= I <template-arg>+ E
3525 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3526 mangleTemplateArg(TemplateArgs[i]);
3530 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3531 // <template-arg> ::= <type> # type or template
3532 // ::= X <expression> E # expression
3533 // ::= <expr-primary> # simple expressions
3534 // ::= J <template-arg>* E # argument pack
3535 if (!A.isInstantiationDependent() || A.isDependent())
3536 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3538 switch (A.getKind()) {
3539 case TemplateArgument::Null:
3540 llvm_unreachable("Cannot mangle NULL template argument");
3542 case TemplateArgument::Type:
3543 mangleType(A.getAsType());
3545 case TemplateArgument::Template:
3546 // This is mangled as <type>.
3547 mangleType(A.getAsTemplate());
3549 case TemplateArgument::TemplateExpansion:
3550 // <type> ::= Dp <type> # pack expansion (C++0x)
3552 mangleType(A.getAsTemplateOrTemplatePattern());
3554 case TemplateArgument::Expression: {
3555 // It's possible to end up with a DeclRefExpr here in certain
3556 // dependent cases, in which case we should mangle as a
3558 const Expr *E = A.getAsExpr()->IgnoreParens();
3559 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3560 const ValueDecl *D = DRE->getDecl();
3561 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3570 mangleExpression(E);
3574 case TemplateArgument::Integral:
3575 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3577 case TemplateArgument::Declaration: {
3578 // <expr-primary> ::= L <mangled-name> E # external name
3579 // Clang produces AST's where pointer-to-member-function expressions
3580 // and pointer-to-function expressions are represented as a declaration not
3581 // an expression. We compensate for it here to produce the correct mangling.
3582 ValueDecl *D = A.getAsDecl();
3583 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
3584 if (compensateMangling) {
3586 mangleOperatorName(OO_Amp, 1);
3590 // References to external entities use the mangled name; if the name would
3591 // not normally be manged then mangle it as unqualified.
3595 if (compensateMangling)
3600 case TemplateArgument::NullPtr: {
3601 // <expr-primary> ::= L <type> 0 E
3603 mangleType(A.getNullPtrType());
3607 case TemplateArgument::Pack: {
3608 // <template-arg> ::= J <template-arg>* E
3610 for (const auto &P : A.pack_elements())
3611 mangleTemplateArg(P);
3617 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3618 // <template-param> ::= T_ # first template parameter
3619 // ::= T <parameter-2 non-negative number> _
3623 Out << 'T' << (Index - 1) << '_';
3626 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3629 else if (SeqID > 1) {
3632 // <seq-id> is encoded in base-36, using digits and upper case letters.
3633 char Buffer[7]; // log(2**32) / log(36) ~= 7
3634 MutableArrayRef<char> BufferRef(Buffer);
3635 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
3637 for (; SeqID != 0; SeqID /= 36) {
3638 unsigned C = SeqID % 36;
3639 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3642 Out.write(I.base(), I - BufferRef.rbegin());
3647 void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3648 bool result = mangleSubstitution(type);
3649 assert(result && "no existing substitution for type");
3653 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3654 bool result = mangleSubstitution(tname);
3655 assert(result && "no existing substitution for template name");
3659 // <substitution> ::= S <seq-id> _
3661 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3662 // Try one of the standard substitutions first.
3663 if (mangleStandardSubstitution(ND))
3666 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3667 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3670 /// Determine whether the given type has any qualifiers that are relevant for
3672 static bool hasMangledSubstitutionQualifiers(QualType T) {
3673 Qualifiers Qs = T.getQualifiers();
3674 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3677 bool CXXNameMangler::mangleSubstitution(QualType T) {
3678 if (!hasMangledSubstitutionQualifiers(T)) {
3679 if (const RecordType *RT = T->getAs<RecordType>())
3680 return mangleSubstitution(RT->getDecl());
3683 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3685 return mangleSubstitution(TypePtr);
3688 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3689 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3690 return mangleSubstitution(TD);
3692 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3693 return mangleSubstitution(
3694 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3697 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3698 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3699 if (I == Substitutions.end())
3702 unsigned SeqID = I->second;
3709 static bool isCharType(QualType T) {
3713 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3714 T->isSpecificBuiltinType(BuiltinType::Char_U);
3717 /// Returns whether a given type is a template specialization of a given name
3718 /// with a single argument of type char.
3719 static bool isCharSpecialization(QualType T, const char *Name) {
3723 const RecordType *RT = T->getAs<RecordType>();
3727 const ClassTemplateSpecializationDecl *SD =
3728 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3732 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3735 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3736 if (TemplateArgs.size() != 1)
3739 if (!isCharType(TemplateArgs[0].getAsType()))
3742 return SD->getIdentifier()->getName() == Name;
3745 template <std::size_t StrLen>
3746 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3747 const char (&Str)[StrLen]) {
3748 if (!SD->getIdentifier()->isStr(Str))
3751 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3752 if (TemplateArgs.size() != 2)
3755 if (!isCharType(TemplateArgs[0].getAsType()))
3758 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3764 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3765 // <substitution> ::= St # ::std::
3766 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3773 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3774 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3777 // <substitution> ::= Sa # ::std::allocator
3778 if (TD->getIdentifier()->isStr("allocator")) {
3783 // <<substitution> ::= Sb # ::std::basic_string
3784 if (TD->getIdentifier()->isStr("basic_string")) {
3790 if (const ClassTemplateSpecializationDecl *SD =
3791 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3792 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3795 // <substitution> ::= Ss # ::std::basic_string<char,
3796 // ::std::char_traits<char>,
3797 // ::std::allocator<char> >
3798 if (SD->getIdentifier()->isStr("basic_string")) {
3799 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3801 if (TemplateArgs.size() != 3)
3804 if (!isCharType(TemplateArgs[0].getAsType()))
3807 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3810 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3817 // <substitution> ::= Si # ::std::basic_istream<char,
3818 // ::std::char_traits<char> >
3819 if (isStreamCharSpecialization(SD, "basic_istream")) {
3824 // <substitution> ::= So # ::std::basic_ostream<char,
3825 // ::std::char_traits<char> >
3826 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3831 // <substitution> ::= Sd # ::std::basic_iostream<char,
3832 // ::std::char_traits<char> >
3833 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3841 void CXXNameMangler::addSubstitution(QualType T) {
3842 if (!hasMangledSubstitutionQualifiers(T)) {
3843 if (const RecordType *RT = T->getAs<RecordType>()) {
3844 addSubstitution(RT->getDecl());
3849 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3850 addSubstitution(TypePtr);
3853 void CXXNameMangler::addSubstitution(TemplateName Template) {
3854 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3855 return addSubstitution(TD);
3857 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3858 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3861 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3862 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3863 Substitutions[Ptr] = SeqID++;
3868 /// Mangles the name of the declaration D and emits that name to the given
3871 /// If the declaration D requires a mangled name, this routine will emit that
3872 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3873 /// and this routine will return false. In this case, the caller should just
3874 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
3876 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
3878 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3879 "Invalid mangleName() call, argument is not a variable or function!");
3880 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3881 "Invalid mangleName() call on 'structor decl!");
3883 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3884 getASTContext().getSourceManager(),
3885 "Mangling declaration");
3887 CXXNameMangler Mangler(*this, Out, D);
3891 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3894 CXXNameMangler Mangler(*this, Out, D, Type);
3898 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3901 CXXNameMangler Mangler(*this, Out, D, Type);
3905 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
3907 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
3911 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
3913 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
3917 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3918 const ThunkInfo &Thunk,
3920 // <special-name> ::= T <call-offset> <base encoding>
3921 // # base is the nominal target function of thunk
3922 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3923 // # base is the nominal target function of thunk
3924 // # first call-offset is 'this' adjustment
3925 // # second call-offset is result adjustment
3927 assert(!isa<CXXDestructorDecl>(MD) &&
3928 "Use mangleCXXDtor for destructor decls!");
3929 CXXNameMangler Mangler(*this, Out);
3930 Mangler.getStream() << "_ZT";
3931 if (!Thunk.Return.isEmpty())
3932 Mangler.getStream() << 'c';
3934 // Mangle the 'this' pointer adjustment.
3935 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
3936 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
3938 // Mangle the return pointer adjustment if there is one.
3939 if (!Thunk.Return.isEmpty())
3940 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
3941 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
3943 Mangler.mangleFunctionEncoding(MD);
3946 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
3947 const CXXDestructorDecl *DD, CXXDtorType Type,
3948 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
3949 // <special-name> ::= T <call-offset> <base encoding>
3950 // # base is the nominal target function of thunk
3951 CXXNameMangler Mangler(*this, Out, DD, Type);
3952 Mangler.getStream() << "_ZT";
3954 // Mangle the 'this' pointer adjustment.
3955 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
3956 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
3958 Mangler.mangleFunctionEncoding(DD);
3961 /// Returns the mangled name for a guard variable for the passed in VarDecl.
3962 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
3964 // <special-name> ::= GV <object name> # Guard variable for one-time
3966 CXXNameMangler Mangler(*this, Out);
3967 Mangler.getStream() << "_ZGV";
3968 Mangler.mangleName(D);
3971 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
3973 // These symbols are internal in the Itanium ABI, so the names don't matter.
3974 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
3975 // avoid duplicate symbols.
3976 Out << "__cxx_global_var_init";
3979 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3981 // Prefix the mangling of D with __dtor_.
3982 CXXNameMangler Mangler(*this, Out);
3983 Mangler.getStream() << "__dtor_";
3984 if (shouldMangleDeclName(D))
3987 Mangler.getStream() << D->getName();
3990 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
3991 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3992 CXXNameMangler Mangler(*this, Out);
3993 Mangler.getStream() << "__filt_";
3994 if (shouldMangleDeclName(EnclosingDecl))
3995 Mangler.mangle(EnclosingDecl);
3997 Mangler.getStream() << EnclosingDecl->getName();
4000 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4001 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4002 CXXNameMangler Mangler(*this, Out);
4003 Mangler.getStream() << "__fin_";
4004 if (shouldMangleDeclName(EnclosingDecl))
4005 Mangler.mangle(EnclosingDecl);
4007 Mangler.getStream() << EnclosingDecl->getName();
4010 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4012 // <special-name> ::= TH <object name>
4013 CXXNameMangler Mangler(*this, Out);
4014 Mangler.getStream() << "_ZTH";
4015 Mangler.mangleName(D);
4019 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4021 // <special-name> ::= TW <object name>
4022 CXXNameMangler Mangler(*this, Out);
4023 Mangler.getStream() << "_ZTW";
4024 Mangler.mangleName(D);
4027 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
4028 unsigned ManglingNumber,
4030 // We match the GCC mangling here.
4031 // <special-name> ::= GR <object name>
4032 CXXNameMangler Mangler(*this, Out);
4033 Mangler.getStream() << "_ZGR";
4034 Mangler.mangleName(D);
4035 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
4036 Mangler.mangleSeqID(ManglingNumber - 1);
4039 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4041 // <special-name> ::= TV <type> # virtual table
4042 CXXNameMangler Mangler(*this, Out);
4043 Mangler.getStream() << "_ZTV";
4044 Mangler.mangleNameOrStandardSubstitution(RD);
4047 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4049 // <special-name> ::= TT <type> # VTT structure
4050 CXXNameMangler Mangler(*this, Out);
4051 Mangler.getStream() << "_ZTT";
4052 Mangler.mangleNameOrStandardSubstitution(RD);
4055 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4057 const CXXRecordDecl *Type,
4059 // <special-name> ::= TC <type> <offset number> _ <base type>
4060 CXXNameMangler Mangler(*this, Out);
4061 Mangler.getStream() << "_ZTC";
4062 Mangler.mangleNameOrStandardSubstitution(RD);
4063 Mangler.getStream() << Offset;
4064 Mangler.getStream() << '_';
4065 Mangler.mangleNameOrStandardSubstitution(Type);
4068 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
4069 // <special-name> ::= TI <type> # typeinfo structure
4070 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4071 CXXNameMangler Mangler(*this, Out);
4072 Mangler.getStream() << "_ZTI";
4073 Mangler.mangleType(Ty);
4076 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4078 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4079 CXXNameMangler Mangler(*this, Out);
4080 Mangler.getStream() << "_ZTS";
4081 Mangler.mangleType(Ty);
4084 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4085 mangleCXXRTTIName(Ty, Out);
4088 void ItaniumMangleContextImpl::mangleCXXVTableBitSet(const CXXRecordDecl *RD,
4090 if (!RD->isExternallyVisible()) {
4091 // This part of the identifier needs to be unique across all translation
4092 // units in the linked program. The scheme fails if multiple translation
4093 // units are compiled using the same relative source file path, or if
4094 // multiple translation units are built from the same source file.
4095 SourceManager &SM = getASTContext().getSourceManager();
4096 Out << "[" << SM.getFileEntryForID(SM.getMainFileID())->getName() << "]";
4099 CXXNameMangler Mangler(*this, Out);
4100 Mangler.mangleType(QualType(RD->getTypeForDecl(), 0));
4103 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4104 llvm_unreachable("Can't mangle string literals");
4107 ItaniumMangleContext *
4108 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4109 return new ItaniumMangleContextImpl(Context, Diags);