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 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
178 // Lambda closure types are already numbered.
182 // Anonymous tags are already numbered.
183 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
184 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
188 // Use the canonical number for externally visible decls.
189 if (ND->isExternallyVisible()) {
190 unsigned discriminator = getASTContext().getManglingNumber(ND);
191 if (discriminator == 1)
193 disc = discriminator - 2;
197 // Make up a reasonable number for internal decls.
198 unsigned &discriminator = Uniquifier[ND];
199 if (!discriminator) {
200 const DeclContext *DC = getEffectiveDeclContext(ND);
201 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
203 if (discriminator == 1)
205 disc = discriminator-2;
211 /// Manage the mangling of a single name.
212 class CXXNameMangler {
213 ItaniumMangleContextImpl &Context;
216 /// The "structor" is the top-level declaration being mangled, if
217 /// that's not a template specialization; otherwise it's the pattern
218 /// for that specialization.
219 const NamedDecl *Structor;
220 unsigned StructorType;
222 /// The next substitution sequence number.
225 class FunctionTypeDepthState {
228 enum { InResultTypeMask = 1 };
231 FunctionTypeDepthState() : Bits(0) {}
233 /// The number of function types we're inside.
234 unsigned getDepth() const {
238 /// True if we're in the return type of the innermost function type.
239 bool isInResultType() const {
240 return Bits & InResultTypeMask;
243 FunctionTypeDepthState push() {
244 FunctionTypeDepthState tmp = *this;
245 Bits = (Bits & ~InResultTypeMask) + 2;
249 void enterResultType() {
250 Bits |= InResultTypeMask;
253 void leaveResultType() {
254 Bits &= ~InResultTypeMask;
257 void pop(FunctionTypeDepthState saved) {
258 assert(getDepth() == saved.getDepth() + 1);
264 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
266 ASTContext &getASTContext() const { return Context.getASTContext(); }
269 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
270 const NamedDecl *D = nullptr)
271 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
273 // These can't be mangled without a ctor type or dtor type.
274 assert(!D || (!isa<CXXDestructorDecl>(D) &&
275 !isa<CXXConstructorDecl>(D)));
277 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
278 const CXXConstructorDecl *D, CXXCtorType Type)
279 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
281 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
282 const CXXDestructorDecl *D, CXXDtorType Type)
283 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
288 if (Out.str()[0] == '\01')
292 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
293 assert(status == 0 && "Could not demangle mangled name!");
297 raw_ostream &getStream() { return Out; }
299 void mangle(const NamedDecl *D);
300 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
301 void mangleNumber(const llvm::APSInt &I);
302 void mangleNumber(int64_t Number);
303 void mangleFloat(const llvm::APFloat &F);
304 void mangleFunctionEncoding(const FunctionDecl *FD);
305 void mangleSeqID(unsigned SeqID);
306 void mangleName(const NamedDecl *ND);
307 void mangleType(QualType T);
308 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
312 bool mangleSubstitution(const NamedDecl *ND);
313 bool mangleSubstitution(QualType T);
314 bool mangleSubstitution(TemplateName Template);
315 bool mangleSubstitution(uintptr_t Ptr);
317 void mangleExistingSubstitution(QualType type);
318 void mangleExistingSubstitution(TemplateName name);
320 bool mangleStandardSubstitution(const NamedDecl *ND);
322 void addSubstitution(const NamedDecl *ND) {
323 ND = cast<NamedDecl>(ND->getCanonicalDecl());
325 addSubstitution(reinterpret_cast<uintptr_t>(ND));
327 void addSubstitution(QualType T);
328 void addSubstitution(TemplateName Template);
329 void addSubstitution(uintptr_t Ptr);
331 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
332 bool recursive = false);
333 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
334 DeclarationName name,
335 unsigned KnownArity = UnknownArity);
337 void mangleName(const TemplateDecl *TD,
338 const TemplateArgument *TemplateArgs,
339 unsigned NumTemplateArgs);
340 void mangleUnqualifiedName(const NamedDecl *ND) {
341 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
343 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
344 unsigned KnownArity);
345 void mangleUnscopedName(const NamedDecl *ND);
346 void mangleUnscopedTemplateName(const TemplateDecl *ND);
347 void mangleUnscopedTemplateName(TemplateName);
348 void mangleSourceName(const IdentifierInfo *II);
349 void mangleLocalName(const Decl *D);
350 void mangleBlockForPrefix(const BlockDecl *Block);
351 void mangleUnqualifiedBlock(const BlockDecl *Block);
352 void mangleLambda(const CXXRecordDecl *Lambda);
353 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
354 bool NoFunction=false);
355 void mangleNestedName(const TemplateDecl *TD,
356 const TemplateArgument *TemplateArgs,
357 unsigned NumTemplateArgs);
358 void manglePrefix(NestedNameSpecifier *qualifier);
359 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
360 void manglePrefix(QualType type);
361 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
362 void mangleTemplatePrefix(TemplateName Template);
363 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
364 StringRef Prefix = "");
365 void mangleOperatorName(DeclarationName Name, unsigned Arity);
366 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
367 void mangleQualifiers(Qualifiers Quals);
368 void mangleRefQualifier(RefQualifierKind RefQualifier);
370 void mangleObjCMethodName(const ObjCMethodDecl *MD);
372 // Declare manglers for every type class.
373 #define ABSTRACT_TYPE(CLASS, PARENT)
374 #define NON_CANONICAL_TYPE(CLASS, PARENT)
375 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
376 #include "clang/AST/TypeNodes.def"
378 void mangleType(const TagType*);
379 void mangleType(TemplateName);
380 void mangleBareFunctionType(const FunctionType *T, bool MangleReturnType,
381 const FunctionDecl *FD = nullptr);
382 void mangleNeonVectorType(const VectorType *T);
383 void mangleAArch64NeonVectorType(const VectorType *T);
385 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
386 void mangleMemberExprBase(const Expr *base, bool isArrow);
387 void mangleMemberExpr(const Expr *base, bool isArrow,
388 NestedNameSpecifier *qualifier,
389 NamedDecl *firstQualifierLookup,
390 DeclarationName name,
391 unsigned knownArity);
392 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
393 void mangleInitListElements(const InitListExpr *InitList);
394 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
395 void mangleCXXCtorType(CXXCtorType T);
396 void mangleCXXDtorType(CXXDtorType T);
398 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
399 unsigned NumTemplateArgs);
400 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
401 unsigned NumTemplateArgs);
402 void mangleTemplateArgs(const TemplateArgumentList &AL);
403 void mangleTemplateArg(TemplateArgument A);
405 void mangleTemplateParameter(unsigned Index);
407 void mangleFunctionParam(const ParmVarDecl *parm);
412 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
413 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
415 LanguageLinkage L = FD->getLanguageLinkage();
416 // Overloadable functions need mangling.
417 if (FD->hasAttr<OverloadableAttr>())
420 // "main" is not mangled.
424 // C++ functions and those whose names are not a simple identifier need
426 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
429 // C functions are not mangled.
430 if (L == CLanguageLinkage)
434 // Otherwise, no mangling is done outside C++ mode.
435 if (!getASTContext().getLangOpts().CPlusPlus)
438 const VarDecl *VD = dyn_cast<VarDecl>(D);
440 // C variables are not mangled.
444 // Variables at global scope with non-internal linkage are not mangled
445 const DeclContext *DC = getEffectiveDeclContext(D);
446 // Check for extern variable declared locally.
447 if (DC->isFunctionOrMethod() && D->hasLinkage())
448 while (!DC->isNamespace() && !DC->isTranslationUnit())
449 DC = getEffectiveParentContext(DC);
450 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
451 !isa<VarTemplateSpecializationDecl>(D))
458 void CXXNameMangler::mangle(const NamedDecl *D) {
459 // <mangled-name> ::= _Z <encoding>
461 // ::= <special-name>
463 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
464 mangleFunctionEncoding(FD);
465 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
467 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
468 mangleName(IFD->getAnonField());
470 mangleName(cast<FieldDecl>(D));
473 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
474 // <encoding> ::= <function name> <bare-function-type>
477 // Don't mangle in the type if this isn't a decl we should typically mangle.
478 if (!Context.shouldMangleDeclName(FD))
481 if (FD->hasAttr<EnableIfAttr>()) {
482 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
483 Out << "Ua9enable_ifI";
484 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
486 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
487 E = FD->getAttrs().rend();
489 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
493 mangleExpression(EIA->getCond());
497 FunctionTypeDepth.pop(Saved);
500 // Whether the mangling of a function type includes the return type depends on
501 // the context and the nature of the function. The rules for deciding whether
502 // the return type is included are:
504 // 1. Template functions (names or types) have return types encoded, with
505 // the exceptions listed below.
506 // 2. Function types not appearing as part of a function name mangling,
507 // e.g. parameters, pointer types, etc., have return type encoded, with the
508 // exceptions listed below.
509 // 3. Non-template function names do not have return types encoded.
511 // The exceptions mentioned in (1) and (2) above, for which the return type is
512 // never included, are
515 // 3. Conversion operator functions, e.g. operator int.
516 bool MangleReturnType = false;
517 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
518 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
519 isa<CXXConversionDecl>(FD)))
520 MangleReturnType = true;
522 // Mangle the type of the primary template.
523 FD = PrimaryTemplate->getTemplatedDecl();
526 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
527 MangleReturnType, FD);
530 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
531 while (isa<LinkageSpecDecl>(DC)) {
532 DC = getEffectiveParentContext(DC);
538 /// Return whether a given namespace is the 'std' namespace.
539 static bool isStd(const NamespaceDecl *NS) {
540 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
541 ->isTranslationUnit())
544 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
545 return II && II->isStr("std");
548 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
550 static bool isStdNamespace(const DeclContext *DC) {
551 if (!DC->isNamespace())
554 return isStd(cast<NamespaceDecl>(DC));
557 static const TemplateDecl *
558 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
559 // Check if we have a function template.
560 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
561 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
562 TemplateArgs = FD->getTemplateSpecializationArgs();
567 // Check if we have a class template.
568 if (const ClassTemplateSpecializationDecl *Spec =
569 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
570 TemplateArgs = &Spec->getTemplateArgs();
571 return Spec->getSpecializedTemplate();
574 // Check if we have a variable template.
575 if (const VarTemplateSpecializationDecl *Spec =
576 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
577 TemplateArgs = &Spec->getTemplateArgs();
578 return Spec->getSpecializedTemplate();
584 void CXXNameMangler::mangleName(const NamedDecl *ND) {
585 // <name> ::= <nested-name>
586 // ::= <unscoped-name>
587 // ::= <unscoped-template-name> <template-args>
590 const DeclContext *DC = getEffectiveDeclContext(ND);
592 // If this is an extern variable declared locally, the relevant DeclContext
593 // is that of the containing namespace, or the translation unit.
594 // FIXME: This is a hack; extern variables declared locally should have
595 // a proper semantic declaration context!
596 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
597 while (!DC->isNamespace() && !DC->isTranslationUnit())
598 DC = getEffectiveParentContext(DC);
599 else if (GetLocalClassDecl(ND)) {
604 DC = IgnoreLinkageSpecDecls(DC);
606 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
607 // Check if we have a template.
608 const TemplateArgumentList *TemplateArgs = nullptr;
609 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
610 mangleUnscopedTemplateName(TD);
611 mangleTemplateArgs(*TemplateArgs);
615 mangleUnscopedName(ND);
619 if (isLocalContainerContext(DC)) {
624 mangleNestedName(ND, DC);
626 void CXXNameMangler::mangleName(const TemplateDecl *TD,
627 const TemplateArgument *TemplateArgs,
628 unsigned NumTemplateArgs) {
629 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
631 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
632 mangleUnscopedTemplateName(TD);
633 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
635 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
639 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
640 // <unscoped-name> ::= <unqualified-name>
641 // ::= St <unqualified-name> # ::std::
643 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
646 mangleUnqualifiedName(ND);
649 void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
650 // <unscoped-template-name> ::= <unscoped-name>
651 // ::= <substitution>
652 if (mangleSubstitution(ND))
655 // <template-template-param> ::= <template-param>
656 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
657 mangleTemplateParameter(TTP->getIndex());
659 mangleUnscopedName(ND->getTemplatedDecl());
664 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
665 // <unscoped-template-name> ::= <unscoped-name>
666 // ::= <substitution>
667 if (TemplateDecl *TD = Template.getAsTemplateDecl())
668 return mangleUnscopedTemplateName(TD);
670 if (mangleSubstitution(Template))
673 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
674 assert(Dependent && "Not a dependent template name?");
675 if (const IdentifierInfo *Id = Dependent->getIdentifier())
676 mangleSourceName(Id);
678 mangleOperatorName(Dependent->getOperator(), UnknownArity);
680 addSubstitution(Template);
683 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
685 // Floating-point literals are encoded using a fixed-length
686 // lowercase hexadecimal string corresponding to the internal
687 // representation (IEEE on Itanium), high-order bytes first,
688 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
690 // The 'without leading zeroes' thing seems to be an editorial
691 // mistake; see the discussion on cxx-abi-dev beginning on
694 // Our requirements here are just barely weird enough to justify
695 // using a custom algorithm instead of post-processing APInt::toString().
697 llvm::APInt valueBits = f.bitcastToAPInt();
698 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
699 assert(numCharacters != 0);
701 // Allocate a buffer of the right number of characters.
702 SmallVector<char, 20> buffer(numCharacters);
704 // Fill the buffer left-to-right.
705 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
706 // The bit-index of the next hex digit.
707 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
709 // Project out 4 bits starting at 'digitIndex'.
710 llvm::integerPart hexDigit
711 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
712 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
715 // Map that over to a lowercase hex digit.
716 static const char charForHex[16] = {
717 '0', '1', '2', '3', '4', '5', '6', '7',
718 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
720 buffer[stringIndex] = charForHex[hexDigit];
723 Out.write(buffer.data(), numCharacters);
726 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
727 if (Value.isSigned() && Value.isNegative()) {
729 Value.abs().print(Out, /*signed*/ false);
731 Value.print(Out, /*signed*/ false);
735 void CXXNameMangler::mangleNumber(int64_t Number) {
736 // <number> ::= [n] <non-negative decimal integer>
745 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
746 // <call-offset> ::= h <nv-offset> _
747 // ::= v <v-offset> _
748 // <nv-offset> ::= <offset number> # non-virtual base override
749 // <v-offset> ::= <offset number> _ <virtual offset number>
750 // # virtual base override, with vcall offset
753 mangleNumber(NonVirtual);
759 mangleNumber(NonVirtual);
761 mangleNumber(Virtual);
765 void CXXNameMangler::manglePrefix(QualType type) {
766 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
767 if (!mangleSubstitution(QualType(TST, 0))) {
768 mangleTemplatePrefix(TST->getTemplateName());
770 // FIXME: GCC does not appear to mangle the template arguments when
771 // the template in question is a dependent template name. Should we
772 // emulate that badness?
773 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
774 addSubstitution(QualType(TST, 0));
776 } else if (const auto *DTST =
777 type->getAs<DependentTemplateSpecializationType>()) {
778 if (!mangleSubstitution(QualType(DTST, 0))) {
779 TemplateName Template = getASTContext().getDependentTemplateName(
780 DTST->getQualifier(), DTST->getIdentifier());
781 mangleTemplatePrefix(Template);
783 // FIXME: GCC does not appear to mangle the template arguments when
784 // the template in question is a dependent template name. Should we
785 // emulate that badness?
786 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
787 addSubstitution(QualType(DTST, 0));
790 // We use the QualType mangle type variant here because it handles
796 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
798 /// \param recursive - true if this is being called recursively,
799 /// i.e. if there is more prefix "to the right".
800 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
804 // <unresolved-name> ::= [gs] <base-unresolved-name>
806 // T::x / decltype(p)::x
807 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
809 // T::N::x /decltype(p)::N::x
810 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
811 // <base-unresolved-name>
813 // A::x, N::y, A<T>::z; "gs" means leading "::"
814 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
815 // <base-unresolved-name>
817 switch (qualifier->getKind()) {
818 case NestedNameSpecifier::Global:
821 // We want an 'sr' unless this is the entire NNS.
825 // We never want an 'E' here.
828 case NestedNameSpecifier::Super:
829 llvm_unreachable("Can't mangle __super specifier");
831 case NestedNameSpecifier::Namespace:
832 if (qualifier->getPrefix())
833 mangleUnresolvedPrefix(qualifier->getPrefix(),
837 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
839 case NestedNameSpecifier::NamespaceAlias:
840 if (qualifier->getPrefix())
841 mangleUnresolvedPrefix(qualifier->getPrefix(),
845 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
848 case NestedNameSpecifier::TypeSpec:
849 case NestedNameSpecifier::TypeSpecWithTemplate: {
850 const Type *type = qualifier->getAsType();
852 // We only want to use an unresolved-type encoding if this is one of:
854 // - a template type parameter
855 // - a template template parameter with arguments
856 // In all of these cases, we should have no prefix.
857 if (qualifier->getPrefix()) {
858 mangleUnresolvedPrefix(qualifier->getPrefix(),
861 // Otherwise, all the cases want this.
865 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
871 case NestedNameSpecifier::Identifier:
872 // Member expressions can have these without prefixes.
873 if (qualifier->getPrefix())
874 mangleUnresolvedPrefix(qualifier->getPrefix(),
879 mangleSourceName(qualifier->getAsIdentifier());
883 // If this was the innermost part of the NNS, and we fell out to
884 // here, append an 'E'.
889 /// Mangle an unresolved-name, which is generally used for names which
890 /// weren't resolved to specific entities.
891 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
892 DeclarationName name,
893 unsigned knownArity) {
894 if (qualifier) mangleUnresolvedPrefix(qualifier);
895 switch (name.getNameKind()) {
896 // <base-unresolved-name> ::= <simple-id>
897 case DeclarationName::Identifier:
898 mangleSourceName(name.getAsIdentifierInfo());
900 // <base-unresolved-name> ::= dn <destructor-name>
901 case DeclarationName::CXXDestructorName:
903 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
905 // <base-unresolved-name> ::= on <operator-name>
906 case DeclarationName::CXXConversionFunctionName:
907 case DeclarationName::CXXLiteralOperatorName:
908 case DeclarationName::CXXOperatorName:
910 mangleOperatorName(name, knownArity);
912 case DeclarationName::CXXConstructorName:
913 llvm_unreachable("Can't mangle a constructor name!");
914 case DeclarationName::CXXUsingDirective:
915 llvm_unreachable("Can't mangle a using directive name!");
916 case DeclarationName::ObjCMultiArgSelector:
917 case DeclarationName::ObjCOneArgSelector:
918 case DeclarationName::ObjCZeroArgSelector:
919 llvm_unreachable("Can't mangle Objective-C selector names here!");
923 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
924 DeclarationName Name,
925 unsigned KnownArity) {
926 unsigned Arity = KnownArity;
927 // <unqualified-name> ::= <operator-name>
928 // ::= <ctor-dtor-name>
930 switch (Name.getNameKind()) {
931 case DeclarationName::Identifier: {
932 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
933 // We must avoid conflicts between internally- and externally-
934 // linked variable and function declaration names in the same TU:
935 // void test() { extern void foo(); }
936 // static void foo();
937 // This naming convention is the same as that followed by GCC,
938 // though it shouldn't actually matter.
939 if (ND && ND->getFormalLinkage() == InternalLinkage &&
940 getEffectiveDeclContext(ND)->isFileContext())
943 mangleSourceName(II);
947 // Otherwise, an anonymous entity. We must have a declaration.
948 assert(ND && "mangling empty name without declaration");
950 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
951 if (NS->isAnonymousNamespace()) {
952 // This is how gcc mangles these names.
953 Out << "12_GLOBAL__N_1";
958 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
959 // We must have an anonymous union or struct declaration.
960 const RecordDecl *RD =
961 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
963 // Itanium C++ ABI 5.1.2:
965 // For the purposes of mangling, the name of an anonymous union is
966 // considered to be the name of the first named data member found by a
967 // pre-order, depth-first, declaration-order walk of the data members of
968 // the anonymous union. If there is no such data member (i.e., if all of
969 // the data members in the union are unnamed), then there is no way for
970 // a program to refer to the anonymous union, and there is therefore no
971 // need to mangle its name.
972 assert(RD->isAnonymousStructOrUnion()
973 && "Expected anonymous struct or union!");
974 const FieldDecl *FD = RD->findFirstNamedDataMember();
976 // It's actually possible for various reasons for us to get here
977 // with an empty anonymous struct / union. Fortunately, it
978 // doesn't really matter what name we generate.
980 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
982 mangleSourceName(FD->getIdentifier());
986 // Class extensions have no name as a category, and it's possible
987 // for them to be the semantic parent of certain declarations
988 // (primarily, tag decls defined within declarations). Such
989 // declarations will always have internal linkage, so the name
990 // doesn't really matter, but we shouldn't crash on them. For
991 // safety, just handle all ObjC containers here.
992 if (isa<ObjCContainerDecl>(ND))
995 // We must have an anonymous struct.
996 const TagDecl *TD = cast<TagDecl>(ND);
997 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
998 assert(TD->getDeclContext() == D->getDeclContext() &&
999 "Typedef should not be in another decl context!");
1000 assert(D->getDeclName().getAsIdentifierInfo() &&
1001 "Typedef was not named!");
1002 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1006 // <unnamed-type-name> ::= <closure-type-name>
1008 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1009 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1010 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1011 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1012 mangleLambda(Record);
1017 if (TD->isExternallyVisible()) {
1018 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1020 if (UnnamedMangle > 1)
1021 Out << UnnamedMangle - 2;
1026 // Get a unique id for the anonymous struct.
1027 unsigned AnonStructId = Context.getAnonymousStructId(TD);
1029 // Mangle it as a source name in the form
1031 // where n is the length of the string.
1034 Str += llvm::utostr(AnonStructId);
1041 case DeclarationName::ObjCZeroArgSelector:
1042 case DeclarationName::ObjCOneArgSelector:
1043 case DeclarationName::ObjCMultiArgSelector:
1044 llvm_unreachable("Can't mangle Objective-C selector names here!");
1046 case DeclarationName::CXXConstructorName:
1048 // If the named decl is the C++ constructor we're mangling, use the type
1050 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1052 // Otherwise, use the complete constructor name. This is relevant if a
1053 // class with a constructor is declared within a constructor.
1054 mangleCXXCtorType(Ctor_Complete);
1057 case DeclarationName::CXXDestructorName:
1059 // If the named decl is the C++ destructor we're mangling, use the type we
1061 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1063 // Otherwise, use the complete destructor name. This is relevant if a
1064 // class with a destructor is declared within a destructor.
1065 mangleCXXDtorType(Dtor_Complete);
1068 case DeclarationName::CXXOperatorName:
1069 if (ND && Arity == UnknownArity) {
1070 Arity = cast<FunctionDecl>(ND)->getNumParams();
1072 // If we have a member function, we need to include the 'this' pointer.
1073 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1074 if (!MD->isStatic())
1078 case DeclarationName::CXXConversionFunctionName:
1079 case DeclarationName::CXXLiteralOperatorName:
1080 mangleOperatorName(Name, Arity);
1083 case DeclarationName::CXXUsingDirective:
1084 llvm_unreachable("Can't mangle a using directive name!");
1088 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1089 // <source-name> ::= <positive length number> <identifier>
1090 // <number> ::= [n] <non-negative decimal integer>
1091 // <identifier> ::= <unqualified source code identifier>
1092 Out << II->getLength() << II->getName();
1095 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1096 const DeclContext *DC,
1099 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1100 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1101 // <template-args> E
1104 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1105 Qualifiers MethodQuals =
1106 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1107 // We do not consider restrict a distinguishing attribute for overloading
1108 // purposes so we must not mangle it.
1109 MethodQuals.removeRestrict();
1110 mangleQualifiers(MethodQuals);
1111 mangleRefQualifier(Method->getRefQualifier());
1114 // Check if we have a template.
1115 const TemplateArgumentList *TemplateArgs = nullptr;
1116 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1117 mangleTemplatePrefix(TD, NoFunction);
1118 mangleTemplateArgs(*TemplateArgs);
1121 manglePrefix(DC, NoFunction);
1122 mangleUnqualifiedName(ND);
1127 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1128 const TemplateArgument *TemplateArgs,
1129 unsigned NumTemplateArgs) {
1130 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1134 mangleTemplatePrefix(TD);
1135 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1140 void CXXNameMangler::mangleLocalName(const Decl *D) {
1141 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1142 // := Z <function encoding> E s [<discriminator>]
1143 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1145 // <discriminator> := _ <non-negative number>
1146 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1147 const RecordDecl *RD = GetLocalClassDecl(D);
1148 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1152 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1153 mangleObjCMethodName(MD);
1154 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1155 mangleBlockForPrefix(BD);
1157 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1162 // The parameter number is omitted for the last parameter, 0 for the
1163 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1164 // <entity name> will of course contain a <closure-type-name>: Its
1165 // numbering will be local to the particular argument in which it appears
1166 // -- other default arguments do not affect its encoding.
1167 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1168 if (CXXRD->isLambda()) {
1169 if (const ParmVarDecl *Parm
1170 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1171 if (const FunctionDecl *Func
1172 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1174 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1176 mangleNumber(Num - 2);
1182 // Mangle the name relative to the closest enclosing function.
1183 // equality ok because RD derived from ND above
1185 mangleUnqualifiedName(RD);
1186 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1187 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1188 mangleUnqualifiedBlock(BD);
1190 const NamedDecl *ND = cast<NamedDecl>(D);
1191 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
1193 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1194 // Mangle a block in a default parameter; see above explanation for
1196 if (const ParmVarDecl *Parm
1197 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1198 if (const FunctionDecl *Func
1199 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1201 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1203 mangleNumber(Num - 2);
1208 mangleUnqualifiedBlock(BD);
1210 mangleUnqualifiedName(cast<NamedDecl>(D));
1213 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1215 if (Context.getNextDiscriminator(ND, disc)) {
1219 Out << "__" << disc << '_';
1224 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1225 if (GetLocalClassDecl(Block)) {
1226 mangleLocalName(Block);
1229 const DeclContext *DC = getEffectiveDeclContext(Block);
1230 if (isLocalContainerContext(DC)) {
1231 mangleLocalName(Block);
1234 manglePrefix(getEffectiveDeclContext(Block));
1235 mangleUnqualifiedBlock(Block);
1238 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1239 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1240 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1241 Context->getDeclContext()->isRecord()) {
1242 if (const IdentifierInfo *Name
1243 = cast<NamedDecl>(Context)->getIdentifier()) {
1244 mangleSourceName(Name);
1250 // If we have a block mangling number, use it.
1251 unsigned Number = Block->getBlockManglingNumber();
1252 // Otherwise, just make up a number. It doesn't matter what it is because
1253 // the symbol in question isn't externally visible.
1255 Number = Context.getBlockId(Block, false);
1262 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1263 // If the context of a closure type is an initializer for a class member
1264 // (static or nonstatic), it is encoded in a qualified name with a final
1265 // <prefix> of the form:
1267 // <data-member-prefix> := <member source-name> M
1269 // Technically, the data-member-prefix is part of the <prefix>. However,
1270 // since a closure type will always be mangled with a prefix, it's easier
1271 // to emit that last part of the prefix here.
1272 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1273 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1274 Context->getDeclContext()->isRecord()) {
1275 if (const IdentifierInfo *Name
1276 = cast<NamedDecl>(Context)->getIdentifier()) {
1277 mangleSourceName(Name);
1284 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1285 getAs<FunctionProtoType>();
1286 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1287 Lambda->getLambdaStaticInvoker());
1290 // The number is omitted for the first closure type with a given
1291 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1292 // (in lexical order) with that same <lambda-sig> and context.
1294 // The AST keeps track of the number for us.
1295 unsigned Number = Lambda->getLambdaManglingNumber();
1296 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1298 mangleNumber(Number - 2);
1302 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1303 switch (qualifier->getKind()) {
1304 case NestedNameSpecifier::Global:
1308 case NestedNameSpecifier::Super:
1309 llvm_unreachable("Can't mangle __super specifier");
1311 case NestedNameSpecifier::Namespace:
1312 mangleName(qualifier->getAsNamespace());
1315 case NestedNameSpecifier::NamespaceAlias:
1316 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1319 case NestedNameSpecifier::TypeSpec:
1320 case NestedNameSpecifier::TypeSpecWithTemplate:
1321 manglePrefix(QualType(qualifier->getAsType(), 0));
1324 case NestedNameSpecifier::Identifier:
1325 // Member expressions can have these without prefixes, but that
1326 // should end up in mangleUnresolvedPrefix instead.
1327 assert(qualifier->getPrefix());
1328 manglePrefix(qualifier->getPrefix());
1330 mangleSourceName(qualifier->getAsIdentifier());
1334 llvm_unreachable("unexpected nested name specifier");
1337 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1338 // <prefix> ::= <prefix> <unqualified-name>
1339 // ::= <template-prefix> <template-args>
1340 // ::= <template-param>
1342 // ::= <substitution>
1344 DC = IgnoreLinkageSpecDecls(DC);
1346 if (DC->isTranslationUnit())
1349 if (NoFunction && isLocalContainerContext(DC))
1352 assert(!isLocalContainerContext(DC));
1354 const NamedDecl *ND = cast<NamedDecl>(DC);
1355 if (mangleSubstitution(ND))
1358 // Check if we have a template.
1359 const TemplateArgumentList *TemplateArgs = nullptr;
1360 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1361 mangleTemplatePrefix(TD);
1362 mangleTemplateArgs(*TemplateArgs);
1364 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1365 mangleUnqualifiedName(ND);
1368 addSubstitution(ND);
1371 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1372 // <template-prefix> ::= <prefix> <template unqualified-name>
1373 // ::= <template-param>
1374 // ::= <substitution>
1375 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1376 return mangleTemplatePrefix(TD);
1378 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1379 manglePrefix(Qualified->getQualifier());
1381 if (OverloadedTemplateStorage *Overloaded
1382 = Template.getAsOverloadedTemplate()) {
1383 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
1388 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1389 assert(Dependent && "Unknown template name kind?");
1390 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1391 manglePrefix(Qualifier);
1392 mangleUnscopedTemplateName(Template);
1395 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1397 // <template-prefix> ::= <prefix> <template unqualified-name>
1398 // ::= <template-param>
1399 // ::= <substitution>
1400 // <template-template-param> ::= <template-param>
1403 if (mangleSubstitution(ND))
1406 // <template-template-param> ::= <template-param>
1407 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1408 mangleTemplateParameter(TTP->getIndex());
1410 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1411 mangleUnqualifiedName(ND->getTemplatedDecl());
1414 addSubstitution(ND);
1417 /// Mangles a template name under the production <type>. Required for
1418 /// template template arguments.
1419 /// <type> ::= <class-enum-type>
1420 /// ::= <template-param>
1421 /// ::= <substitution>
1422 void CXXNameMangler::mangleType(TemplateName TN) {
1423 if (mangleSubstitution(TN))
1426 TemplateDecl *TD = nullptr;
1428 switch (TN.getKind()) {
1429 case TemplateName::QualifiedTemplate:
1430 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1433 case TemplateName::Template:
1434 TD = TN.getAsTemplateDecl();
1438 if (isa<TemplateTemplateParmDecl>(TD))
1439 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1444 case TemplateName::OverloadedTemplate:
1445 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1447 case TemplateName::DependentTemplate: {
1448 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1449 assert(Dependent->isIdentifier());
1451 // <class-enum-type> ::= <name>
1452 // <name> ::= <nested-name>
1453 mangleUnresolvedPrefix(Dependent->getQualifier());
1454 mangleSourceName(Dependent->getIdentifier());
1458 case TemplateName::SubstTemplateTemplateParm: {
1459 // Substituted template parameters are mangled as the substituted
1460 // template. This will check for the substitution twice, which is
1461 // fine, but we have to return early so that we don't try to *add*
1462 // the substitution twice.
1463 SubstTemplateTemplateParmStorage *subst
1464 = TN.getAsSubstTemplateTemplateParm();
1465 mangleType(subst->getReplacement());
1469 case TemplateName::SubstTemplateTemplateParmPack: {
1470 // FIXME: not clear how to mangle this!
1471 // template <template <class> class T...> class A {
1472 // template <template <class> class U...> void foo(B<T,U> x...);
1474 Out << "_SUBSTPACK_";
1479 addSubstitution(TN);
1482 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1484 // Only certain other types are valid as prefixes; enumerate them.
1485 switch (Ty->getTypeClass()) {
1488 case Type::Adjusted:
1491 case Type::BlockPointer:
1492 case Type::LValueReference:
1493 case Type::RValueReference:
1494 case Type::MemberPointer:
1495 case Type::ConstantArray:
1496 case Type::IncompleteArray:
1497 case Type::VariableArray:
1498 case Type::DependentSizedArray:
1499 case Type::DependentSizedExtVector:
1501 case Type::ExtVector:
1502 case Type::FunctionProto:
1503 case Type::FunctionNoProto:
1505 case Type::Attributed:
1507 case Type::PackExpansion:
1508 case Type::ObjCObject:
1509 case Type::ObjCInterface:
1510 case Type::ObjCObjectPointer:
1512 llvm_unreachable("type is illegal as a nested name specifier");
1514 case Type::SubstTemplateTypeParmPack:
1515 // FIXME: not clear how to mangle this!
1516 // template <class T...> class A {
1517 // template <class U...> void foo(decltype(T::foo(U())) x...);
1519 Out << "_SUBSTPACK_";
1522 // <unresolved-type> ::= <template-param>
1524 // ::= <template-template-param> <template-args>
1525 // (this last is not official yet)
1526 case Type::TypeOfExpr:
1528 case Type::Decltype:
1529 case Type::TemplateTypeParm:
1530 case Type::UnaryTransform:
1531 case Type::SubstTemplateTypeParm:
1533 // Some callers want a prefix before the mangled type.
1536 // This seems to do everything we want. It's not really
1537 // sanctioned for a substituted template parameter, though.
1540 // We never want to print 'E' directly after an unresolved-type,
1541 // so we return directly.
1545 mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
1548 case Type::UnresolvedUsing:
1550 cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
1555 mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
1558 case Type::TemplateSpecialization: {
1559 const TemplateSpecializationType *TST =
1560 cast<TemplateSpecializationType>(Ty);
1561 TemplateName TN = TST->getTemplateName();
1562 switch (TN.getKind()) {
1563 case TemplateName::Template:
1564 case TemplateName::QualifiedTemplate: {
1565 TemplateDecl *TD = TN.getAsTemplateDecl();
1567 // If the base is a template template parameter, this is an
1569 assert(TD && "no template for template specialization type");
1570 if (isa<TemplateTemplateParmDecl>(TD))
1571 goto unresolvedType;
1573 mangleSourceName(TD->getIdentifier());
1577 case TemplateName::OverloadedTemplate:
1578 case TemplateName::DependentTemplate:
1579 llvm_unreachable("invalid base for a template specialization type");
1581 case TemplateName::SubstTemplateTemplateParm: {
1582 SubstTemplateTemplateParmStorage *subst =
1583 TN.getAsSubstTemplateTemplateParm();
1584 mangleExistingSubstitution(subst->getReplacement());
1588 case TemplateName::SubstTemplateTemplateParmPack: {
1589 // FIXME: not clear how to mangle this!
1590 // template <template <class U> class T...> class A {
1591 // template <class U...> void foo(decltype(T<U>::foo) x...);
1593 Out << "_SUBSTPACK_";
1598 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1602 case Type::InjectedClassName:
1604 cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
1607 case Type::DependentName:
1608 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1611 case Type::DependentTemplateSpecialization: {
1612 const DependentTemplateSpecializationType *DTST =
1613 cast<DependentTemplateSpecializationType>(Ty);
1614 mangleSourceName(DTST->getIdentifier());
1615 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1619 case Type::Elaborated:
1620 return mangleUnresolvedTypeOrSimpleId(
1621 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1627 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1628 switch (Name.getNameKind()) {
1629 case DeclarationName::CXXConstructorName:
1630 case DeclarationName::CXXDestructorName:
1631 case DeclarationName::CXXUsingDirective:
1632 case DeclarationName::Identifier:
1633 case DeclarationName::ObjCMultiArgSelector:
1634 case DeclarationName::ObjCOneArgSelector:
1635 case DeclarationName::ObjCZeroArgSelector:
1636 llvm_unreachable("Not an operator name");
1638 case DeclarationName::CXXConversionFunctionName:
1639 // <operator-name> ::= cv <type> # (cast)
1641 mangleType(Name.getCXXNameType());
1644 case DeclarationName::CXXLiteralOperatorName:
1646 mangleSourceName(Name.getCXXLiteralIdentifier());
1649 case DeclarationName::CXXOperatorName:
1650 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1658 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1660 // <operator-name> ::= nw # new
1661 case OO_New: Out << "nw"; break;
1663 case OO_Array_New: Out << "na"; break;
1665 case OO_Delete: Out << "dl"; break;
1666 // ::= da # delete[]
1667 case OO_Array_Delete: Out << "da"; break;
1668 // ::= ps # + (unary)
1669 // ::= pl # + (binary or unknown)
1671 Out << (Arity == 1? "ps" : "pl"); break;
1672 // ::= ng # - (unary)
1673 // ::= mi # - (binary or unknown)
1675 Out << (Arity == 1? "ng" : "mi"); break;
1676 // ::= ad # & (unary)
1677 // ::= an # & (binary or unknown)
1679 Out << (Arity == 1? "ad" : "an"); break;
1680 // ::= de # * (unary)
1681 // ::= ml # * (binary or unknown)
1683 // Use binary when unknown.
1684 Out << (Arity == 1? "de" : "ml"); break;
1686 case OO_Tilde: Out << "co"; break;
1688 case OO_Slash: Out << "dv"; break;
1690 case OO_Percent: Out << "rm"; break;
1692 case OO_Pipe: Out << "or"; break;
1694 case OO_Caret: Out << "eo"; break;
1696 case OO_Equal: Out << "aS"; break;
1698 case OO_PlusEqual: Out << "pL"; break;
1700 case OO_MinusEqual: Out << "mI"; break;
1702 case OO_StarEqual: Out << "mL"; break;
1704 case OO_SlashEqual: Out << "dV"; break;
1706 case OO_PercentEqual: Out << "rM"; break;
1708 case OO_AmpEqual: Out << "aN"; break;
1710 case OO_PipeEqual: Out << "oR"; break;
1712 case OO_CaretEqual: Out << "eO"; break;
1714 case OO_LessLess: Out << "ls"; break;
1716 case OO_GreaterGreater: Out << "rs"; break;
1718 case OO_LessLessEqual: Out << "lS"; break;
1720 case OO_GreaterGreaterEqual: Out << "rS"; break;
1722 case OO_EqualEqual: Out << "eq"; break;
1724 case OO_ExclaimEqual: Out << "ne"; break;
1726 case OO_Less: Out << "lt"; break;
1728 case OO_Greater: Out << "gt"; break;
1730 case OO_LessEqual: Out << "le"; break;
1732 case OO_GreaterEqual: Out << "ge"; break;
1734 case OO_Exclaim: Out << "nt"; break;
1736 case OO_AmpAmp: Out << "aa"; break;
1738 case OO_PipePipe: Out << "oo"; break;
1740 case OO_PlusPlus: Out << "pp"; break;
1742 case OO_MinusMinus: Out << "mm"; break;
1744 case OO_Comma: Out << "cm"; break;
1746 case OO_ArrowStar: Out << "pm"; break;
1748 case OO_Arrow: Out << "pt"; break;
1750 case OO_Call: Out << "cl"; break;
1752 case OO_Subscript: Out << "ix"; break;
1755 // The conditional operator can't be overloaded, but we still handle it when
1756 // mangling expressions.
1757 case OO_Conditional: Out << "qu"; break;
1758 // Proposal on cxx-abi-dev, 2015-10-21.
1759 // ::= aw # co_await
1760 case OO_Coawait: Out << "aw"; break;
1763 case NUM_OVERLOADED_OPERATORS:
1764 llvm_unreachable("Not an overloaded operator");
1768 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1769 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1770 if (Quals.hasRestrict())
1772 if (Quals.hasVolatile())
1774 if (Quals.hasConst())
1777 if (Quals.hasAddressSpace()) {
1778 // Address space extension:
1780 // <type> ::= U <target-addrspace>
1781 // <type> ::= U <OpenCL-addrspace>
1782 // <type> ::= U <CUDA-addrspace>
1784 SmallString<64> ASString;
1785 unsigned AS = Quals.getAddressSpace();
1787 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1788 // <target-addrspace> ::= "AS" <address-space-number>
1789 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1790 ASString = "AS" + llvm::utostr_32(TargetAS);
1793 default: llvm_unreachable("Not a language specific address space");
1794 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1795 case LangAS::opencl_global: ASString = "CLglobal"; break;
1796 case LangAS::opencl_local: ASString = "CLlocal"; break;
1797 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1798 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1799 case LangAS::cuda_device: ASString = "CUdevice"; break;
1800 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1801 case LangAS::cuda_shared: ASString = "CUshared"; break;
1804 Out << 'U' << ASString.size() << ASString;
1807 StringRef LifetimeName;
1808 switch (Quals.getObjCLifetime()) {
1809 // Objective-C ARC Extension:
1811 // <type> ::= U "__strong"
1812 // <type> ::= U "__weak"
1813 // <type> ::= U "__autoreleasing"
1814 case Qualifiers::OCL_None:
1817 case Qualifiers::OCL_Weak:
1818 LifetimeName = "__weak";
1821 case Qualifiers::OCL_Strong:
1822 LifetimeName = "__strong";
1825 case Qualifiers::OCL_Autoreleasing:
1826 LifetimeName = "__autoreleasing";
1829 case Qualifiers::OCL_ExplicitNone:
1830 // The __unsafe_unretained qualifier is *not* mangled, so that
1831 // __unsafe_unretained types in ARC produce the same manglings as the
1832 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1833 // better ABI compatibility.
1835 // It's safe to do this because unqualified 'id' won't show up
1836 // in any type signatures that need to be mangled.
1839 if (!LifetimeName.empty())
1840 Out << 'U' << LifetimeName.size() << LifetimeName;
1843 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1844 // <ref-qualifier> ::= R # lvalue reference
1845 // ::= O # rvalue-reference
1846 switch (RefQualifier) {
1860 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1861 Context.mangleObjCMethodName(MD, Out);
1864 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1867 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1869 if (Ty->isOpenCLSpecificType())
1871 if (Ty->isBuiltinType())
1877 void CXXNameMangler::mangleType(QualType T) {
1878 // If our type is instantiation-dependent but not dependent, we mangle
1879 // it as it was written in the source, removing any top-level sugar.
1880 // Otherwise, use the canonical type.
1882 // FIXME: This is an approximation of the instantiation-dependent name
1883 // mangling rules, since we should really be using the type as written and
1884 // augmented via semantic analysis (i.e., with implicit conversions and
1885 // default template arguments) for any instantiation-dependent type.
1886 // Unfortunately, that requires several changes to our AST:
1887 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1888 // uniqued, so that we can handle substitutions properly
1889 // - Default template arguments will need to be represented in the
1890 // TemplateSpecializationType, since they need to be mangled even though
1891 // they aren't written.
1892 // - Conversions on non-type template arguments need to be expressed, since
1893 // they can affect the mangling of sizeof/alignof.
1894 if (!T->isInstantiationDependentType() || T->isDependentType())
1895 T = T.getCanonicalType();
1897 // Desugar any types that are purely sugar.
1899 // Don't desugar through template specialization types that aren't
1900 // type aliases. We need to mangle the template arguments as written.
1901 if (const TemplateSpecializationType *TST
1902 = dyn_cast<TemplateSpecializationType>(T))
1903 if (!TST->isTypeAlias())
1907 = T.getSingleStepDesugaredType(Context.getASTContext());
1914 SplitQualType split = T.split();
1915 Qualifiers quals = split.Quals;
1916 const Type *ty = split.Ty;
1918 bool isSubstitutable = isTypeSubstitutable(quals, ty);
1919 if (isSubstitutable && mangleSubstitution(T))
1922 // If we're mangling a qualified array type, push the qualifiers to
1923 // the element type.
1924 if (quals && isa<ArrayType>(T)) {
1925 ty = Context.getASTContext().getAsArrayType(T);
1926 quals = Qualifiers();
1928 // Note that we don't update T: we want to add the
1929 // substitution at the original type.
1933 mangleQualifiers(quals);
1934 // Recurse: even if the qualified type isn't yet substitutable,
1935 // the unqualified type might be.
1936 mangleType(QualType(ty, 0));
1938 switch (ty->getTypeClass()) {
1939 #define ABSTRACT_TYPE(CLASS, PARENT)
1940 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1942 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1944 #define TYPE(CLASS, PARENT) \
1946 mangleType(static_cast<const CLASS##Type*>(ty)); \
1948 #include "clang/AST/TypeNodes.def"
1952 // Add the substitution.
1953 if (isSubstitutable)
1957 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1958 if (!mangleStandardSubstitution(ND))
1962 void CXXNameMangler::mangleType(const BuiltinType *T) {
1963 // <type> ::= <builtin-type>
1964 // <builtin-type> ::= v # void
1968 // ::= a # signed char
1969 // ::= h # unsigned char
1971 // ::= t # unsigned short
1973 // ::= j # unsigned int
1975 // ::= m # unsigned long
1976 // ::= x # long long, __int64
1977 // ::= y # unsigned long long, __int64
1979 // ::= o # unsigned __int128
1982 // ::= e # long double, __float80
1983 // UNSUPPORTED: ::= g # __float128
1984 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1985 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1986 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1987 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1988 // ::= Di # char32_t
1989 // ::= Ds # char16_t
1990 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1991 // ::= u <source-name> # vendor extended type
1992 switch (T->getKind()) {
1993 case BuiltinType::Void:
1996 case BuiltinType::Bool:
1999 case BuiltinType::Char_U:
2000 case BuiltinType::Char_S:
2003 case BuiltinType::UChar:
2006 case BuiltinType::UShort:
2009 case BuiltinType::UInt:
2012 case BuiltinType::ULong:
2015 case BuiltinType::ULongLong:
2018 case BuiltinType::UInt128:
2021 case BuiltinType::SChar:
2024 case BuiltinType::WChar_S:
2025 case BuiltinType::WChar_U:
2028 case BuiltinType::Char16:
2031 case BuiltinType::Char32:
2034 case BuiltinType::Short:
2037 case BuiltinType::Int:
2040 case BuiltinType::Long:
2043 case BuiltinType::LongLong:
2046 case BuiltinType::Int128:
2049 case BuiltinType::Half:
2052 case BuiltinType::Float:
2055 case BuiltinType::Double:
2058 case BuiltinType::LongDouble:
2059 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2063 case BuiltinType::NullPtr:
2067 #define BUILTIN_TYPE(Id, SingletonId)
2068 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2069 case BuiltinType::Id:
2070 #include "clang/AST/BuiltinTypes.def"
2071 case BuiltinType::Dependent:
2072 llvm_unreachable("mangling a placeholder type");
2073 case BuiltinType::ObjCId:
2074 Out << "11objc_object";
2076 case BuiltinType::ObjCClass:
2077 Out << "10objc_class";
2079 case BuiltinType::ObjCSel:
2080 Out << "13objc_selector";
2082 case BuiltinType::OCLImage1d:
2083 Out << "11ocl_image1d";
2085 case BuiltinType::OCLImage1dArray:
2086 Out << "16ocl_image1darray";
2088 case BuiltinType::OCLImage1dBuffer:
2089 Out << "17ocl_image1dbuffer";
2091 case BuiltinType::OCLImage2d:
2092 Out << "11ocl_image2d";
2094 case BuiltinType::OCLImage2dArray:
2095 Out << "16ocl_image2darray";
2097 case BuiltinType::OCLImage2dDepth:
2098 Out << "16ocl_image2ddepth";
2100 case BuiltinType::OCLImage2dArrayDepth:
2101 Out << "21ocl_image2darraydepth";
2103 case BuiltinType::OCLImage2dMSAA:
2104 Out << "15ocl_image2dmsaa";
2106 case BuiltinType::OCLImage2dArrayMSAA:
2107 Out << "20ocl_image2darraymsaa";
2109 case BuiltinType::OCLImage2dMSAADepth:
2110 Out << "20ocl_image2dmsaadepth";
2112 case BuiltinType::OCLImage2dArrayMSAADepth:
2113 Out << "35ocl_image2darraymsaadepth";
2115 case BuiltinType::OCLImage3d:
2116 Out << "11ocl_image3d";
2118 case BuiltinType::OCLSampler:
2119 Out << "11ocl_sampler";
2121 case BuiltinType::OCLEvent:
2122 Out << "9ocl_event";
2124 case BuiltinType::OCLClkEvent:
2125 Out << "12ocl_clkevent";
2127 case BuiltinType::OCLQueue:
2128 Out << "9ocl_queue";
2130 case BuiltinType::OCLNDRange:
2131 Out << "11ocl_ndrange";
2133 case BuiltinType::OCLReserveID:
2134 Out << "13ocl_reserveid";
2139 // <type> ::= <function-type>
2140 // <function-type> ::= [<CV-qualifiers>] F [Y]
2141 // <bare-function-type> [<ref-qualifier>] E
2142 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2143 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2144 // e.g. "const" in "int (A::*)() const".
2145 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2149 // FIXME: We don't have enough information in the AST to produce the 'Y'
2150 // encoding for extern "C" function types.
2151 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2153 // Mangle the ref-qualifier, if present.
2154 mangleRefQualifier(T->getRefQualifier());
2159 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2160 // Function types without prototypes can arise when mangling a function type
2161 // within an overloadable function in C. We mangle these as the absence of any
2162 // parameter types (not even an empty parameter list).
2165 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2167 FunctionTypeDepth.enterResultType();
2168 mangleType(T->getReturnType());
2169 FunctionTypeDepth.leaveResultType();
2171 FunctionTypeDepth.pop(saved);
2175 void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
2176 bool MangleReturnType,
2177 const FunctionDecl *FD) {
2178 // We should never be mangling something without a prototype.
2179 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2181 // Record that we're in a function type. See mangleFunctionParam
2182 // for details on what we're trying to achieve here.
2183 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2185 // <bare-function-type> ::= <signature type>+
2186 if (MangleReturnType) {
2187 FunctionTypeDepth.enterResultType();
2188 mangleType(Proto->getReturnType());
2189 FunctionTypeDepth.leaveResultType();
2192 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2193 // <builtin-type> ::= v # void
2196 FunctionTypeDepth.pop(saved);
2200 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2201 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2202 const auto &ParamTy = Proto->getParamType(I);
2203 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2206 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2207 // Attr can only take 1 character, so we can hardcode the length below.
2208 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2209 Out << "U17pass_object_size" << Attr->getType();
2214 FunctionTypeDepth.pop(saved);
2216 // <builtin-type> ::= z # ellipsis
2217 if (Proto->isVariadic())
2221 // <type> ::= <class-enum-type>
2222 // <class-enum-type> ::= <name>
2223 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2224 mangleName(T->getDecl());
2227 // <type> ::= <class-enum-type>
2228 // <class-enum-type> ::= <name>
2229 void CXXNameMangler::mangleType(const EnumType *T) {
2230 mangleType(static_cast<const TagType*>(T));
2232 void CXXNameMangler::mangleType(const RecordType *T) {
2233 mangleType(static_cast<const TagType*>(T));
2235 void CXXNameMangler::mangleType(const TagType *T) {
2236 mangleName(T->getDecl());
2239 // <type> ::= <array-type>
2240 // <array-type> ::= A <positive dimension number> _ <element type>
2241 // ::= A [<dimension expression>] _ <element type>
2242 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2243 Out << 'A' << T->getSize() << '_';
2244 mangleType(T->getElementType());
2246 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2248 // decayed vla types (size 0) will just be skipped.
2249 if (T->getSizeExpr())
2250 mangleExpression(T->getSizeExpr());
2252 mangleType(T->getElementType());
2254 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2256 mangleExpression(T->getSizeExpr());
2258 mangleType(T->getElementType());
2260 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2262 mangleType(T->getElementType());
2265 // <type> ::= <pointer-to-member-type>
2266 // <pointer-to-member-type> ::= M <class type> <member type>
2267 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2269 mangleType(QualType(T->getClass(), 0));
2270 QualType PointeeType = T->getPointeeType();
2271 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2274 // Itanium C++ ABI 5.1.8:
2276 // The type of a non-static member function is considered to be different,
2277 // for the purposes of substitution, from the type of a namespace-scope or
2278 // static member function whose type appears similar. The types of two
2279 // non-static member functions are considered to be different, for the
2280 // purposes of substitution, if the functions are members of different
2281 // classes. In other words, for the purposes of substitution, the class of
2282 // which the function is a member is considered part of the type of
2285 // Given that we already substitute member function pointers as a
2286 // whole, the net effect of this rule is just to unconditionally
2287 // suppress substitution on the function type in a member pointer.
2288 // We increment the SeqID here to emulate adding an entry to the
2289 // substitution table.
2292 mangleType(PointeeType);
2295 // <type> ::= <template-param>
2296 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2297 mangleTemplateParameter(T->getIndex());
2300 // <type> ::= <template-param>
2301 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2302 // FIXME: not clear how to mangle this!
2303 // template <class T...> class A {
2304 // template <class U...> void foo(T(*)(U) x...);
2306 Out << "_SUBSTPACK_";
2309 // <type> ::= P <type> # pointer-to
2310 void CXXNameMangler::mangleType(const PointerType *T) {
2312 mangleType(T->getPointeeType());
2314 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2316 mangleType(T->getPointeeType());
2319 // <type> ::= R <type> # reference-to
2320 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2322 mangleType(T->getPointeeType());
2325 // <type> ::= O <type> # rvalue reference-to (C++0x)
2326 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2328 mangleType(T->getPointeeType());
2331 // <type> ::= C <type> # complex pair (C 2000)
2332 void CXXNameMangler::mangleType(const ComplexType *T) {
2334 mangleType(T->getElementType());
2337 // ARM's ABI for Neon vector types specifies that they should be mangled as
2338 // if they are structs (to match ARM's initial implementation). The
2339 // vector type must be one of the special types predefined by ARM.
2340 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2341 QualType EltType = T->getElementType();
2342 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2343 const char *EltName = nullptr;
2344 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2345 switch (cast<BuiltinType>(EltType)->getKind()) {
2346 case BuiltinType::SChar:
2347 case BuiltinType::UChar:
2348 EltName = "poly8_t";
2350 case BuiltinType::Short:
2351 case BuiltinType::UShort:
2352 EltName = "poly16_t";
2354 case BuiltinType::ULongLong:
2355 EltName = "poly64_t";
2357 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2360 switch (cast<BuiltinType>(EltType)->getKind()) {
2361 case BuiltinType::SChar: EltName = "int8_t"; break;
2362 case BuiltinType::UChar: EltName = "uint8_t"; break;
2363 case BuiltinType::Short: EltName = "int16_t"; break;
2364 case BuiltinType::UShort: EltName = "uint16_t"; break;
2365 case BuiltinType::Int: EltName = "int32_t"; break;
2366 case BuiltinType::UInt: EltName = "uint32_t"; break;
2367 case BuiltinType::LongLong: EltName = "int64_t"; break;
2368 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2369 case BuiltinType::Double: EltName = "float64_t"; break;
2370 case BuiltinType::Float: EltName = "float32_t"; break;
2371 case BuiltinType::Half: EltName = "float16_t";break;
2373 llvm_unreachable("unexpected Neon vector element type");
2376 const char *BaseName = nullptr;
2377 unsigned BitSize = (T->getNumElements() *
2378 getASTContext().getTypeSize(EltType));
2380 BaseName = "__simd64_";
2382 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2383 BaseName = "__simd128_";
2385 Out << strlen(BaseName) + strlen(EltName);
2386 Out << BaseName << EltName;
2389 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2390 switch (EltType->getKind()) {
2391 case BuiltinType::SChar:
2393 case BuiltinType::Short:
2395 case BuiltinType::Int:
2397 case BuiltinType::Long:
2398 case BuiltinType::LongLong:
2400 case BuiltinType::UChar:
2402 case BuiltinType::UShort:
2404 case BuiltinType::UInt:
2406 case BuiltinType::ULong:
2407 case BuiltinType::ULongLong:
2409 case BuiltinType::Half:
2411 case BuiltinType::Float:
2413 case BuiltinType::Double:
2416 llvm_unreachable("Unexpected vector element base type");
2420 // AArch64's ABI for Neon vector types specifies that they should be mangled as
2421 // the equivalent internal name. The vector type must be one of the special
2422 // types predefined by ARM.
2423 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2424 QualType EltType = T->getElementType();
2425 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2427 (T->getNumElements() * getASTContext().getTypeSize(EltType));
2428 (void)BitSize; // Silence warning.
2430 assert((BitSize == 64 || BitSize == 128) &&
2431 "Neon vector type not 64 or 128 bits");
2434 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2435 switch (cast<BuiltinType>(EltType)->getKind()) {
2436 case BuiltinType::UChar:
2439 case BuiltinType::UShort:
2442 case BuiltinType::ULong:
2443 case BuiltinType::ULongLong:
2447 llvm_unreachable("unexpected Neon polynomial vector element type");
2450 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2452 std::string TypeName =
2453 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
2454 Out << TypeName.length() << TypeName;
2457 // GNU extension: vector types
2458 // <type> ::= <vector-type>
2459 // <vector-type> ::= Dv <positive dimension number> _
2460 // <extended element type>
2461 // ::= Dv [<dimension expression>] _ <element type>
2462 // <extended element type> ::= <element type>
2463 // ::= p # AltiVec vector pixel
2464 // ::= b # Altivec vector bool
2465 void CXXNameMangler::mangleType(const VectorType *T) {
2466 if ((T->getVectorKind() == VectorType::NeonVector ||
2467 T->getVectorKind() == VectorType::NeonPolyVector)) {
2468 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
2469 llvm::Triple::ArchType Arch =
2470 getASTContext().getTargetInfo().getTriple().getArch();
2471 if ((Arch == llvm::Triple::aarch64 ||
2472 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
2473 mangleAArch64NeonVectorType(T);
2475 mangleNeonVectorType(T);
2478 Out << "Dv" << T->getNumElements() << '_';
2479 if (T->getVectorKind() == VectorType::AltiVecPixel)
2481 else if (T->getVectorKind() == VectorType::AltiVecBool)
2484 mangleType(T->getElementType());
2486 void CXXNameMangler::mangleType(const ExtVectorType *T) {
2487 mangleType(static_cast<const VectorType*>(T));
2489 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2491 mangleExpression(T->getSizeExpr());
2493 mangleType(T->getElementType());
2496 void CXXNameMangler::mangleType(const PackExpansionType *T) {
2497 // <type> ::= Dp <type> # pack expansion (C++0x)
2499 mangleType(T->getPattern());
2502 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2503 mangleSourceName(T->getDecl()->getIdentifier());
2506 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2507 // Treat __kindof as a vendor extended type qualifier.
2508 if (T->isKindOfType())
2509 Out << "U8__kindof";
2511 if (!T->qual_empty()) {
2512 // Mangle protocol qualifiers.
2513 SmallString<64> QualStr;
2514 llvm::raw_svector_ostream QualOS(QualStr);
2515 QualOS << "objcproto";
2516 for (const auto *I : T->quals()) {
2517 StringRef name = I->getName();
2518 QualOS << name.size() << name;
2520 Out << 'U' << QualStr.size() << QualStr;
2523 mangleType(T->getBaseType());
2525 if (T->isSpecialized()) {
2526 // Mangle type arguments as I <type>+ E
2528 for (auto typeArg : T->getTypeArgs())
2529 mangleType(typeArg);
2534 void CXXNameMangler::mangleType(const BlockPointerType *T) {
2535 Out << "U13block_pointer";
2536 mangleType(T->getPointeeType());
2539 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2540 // Mangle injected class name types as if the user had written the
2541 // specialization out fully. It may not actually be possible to see
2542 // this mangling, though.
2543 mangleType(T->getInjectedSpecializationType());
2546 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2547 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2548 mangleName(TD, T->getArgs(), T->getNumArgs());
2550 if (mangleSubstitution(QualType(T, 0)))
2553 mangleTemplatePrefix(T->getTemplateName());
2555 // FIXME: GCC does not appear to mangle the template arguments when
2556 // the template in question is a dependent template name. Should we
2557 // emulate that badness?
2558 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2559 addSubstitution(QualType(T, 0));
2563 void CXXNameMangler::mangleType(const DependentNameType *T) {
2564 // Proposal by cxx-abi-dev, 2014-03-26
2565 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2566 // # dependent elaborated type specifier using
2568 // ::= Ts <name> # dependent elaborated type specifier using
2569 // # 'struct' or 'class'
2570 // ::= Tu <name> # dependent elaborated type specifier using
2572 // ::= Te <name> # dependent elaborated type specifier using
2574 switch (T->getKeyword()) {
2589 llvm_unreachable("unexpected keyword for dependent type name");
2591 // Typename types are always nested
2593 manglePrefix(T->getQualifier());
2594 mangleSourceName(T->getIdentifier());
2598 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2599 // Dependently-scoped template types are nested if they have a prefix.
2602 // TODO: avoid making this TemplateName.
2603 TemplateName Prefix =
2604 getASTContext().getDependentTemplateName(T->getQualifier(),
2605 T->getIdentifier());
2606 mangleTemplatePrefix(Prefix);
2608 // FIXME: GCC does not appear to mangle the template arguments when
2609 // the template in question is a dependent template name. Should we
2610 // emulate that badness?
2611 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2615 void CXXNameMangler::mangleType(const TypeOfType *T) {
2616 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2617 // "extension with parameters" mangling.
2621 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2622 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2623 // "extension with parameters" mangling.
2627 void CXXNameMangler::mangleType(const DecltypeType *T) {
2628 Expr *E = T->getUnderlyingExpr();
2630 // type ::= Dt <expression> E # decltype of an id-expression
2631 // # or class member access
2632 // ::= DT <expression> E # decltype of an expression
2634 // This purports to be an exhaustive list of id-expressions and
2635 // class member accesses. Note that we do not ignore parentheses;
2636 // parentheses change the semantics of decltype for these
2637 // expressions (and cause the mangler to use the other form).
2638 if (isa<DeclRefExpr>(E) ||
2639 isa<MemberExpr>(E) ||
2640 isa<UnresolvedLookupExpr>(E) ||
2641 isa<DependentScopeDeclRefExpr>(E) ||
2642 isa<CXXDependentScopeMemberExpr>(E) ||
2643 isa<UnresolvedMemberExpr>(E))
2647 mangleExpression(E);
2651 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2652 // If this is dependent, we need to record that. If not, we simply
2653 // mangle it as the underlying type since they are equivalent.
2654 if (T->isDependentType()) {
2657 switch (T->getUTTKind()) {
2658 case UnaryTransformType::EnumUnderlyingType:
2664 mangleType(T->getUnderlyingType());
2667 void CXXNameMangler::mangleType(const AutoType *T) {
2668 QualType D = T->getDeducedType();
2669 // <builtin-type> ::= Da # dependent auto
2671 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2672 "shouldn't need to mangle __auto_type!");
2673 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
2678 void CXXNameMangler::mangleType(const AtomicType *T) {
2679 // <type> ::= U <source-name> <type> # vendor extended type qualifier
2680 // (Until there's a standardized mangling...)
2682 mangleType(T->getValueType());
2685 void CXXNameMangler::mangleIntegerLiteral(QualType T,
2686 const llvm::APSInt &Value) {
2687 // <expr-primary> ::= L <type> <value number> E # integer literal
2691 if (T->isBooleanType()) {
2692 // Boolean values are encoded as 0/1.
2693 Out << (Value.getBoolValue() ? '1' : '0');
2695 mangleNumber(Value);
2701 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2702 // Ignore member expressions involving anonymous unions.
2703 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2704 if (!RT->getDecl()->isAnonymousStructOrUnion())
2706 const auto *ME = dyn_cast<MemberExpr>(Base);
2709 Base = ME->getBase();
2710 IsArrow = ME->isArrow();
2713 if (Base->isImplicitCXXThis()) {
2714 // Note: GCC mangles member expressions to the implicit 'this' as
2715 // *this., whereas we represent them as this->. The Itanium C++ ABI
2716 // does not specify anything here, so we follow GCC.
2719 Out << (IsArrow ? "pt" : "dt");
2720 mangleExpression(Base);
2724 /// Mangles a member expression.
2725 void CXXNameMangler::mangleMemberExpr(const Expr *base,
2727 NestedNameSpecifier *qualifier,
2728 NamedDecl *firstQualifierLookup,
2729 DeclarationName member,
2731 // <expression> ::= dt <expression> <unresolved-name>
2732 // ::= pt <expression> <unresolved-name>
2734 mangleMemberExprBase(base, isArrow);
2735 mangleUnresolvedName(qualifier, member, arity);
2738 /// Look at the callee of the given call expression and determine if
2739 /// it's a parenthesized id-expression which would have triggered ADL
2741 static bool isParenthesizedADLCallee(const CallExpr *call) {
2742 const Expr *callee = call->getCallee();
2743 const Expr *fn = callee->IgnoreParens();
2745 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2746 // too, but for those to appear in the callee, it would have to be
2748 if (callee == fn) return false;
2750 // Must be an unresolved lookup.
2751 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2752 if (!lookup) return false;
2754 assert(!lookup->requiresADL());
2756 // Must be an unqualified lookup.
2757 if (lookup->getQualifier()) return false;
2759 // Must not have found a class member. Note that if one is a class
2760 // member, they're all class members.
2761 if (lookup->getNumDecls() > 0 &&
2762 (*lookup->decls_begin())->isCXXClassMember())
2765 // Otherwise, ADL would have been triggered.
2769 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2770 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2771 Out << CastEncoding;
2772 mangleType(ECE->getType());
2773 mangleExpression(ECE->getSubExpr());
2776 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2777 if (auto *Syntactic = InitList->getSyntacticForm())
2778 InitList = Syntactic;
2779 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2780 mangleExpression(InitList->getInit(i));
2783 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2784 // <expression> ::= <unary operator-name> <expression>
2785 // ::= <binary operator-name> <expression> <expression>
2786 // ::= <trinary operator-name> <expression> <expression> <expression>
2787 // ::= cv <type> expression # conversion with one argument
2788 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2789 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2790 // ::= sc <type> <expression> # static_cast<type> (expression)
2791 // ::= cc <type> <expression> # const_cast<type> (expression)
2792 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
2793 // ::= st <type> # sizeof (a type)
2794 // ::= at <type> # alignof (a type)
2795 // ::= <template-param>
2796 // ::= <function-param>
2797 // ::= sr <type> <unqualified-name> # dependent name
2798 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2799 // ::= ds <expression> <expression> # expr.*expr
2800 // ::= sZ <template-param> # size of a parameter pack
2801 // ::= sZ <function-param> # size of a function parameter pack
2802 // ::= <expr-primary>
2803 // <expr-primary> ::= L <type> <value number> E # integer literal
2804 // ::= L <type <value float> E # floating literal
2805 // ::= L <mangled-name> E # external name
2806 // ::= fpT # 'this' expression
2807 QualType ImplicitlyConvertedToType;
2810 switch (E->getStmtClass()) {
2811 case Expr::NoStmtClass:
2812 #define ABSTRACT_STMT(Type)
2813 #define EXPR(Type, Base)
2814 #define STMT(Type, Base) \
2815 case Expr::Type##Class:
2816 #include "clang/AST/StmtNodes.inc"
2819 // These all can only appear in local or variable-initialization
2820 // contexts and so should never appear in a mangling.
2821 case Expr::AddrLabelExprClass:
2822 case Expr::DesignatedInitUpdateExprClass:
2823 case Expr::ImplicitValueInitExprClass:
2824 case Expr::NoInitExprClass:
2825 case Expr::ParenListExprClass:
2826 case Expr::LambdaExprClass:
2827 case Expr::MSPropertyRefExprClass:
2828 case Expr::MSPropertySubscriptExprClass:
2829 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
2830 case Expr::OMPArraySectionExprClass:
2831 llvm_unreachable("unexpected statement kind");
2833 // FIXME: invent manglings for all these.
2834 case Expr::BlockExprClass:
2835 case Expr::ChooseExprClass:
2836 case Expr::CompoundLiteralExprClass:
2837 case Expr::DesignatedInitExprClass:
2838 case Expr::ExtVectorElementExprClass:
2839 case Expr::GenericSelectionExprClass:
2840 case Expr::ObjCEncodeExprClass:
2841 case Expr::ObjCIsaExprClass:
2842 case Expr::ObjCIvarRefExprClass:
2843 case Expr::ObjCMessageExprClass:
2844 case Expr::ObjCPropertyRefExprClass:
2845 case Expr::ObjCProtocolExprClass:
2846 case Expr::ObjCSelectorExprClass:
2847 case Expr::ObjCStringLiteralClass:
2848 case Expr::ObjCBoxedExprClass:
2849 case Expr::ObjCArrayLiteralClass:
2850 case Expr::ObjCDictionaryLiteralClass:
2851 case Expr::ObjCSubscriptRefExprClass:
2852 case Expr::ObjCIndirectCopyRestoreExprClass:
2853 case Expr::OffsetOfExprClass:
2854 case Expr::PredefinedExprClass:
2855 case Expr::ShuffleVectorExprClass:
2856 case Expr::ConvertVectorExprClass:
2857 case Expr::StmtExprClass:
2858 case Expr::TypeTraitExprClass:
2859 case Expr::ArrayTypeTraitExprClass:
2860 case Expr::ExpressionTraitExprClass:
2861 case Expr::VAArgExprClass:
2862 case Expr::CUDAKernelCallExprClass:
2863 case Expr::AsTypeExprClass:
2864 case Expr::PseudoObjectExprClass:
2865 case Expr::AtomicExprClass:
2867 // As bad as this diagnostic is, it's better than crashing.
2868 DiagnosticsEngine &Diags = Context.getDiags();
2869 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2870 "cannot yet mangle expression type %0");
2871 Diags.Report(E->getExprLoc(), DiagID)
2872 << E->getStmtClassName() << E->getSourceRange();
2876 case Expr::CXXUuidofExprClass: {
2877 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2878 if (UE->isTypeOperand()) {
2879 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2880 Out << "u8__uuidoft";
2883 Expr *UuidExp = UE->getExprOperand();
2884 Out << "u8__uuidofz";
2885 mangleExpression(UuidExp, Arity);
2890 // Even gcc-4.5 doesn't mangle this.
2891 case Expr::BinaryConditionalOperatorClass: {
2892 DiagnosticsEngine &Diags = Context.getDiags();
2894 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2895 "?: operator with omitted middle operand cannot be mangled");
2896 Diags.Report(E->getExprLoc(), DiagID)
2897 << E->getStmtClassName() << E->getSourceRange();
2901 // These are used for internal purposes and cannot be meaningfully mangled.
2902 case Expr::OpaqueValueExprClass:
2903 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2905 case Expr::InitListExprClass: {
2907 mangleInitListElements(cast<InitListExpr>(E));
2912 case Expr::CXXDefaultArgExprClass:
2913 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2916 case Expr::CXXDefaultInitExprClass:
2917 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2920 case Expr::CXXStdInitializerListExprClass:
2921 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2924 case Expr::SubstNonTypeTemplateParmExprClass:
2925 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2929 case Expr::UserDefinedLiteralClass:
2930 // We follow g++'s approach of mangling a UDL as a call to the literal
2932 case Expr::CXXMemberCallExprClass: // fallthrough
2933 case Expr::CallExprClass: {
2934 const CallExpr *CE = cast<CallExpr>(E);
2936 // <expression> ::= cp <simple-id> <expression>* E
2937 // We use this mangling only when the call would use ADL except
2938 // for being parenthesized. Per discussion with David
2939 // Vandervoorde, 2011.04.25.
2940 if (isParenthesizedADLCallee(CE)) {
2942 // The callee here is a parenthesized UnresolvedLookupExpr with
2943 // no qualifier and should always get mangled as a <simple-id>
2946 // <expression> ::= cl <expression>* E
2951 unsigned CallArity = CE->getNumArgs();
2952 for (const Expr *Arg : CE->arguments())
2953 if (isa<PackExpansionExpr>(Arg))
2954 CallArity = UnknownArity;
2956 mangleExpression(CE->getCallee(), CallArity);
2957 for (const Expr *Arg : CE->arguments())
2958 mangleExpression(Arg);
2963 case Expr::CXXNewExprClass: {
2964 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2965 if (New->isGlobalNew()) Out << "gs";
2966 Out << (New->isArray() ? "na" : "nw");
2967 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2968 E = New->placement_arg_end(); I != E; ++I)
2969 mangleExpression(*I);
2971 mangleType(New->getAllocatedType());
2972 if (New->hasInitializer()) {
2973 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2977 const Expr *Init = New->getInitializer();
2978 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2979 // Directly inline the initializers.
2980 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2983 mangleExpression(*I);
2984 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2985 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2986 mangleExpression(PLE->getExpr(i));
2987 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2988 isa<InitListExpr>(Init)) {
2989 // Only take InitListExprs apart for list-initialization.
2990 mangleInitListElements(cast<InitListExpr>(Init));
2992 mangleExpression(Init);
2998 case Expr::CXXPseudoDestructorExprClass: {
2999 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3000 if (const Expr *Base = PDE->getBase())
3001 mangleMemberExprBase(Base, PDE->isArrow());
3002 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3004 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3006 mangleUnresolvedPrefix(Qualifier,
3007 /*Recursive=*/true);
3008 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3012 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3015 } else if (Qualifier) {
3016 mangleUnresolvedPrefix(Qualifier);
3018 // <base-unresolved-name> ::= dn <destructor-name>
3020 QualType DestroyedType = PDE->getDestroyedType();
3021 mangleUnresolvedTypeOrSimpleId(DestroyedType);
3025 case Expr::MemberExprClass: {
3026 const MemberExpr *ME = cast<MemberExpr>(E);
3027 mangleMemberExpr(ME->getBase(), ME->isArrow(),
3028 ME->getQualifier(), nullptr,
3029 ME->getMemberDecl()->getDeclName(), Arity);
3033 case Expr::UnresolvedMemberExprClass: {
3034 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
3035 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3036 ME->isArrow(), ME->getQualifier(), nullptr,
3037 ME->getMemberName(), Arity);
3038 if (ME->hasExplicitTemplateArgs())
3039 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
3043 case Expr::CXXDependentScopeMemberExprClass: {
3044 const CXXDependentScopeMemberExpr *ME
3045 = cast<CXXDependentScopeMemberExpr>(E);
3046 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3047 ME->isArrow(), ME->getQualifier(),
3048 ME->getFirstQualifierFoundInScope(),
3049 ME->getMember(), Arity);
3050 if (ME->hasExplicitTemplateArgs())
3051 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
3055 case Expr::UnresolvedLookupExprClass: {
3056 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
3057 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
3059 // All the <unresolved-name> productions end in a
3060 // base-unresolved-name, where <template-args> are just tacked
3062 if (ULE->hasExplicitTemplateArgs())
3063 mangleTemplateArgs(ULE->getTemplateArgs(), ULE->getNumTemplateArgs());
3067 case Expr::CXXUnresolvedConstructExprClass: {
3068 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3069 unsigned N = CE->arg_size();
3072 mangleType(CE->getType());
3073 if (N != 1) Out << '_';
3074 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3075 if (N != 1) Out << 'E';
3079 case Expr::CXXConstructExprClass: {
3080 const auto *CE = cast<CXXConstructExpr>(E);
3081 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
3083 CE->getNumArgs() >= 1 &&
3084 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3085 "implicit CXXConstructExpr must have one argument");
3086 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3089 for (auto *E : CE->arguments())
3090 mangleExpression(E);
3095 case Expr::CXXTemporaryObjectExprClass: {
3096 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3097 unsigned N = CE->getNumArgs();
3098 bool List = CE->isListInitialization();
3104 mangleType(CE->getType());
3105 if (!List && N != 1)
3107 if (CE->isStdInitListInitialization()) {
3108 // We implicitly created a std::initializer_list<T> for the first argument
3109 // of a constructor of type U in an expression of the form U{a, b, c}.
3110 // Strip all the semantic gunk off the initializer list.
3112 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3113 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3114 mangleInitListElements(ILE);
3116 for (auto *E : CE->arguments())
3117 mangleExpression(E);
3124 case Expr::CXXScalarValueInitExprClass:
3126 mangleType(E->getType());
3130 case Expr::CXXNoexceptExprClass:
3132 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3135 case Expr::UnaryExprOrTypeTraitExprClass: {
3136 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3138 if (!SAE->isInstantiationDependent()) {
3140 // If the operand of a sizeof or alignof operator is not
3141 // instantiation-dependent it is encoded as an integer literal
3142 // reflecting the result of the operator.
3144 // If the result of the operator is implicitly converted to a known
3145 // integer type, that type is used for the literal; otherwise, the type
3146 // of std::size_t or std::ptrdiff_t is used.
3147 QualType T = (ImplicitlyConvertedToType.isNull() ||
3148 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3149 : ImplicitlyConvertedToType;
3150 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3151 mangleIntegerLiteral(T, V);
3155 switch(SAE->getKind()) {
3162 case UETT_VecStep: {
3163 DiagnosticsEngine &Diags = Context.getDiags();
3164 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3165 "cannot yet mangle vec_step expression");
3166 Diags.Report(DiagID);
3169 case UETT_OpenMPRequiredSimdAlign:
3170 DiagnosticsEngine &Diags = Context.getDiags();
3171 unsigned DiagID = Diags.getCustomDiagID(
3172 DiagnosticsEngine::Error,
3173 "cannot yet mangle __builtin_omp_required_simd_align expression");
3174 Diags.Report(DiagID);
3177 if (SAE->isArgumentType()) {
3179 mangleType(SAE->getArgumentType());
3182 mangleExpression(SAE->getArgumentExpr());
3187 case Expr::CXXThrowExprClass: {
3188 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
3189 // <expression> ::= tw <expression> # throw expression
3191 if (TE->getSubExpr()) {
3193 mangleExpression(TE->getSubExpr());
3200 case Expr::CXXTypeidExprClass: {
3201 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
3202 // <expression> ::= ti <type> # typeid (type)
3203 // ::= te <expression> # typeid (expression)
3204 if (TIE->isTypeOperand()) {
3206 mangleType(TIE->getTypeOperand(Context.getASTContext()));
3209 mangleExpression(TIE->getExprOperand());
3214 case Expr::CXXDeleteExprClass: {
3215 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
3216 // <expression> ::= [gs] dl <expression> # [::] delete expr
3217 // ::= [gs] da <expression> # [::] delete [] expr
3218 if (DE->isGlobalDelete()) Out << "gs";
3219 Out << (DE->isArrayForm() ? "da" : "dl");
3220 mangleExpression(DE->getArgument());
3224 case Expr::UnaryOperatorClass: {
3225 const UnaryOperator *UO = cast<UnaryOperator>(E);
3226 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3228 mangleExpression(UO->getSubExpr());
3232 case Expr::ArraySubscriptExprClass: {
3233 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3235 // Array subscript is treated as a syntactically weird form of
3238 mangleExpression(AE->getLHS());
3239 mangleExpression(AE->getRHS());
3243 case Expr::CompoundAssignOperatorClass: // fallthrough
3244 case Expr::BinaryOperatorClass: {
3245 const BinaryOperator *BO = cast<BinaryOperator>(E);
3246 if (BO->getOpcode() == BO_PtrMemD)
3249 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3251 mangleExpression(BO->getLHS());
3252 mangleExpression(BO->getRHS());
3256 case Expr::ConditionalOperatorClass: {
3257 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3258 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3259 mangleExpression(CO->getCond());
3260 mangleExpression(CO->getLHS(), Arity);
3261 mangleExpression(CO->getRHS(), Arity);
3265 case Expr::ImplicitCastExprClass: {
3266 ImplicitlyConvertedToType = E->getType();
3267 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3271 case Expr::ObjCBridgedCastExprClass: {
3272 // Mangle ownership casts as a vendor extended operator __bridge,
3273 // __bridge_transfer, or __bridge_retain.
3274 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3275 Out << "v1U" << Kind.size() << Kind;
3277 // Fall through to mangle the cast itself.
3279 case Expr::CStyleCastExprClass:
3280 mangleCastExpression(E, "cv");
3283 case Expr::CXXFunctionalCastExprClass: {
3284 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3285 // FIXME: Add isImplicit to CXXConstructExpr.
3286 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3287 if (CCE->getParenOrBraceRange().isInvalid())
3288 Sub = CCE->getArg(0)->IgnoreImplicit();
3289 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3290 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3291 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3293 mangleType(E->getType());
3294 mangleInitListElements(IL);
3297 mangleCastExpression(E, "cv");
3302 case Expr::CXXStaticCastExprClass:
3303 mangleCastExpression(E, "sc");
3305 case Expr::CXXDynamicCastExprClass:
3306 mangleCastExpression(E, "dc");
3308 case Expr::CXXReinterpretCastExprClass:
3309 mangleCastExpression(E, "rc");
3311 case Expr::CXXConstCastExprClass:
3312 mangleCastExpression(E, "cc");
3315 case Expr::CXXOperatorCallExprClass: {
3316 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3317 unsigned NumArgs = CE->getNumArgs();
3318 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3319 // Mangle the arguments.
3320 for (unsigned i = 0; i != NumArgs; ++i)
3321 mangleExpression(CE->getArg(i));
3325 case Expr::ParenExprClass:
3326 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3329 case Expr::DeclRefExprClass: {
3330 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3332 switch (D->getKind()) {
3334 // <expr-primary> ::= L <mangled-name> E # external name
3341 mangleFunctionParam(cast<ParmVarDecl>(D));
3344 case Decl::EnumConstant: {
3345 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3346 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3350 case Decl::NonTypeTemplateParm: {
3351 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3352 mangleTemplateParameter(PD->getIndex());
3361 case Expr::SubstNonTypeTemplateParmPackExprClass:
3362 // FIXME: not clear how to mangle this!
3363 // template <unsigned N...> class A {
3364 // template <class U...> void foo(U (&x)[N]...);
3366 Out << "_SUBSTPACK_";
3369 case Expr::FunctionParmPackExprClass: {
3370 // FIXME: not clear how to mangle this!
3371 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3372 Out << "v110_SUBSTPACK";
3373 mangleFunctionParam(FPPE->getParameterPack());
3377 case Expr::DependentScopeDeclRefExprClass: {
3378 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
3379 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
3381 // All the <unresolved-name> productions end in a
3382 // base-unresolved-name, where <template-args> are just tacked
3384 if (DRE->hasExplicitTemplateArgs())
3385 mangleTemplateArgs(DRE->getTemplateArgs(), DRE->getNumTemplateArgs());
3389 case Expr::CXXBindTemporaryExprClass:
3390 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3393 case Expr::ExprWithCleanupsClass:
3394 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3397 case Expr::FloatingLiteralClass: {
3398 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3400 mangleType(FL->getType());
3401 mangleFloat(FL->getValue());
3406 case Expr::CharacterLiteralClass:
3408 mangleType(E->getType());
3409 Out << cast<CharacterLiteral>(E)->getValue();
3413 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3414 case Expr::ObjCBoolLiteralExprClass:
3416 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3420 case Expr::CXXBoolLiteralExprClass:
3422 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3426 case Expr::IntegerLiteralClass: {
3427 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3428 if (E->getType()->isSignedIntegerType())
3429 Value.setIsSigned(true);
3430 mangleIntegerLiteral(E->getType(), Value);
3434 case Expr::ImaginaryLiteralClass: {
3435 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3436 // Mangle as if a complex literal.
3437 // Proposal from David Vandevoorde, 2010.06.30.
3439 mangleType(E->getType());
3440 if (const FloatingLiteral *Imag =
3441 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3442 // Mangle a floating-point zero of the appropriate type.
3443 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3445 mangleFloat(Imag->getValue());
3448 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3449 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3450 Value.setIsSigned(true);
3451 mangleNumber(Value);
3457 case Expr::StringLiteralClass: {
3458 // Revised proposal from David Vandervoorde, 2010.07.15.
3460 assert(isa<ConstantArrayType>(E->getType()));
3461 mangleType(E->getType());
3466 case Expr::GNUNullExprClass:
3467 // FIXME: should this really be mangled the same as nullptr?
3470 case Expr::CXXNullPtrLiteralExprClass: {
3475 case Expr::PackExpansionExprClass:
3477 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3480 case Expr::SizeOfPackExprClass: {
3481 auto *SPE = cast<SizeOfPackExpr>(E);
3482 if (SPE->isPartiallySubstituted()) {
3484 for (const auto &A : SPE->getPartialArguments())
3485 mangleTemplateArg(A);
3491 const NamedDecl *Pack = SPE->getPack();
3492 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3493 mangleTemplateParameter(TTP->getIndex());
3494 else if (const NonTypeTemplateParmDecl *NTTP
3495 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3496 mangleTemplateParameter(NTTP->getIndex());
3497 else if (const TemplateTemplateParmDecl *TempTP
3498 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3499 mangleTemplateParameter(TempTP->getIndex());
3501 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3505 case Expr::MaterializeTemporaryExprClass: {
3506 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3510 case Expr::CXXFoldExprClass: {
3511 auto *FE = cast<CXXFoldExpr>(E);
3512 if (FE->isLeftFold())
3513 Out << (FE->getInit() ? "fL" : "fl");
3515 Out << (FE->getInit() ? "fR" : "fr");
3517 if (FE->getOperator() == BO_PtrMemD)
3521 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3525 mangleExpression(FE->getLHS());
3527 mangleExpression(FE->getRHS());
3531 case Expr::CXXThisExprClass:
3535 case Expr::CoawaitExprClass:
3536 // FIXME: Propose a non-vendor mangling.
3537 Out << "v18co_await";
3538 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3541 case Expr::CoyieldExprClass:
3542 // FIXME: Propose a non-vendor mangling.
3543 Out << "v18co_yield";
3544 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3549 /// Mangle an expression which refers to a parameter variable.
3551 /// <expression> ::= <function-param>
3552 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3553 /// <function-param> ::= fp <top-level CV-qualifiers>
3554 /// <parameter-2 non-negative number> _ # L == 0, I > 0
3555 /// <function-param> ::= fL <L-1 non-negative number>
3556 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
3557 /// <function-param> ::= fL <L-1 non-negative number>
3558 /// p <top-level CV-qualifiers>
3559 /// <I-1 non-negative number> _ # L > 0, I > 0
3561 /// L is the nesting depth of the parameter, defined as 1 if the
3562 /// parameter comes from the innermost function prototype scope
3563 /// enclosing the current context, 2 if from the next enclosing
3564 /// function prototype scope, and so on, with one special case: if
3565 /// we've processed the full parameter clause for the innermost
3566 /// function type, then L is one less. This definition conveniently
3567 /// makes it irrelevant whether a function's result type was written
3568 /// trailing or leading, but is otherwise overly complicated; the
3569 /// numbering was first designed without considering references to
3570 /// parameter in locations other than return types, and then the
3571 /// mangling had to be generalized without changing the existing
3574 /// I is the zero-based index of the parameter within its parameter
3575 /// declaration clause. Note that the original ABI document describes
3576 /// this using 1-based ordinals.
3577 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3578 unsigned parmDepth = parm->getFunctionScopeDepth();
3579 unsigned parmIndex = parm->getFunctionScopeIndex();
3582 // parmDepth does not include the declaring function prototype.
3583 // FunctionTypeDepth does account for that.
3584 assert(parmDepth < FunctionTypeDepth.getDepth());
3585 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3586 if (FunctionTypeDepth.isInResultType())
3589 if (nestingDepth == 0) {
3592 Out << "fL" << (nestingDepth - 1) << 'p';
3595 // Top-level qualifiers. We don't have to worry about arrays here,
3596 // because parameters declared as arrays should already have been
3597 // transformed to have pointer type. FIXME: apparently these don't
3598 // get mangled if used as an rvalue of a known non-class type?
3599 assert(!parm->getType()->isArrayType()
3600 && "parameter's type is still an array type?");
3601 mangleQualifiers(parm->getType().getQualifiers());
3604 if (parmIndex != 0) {
3605 Out << (parmIndex - 1);
3610 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3611 // <ctor-dtor-name> ::= C1 # complete object constructor
3612 // ::= C2 # base object constructor
3614 // In addition, C5 is a comdat name with C1 and C2 in it.
3625 case Ctor_DefaultClosure:
3626 case Ctor_CopyingClosure:
3627 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
3631 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3632 // <ctor-dtor-name> ::= D0 # deleting destructor
3633 // ::= D1 # complete object destructor
3634 // ::= D2 # base object destructor
3636 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
3653 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
3654 unsigned NumTemplateArgs) {
3655 // <template-args> ::= I <template-arg>+ E
3657 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3658 mangleTemplateArg(TemplateArgs[i].getArgument());
3662 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3663 // <template-args> ::= I <template-arg>+ E
3665 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3666 mangleTemplateArg(AL[i]);
3670 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3671 unsigned NumTemplateArgs) {
3672 // <template-args> ::= I <template-arg>+ E
3674 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3675 mangleTemplateArg(TemplateArgs[i]);
3679 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3680 // <template-arg> ::= <type> # type or template
3681 // ::= X <expression> E # expression
3682 // ::= <expr-primary> # simple expressions
3683 // ::= J <template-arg>* E # argument pack
3684 if (!A.isInstantiationDependent() || A.isDependent())
3685 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3687 switch (A.getKind()) {
3688 case TemplateArgument::Null:
3689 llvm_unreachable("Cannot mangle NULL template argument");
3691 case TemplateArgument::Type:
3692 mangleType(A.getAsType());
3694 case TemplateArgument::Template:
3695 // This is mangled as <type>.
3696 mangleType(A.getAsTemplate());
3698 case TemplateArgument::TemplateExpansion:
3699 // <type> ::= Dp <type> # pack expansion (C++0x)
3701 mangleType(A.getAsTemplateOrTemplatePattern());
3703 case TemplateArgument::Expression: {
3704 // It's possible to end up with a DeclRefExpr here in certain
3705 // dependent cases, in which case we should mangle as a
3707 const Expr *E = A.getAsExpr()->IgnoreParens();
3708 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3709 const ValueDecl *D = DRE->getDecl();
3710 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3719 mangleExpression(E);
3723 case TemplateArgument::Integral:
3724 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3726 case TemplateArgument::Declaration: {
3727 // <expr-primary> ::= L <mangled-name> E # external name
3728 // Clang produces AST's where pointer-to-member-function expressions
3729 // and pointer-to-function expressions are represented as a declaration not
3730 // an expression. We compensate for it here to produce the correct mangling.
3731 ValueDecl *D = A.getAsDecl();
3732 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
3733 if (compensateMangling) {
3735 mangleOperatorName(OO_Amp, 1);
3739 // References to external entities use the mangled name; if the name would
3740 // not normally be manged then mangle it as unqualified.
3744 if (compensateMangling)
3749 case TemplateArgument::NullPtr: {
3750 // <expr-primary> ::= L <type> 0 E
3752 mangleType(A.getNullPtrType());
3756 case TemplateArgument::Pack: {
3757 // <template-arg> ::= J <template-arg>* E
3759 for (const auto &P : A.pack_elements())
3760 mangleTemplateArg(P);
3766 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3767 // <template-param> ::= T_ # first template parameter
3768 // ::= T <parameter-2 non-negative number> _
3772 Out << 'T' << (Index - 1) << '_';
3775 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3778 else if (SeqID > 1) {
3781 // <seq-id> is encoded in base-36, using digits and upper case letters.
3782 char Buffer[7]; // log(2**32) / log(36) ~= 7
3783 MutableArrayRef<char> BufferRef(Buffer);
3784 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
3786 for (; SeqID != 0; SeqID /= 36) {
3787 unsigned C = SeqID % 36;
3788 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3791 Out.write(I.base(), I - BufferRef.rbegin());
3796 void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3797 bool result = mangleSubstitution(type);
3798 assert(result && "no existing substitution for type");
3802 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3803 bool result = mangleSubstitution(tname);
3804 assert(result && "no existing substitution for template name");
3808 // <substitution> ::= S <seq-id> _
3810 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3811 // Try one of the standard substitutions first.
3812 if (mangleStandardSubstitution(ND))
3815 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3816 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3819 /// Determine whether the given type has any qualifiers that are relevant for
3821 static bool hasMangledSubstitutionQualifiers(QualType T) {
3822 Qualifiers Qs = T.getQualifiers();
3823 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3826 bool CXXNameMangler::mangleSubstitution(QualType T) {
3827 if (!hasMangledSubstitutionQualifiers(T)) {
3828 if (const RecordType *RT = T->getAs<RecordType>())
3829 return mangleSubstitution(RT->getDecl());
3832 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3834 return mangleSubstitution(TypePtr);
3837 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3838 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3839 return mangleSubstitution(TD);
3841 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3842 return mangleSubstitution(
3843 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3846 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3847 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3848 if (I == Substitutions.end())
3851 unsigned SeqID = I->second;
3858 static bool isCharType(QualType T) {
3862 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3863 T->isSpecificBuiltinType(BuiltinType::Char_U);
3866 /// Returns whether a given type is a template specialization of a given name
3867 /// with a single argument of type char.
3868 static bool isCharSpecialization(QualType T, const char *Name) {
3872 const RecordType *RT = T->getAs<RecordType>();
3876 const ClassTemplateSpecializationDecl *SD =
3877 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3881 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3884 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3885 if (TemplateArgs.size() != 1)
3888 if (!isCharType(TemplateArgs[0].getAsType()))
3891 return SD->getIdentifier()->getName() == Name;
3894 template <std::size_t StrLen>
3895 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3896 const char (&Str)[StrLen]) {
3897 if (!SD->getIdentifier()->isStr(Str))
3900 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3901 if (TemplateArgs.size() != 2)
3904 if (!isCharType(TemplateArgs[0].getAsType()))
3907 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3913 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3914 // <substitution> ::= St # ::std::
3915 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3922 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3923 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3926 // <substitution> ::= Sa # ::std::allocator
3927 if (TD->getIdentifier()->isStr("allocator")) {
3932 // <<substitution> ::= Sb # ::std::basic_string
3933 if (TD->getIdentifier()->isStr("basic_string")) {
3939 if (const ClassTemplateSpecializationDecl *SD =
3940 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3941 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3944 // <substitution> ::= Ss # ::std::basic_string<char,
3945 // ::std::char_traits<char>,
3946 // ::std::allocator<char> >
3947 if (SD->getIdentifier()->isStr("basic_string")) {
3948 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3950 if (TemplateArgs.size() != 3)
3953 if (!isCharType(TemplateArgs[0].getAsType()))
3956 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3959 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3966 // <substitution> ::= Si # ::std::basic_istream<char,
3967 // ::std::char_traits<char> >
3968 if (isStreamCharSpecialization(SD, "basic_istream")) {
3973 // <substitution> ::= So # ::std::basic_ostream<char,
3974 // ::std::char_traits<char> >
3975 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3980 // <substitution> ::= Sd # ::std::basic_iostream<char,
3981 // ::std::char_traits<char> >
3982 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3990 void CXXNameMangler::addSubstitution(QualType T) {
3991 if (!hasMangledSubstitutionQualifiers(T)) {
3992 if (const RecordType *RT = T->getAs<RecordType>()) {
3993 addSubstitution(RT->getDecl());
3998 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3999 addSubstitution(TypePtr);
4002 void CXXNameMangler::addSubstitution(TemplateName Template) {
4003 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4004 return addSubstitution(TD);
4006 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4007 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4010 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4011 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4012 Substitutions[Ptr] = SeqID++;
4017 /// Mangles the name of the declaration D and emits that name to the given
4020 /// If the declaration D requires a mangled name, this routine will emit that
4021 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4022 /// and this routine will return false. In this case, the caller should just
4023 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
4025 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4027 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4028 "Invalid mangleName() call, argument is not a variable or function!");
4029 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4030 "Invalid mangleName() call on 'structor decl!");
4032 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4033 getASTContext().getSourceManager(),
4034 "Mangling declaration");
4036 CXXNameMangler Mangler(*this, Out, D);
4040 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4043 CXXNameMangler Mangler(*this, Out, D, Type);
4047 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4050 CXXNameMangler Mangler(*this, Out, D, Type);
4054 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4056 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4060 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4062 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4066 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4067 const ThunkInfo &Thunk,
4069 // <special-name> ::= T <call-offset> <base encoding>
4070 // # base is the nominal target function of thunk
4071 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4072 // # base is the nominal target function of thunk
4073 // # first call-offset is 'this' adjustment
4074 // # second call-offset is result adjustment
4076 assert(!isa<CXXDestructorDecl>(MD) &&
4077 "Use mangleCXXDtor for destructor decls!");
4078 CXXNameMangler Mangler(*this, Out);
4079 Mangler.getStream() << "_ZT";
4080 if (!Thunk.Return.isEmpty())
4081 Mangler.getStream() << 'c';
4083 // Mangle the 'this' pointer adjustment.
4084 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4085 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4087 // Mangle the return pointer adjustment if there is one.
4088 if (!Thunk.Return.isEmpty())
4089 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
4090 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4092 Mangler.mangleFunctionEncoding(MD);
4095 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4096 const CXXDestructorDecl *DD, CXXDtorType Type,
4097 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
4098 // <special-name> ::= T <call-offset> <base encoding>
4099 // # base is the nominal target function of thunk
4100 CXXNameMangler Mangler(*this, Out, DD, Type);
4101 Mangler.getStream() << "_ZT";
4103 // Mangle the 'this' pointer adjustment.
4104 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
4105 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
4107 Mangler.mangleFunctionEncoding(DD);
4110 /// Returns the mangled name for a guard variable for the passed in VarDecl.
4111 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4113 // <special-name> ::= GV <object name> # Guard variable for one-time
4115 CXXNameMangler Mangler(*this, Out);
4116 Mangler.getStream() << "_ZGV";
4117 Mangler.mangleName(D);
4120 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4122 // These symbols are internal in the Itanium ABI, so the names don't matter.
4123 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4124 // avoid duplicate symbols.
4125 Out << "__cxx_global_var_init";
4128 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4130 // Prefix the mangling of D with __dtor_.
4131 CXXNameMangler Mangler(*this, Out);
4132 Mangler.getStream() << "__dtor_";
4133 if (shouldMangleDeclName(D))
4136 Mangler.getStream() << D->getName();
4139 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4140 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4141 CXXNameMangler Mangler(*this, Out);
4142 Mangler.getStream() << "__filt_";
4143 if (shouldMangleDeclName(EnclosingDecl))
4144 Mangler.mangle(EnclosingDecl);
4146 Mangler.getStream() << EnclosingDecl->getName();
4149 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4150 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4151 CXXNameMangler Mangler(*this, Out);
4152 Mangler.getStream() << "__fin_";
4153 if (shouldMangleDeclName(EnclosingDecl))
4154 Mangler.mangle(EnclosingDecl);
4156 Mangler.getStream() << EnclosingDecl->getName();
4159 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4161 // <special-name> ::= TH <object name>
4162 CXXNameMangler Mangler(*this, Out);
4163 Mangler.getStream() << "_ZTH";
4164 Mangler.mangleName(D);
4168 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4170 // <special-name> ::= TW <object name>
4171 CXXNameMangler Mangler(*this, Out);
4172 Mangler.getStream() << "_ZTW";
4173 Mangler.mangleName(D);
4176 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
4177 unsigned ManglingNumber,
4179 // We match the GCC mangling here.
4180 // <special-name> ::= GR <object name>
4181 CXXNameMangler Mangler(*this, Out);
4182 Mangler.getStream() << "_ZGR";
4183 Mangler.mangleName(D);
4184 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
4185 Mangler.mangleSeqID(ManglingNumber - 1);
4188 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4190 // <special-name> ::= TV <type> # virtual table
4191 CXXNameMangler Mangler(*this, Out);
4192 Mangler.getStream() << "_ZTV";
4193 Mangler.mangleNameOrStandardSubstitution(RD);
4196 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4198 // <special-name> ::= TT <type> # VTT structure
4199 CXXNameMangler Mangler(*this, Out);
4200 Mangler.getStream() << "_ZTT";
4201 Mangler.mangleNameOrStandardSubstitution(RD);
4204 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4206 const CXXRecordDecl *Type,
4208 // <special-name> ::= TC <type> <offset number> _ <base type>
4209 CXXNameMangler Mangler(*this, Out);
4210 Mangler.getStream() << "_ZTC";
4211 Mangler.mangleNameOrStandardSubstitution(RD);
4212 Mangler.getStream() << Offset;
4213 Mangler.getStream() << '_';
4214 Mangler.mangleNameOrStandardSubstitution(Type);
4217 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
4218 // <special-name> ::= TI <type> # typeinfo structure
4219 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4220 CXXNameMangler Mangler(*this, Out);
4221 Mangler.getStream() << "_ZTI";
4222 Mangler.mangleType(Ty);
4225 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4227 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4228 CXXNameMangler Mangler(*this, Out);
4229 Mangler.getStream() << "_ZTS";
4230 Mangler.mangleType(Ty);
4233 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4234 mangleCXXRTTIName(Ty, Out);
4237 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4238 llvm_unreachable("Can't mangle string literals");
4241 ItaniumMangleContext *
4242 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4243 return new ItaniumMangleContextImpl(Context, Diags);