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://itanium-cxx-abi.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/DeclOpenMP.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/ABI.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
36 using namespace clang;
40 /// Retrieve the declaration context that should be used when mangling the given
42 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
43 // The ABI assumes that lambda closure types that occur within
44 // default arguments live in the context of the function. However, due to
45 // the way in which Clang parses and creates function declarations, this is
46 // not the case: the lambda closure type ends up living in the context
47 // where the function itself resides, because the function declaration itself
48 // had not yet been created. Fix the context here.
49 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
51 if (ParmVarDecl *ContextParam
52 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
53 return ContextParam->getDeclContext();
56 // Perform the same check for block literals.
57 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
58 if (ParmVarDecl *ContextParam
59 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
60 return ContextParam->getDeclContext();
63 const DeclContext *DC = D->getDeclContext();
64 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
65 return getEffectiveDeclContext(cast<Decl>(DC));
68 if (const auto *VD = dyn_cast<VarDecl>(D))
70 return VD->getASTContext().getTranslationUnitDecl();
72 if (const auto *FD = dyn_cast<FunctionDecl>(D))
74 return FD->getASTContext().getTranslationUnitDecl();
76 return DC->getRedeclContext();
79 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
80 return getEffectiveDeclContext(cast<Decl>(DC));
83 static bool isLocalContainerContext(const DeclContext *DC) {
84 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
87 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
88 const DeclContext *DC = getEffectiveDeclContext(D);
89 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
90 if (isLocalContainerContext(DC))
91 return dyn_cast<RecordDecl>(D);
93 DC = getEffectiveDeclContext(D);
98 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
99 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
100 return ftd->getTemplatedDecl();
105 static const NamedDecl *getStructor(const NamedDecl *decl) {
106 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
107 return (fn ? getStructor(fn) : decl);
110 static bool isLambda(const NamedDecl *ND) {
111 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
115 return Record->isLambda();
118 static const unsigned UnknownArity = ~0U;
120 class ItaniumMangleContextImpl : public ItaniumMangleContext {
121 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
122 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
123 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
126 explicit ItaniumMangleContextImpl(ASTContext &Context,
127 DiagnosticsEngine &Diags)
128 : ItaniumMangleContext(Context, Diags) {}
130 /// @name Mangler Entry Points
133 bool shouldMangleCXXName(const NamedDecl *D) override;
134 bool shouldMangleStringLiteral(const StringLiteral *) override {
137 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
138 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
139 raw_ostream &) override;
140 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
141 const ThisAdjustment &ThisAdjustment,
142 raw_ostream &) override;
143 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
144 raw_ostream &) override;
145 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
146 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
147 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
148 const CXXRecordDecl *Type, raw_ostream &) override;
149 void mangleCXXRTTI(QualType T, raw_ostream &) override;
150 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
151 void mangleTypeName(QualType T, raw_ostream &) override;
152 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
153 raw_ostream &) override;
154 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
155 raw_ostream &) override;
157 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
158 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
159 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
160 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
161 void mangleDynamicAtExitDestructor(const VarDecl *D,
162 raw_ostream &Out) override;
163 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
164 raw_ostream &Out) override;
165 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
166 raw_ostream &Out) override;
167 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
168 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
169 raw_ostream &) override;
171 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
173 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
174 // Lambda closure types are already numbered.
178 // Anonymous tags are already numbered.
179 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
180 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
184 // Use the canonical number for externally visible decls.
185 if (ND->isExternallyVisible()) {
186 unsigned discriminator = getASTContext().getManglingNumber(ND);
187 if (discriminator == 1)
189 disc = discriminator - 2;
193 // Make up a reasonable number for internal decls.
194 unsigned &discriminator = Uniquifier[ND];
195 if (!discriminator) {
196 const DeclContext *DC = getEffectiveDeclContext(ND);
197 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
199 if (discriminator == 1)
201 disc = discriminator-2;
207 /// Manage the mangling of a single name.
208 class CXXNameMangler {
209 ItaniumMangleContextImpl &Context;
211 bool NullOut = false;
212 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
213 /// This mode is used when mangler creates another mangler recursively to
214 /// calculate ABI tags for the function return value or the variable type.
215 /// Also it is required to avoid infinite recursion in some cases.
216 bool DisableDerivedAbiTags = false;
218 /// The "structor" is the top-level declaration being mangled, if
219 /// that's not a template specialization; otherwise it's the pattern
220 /// for that specialization.
221 const NamedDecl *Structor;
222 unsigned StructorType;
224 /// The next substitution sequence number.
227 class FunctionTypeDepthState {
230 enum { InResultTypeMask = 1 };
233 FunctionTypeDepthState() : Bits(0) {}
235 /// The number of function types we're inside.
236 unsigned getDepth() const {
240 /// True if we're in the return type of the innermost function type.
241 bool isInResultType() const {
242 return Bits & InResultTypeMask;
245 FunctionTypeDepthState push() {
246 FunctionTypeDepthState tmp = *this;
247 Bits = (Bits & ~InResultTypeMask) + 2;
251 void enterResultType() {
252 Bits |= InResultTypeMask;
255 void leaveResultType() {
256 Bits &= ~InResultTypeMask;
259 void pop(FunctionTypeDepthState saved) {
260 assert(getDepth() == saved.getDepth() + 1);
266 // abi_tag is a gcc attribute, taking one or more strings called "tags".
267 // The goal is to annotate against which version of a library an object was
268 // built and to be able to provide backwards compatibility ("dual abi").
269 // For more information see docs/ItaniumMangleAbiTags.rst.
270 typedef SmallVector<StringRef, 4> AbiTagList;
272 // State to gather all implicit and explicit tags used in a mangled name.
273 // Must always have an instance of this while emitting any name to keep
275 class AbiTagState final {
277 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
283 AbiTagState(const AbiTagState &) = delete;
284 AbiTagState &operator=(const AbiTagState &) = delete;
286 ~AbiTagState() { pop(); }
288 void write(raw_ostream &Out, const NamedDecl *ND,
289 const AbiTagList *AdditionalAbiTags) {
290 ND = cast<NamedDecl>(ND->getCanonicalDecl());
291 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
293 !AdditionalAbiTags &&
294 "only function and variables need a list of additional abi tags");
295 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
296 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
297 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
298 AbiTag->tags().end());
300 // Don't emit abi tags for namespaces.
306 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
307 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
308 AbiTag->tags().end());
309 TagList.insert(TagList.end(), AbiTag->tags().begin(),
310 AbiTag->tags().end());
313 if (AdditionalAbiTags) {
314 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
315 AdditionalAbiTags->end());
316 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
317 AdditionalAbiTags->end());
321 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
323 writeSortedUniqueAbiTags(Out, TagList);
326 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
327 void setUsedAbiTags(const AbiTagList &AbiTags) {
328 UsedAbiTags = AbiTags;
331 const AbiTagList &getEmittedAbiTags() const {
332 return EmittedAbiTags;
335 const AbiTagList &getSortedUniqueUsedAbiTags() {
336 llvm::sort(UsedAbiTags);
337 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
343 //! All abi tags used implicitly or explicitly.
344 AbiTagList UsedAbiTags;
345 //! All explicit abi tags (i.e. not from namespace).
346 AbiTagList EmittedAbiTags;
348 AbiTagState *&LinkHead;
349 AbiTagState *Parent = nullptr;
352 assert(LinkHead == this &&
353 "abi tag link head must point to us on destruction");
355 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
356 UsedAbiTags.begin(), UsedAbiTags.end());
357 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
358 EmittedAbiTags.begin(),
359 EmittedAbiTags.end());
364 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
365 for (const auto &Tag : AbiTags) {
366 EmittedAbiTags.push_back(Tag);
374 AbiTagState *AbiTags = nullptr;
375 AbiTagState AbiTagsRoot;
377 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
378 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
380 ASTContext &getASTContext() const { return Context.getASTContext(); }
383 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
384 const NamedDecl *D = nullptr, bool NullOut_ = false)
385 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
386 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
387 // These can't be mangled without a ctor type or dtor type.
388 assert(!D || (!isa<CXXDestructorDecl>(D) &&
389 !isa<CXXConstructorDecl>(D)));
391 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
392 const CXXConstructorDecl *D, CXXCtorType Type)
393 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
394 SeqID(0), AbiTagsRoot(AbiTags) { }
395 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
396 const CXXDestructorDecl *D, CXXDtorType Type)
397 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
398 SeqID(0), AbiTagsRoot(AbiTags) { }
400 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
401 : Context(Outer.Context), Out(Out_), NullOut(false),
402 Structor(Outer.Structor), StructorType(Outer.StructorType),
403 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
404 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
406 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
407 : Context(Outer.Context), Out(Out_), NullOut(true),
408 Structor(Outer.Structor), StructorType(Outer.StructorType),
409 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
410 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
412 raw_ostream &getStream() { return Out; }
414 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
415 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
417 void mangle(const NamedDecl *D);
418 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
419 void mangleNumber(const llvm::APSInt &I);
420 void mangleNumber(int64_t Number);
421 void mangleFloat(const llvm::APFloat &F);
422 void mangleFunctionEncoding(const FunctionDecl *FD);
423 void mangleSeqID(unsigned SeqID);
424 void mangleName(const NamedDecl *ND);
425 void mangleType(QualType T);
426 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
430 bool mangleSubstitution(const NamedDecl *ND);
431 bool mangleSubstitution(QualType T);
432 bool mangleSubstitution(TemplateName Template);
433 bool mangleSubstitution(uintptr_t Ptr);
435 void mangleExistingSubstitution(TemplateName name);
437 bool mangleStandardSubstitution(const NamedDecl *ND);
439 void addSubstitution(const NamedDecl *ND) {
440 ND = cast<NamedDecl>(ND->getCanonicalDecl());
442 addSubstitution(reinterpret_cast<uintptr_t>(ND));
444 void addSubstitution(QualType T);
445 void addSubstitution(TemplateName Template);
446 void addSubstitution(uintptr_t Ptr);
447 // Destructive copy substitutions from other mangler.
448 void extendSubstitutions(CXXNameMangler* Other);
450 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
451 bool recursive = false);
452 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
453 DeclarationName name,
454 const TemplateArgumentLoc *TemplateArgs,
455 unsigned NumTemplateArgs,
456 unsigned KnownArity = UnknownArity);
458 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
460 void mangleNameWithAbiTags(const NamedDecl *ND,
461 const AbiTagList *AdditionalAbiTags);
462 void mangleModuleName(const Module *M);
463 void mangleModuleNamePrefix(StringRef Name);
464 void mangleTemplateName(const TemplateDecl *TD,
465 const TemplateArgument *TemplateArgs,
466 unsigned NumTemplateArgs);
467 void mangleUnqualifiedName(const NamedDecl *ND,
468 const AbiTagList *AdditionalAbiTags) {
469 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
472 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
474 const AbiTagList *AdditionalAbiTags);
475 void mangleUnscopedName(const NamedDecl *ND,
476 const AbiTagList *AdditionalAbiTags);
477 void mangleUnscopedTemplateName(const TemplateDecl *ND,
478 const AbiTagList *AdditionalAbiTags);
479 void mangleUnscopedTemplateName(TemplateName,
480 const AbiTagList *AdditionalAbiTags);
481 void mangleSourceName(const IdentifierInfo *II);
482 void mangleRegCallName(const IdentifierInfo *II);
483 void mangleSourceNameWithAbiTags(
484 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
485 void mangleLocalName(const Decl *D,
486 const AbiTagList *AdditionalAbiTags);
487 void mangleBlockForPrefix(const BlockDecl *Block);
488 void mangleUnqualifiedBlock(const BlockDecl *Block);
489 void mangleLambda(const CXXRecordDecl *Lambda);
490 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
491 const AbiTagList *AdditionalAbiTags,
492 bool NoFunction=false);
493 void mangleNestedName(const TemplateDecl *TD,
494 const TemplateArgument *TemplateArgs,
495 unsigned NumTemplateArgs);
496 void manglePrefix(NestedNameSpecifier *qualifier);
497 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
498 void manglePrefix(QualType type);
499 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
500 void mangleTemplatePrefix(TemplateName Template);
501 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
502 StringRef Prefix = "");
503 void mangleOperatorName(DeclarationName Name, unsigned Arity);
504 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
505 void mangleVendorQualifier(StringRef qualifier);
506 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
507 void mangleRefQualifier(RefQualifierKind RefQualifier);
509 void mangleObjCMethodName(const ObjCMethodDecl *MD);
511 // Declare manglers for every type class.
512 #define ABSTRACT_TYPE(CLASS, PARENT)
513 #define NON_CANONICAL_TYPE(CLASS, PARENT)
514 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
515 #include "clang/AST/TypeNodes.def"
517 void mangleType(const TagType*);
518 void mangleType(TemplateName);
519 static StringRef getCallingConvQualifierName(CallingConv CC);
520 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
521 void mangleExtFunctionInfo(const FunctionType *T);
522 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
523 const FunctionDecl *FD = nullptr);
524 void mangleNeonVectorType(const VectorType *T);
525 void mangleNeonVectorType(const DependentVectorType *T);
526 void mangleAArch64NeonVectorType(const VectorType *T);
527 void mangleAArch64NeonVectorType(const DependentVectorType *T);
529 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
530 void mangleMemberExprBase(const Expr *base, bool isArrow);
531 void mangleMemberExpr(const Expr *base, bool isArrow,
532 NestedNameSpecifier *qualifier,
533 NamedDecl *firstQualifierLookup,
534 DeclarationName name,
535 const TemplateArgumentLoc *TemplateArgs,
536 unsigned NumTemplateArgs,
537 unsigned knownArity);
538 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
539 void mangleInitListElements(const InitListExpr *InitList);
540 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
541 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
542 void mangleCXXDtorType(CXXDtorType T);
544 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
545 unsigned NumTemplateArgs);
546 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
547 unsigned NumTemplateArgs);
548 void mangleTemplateArgs(const TemplateArgumentList &AL);
549 void mangleTemplateArg(TemplateArgument A);
551 void mangleTemplateParameter(unsigned Index);
553 void mangleFunctionParam(const ParmVarDecl *parm);
555 void writeAbiTags(const NamedDecl *ND,
556 const AbiTagList *AdditionalAbiTags);
558 // Returns sorted unique list of ABI tags.
559 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
560 // Returns sorted unique list of ABI tags.
561 AbiTagList makeVariableTypeTags(const VarDecl *VD);
566 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
567 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
569 LanguageLinkage L = FD->getLanguageLinkage();
570 // Overloadable functions need mangling.
571 if (FD->hasAttr<OverloadableAttr>())
574 // "main" is not mangled.
578 // The Windows ABI expects that we would never mangle "typical"
579 // user-defined entry points regardless of visibility or freestanding-ness.
581 // N.B. This is distinct from asking about "main". "main" has a lot of
582 // special rules associated with it in the standard while these
583 // user-defined entry points are outside of the purview of the standard.
584 // For example, there can be only one definition for "main" in a standards
585 // compliant program; however nothing forbids the existence of wmain and
586 // WinMain in the same translation unit.
587 if (FD->isMSVCRTEntryPoint())
590 // C++ functions and those whose names are not a simple identifier need
592 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
595 // C functions are not mangled.
596 if (L == CLanguageLinkage)
600 // Otherwise, no mangling is done outside C++ mode.
601 if (!getASTContext().getLangOpts().CPlusPlus)
604 const VarDecl *VD = dyn_cast<VarDecl>(D);
605 if (VD && !isa<DecompositionDecl>(D)) {
606 // C variables are not mangled.
610 // Variables at global scope with non-internal linkage are not mangled
611 const DeclContext *DC = getEffectiveDeclContext(D);
612 // Check for extern variable declared locally.
613 if (DC->isFunctionOrMethod() && D->hasLinkage())
614 while (!DC->isNamespace() && !DC->isTranslationUnit())
615 DC = getEffectiveParentContext(DC);
616 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
617 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
618 !isa<VarTemplateSpecializationDecl>(D))
625 void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
626 const AbiTagList *AdditionalAbiTags) {
627 assert(AbiTags && "require AbiTagState");
628 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
631 void CXXNameMangler::mangleSourceNameWithAbiTags(
632 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
633 mangleSourceName(ND->getIdentifier());
634 writeAbiTags(ND, AdditionalAbiTags);
637 void CXXNameMangler::mangle(const NamedDecl *D) {
638 // <mangled-name> ::= _Z <encoding>
640 // ::= <special-name>
642 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
643 mangleFunctionEncoding(FD);
644 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
646 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
647 mangleName(IFD->getAnonField());
649 mangleName(cast<FieldDecl>(D));
652 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
653 // <encoding> ::= <function name> <bare-function-type>
655 // Don't mangle in the type if this isn't a decl we should typically mangle.
656 if (!Context.shouldMangleDeclName(FD)) {
661 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
662 if (ReturnTypeAbiTags.empty()) {
663 // There are no tags for return type, the simplest case.
665 mangleFunctionEncodingBareType(FD);
669 // Mangle function name and encoding to temporary buffer.
670 // We have to output name and encoding to the same mangler to get the same
671 // substitution as it will be in final mangling.
672 SmallString<256> FunctionEncodingBuf;
673 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
674 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
675 // Output name of the function.
676 FunctionEncodingMangler.disableDerivedAbiTags();
677 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
679 // Remember length of the function name in the buffer.
680 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
681 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
683 // Get tags from return type that are not present in function name or
685 const AbiTagList &UsedAbiTags =
686 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
687 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
688 AdditionalAbiTags.erase(
689 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
690 UsedAbiTags.begin(), UsedAbiTags.end(),
691 AdditionalAbiTags.begin()),
692 AdditionalAbiTags.end());
694 // Output name with implicit tags and function encoding from temporary buffer.
695 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
696 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
698 // Function encoding could create new substitutions so we have to add
699 // temp mangled substitutions to main mangler.
700 extendSubstitutions(&FunctionEncodingMangler);
703 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
704 if (FD->hasAttr<EnableIfAttr>()) {
705 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
706 Out << "Ua9enable_ifI";
707 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
708 E = FD->getAttrs().end();
710 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
714 mangleExpression(EIA->getCond());
718 FunctionTypeDepth.pop(Saved);
721 // When mangling an inheriting constructor, the bare function type used is
722 // that of the inherited constructor.
723 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
724 if (auto Inherited = CD->getInheritedConstructor())
725 FD = Inherited.getConstructor();
727 // Whether the mangling of a function type includes the return type depends on
728 // the context and the nature of the function. The rules for deciding whether
729 // the return type is included are:
731 // 1. Template functions (names or types) have return types encoded, with
732 // the exceptions listed below.
733 // 2. Function types not appearing as part of a function name mangling,
734 // e.g. parameters, pointer types, etc., have return type encoded, with the
735 // exceptions listed below.
736 // 3. Non-template function names do not have return types encoded.
738 // The exceptions mentioned in (1) and (2) above, for which the return type is
739 // never included, are
742 // 3. Conversion operator functions, e.g. operator int.
743 bool MangleReturnType = false;
744 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
745 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
746 isa<CXXConversionDecl>(FD)))
747 MangleReturnType = true;
749 // Mangle the type of the primary template.
750 FD = PrimaryTemplate->getTemplatedDecl();
753 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
754 MangleReturnType, FD);
757 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
758 while (isa<LinkageSpecDecl>(DC)) {
759 DC = getEffectiveParentContext(DC);
765 /// Return whether a given namespace is the 'std' namespace.
766 static bool isStd(const NamespaceDecl *NS) {
767 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
768 ->isTranslationUnit())
771 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
772 return II && II->isStr("std");
775 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
777 static bool isStdNamespace(const DeclContext *DC) {
778 if (!DC->isNamespace())
781 return isStd(cast<NamespaceDecl>(DC));
784 static const TemplateDecl *
785 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
786 // Check if we have a function template.
787 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
788 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
789 TemplateArgs = FD->getTemplateSpecializationArgs();
794 // Check if we have a class template.
795 if (const ClassTemplateSpecializationDecl *Spec =
796 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
797 TemplateArgs = &Spec->getTemplateArgs();
798 return Spec->getSpecializedTemplate();
801 // Check if we have a variable template.
802 if (const VarTemplateSpecializationDecl *Spec =
803 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
804 TemplateArgs = &Spec->getTemplateArgs();
805 return Spec->getSpecializedTemplate();
811 void CXXNameMangler::mangleName(const NamedDecl *ND) {
812 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
813 // Variables should have implicit tags from its type.
814 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
815 if (VariableTypeAbiTags.empty()) {
816 // Simple case no variable type tags.
817 mangleNameWithAbiTags(VD, nullptr);
821 // Mangle variable name to null stream to collect tags.
822 llvm::raw_null_ostream NullOutStream;
823 CXXNameMangler VariableNameMangler(*this, NullOutStream);
824 VariableNameMangler.disableDerivedAbiTags();
825 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
827 // Get tags from variable type that are not present in its name.
828 const AbiTagList &UsedAbiTags =
829 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
830 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
831 AdditionalAbiTags.erase(
832 std::set_difference(VariableTypeAbiTags.begin(),
833 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
834 UsedAbiTags.end(), AdditionalAbiTags.begin()),
835 AdditionalAbiTags.end());
837 // Output name with implicit tags.
838 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
840 mangleNameWithAbiTags(ND, nullptr);
844 void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
845 const AbiTagList *AdditionalAbiTags) {
846 // <name> ::= [<module-name>] <nested-name>
847 // ::= [<module-name>] <unscoped-name>
848 // ::= [<module-name>] <unscoped-template-name> <template-args>
851 const DeclContext *DC = getEffectiveDeclContext(ND);
853 // If this is an extern variable declared locally, the relevant DeclContext
854 // is that of the containing namespace, or the translation unit.
855 // FIXME: This is a hack; extern variables declared locally should have
856 // a proper semantic declaration context!
857 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
858 while (!DC->isNamespace() && !DC->isTranslationUnit())
859 DC = getEffectiveParentContext(DC);
860 else if (GetLocalClassDecl(ND)) {
861 mangleLocalName(ND, AdditionalAbiTags);
865 DC = IgnoreLinkageSpecDecls(DC);
867 if (isLocalContainerContext(DC)) {
868 mangleLocalName(ND, AdditionalAbiTags);
872 // Do not mangle the owning module for an external linkage declaration.
873 // This enables backwards-compatibility with non-modular code, and is
874 // a valid choice since conflicts are not permitted by C++ Modules TS
875 // [basic.def.odr]/6.2.
876 if (!ND->hasExternalFormalLinkage())
877 if (Module *M = ND->getOwningModuleForLinkage())
880 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
881 // Check if we have a template.
882 const TemplateArgumentList *TemplateArgs = nullptr;
883 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
884 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
885 mangleTemplateArgs(*TemplateArgs);
889 mangleUnscopedName(ND, AdditionalAbiTags);
893 mangleNestedName(ND, DC, AdditionalAbiTags);
896 void CXXNameMangler::mangleModuleName(const Module *M) {
897 // Implement the C++ Modules TS name mangling proposal; see
898 // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
900 // <module-name> ::= W <unscoped-name>+ E
901 // ::= W <module-subst> <unscoped-name>* E
903 mangleModuleNamePrefix(M->Name);
907 void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
908 // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
909 // ::= W <seq-id - 10> _ # otherwise
910 auto It = ModuleSubstitutions.find(Name);
911 if (It != ModuleSubstitutions.end()) {
913 Out << '_' << static_cast<char>('0' + It->second);
915 Out << 'W' << (It->second - 10) << '_';
919 // FIXME: Preserve hierarchy in module names rather than flattening
920 // them to strings; use Module*s as substitution keys.
921 auto Parts = Name.rsplit('.');
922 if (Parts.second.empty())
923 Parts.second = Parts.first;
925 mangleModuleNamePrefix(Parts.first);
927 Out << Parts.second.size() << Parts.second;
928 ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
931 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
932 const TemplateArgument *TemplateArgs,
933 unsigned NumTemplateArgs) {
934 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
936 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
937 mangleUnscopedTemplateName(TD, nullptr);
938 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
940 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
944 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
945 const AbiTagList *AdditionalAbiTags) {
946 // <unscoped-name> ::= <unqualified-name>
947 // ::= St <unqualified-name> # ::std::
949 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
952 mangleUnqualifiedName(ND, AdditionalAbiTags);
955 void CXXNameMangler::mangleUnscopedTemplateName(
956 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
957 // <unscoped-template-name> ::= <unscoped-name>
958 // ::= <substitution>
959 if (mangleSubstitution(ND))
962 // <template-template-param> ::= <template-param>
963 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
964 assert(!AdditionalAbiTags &&
965 "template template param cannot have abi tags");
966 mangleTemplateParameter(TTP->getIndex());
967 } else if (isa<BuiltinTemplateDecl>(ND)) {
968 mangleUnscopedName(ND, AdditionalAbiTags);
970 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
976 void CXXNameMangler::mangleUnscopedTemplateName(
977 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
978 // <unscoped-template-name> ::= <unscoped-name>
979 // ::= <substitution>
980 if (TemplateDecl *TD = Template.getAsTemplateDecl())
981 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
983 if (mangleSubstitution(Template))
986 assert(!AdditionalAbiTags &&
987 "dependent template name cannot have abi tags");
989 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
990 assert(Dependent && "Not a dependent template name?");
991 if (const IdentifierInfo *Id = Dependent->getIdentifier())
992 mangleSourceName(Id);
994 mangleOperatorName(Dependent->getOperator(), UnknownArity);
996 addSubstitution(Template);
999 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1001 // Floating-point literals are encoded using a fixed-length
1002 // lowercase hexadecimal string corresponding to the internal
1003 // representation (IEEE on Itanium), high-order bytes first,
1004 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1006 // The 'without leading zeroes' thing seems to be an editorial
1007 // mistake; see the discussion on cxx-abi-dev beginning on
1010 // Our requirements here are just barely weird enough to justify
1011 // using a custom algorithm instead of post-processing APInt::toString().
1013 llvm::APInt valueBits = f.bitcastToAPInt();
1014 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1015 assert(numCharacters != 0);
1017 // Allocate a buffer of the right number of characters.
1018 SmallVector<char, 20> buffer(numCharacters);
1020 // Fill the buffer left-to-right.
1021 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1022 // The bit-index of the next hex digit.
1023 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1025 // Project out 4 bits starting at 'digitIndex'.
1026 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1027 hexDigit >>= (digitBitIndex % 64);
1030 // Map that over to a lowercase hex digit.
1031 static const char charForHex[16] = {
1032 '0', '1', '2', '3', '4', '5', '6', '7',
1033 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1035 buffer[stringIndex] = charForHex[hexDigit];
1038 Out.write(buffer.data(), numCharacters);
1041 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1042 if (Value.isSigned() && Value.isNegative()) {
1044 Value.abs().print(Out, /*signed*/ false);
1046 Value.print(Out, /*signed*/ false);
1050 void CXXNameMangler::mangleNumber(int64_t Number) {
1051 // <number> ::= [n] <non-negative decimal integer>
1060 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1061 // <call-offset> ::= h <nv-offset> _
1062 // ::= v <v-offset> _
1063 // <nv-offset> ::= <offset number> # non-virtual base override
1064 // <v-offset> ::= <offset number> _ <virtual offset number>
1065 // # virtual base override, with vcall offset
1068 mangleNumber(NonVirtual);
1074 mangleNumber(NonVirtual);
1076 mangleNumber(Virtual);
1080 void CXXNameMangler::manglePrefix(QualType type) {
1081 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1082 if (!mangleSubstitution(QualType(TST, 0))) {
1083 mangleTemplatePrefix(TST->getTemplateName());
1085 // FIXME: GCC does not appear to mangle the template arguments when
1086 // the template in question is a dependent template name. Should we
1087 // emulate that badness?
1088 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1089 addSubstitution(QualType(TST, 0));
1091 } else if (const auto *DTST =
1092 type->getAs<DependentTemplateSpecializationType>()) {
1093 if (!mangleSubstitution(QualType(DTST, 0))) {
1094 TemplateName Template = getASTContext().getDependentTemplateName(
1095 DTST->getQualifier(), DTST->getIdentifier());
1096 mangleTemplatePrefix(Template);
1098 // FIXME: GCC does not appear to mangle the template arguments when
1099 // the template in question is a dependent template name. Should we
1100 // emulate that badness?
1101 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1102 addSubstitution(QualType(DTST, 0));
1105 // We use the QualType mangle type variant here because it handles
1111 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1113 /// \param recursive - true if this is being called recursively,
1114 /// i.e. if there is more prefix "to the right".
1115 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1119 // <unresolved-name> ::= [gs] <base-unresolved-name>
1121 // T::x / decltype(p)::x
1122 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1124 // T::N::x /decltype(p)::N::x
1125 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1126 // <base-unresolved-name>
1128 // A::x, N::y, A<T>::z; "gs" means leading "::"
1129 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1130 // <base-unresolved-name>
1132 switch (qualifier->getKind()) {
1133 case NestedNameSpecifier::Global:
1136 // We want an 'sr' unless this is the entire NNS.
1140 // We never want an 'E' here.
1143 case NestedNameSpecifier::Super:
1144 llvm_unreachable("Can't mangle __super specifier");
1146 case NestedNameSpecifier::Namespace:
1147 if (qualifier->getPrefix())
1148 mangleUnresolvedPrefix(qualifier->getPrefix(),
1149 /*recursive*/ true);
1152 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1154 case NestedNameSpecifier::NamespaceAlias:
1155 if (qualifier->getPrefix())
1156 mangleUnresolvedPrefix(qualifier->getPrefix(),
1157 /*recursive*/ true);
1160 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1163 case NestedNameSpecifier::TypeSpec:
1164 case NestedNameSpecifier::TypeSpecWithTemplate: {
1165 const Type *type = qualifier->getAsType();
1167 // We only want to use an unresolved-type encoding if this is one of:
1169 // - a template type parameter
1170 // - a template template parameter with arguments
1171 // In all of these cases, we should have no prefix.
1172 if (qualifier->getPrefix()) {
1173 mangleUnresolvedPrefix(qualifier->getPrefix(),
1174 /*recursive*/ true);
1176 // Otherwise, all the cases want this.
1180 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1186 case NestedNameSpecifier::Identifier:
1187 // Member expressions can have these without prefixes.
1188 if (qualifier->getPrefix())
1189 mangleUnresolvedPrefix(qualifier->getPrefix(),
1190 /*recursive*/ true);
1194 mangleSourceName(qualifier->getAsIdentifier());
1195 // An Identifier has no type information, so we can't emit abi tags for it.
1199 // If this was the innermost part of the NNS, and we fell out to
1200 // here, append an 'E'.
1205 /// Mangle an unresolved-name, which is generally used for names which
1206 /// weren't resolved to specific entities.
1207 void CXXNameMangler::mangleUnresolvedName(
1208 NestedNameSpecifier *qualifier, DeclarationName name,
1209 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1210 unsigned knownArity) {
1211 if (qualifier) mangleUnresolvedPrefix(qualifier);
1212 switch (name.getNameKind()) {
1213 // <base-unresolved-name> ::= <simple-id>
1214 case DeclarationName::Identifier:
1215 mangleSourceName(name.getAsIdentifierInfo());
1217 // <base-unresolved-name> ::= dn <destructor-name>
1218 case DeclarationName::CXXDestructorName:
1220 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1222 // <base-unresolved-name> ::= on <operator-name>
1223 case DeclarationName::CXXConversionFunctionName:
1224 case DeclarationName::CXXLiteralOperatorName:
1225 case DeclarationName::CXXOperatorName:
1227 mangleOperatorName(name, knownArity);
1229 case DeclarationName::CXXConstructorName:
1230 llvm_unreachable("Can't mangle a constructor name!");
1231 case DeclarationName::CXXUsingDirective:
1232 llvm_unreachable("Can't mangle a using directive name!");
1233 case DeclarationName::CXXDeductionGuideName:
1234 llvm_unreachable("Can't mangle a deduction guide name!");
1235 case DeclarationName::ObjCMultiArgSelector:
1236 case DeclarationName::ObjCOneArgSelector:
1237 case DeclarationName::ObjCZeroArgSelector:
1238 llvm_unreachable("Can't mangle Objective-C selector names here!");
1241 // The <simple-id> and on <operator-name> productions end in an optional
1244 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1247 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1248 DeclarationName Name,
1249 unsigned KnownArity,
1250 const AbiTagList *AdditionalAbiTags) {
1251 unsigned Arity = KnownArity;
1252 // <unqualified-name> ::= <operator-name>
1253 // ::= <ctor-dtor-name>
1254 // ::= <source-name>
1255 switch (Name.getNameKind()) {
1256 case DeclarationName::Identifier: {
1257 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1259 // We mangle decomposition declarations as the names of their bindings.
1260 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1261 // FIXME: Non-standard mangling for decomposition declarations:
1263 // <unqualified-name> ::= DC <source-name>* E
1265 // These can never be referenced across translation units, so we do
1266 // not need a cross-vendor mangling for anything other than demanglers.
1267 // Proposed on cxx-abi-dev on 2016-08-12
1269 for (auto *BD : DD->bindings())
1270 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1272 writeAbiTags(ND, AdditionalAbiTags);
1277 // Match GCC's naming convention for internal linkage symbols, for
1278 // symbols that are not actually visible outside of this TU. GCC
1279 // distinguishes between internal and external linkage symbols in
1280 // its mangling, to support cases like this that were valid C++ prior
1283 // void test() { extern void foo(); }
1284 // static void foo();
1286 // Don't bother with the L marker for names in anonymous namespaces; the
1287 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1288 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1289 // implying internal linkage.
1290 if (ND && ND->getFormalLinkage() == InternalLinkage &&
1291 !ND->isExternallyVisible() &&
1292 getEffectiveDeclContext(ND)->isFileContext() &&
1293 !ND->isInAnonymousNamespace())
1296 auto *FD = dyn_cast<FunctionDecl>(ND);
1297 bool IsRegCall = FD &&
1298 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1299 clang::CC_X86RegCall;
1301 mangleRegCallName(II);
1303 mangleSourceName(II);
1305 writeAbiTags(ND, AdditionalAbiTags);
1309 // Otherwise, an anonymous entity. We must have a declaration.
1310 assert(ND && "mangling empty name without declaration");
1312 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1313 if (NS->isAnonymousNamespace()) {
1314 // This is how gcc mangles these names.
1315 Out << "12_GLOBAL__N_1";
1320 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1321 // We must have an anonymous union or struct declaration.
1322 const RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
1324 // Itanium C++ ABI 5.1.2:
1326 // For the purposes of mangling, the name of an anonymous union is
1327 // considered to be the name of the first named data member found by a
1328 // pre-order, depth-first, declaration-order walk of the data members of
1329 // the anonymous union. If there is no such data member (i.e., if all of
1330 // the data members in the union are unnamed), then there is no way for
1331 // a program to refer to the anonymous union, and there is therefore no
1332 // need to mangle its name.
1333 assert(RD->isAnonymousStructOrUnion()
1334 && "Expected anonymous struct or union!");
1335 const FieldDecl *FD = RD->findFirstNamedDataMember();
1337 // It's actually possible for various reasons for us to get here
1338 // with an empty anonymous struct / union. Fortunately, it
1339 // doesn't really matter what name we generate.
1341 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1343 mangleSourceName(FD->getIdentifier());
1344 // Not emitting abi tags: internal name anyway.
1348 // Class extensions have no name as a category, and it's possible
1349 // for them to be the semantic parent of certain declarations
1350 // (primarily, tag decls defined within declarations). Such
1351 // declarations will always have internal linkage, so the name
1352 // doesn't really matter, but we shouldn't crash on them. For
1353 // safety, just handle all ObjC containers here.
1354 if (isa<ObjCContainerDecl>(ND))
1357 // We must have an anonymous struct.
1358 const TagDecl *TD = cast<TagDecl>(ND);
1359 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1360 assert(TD->getDeclContext() == D->getDeclContext() &&
1361 "Typedef should not be in another decl context!");
1362 assert(D->getDeclName().getAsIdentifierInfo() &&
1363 "Typedef was not named!");
1364 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1365 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1366 // Explicit abi tags are still possible; take from underlying type, not
1368 writeAbiTags(TD, nullptr);
1372 // <unnamed-type-name> ::= <closure-type-name>
1374 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1375 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1376 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1377 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1378 assert(!AdditionalAbiTags &&
1379 "Lambda type cannot have additional abi tags");
1380 mangleLambda(Record);
1385 if (TD->isExternallyVisible()) {
1386 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1388 if (UnnamedMangle > 1)
1389 Out << UnnamedMangle - 2;
1391 writeAbiTags(TD, AdditionalAbiTags);
1395 // Get a unique id for the anonymous struct. If it is not a real output
1396 // ID doesn't matter so use fake one.
1397 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
1399 // Mangle it as a source name in the form
1401 // where n is the length of the string.
1404 Str += llvm::utostr(AnonStructId);
1411 case DeclarationName::ObjCZeroArgSelector:
1412 case DeclarationName::ObjCOneArgSelector:
1413 case DeclarationName::ObjCMultiArgSelector:
1414 llvm_unreachable("Can't mangle Objective-C selector names here!");
1416 case DeclarationName::CXXConstructorName: {
1417 const CXXRecordDecl *InheritedFrom = nullptr;
1418 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1419 if (auto Inherited =
1420 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1421 InheritedFrom = Inherited.getConstructor()->getParent();
1422 InheritedTemplateArgs =
1423 Inherited.getConstructor()->getTemplateSpecializationArgs();
1427 // If the named decl is the C++ constructor we're mangling, use the type
1429 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1431 // Otherwise, use the complete constructor name. This is relevant if a
1432 // class with a constructor is declared within a constructor.
1433 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1435 // FIXME: The template arguments are part of the enclosing prefix or
1436 // nested-name, but it's more convenient to mangle them here.
1437 if (InheritedTemplateArgs)
1438 mangleTemplateArgs(*InheritedTemplateArgs);
1440 writeAbiTags(ND, AdditionalAbiTags);
1444 case DeclarationName::CXXDestructorName:
1446 // If the named decl is the C++ destructor we're mangling, use the type we
1448 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1450 // Otherwise, use the complete destructor name. This is relevant if a
1451 // class with a destructor is declared within a destructor.
1452 mangleCXXDtorType(Dtor_Complete);
1453 writeAbiTags(ND, AdditionalAbiTags);
1456 case DeclarationName::CXXOperatorName:
1457 if (ND && Arity == UnknownArity) {
1458 Arity = cast<FunctionDecl>(ND)->getNumParams();
1460 // If we have a member function, we need to include the 'this' pointer.
1461 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1462 if (!MD->isStatic())
1466 case DeclarationName::CXXConversionFunctionName:
1467 case DeclarationName::CXXLiteralOperatorName:
1468 mangleOperatorName(Name, Arity);
1469 writeAbiTags(ND, AdditionalAbiTags);
1472 case DeclarationName::CXXDeductionGuideName:
1473 llvm_unreachable("Can't mangle a deduction guide name!");
1475 case DeclarationName::CXXUsingDirective:
1476 llvm_unreachable("Can't mangle a using directive name!");
1480 void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1481 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1482 // <number> ::= [n] <non-negative decimal integer>
1483 // <identifier> ::= <unqualified source code identifier>
1484 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1488 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1489 // <source-name> ::= <positive length number> <identifier>
1490 // <number> ::= [n] <non-negative decimal integer>
1491 // <identifier> ::= <unqualified source code identifier>
1492 Out << II->getLength() << II->getName();
1495 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1496 const DeclContext *DC,
1497 const AbiTagList *AdditionalAbiTags,
1500 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1501 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1502 // <template-args> E
1505 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1506 Qualifiers MethodQuals = Method->getTypeQualifiers();
1507 // We do not consider restrict a distinguishing attribute for overloading
1508 // purposes so we must not mangle it.
1509 MethodQuals.removeRestrict();
1510 mangleQualifiers(MethodQuals);
1511 mangleRefQualifier(Method->getRefQualifier());
1514 // Check if we have a template.
1515 const TemplateArgumentList *TemplateArgs = nullptr;
1516 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1517 mangleTemplatePrefix(TD, NoFunction);
1518 mangleTemplateArgs(*TemplateArgs);
1521 manglePrefix(DC, NoFunction);
1522 mangleUnqualifiedName(ND, AdditionalAbiTags);
1527 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1528 const TemplateArgument *TemplateArgs,
1529 unsigned NumTemplateArgs) {
1530 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1534 mangleTemplatePrefix(TD);
1535 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1540 void CXXNameMangler::mangleLocalName(const Decl *D,
1541 const AbiTagList *AdditionalAbiTags) {
1542 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1543 // := Z <function encoding> E s [<discriminator>]
1544 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1546 // <discriminator> := _ <non-negative number>
1547 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1548 const RecordDecl *RD = GetLocalClassDecl(D);
1549 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1554 AbiTagState LocalAbiTags(AbiTags);
1556 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1557 mangleObjCMethodName(MD);
1558 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1559 mangleBlockForPrefix(BD);
1561 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1563 // Implicit ABI tags (from namespace) are not available in the following
1564 // entity; reset to actually emitted tags, which are available.
1565 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1570 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1571 // be a bug that is fixed in trunk.
1574 // The parameter number is omitted for the last parameter, 0 for the
1575 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1576 // <entity name> will of course contain a <closure-type-name>: Its
1577 // numbering will be local to the particular argument in which it appears
1578 // -- other default arguments do not affect its encoding.
1579 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1580 if (CXXRD && CXXRD->isLambda()) {
1581 if (const ParmVarDecl *Parm
1582 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1583 if (const FunctionDecl *Func
1584 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1586 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1588 mangleNumber(Num - 2);
1594 // Mangle the name relative to the closest enclosing function.
1595 // equality ok because RD derived from ND above
1597 mangleUnqualifiedName(RD, AdditionalAbiTags);
1598 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1599 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1600 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1601 mangleUnqualifiedBlock(BD);
1603 const NamedDecl *ND = cast<NamedDecl>(D);
1604 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1605 true /*NoFunction*/);
1607 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1608 // Mangle a block in a default parameter; see above explanation for
1610 if (const ParmVarDecl *Parm
1611 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1612 if (const FunctionDecl *Func
1613 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1615 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1617 mangleNumber(Num - 2);
1622 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1623 mangleUnqualifiedBlock(BD);
1625 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
1628 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1630 if (Context.getNextDiscriminator(ND, disc)) {
1634 Out << "__" << disc << '_';
1639 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1640 if (GetLocalClassDecl(Block)) {
1641 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1644 const DeclContext *DC = getEffectiveDeclContext(Block);
1645 if (isLocalContainerContext(DC)) {
1646 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1649 manglePrefix(getEffectiveDeclContext(Block));
1650 mangleUnqualifiedBlock(Block);
1653 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1654 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1655 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1656 Context->getDeclContext()->isRecord()) {
1657 const auto *ND = cast<NamedDecl>(Context);
1658 if (ND->getIdentifier()) {
1659 mangleSourceNameWithAbiTags(ND);
1665 // If we have a block mangling number, use it.
1666 unsigned Number = Block->getBlockManglingNumber();
1667 // Otherwise, just make up a number. It doesn't matter what it is because
1668 // the symbol in question isn't externally visible.
1670 Number = Context.getBlockId(Block, false);
1672 // Stored mangling numbers are 1-based.
1681 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1682 // If the context of a closure type is an initializer for a class member
1683 // (static or nonstatic), it is encoded in a qualified name with a final
1684 // <prefix> of the form:
1686 // <data-member-prefix> := <member source-name> M
1688 // Technically, the data-member-prefix is part of the <prefix>. However,
1689 // since a closure type will always be mangled with a prefix, it's easier
1690 // to emit that last part of the prefix here.
1691 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1692 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1693 !isa<ParmVarDecl>(Context)) {
1694 // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
1695 // reasonable mangling here.
1696 if (const IdentifierInfo *Name
1697 = cast<NamedDecl>(Context)->getIdentifier()) {
1698 mangleSourceName(Name);
1699 const TemplateArgumentList *TemplateArgs = nullptr;
1700 if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
1701 mangleTemplateArgs(*TemplateArgs);
1708 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1709 getAs<FunctionProtoType>();
1710 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1711 Lambda->getLambdaStaticInvoker());
1714 // The number is omitted for the first closure type with a given
1715 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1716 // (in lexical order) with that same <lambda-sig> and context.
1718 // The AST keeps track of the number for us.
1719 unsigned Number = Lambda->getLambdaManglingNumber();
1720 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1722 mangleNumber(Number - 2);
1726 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1727 switch (qualifier->getKind()) {
1728 case NestedNameSpecifier::Global:
1732 case NestedNameSpecifier::Super:
1733 llvm_unreachable("Can't mangle __super specifier");
1735 case NestedNameSpecifier::Namespace:
1736 mangleName(qualifier->getAsNamespace());
1739 case NestedNameSpecifier::NamespaceAlias:
1740 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1743 case NestedNameSpecifier::TypeSpec:
1744 case NestedNameSpecifier::TypeSpecWithTemplate:
1745 manglePrefix(QualType(qualifier->getAsType(), 0));
1748 case NestedNameSpecifier::Identifier:
1749 // Member expressions can have these without prefixes, but that
1750 // should end up in mangleUnresolvedPrefix instead.
1751 assert(qualifier->getPrefix());
1752 manglePrefix(qualifier->getPrefix());
1754 mangleSourceName(qualifier->getAsIdentifier());
1758 llvm_unreachable("unexpected nested name specifier");
1761 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1762 // <prefix> ::= <prefix> <unqualified-name>
1763 // ::= <template-prefix> <template-args>
1764 // ::= <template-param>
1766 // ::= <substitution>
1768 DC = IgnoreLinkageSpecDecls(DC);
1770 if (DC->isTranslationUnit())
1773 if (NoFunction && isLocalContainerContext(DC))
1776 assert(!isLocalContainerContext(DC));
1778 const NamedDecl *ND = cast<NamedDecl>(DC);
1779 if (mangleSubstitution(ND))
1782 // Check if we have a template.
1783 const TemplateArgumentList *TemplateArgs = nullptr;
1784 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1785 mangleTemplatePrefix(TD);
1786 mangleTemplateArgs(*TemplateArgs);
1788 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1789 mangleUnqualifiedName(ND, nullptr);
1792 addSubstitution(ND);
1795 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1796 // <template-prefix> ::= <prefix> <template unqualified-name>
1797 // ::= <template-param>
1798 // ::= <substitution>
1799 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1800 return mangleTemplatePrefix(TD);
1802 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1803 manglePrefix(Qualified->getQualifier());
1805 if (OverloadedTemplateStorage *Overloaded
1806 = Template.getAsOverloadedTemplate()) {
1807 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
1808 UnknownArity, nullptr);
1812 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1813 assert(Dependent && "Unknown template name kind?");
1814 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1815 manglePrefix(Qualifier);
1816 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
1819 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1821 // <template-prefix> ::= <prefix> <template unqualified-name>
1822 // ::= <template-param>
1823 // ::= <substitution>
1824 // <template-template-param> ::= <template-param>
1827 if (mangleSubstitution(ND))
1830 // <template-template-param> ::= <template-param>
1831 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1832 mangleTemplateParameter(TTP->getIndex());
1834 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1835 if (isa<BuiltinTemplateDecl>(ND))
1836 mangleUnqualifiedName(ND, nullptr);
1838 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
1841 addSubstitution(ND);
1844 /// Mangles a template name under the production <type>. Required for
1845 /// template template arguments.
1846 /// <type> ::= <class-enum-type>
1847 /// ::= <template-param>
1848 /// ::= <substitution>
1849 void CXXNameMangler::mangleType(TemplateName TN) {
1850 if (mangleSubstitution(TN))
1853 TemplateDecl *TD = nullptr;
1855 switch (TN.getKind()) {
1856 case TemplateName::QualifiedTemplate:
1857 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1860 case TemplateName::Template:
1861 TD = TN.getAsTemplateDecl();
1865 if (isa<TemplateTemplateParmDecl>(TD))
1866 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1871 case TemplateName::OverloadedTemplate:
1872 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1874 case TemplateName::DependentTemplate: {
1875 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1876 assert(Dependent->isIdentifier());
1878 // <class-enum-type> ::= <name>
1879 // <name> ::= <nested-name>
1880 mangleUnresolvedPrefix(Dependent->getQualifier());
1881 mangleSourceName(Dependent->getIdentifier());
1885 case TemplateName::SubstTemplateTemplateParm: {
1886 // Substituted template parameters are mangled as the substituted
1887 // template. This will check for the substitution twice, which is
1888 // fine, but we have to return early so that we don't try to *add*
1889 // the substitution twice.
1890 SubstTemplateTemplateParmStorage *subst
1891 = TN.getAsSubstTemplateTemplateParm();
1892 mangleType(subst->getReplacement());
1896 case TemplateName::SubstTemplateTemplateParmPack: {
1897 // FIXME: not clear how to mangle this!
1898 // template <template <class> class T...> class A {
1899 // template <template <class> class U...> void foo(B<T,U> x...);
1901 Out << "_SUBSTPACK_";
1906 addSubstitution(TN);
1909 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1911 // Only certain other types are valid as prefixes; enumerate them.
1912 switch (Ty->getTypeClass()) {
1915 case Type::Adjusted:
1918 case Type::BlockPointer:
1919 case Type::LValueReference:
1920 case Type::RValueReference:
1921 case Type::MemberPointer:
1922 case Type::ConstantArray:
1923 case Type::IncompleteArray:
1924 case Type::VariableArray:
1925 case Type::DependentSizedArray:
1926 case Type::DependentAddressSpace:
1927 case Type::DependentVector:
1928 case Type::DependentSizedExtVector:
1930 case Type::ExtVector:
1931 case Type::FunctionProto:
1932 case Type::FunctionNoProto:
1934 case Type::Attributed:
1936 case Type::DeducedTemplateSpecialization:
1937 case Type::PackExpansion:
1938 case Type::ObjCObject:
1939 case Type::ObjCInterface:
1940 case Type::ObjCObjectPointer:
1941 case Type::ObjCTypeParam:
1944 llvm_unreachable("type is illegal as a nested name specifier");
1946 case Type::SubstTemplateTypeParmPack:
1947 // FIXME: not clear how to mangle this!
1948 // template <class T...> class A {
1949 // template <class U...> void foo(decltype(T::foo(U())) x...);
1951 Out << "_SUBSTPACK_";
1954 // <unresolved-type> ::= <template-param>
1956 // ::= <template-template-param> <template-args>
1957 // (this last is not official yet)
1958 case Type::TypeOfExpr:
1960 case Type::Decltype:
1961 case Type::TemplateTypeParm:
1962 case Type::UnaryTransform:
1963 case Type::SubstTemplateTypeParm:
1965 // Some callers want a prefix before the mangled type.
1968 // This seems to do everything we want. It's not really
1969 // sanctioned for a substituted template parameter, though.
1972 // We never want to print 'E' directly after an unresolved-type,
1973 // so we return directly.
1977 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
1980 case Type::UnresolvedUsing:
1981 mangleSourceNameWithAbiTags(
1982 cast<UnresolvedUsingType>(Ty)->getDecl());
1987 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
1990 case Type::TemplateSpecialization: {
1991 const TemplateSpecializationType *TST =
1992 cast<TemplateSpecializationType>(Ty);
1993 TemplateName TN = TST->getTemplateName();
1994 switch (TN.getKind()) {
1995 case TemplateName::Template:
1996 case TemplateName::QualifiedTemplate: {
1997 TemplateDecl *TD = TN.getAsTemplateDecl();
1999 // If the base is a template template parameter, this is an
2001 assert(TD && "no template for template specialization type");
2002 if (isa<TemplateTemplateParmDecl>(TD))
2003 goto unresolvedType;
2005 mangleSourceNameWithAbiTags(TD);
2009 case TemplateName::OverloadedTemplate:
2010 case TemplateName::DependentTemplate:
2011 llvm_unreachable("invalid base for a template specialization type");
2013 case TemplateName::SubstTemplateTemplateParm: {
2014 SubstTemplateTemplateParmStorage *subst =
2015 TN.getAsSubstTemplateTemplateParm();
2016 mangleExistingSubstitution(subst->getReplacement());
2020 case TemplateName::SubstTemplateTemplateParmPack: {
2021 // FIXME: not clear how to mangle this!
2022 // template <template <class U> class T...> class A {
2023 // template <class U...> void foo(decltype(T<U>::foo) x...);
2025 Out << "_SUBSTPACK_";
2030 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
2034 case Type::InjectedClassName:
2035 mangleSourceNameWithAbiTags(
2036 cast<InjectedClassNameType>(Ty)->getDecl());
2039 case Type::DependentName:
2040 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2043 case Type::DependentTemplateSpecialization: {
2044 const DependentTemplateSpecializationType *DTST =
2045 cast<DependentTemplateSpecializationType>(Ty);
2046 mangleSourceName(DTST->getIdentifier());
2047 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2051 case Type::Elaborated:
2052 return mangleUnresolvedTypeOrSimpleId(
2053 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2059 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2060 switch (Name.getNameKind()) {
2061 case DeclarationName::CXXConstructorName:
2062 case DeclarationName::CXXDestructorName:
2063 case DeclarationName::CXXDeductionGuideName:
2064 case DeclarationName::CXXUsingDirective:
2065 case DeclarationName::Identifier:
2066 case DeclarationName::ObjCMultiArgSelector:
2067 case DeclarationName::ObjCOneArgSelector:
2068 case DeclarationName::ObjCZeroArgSelector:
2069 llvm_unreachable("Not an operator name");
2071 case DeclarationName::CXXConversionFunctionName:
2072 // <operator-name> ::= cv <type> # (cast)
2074 mangleType(Name.getCXXNameType());
2077 case DeclarationName::CXXLiteralOperatorName:
2079 mangleSourceName(Name.getCXXLiteralIdentifier());
2082 case DeclarationName::CXXOperatorName:
2083 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2089 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2091 // <operator-name> ::= nw # new
2092 case OO_New: Out << "nw"; break;
2094 case OO_Array_New: Out << "na"; break;
2096 case OO_Delete: Out << "dl"; break;
2097 // ::= da # delete[]
2098 case OO_Array_Delete: Out << "da"; break;
2099 // ::= ps # + (unary)
2100 // ::= pl # + (binary or unknown)
2102 Out << (Arity == 1? "ps" : "pl"); break;
2103 // ::= ng # - (unary)
2104 // ::= mi # - (binary or unknown)
2106 Out << (Arity == 1? "ng" : "mi"); break;
2107 // ::= ad # & (unary)
2108 // ::= an # & (binary or unknown)
2110 Out << (Arity == 1? "ad" : "an"); break;
2111 // ::= de # * (unary)
2112 // ::= ml # * (binary or unknown)
2114 // Use binary when unknown.
2115 Out << (Arity == 1? "de" : "ml"); break;
2117 case OO_Tilde: Out << "co"; break;
2119 case OO_Slash: Out << "dv"; break;
2121 case OO_Percent: Out << "rm"; break;
2123 case OO_Pipe: Out << "or"; break;
2125 case OO_Caret: Out << "eo"; break;
2127 case OO_Equal: Out << "aS"; break;
2129 case OO_PlusEqual: Out << "pL"; break;
2131 case OO_MinusEqual: Out << "mI"; break;
2133 case OO_StarEqual: Out << "mL"; break;
2135 case OO_SlashEqual: Out << "dV"; break;
2137 case OO_PercentEqual: Out << "rM"; break;
2139 case OO_AmpEqual: Out << "aN"; break;
2141 case OO_PipeEqual: Out << "oR"; break;
2143 case OO_CaretEqual: Out << "eO"; break;
2145 case OO_LessLess: Out << "ls"; break;
2147 case OO_GreaterGreater: Out << "rs"; break;
2149 case OO_LessLessEqual: Out << "lS"; break;
2151 case OO_GreaterGreaterEqual: Out << "rS"; break;
2153 case OO_EqualEqual: Out << "eq"; break;
2155 case OO_ExclaimEqual: Out << "ne"; break;
2157 case OO_Less: Out << "lt"; break;
2159 case OO_Greater: Out << "gt"; break;
2161 case OO_LessEqual: Out << "le"; break;
2163 case OO_GreaterEqual: Out << "ge"; break;
2165 case OO_Exclaim: Out << "nt"; break;
2167 case OO_AmpAmp: Out << "aa"; break;
2169 case OO_PipePipe: Out << "oo"; break;
2171 case OO_PlusPlus: Out << "pp"; break;
2173 case OO_MinusMinus: Out << "mm"; break;
2175 case OO_Comma: Out << "cm"; break;
2177 case OO_ArrowStar: Out << "pm"; break;
2179 case OO_Arrow: Out << "pt"; break;
2181 case OO_Call: Out << "cl"; break;
2183 case OO_Subscript: Out << "ix"; break;
2186 // The conditional operator can't be overloaded, but we still handle it when
2187 // mangling expressions.
2188 case OO_Conditional: Out << "qu"; break;
2189 // Proposal on cxx-abi-dev, 2015-10-21.
2190 // ::= aw # co_await
2191 case OO_Coawait: Out << "aw"; break;
2192 // Proposed in cxx-abi github issue 43.
2194 case OO_Spaceship: Out << "ss"; break;
2197 case NUM_OVERLOADED_OPERATORS:
2198 llvm_unreachable("Not an overloaded operator");
2202 void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2203 // Vendor qualifiers come first and if they are order-insensitive they must
2204 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2206 // <type> ::= U <addrspace-expr>
2209 mangleExpression(DAST->getAddrSpaceExpr());
2213 // Address space qualifiers start with an ordinary letter.
2214 if (Quals.hasAddressSpace()) {
2215 // Address space extension:
2217 // <type> ::= U <target-addrspace>
2218 // <type> ::= U <OpenCL-addrspace>
2219 // <type> ::= U <CUDA-addrspace>
2221 SmallString<64> ASString;
2222 LangAS AS = Quals.getAddressSpace();
2224 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2225 // <target-addrspace> ::= "AS" <address-space-number>
2226 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2228 ASString = "AS" + llvm::utostr(TargetAS);
2231 default: llvm_unreachable("Not a language specific address space");
2232 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2233 // "private"| "generic" ]
2234 case LangAS::opencl_global: ASString = "CLglobal"; break;
2235 case LangAS::opencl_local: ASString = "CLlocal"; break;
2236 case LangAS::opencl_constant: ASString = "CLconstant"; break;
2237 case LangAS::opencl_private: ASString = "CLprivate"; break;
2238 case LangAS::opencl_generic: ASString = "CLgeneric"; break;
2239 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2240 case LangAS::cuda_device: ASString = "CUdevice"; break;
2241 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2242 case LangAS::cuda_shared: ASString = "CUshared"; break;
2245 if (!ASString.empty())
2246 mangleVendorQualifier(ASString);
2249 // The ARC ownership qualifiers start with underscores.
2250 // Objective-C ARC Extension:
2252 // <type> ::= U "__strong"
2253 // <type> ::= U "__weak"
2254 // <type> ::= U "__autoreleasing"
2256 // Note: we emit __weak first to preserve the order as
2257 // required by the Itanium ABI.
2258 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2259 mangleVendorQualifier("__weak");
2261 // __unaligned (from -fms-extensions)
2262 if (Quals.hasUnaligned())
2263 mangleVendorQualifier("__unaligned");
2265 // Remaining ARC ownership qualifiers.
2266 switch (Quals.getObjCLifetime()) {
2267 case Qualifiers::OCL_None:
2270 case Qualifiers::OCL_Weak:
2271 // Do nothing as we already handled this case above.
2274 case Qualifiers::OCL_Strong:
2275 mangleVendorQualifier("__strong");
2278 case Qualifiers::OCL_Autoreleasing:
2279 mangleVendorQualifier("__autoreleasing");
2282 case Qualifiers::OCL_ExplicitNone:
2283 // The __unsafe_unretained qualifier is *not* mangled, so that
2284 // __unsafe_unretained types in ARC produce the same manglings as the
2285 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2286 // better ABI compatibility.
2288 // It's safe to do this because unqualified 'id' won't show up
2289 // in any type signatures that need to be mangled.
2293 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2294 if (Quals.hasRestrict())
2296 if (Quals.hasVolatile())
2298 if (Quals.hasConst())
2302 void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2303 Out << 'U' << name.size() << name;
2306 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2307 // <ref-qualifier> ::= R # lvalue reference
2308 // ::= O # rvalue-reference
2309 switch (RefQualifier) {
2323 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2324 Context.mangleObjCMethodName(MD, Out);
2327 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2331 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2333 if (Ty->isOpenCLSpecificType())
2335 if (Ty->isBuiltinType())
2337 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2338 // substitution candidates.
2339 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2345 void CXXNameMangler::mangleType(QualType T) {
2346 // If our type is instantiation-dependent but not dependent, we mangle
2347 // it as it was written in the source, removing any top-level sugar.
2348 // Otherwise, use the canonical type.
2350 // FIXME: This is an approximation of the instantiation-dependent name
2351 // mangling rules, since we should really be using the type as written and
2352 // augmented via semantic analysis (i.e., with implicit conversions and
2353 // default template arguments) for any instantiation-dependent type.
2354 // Unfortunately, that requires several changes to our AST:
2355 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2356 // uniqued, so that we can handle substitutions properly
2357 // - Default template arguments will need to be represented in the
2358 // TemplateSpecializationType, since they need to be mangled even though
2359 // they aren't written.
2360 // - Conversions on non-type template arguments need to be expressed, since
2361 // they can affect the mangling of sizeof/alignof.
2363 // FIXME: This is wrong when mapping to the canonical type for a dependent
2364 // type discards instantiation-dependent portions of the type, such as for:
2366 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2367 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2369 // It's also wrong in the opposite direction when instantiation-dependent,
2370 // canonically-equivalent types differ in some irrelevant portion of inner
2371 // type sugar. In such cases, we fail to form correct substitutions, eg:
2373 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2375 // We should instead canonicalize the non-instantiation-dependent parts,
2376 // regardless of whether the type as a whole is dependent or instantiation
2378 if (!T->isInstantiationDependentType() || T->isDependentType())
2379 T = T.getCanonicalType();
2381 // Desugar any types that are purely sugar.
2383 // Don't desugar through template specialization types that aren't
2384 // type aliases. We need to mangle the template arguments as written.
2385 if (const TemplateSpecializationType *TST
2386 = dyn_cast<TemplateSpecializationType>(T))
2387 if (!TST->isTypeAlias())
2391 = T.getSingleStepDesugaredType(Context.getASTContext());
2398 SplitQualType split = T.split();
2399 Qualifiers quals = split.Quals;
2400 const Type *ty = split.Ty;
2402 bool isSubstitutable =
2403 isTypeSubstitutable(quals, ty, Context.getASTContext());
2404 if (isSubstitutable && mangleSubstitution(T))
2407 // If we're mangling a qualified array type, push the qualifiers to
2408 // the element type.
2409 if (quals && isa<ArrayType>(T)) {
2410 ty = Context.getASTContext().getAsArrayType(T);
2411 quals = Qualifiers();
2413 // Note that we don't update T: we want to add the
2414 // substitution at the original type.
2417 if (quals || ty->isDependentAddressSpaceType()) {
2418 if (const DependentAddressSpaceType *DAST =
2419 dyn_cast<DependentAddressSpaceType>(ty)) {
2420 SplitQualType splitDAST = DAST->getPointeeType().split();
2421 mangleQualifiers(splitDAST.Quals, DAST);
2422 mangleType(QualType(splitDAST.Ty, 0));
2424 mangleQualifiers(quals);
2426 // Recurse: even if the qualified type isn't yet substitutable,
2427 // the unqualified type might be.
2428 mangleType(QualType(ty, 0));
2431 switch (ty->getTypeClass()) {
2432 #define ABSTRACT_TYPE(CLASS, PARENT)
2433 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
2435 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2437 #define TYPE(CLASS, PARENT) \
2439 mangleType(static_cast<const CLASS##Type*>(ty)); \
2441 #include "clang/AST/TypeNodes.def"
2445 // Add the substitution.
2446 if (isSubstitutable)
2450 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2451 if (!mangleStandardSubstitution(ND))
2455 void CXXNameMangler::mangleType(const BuiltinType *T) {
2456 // <type> ::= <builtin-type>
2457 // <builtin-type> ::= v # void
2461 // ::= a # signed char
2462 // ::= h # unsigned char
2464 // ::= t # unsigned short
2466 // ::= j # unsigned int
2468 // ::= m # unsigned long
2469 // ::= x # long long, __int64
2470 // ::= y # unsigned long long, __int64
2472 // ::= o # unsigned __int128
2475 // ::= e # long double, __float80
2476 // ::= g # __float128
2477 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2478 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2479 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2480 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2481 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
2482 // ::= Di # char32_t
2483 // ::= Ds # char16_t
2484 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2485 // ::= u <source-name> # vendor extended type
2486 std::string type_name;
2487 switch (T->getKind()) {
2488 case BuiltinType::Void:
2491 case BuiltinType::Bool:
2494 case BuiltinType::Char_U:
2495 case BuiltinType::Char_S:
2498 case BuiltinType::UChar:
2501 case BuiltinType::UShort:
2504 case BuiltinType::UInt:
2507 case BuiltinType::ULong:
2510 case BuiltinType::ULongLong:
2513 case BuiltinType::UInt128:
2516 case BuiltinType::SChar:
2519 case BuiltinType::WChar_S:
2520 case BuiltinType::WChar_U:
2523 case BuiltinType::Char8:
2526 case BuiltinType::Char16:
2529 case BuiltinType::Char32:
2532 case BuiltinType::Short:
2535 case BuiltinType::Int:
2538 case BuiltinType::Long:
2541 case BuiltinType::LongLong:
2544 case BuiltinType::Int128:
2547 case BuiltinType::Float16:
2550 case BuiltinType::ShortAccum:
2551 case BuiltinType::Accum:
2552 case BuiltinType::LongAccum:
2553 case BuiltinType::UShortAccum:
2554 case BuiltinType::UAccum:
2555 case BuiltinType::ULongAccum:
2556 case BuiltinType::ShortFract:
2557 case BuiltinType::Fract:
2558 case BuiltinType::LongFract:
2559 case BuiltinType::UShortFract:
2560 case BuiltinType::UFract:
2561 case BuiltinType::ULongFract:
2562 case BuiltinType::SatShortAccum:
2563 case BuiltinType::SatAccum:
2564 case BuiltinType::SatLongAccum:
2565 case BuiltinType::SatUShortAccum:
2566 case BuiltinType::SatUAccum:
2567 case BuiltinType::SatULongAccum:
2568 case BuiltinType::SatShortFract:
2569 case BuiltinType::SatFract:
2570 case BuiltinType::SatLongFract:
2571 case BuiltinType::SatUShortFract:
2572 case BuiltinType::SatUFract:
2573 case BuiltinType::SatULongFract:
2574 llvm_unreachable("Fixed point types are disabled for c++");
2575 case BuiltinType::Half:
2578 case BuiltinType::Float:
2581 case BuiltinType::Double:
2584 case BuiltinType::LongDouble:
2585 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2589 case BuiltinType::Float128:
2590 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2591 Out << "U10__float128"; // Match the GCC mangling
2595 case BuiltinType::NullPtr:
2599 #define BUILTIN_TYPE(Id, SingletonId)
2600 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2601 case BuiltinType::Id:
2602 #include "clang/AST/BuiltinTypes.def"
2603 case BuiltinType::Dependent:
2605 llvm_unreachable("mangling a placeholder type");
2607 case BuiltinType::ObjCId:
2608 Out << "11objc_object";
2610 case BuiltinType::ObjCClass:
2611 Out << "10objc_class";
2613 case BuiltinType::ObjCSel:
2614 Out << "13objc_selector";
2616 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2617 case BuiltinType::Id: \
2618 type_name = "ocl_" #ImgType "_" #Suffix; \
2619 Out << type_name.size() << type_name; \
2621 #include "clang/Basic/OpenCLImageTypes.def"
2622 case BuiltinType::OCLSampler:
2623 Out << "11ocl_sampler";
2625 case BuiltinType::OCLEvent:
2626 Out << "9ocl_event";
2628 case BuiltinType::OCLClkEvent:
2629 Out << "12ocl_clkevent";
2631 case BuiltinType::OCLQueue:
2632 Out << "9ocl_queue";
2634 case BuiltinType::OCLReserveID:
2635 Out << "13ocl_reserveid";
2637 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2638 case BuiltinType::Id: \
2639 type_name = "ocl_" #ExtType; \
2640 Out << type_name.size() << type_name; \
2642 #include "clang/Basic/OpenCLExtensionTypes.def"
2646 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2651 case CC_X86VectorCall:
2656 case CC_AArch64VectorCall:
2657 case CC_IntelOclBicc:
2658 case CC_SpirFunction:
2659 case CC_OpenCLKernel:
2660 case CC_PreserveMost:
2661 case CC_PreserveAll:
2662 // FIXME: we should be mangling all of the above.
2665 case CC_X86ThisCall:
2666 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
2667 // used explicitly. At this point, we don't have that much information in
2668 // the AST, since clang tends to bake the convention into the canonical
2669 // function type. thiscall only rarely used explicitly, so don't mangle it
2675 case CC_X86FastCall:
2684 llvm_unreachable("bad calling convention");
2687 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2689 if (T->getExtInfo() == FunctionType::ExtInfo())
2692 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2693 // This will get more complicated in the future if we mangle other
2694 // things here; but for now, since we mangle ns_returns_retained as
2695 // a qualifier on the result type, we can get away with this:
2696 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2697 if (!CCQualifier.empty())
2698 mangleVendorQualifier(CCQualifier);
2705 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2706 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2708 // Note that these are *not* substitution candidates. Demanglers might
2709 // have trouble with this if the parameter type is fully substituted.
2711 switch (PI.getABI()) {
2712 case ParameterABI::Ordinary:
2715 // All of these start with "swift", so they come before "ns_consumed".
2716 case ParameterABI::SwiftContext:
2717 case ParameterABI::SwiftErrorResult:
2718 case ParameterABI::SwiftIndirectResult:
2719 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2723 if (PI.isConsumed())
2724 mangleVendorQualifier("ns_consumed");
2726 if (PI.isNoEscape())
2727 mangleVendorQualifier("noescape");
2730 // <type> ::= <function-type>
2731 // <function-type> ::= [<CV-qualifiers>] F [Y]
2732 // <bare-function-type> [<ref-qualifier>] E
2733 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2734 mangleExtFunctionInfo(T);
2736 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2737 // e.g. "const" in "int (A::*)() const".
2738 mangleQualifiers(T->getTypeQuals());
2740 // Mangle instantiation-dependent exception-specification, if present,
2741 // per cxx-abi-dev proposal on 2016-10-11.
2742 if (T->hasInstantiationDependentExceptionSpec()) {
2743 if (isComputedNoexcept(T->getExceptionSpecType())) {
2745 mangleExpression(T->getNoexceptExpr());
2748 assert(T->getExceptionSpecType() == EST_Dynamic);
2750 for (auto ExceptTy : T->exceptions())
2751 mangleType(ExceptTy);
2754 } else if (T->isNothrow()) {
2760 // FIXME: We don't have enough information in the AST to produce the 'Y'
2761 // encoding for extern "C" function types.
2762 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2764 // Mangle the ref-qualifier, if present.
2765 mangleRefQualifier(T->getRefQualifier());
2770 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2771 // Function types without prototypes can arise when mangling a function type
2772 // within an overloadable function in C. We mangle these as the absence of any
2773 // parameter types (not even an empty parameter list).
2776 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2778 FunctionTypeDepth.enterResultType();
2779 mangleType(T->getReturnType());
2780 FunctionTypeDepth.leaveResultType();
2782 FunctionTypeDepth.pop(saved);
2786 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
2787 bool MangleReturnType,
2788 const FunctionDecl *FD) {
2789 // Record that we're in a function type. See mangleFunctionParam
2790 // for details on what we're trying to achieve here.
2791 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2793 // <bare-function-type> ::= <signature type>+
2794 if (MangleReturnType) {
2795 FunctionTypeDepth.enterResultType();
2797 // Mangle ns_returns_retained as an order-sensitive qualifier here.
2798 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
2799 mangleVendorQualifier("ns_returns_retained");
2801 // Mangle the return type without any direct ARC ownership qualifiers.
2802 QualType ReturnTy = Proto->getReturnType();
2803 if (ReturnTy.getObjCLifetime()) {
2804 auto SplitReturnTy = ReturnTy.split();
2805 SplitReturnTy.Quals.removeObjCLifetime();
2806 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2808 mangleType(ReturnTy);
2810 FunctionTypeDepth.leaveResultType();
2813 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2814 // <builtin-type> ::= v # void
2817 FunctionTypeDepth.pop(saved);
2821 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2822 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2823 // Mangle extended parameter info as order-sensitive qualifiers here.
2824 if (Proto->hasExtParameterInfos() && FD == nullptr) {
2825 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2829 QualType ParamTy = Proto->getParamType(I);
2830 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2833 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2834 // Attr can only take 1 character, so we can hardcode the length below.
2835 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2836 Out << "U17pass_object_size" << Attr->getType();
2841 FunctionTypeDepth.pop(saved);
2843 // <builtin-type> ::= z # ellipsis
2844 if (Proto->isVariadic())
2848 // <type> ::= <class-enum-type>
2849 // <class-enum-type> ::= <name>
2850 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2851 mangleName(T->getDecl());
2854 // <type> ::= <class-enum-type>
2855 // <class-enum-type> ::= <name>
2856 void CXXNameMangler::mangleType(const EnumType *T) {
2857 mangleType(static_cast<const TagType*>(T));
2859 void CXXNameMangler::mangleType(const RecordType *T) {
2860 mangleType(static_cast<const TagType*>(T));
2862 void CXXNameMangler::mangleType(const TagType *T) {
2863 mangleName(T->getDecl());
2866 // <type> ::= <array-type>
2867 // <array-type> ::= A <positive dimension number> _ <element type>
2868 // ::= A [<dimension expression>] _ <element type>
2869 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2870 Out << 'A' << T->getSize() << '_';
2871 mangleType(T->getElementType());
2873 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2875 // decayed vla types (size 0) will just be skipped.
2876 if (T->getSizeExpr())
2877 mangleExpression(T->getSizeExpr());
2879 mangleType(T->getElementType());
2881 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2883 mangleExpression(T->getSizeExpr());
2885 mangleType(T->getElementType());
2887 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2889 mangleType(T->getElementType());
2892 // <type> ::= <pointer-to-member-type>
2893 // <pointer-to-member-type> ::= M <class type> <member type>
2894 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2896 mangleType(QualType(T->getClass(), 0));
2897 QualType PointeeType = T->getPointeeType();
2898 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2901 // Itanium C++ ABI 5.1.8:
2903 // The type of a non-static member function is considered to be different,
2904 // for the purposes of substitution, from the type of a namespace-scope or
2905 // static member function whose type appears similar. The types of two
2906 // non-static member functions are considered to be different, for the
2907 // purposes of substitution, if the functions are members of different
2908 // classes. In other words, for the purposes of substitution, the class of
2909 // which the function is a member is considered part of the type of
2912 // Given that we already substitute member function pointers as a
2913 // whole, the net effect of this rule is just to unconditionally
2914 // suppress substitution on the function type in a member pointer.
2915 // We increment the SeqID here to emulate adding an entry to the
2916 // substitution table.
2919 mangleType(PointeeType);
2922 // <type> ::= <template-param>
2923 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2924 mangleTemplateParameter(T->getIndex());
2927 // <type> ::= <template-param>
2928 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2929 // FIXME: not clear how to mangle this!
2930 // template <class T...> class A {
2931 // template <class U...> void foo(T(*)(U) x...);
2933 Out << "_SUBSTPACK_";
2936 // <type> ::= P <type> # pointer-to
2937 void CXXNameMangler::mangleType(const PointerType *T) {
2939 mangleType(T->getPointeeType());
2941 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2943 mangleType(T->getPointeeType());
2946 // <type> ::= R <type> # reference-to
2947 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2949 mangleType(T->getPointeeType());
2952 // <type> ::= O <type> # rvalue reference-to (C++0x)
2953 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2955 mangleType(T->getPointeeType());
2958 // <type> ::= C <type> # complex pair (C 2000)
2959 void CXXNameMangler::mangleType(const ComplexType *T) {
2961 mangleType(T->getElementType());
2964 // ARM's ABI for Neon vector types specifies that they should be mangled as
2965 // if they are structs (to match ARM's initial implementation). The
2966 // vector type must be one of the special types predefined by ARM.
2967 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2968 QualType EltType = T->getElementType();
2969 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2970 const char *EltName = nullptr;
2971 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2972 switch (cast<BuiltinType>(EltType)->getKind()) {
2973 case BuiltinType::SChar:
2974 case BuiltinType::UChar:
2975 EltName = "poly8_t";
2977 case BuiltinType::Short:
2978 case BuiltinType::UShort:
2979 EltName = "poly16_t";
2981 case BuiltinType::ULongLong:
2982 EltName = "poly64_t";
2984 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2987 switch (cast<BuiltinType>(EltType)->getKind()) {
2988 case BuiltinType::SChar: EltName = "int8_t"; break;
2989 case BuiltinType::UChar: EltName = "uint8_t"; break;
2990 case BuiltinType::Short: EltName = "int16_t"; break;
2991 case BuiltinType::UShort: EltName = "uint16_t"; break;
2992 case BuiltinType::Int: EltName = "int32_t"; break;
2993 case BuiltinType::UInt: EltName = "uint32_t"; break;
2994 case BuiltinType::LongLong: EltName = "int64_t"; break;
2995 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2996 case BuiltinType::Double: EltName = "float64_t"; break;
2997 case BuiltinType::Float: EltName = "float32_t"; break;
2998 case BuiltinType::Half: EltName = "float16_t";break;
3000 llvm_unreachable("unexpected Neon vector element type");
3003 const char *BaseName = nullptr;
3004 unsigned BitSize = (T->getNumElements() *
3005 getASTContext().getTypeSize(EltType));
3007 BaseName = "__simd64_";
3009 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3010 BaseName = "__simd128_";
3012 Out << strlen(BaseName) + strlen(EltName);
3013 Out << BaseName << EltName;
3016 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3017 DiagnosticsEngine &Diags = Context.getDiags();
3018 unsigned DiagID = Diags.getCustomDiagID(
3019 DiagnosticsEngine::Error,
3020 "cannot mangle this dependent neon vector type yet");
3021 Diags.Report(T->getAttributeLoc(), DiagID);
3024 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3025 switch (EltType->getKind()) {
3026 case BuiltinType::SChar:
3028 case BuiltinType::Short:
3030 case BuiltinType::Int:
3032 case BuiltinType::Long:
3033 case BuiltinType::LongLong:
3035 case BuiltinType::UChar:
3037 case BuiltinType::UShort:
3039 case BuiltinType::UInt:
3041 case BuiltinType::ULong:
3042 case BuiltinType::ULongLong:
3044 case BuiltinType::Half:
3046 case BuiltinType::Float:
3048 case BuiltinType::Double:
3051 llvm_unreachable("Unexpected vector element base type");
3055 // AArch64's ABI for Neon vector types specifies that they should be mangled as
3056 // the equivalent internal name. The vector type must be one of the special
3057 // types predefined by ARM.
3058 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3059 QualType EltType = T->getElementType();
3060 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3062 (T->getNumElements() * getASTContext().getTypeSize(EltType));
3063 (void)BitSize; // Silence warning.
3065 assert((BitSize == 64 || BitSize == 128) &&
3066 "Neon vector type not 64 or 128 bits");
3069 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3070 switch (cast<BuiltinType>(EltType)->getKind()) {
3071 case BuiltinType::UChar:
3074 case BuiltinType::UShort:
3077 case BuiltinType::ULong:
3078 case BuiltinType::ULongLong:
3082 llvm_unreachable("unexpected Neon polynomial vector element type");
3085 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3087 std::string TypeName =
3088 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
3089 Out << TypeName.length() << TypeName;
3091 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3092 DiagnosticsEngine &Diags = Context.getDiags();
3093 unsigned DiagID = Diags.getCustomDiagID(
3094 DiagnosticsEngine::Error,
3095 "cannot mangle this dependent neon vector type yet");
3096 Diags.Report(T->getAttributeLoc(), DiagID);
3099 // GNU extension: vector types
3100 // <type> ::= <vector-type>
3101 // <vector-type> ::= Dv <positive dimension number> _
3102 // <extended element type>
3103 // ::= Dv [<dimension expression>] _ <element type>
3104 // <extended element type> ::= <element type>
3105 // ::= p # AltiVec vector pixel
3106 // ::= b # Altivec vector bool
3107 void CXXNameMangler::mangleType(const VectorType *T) {
3108 if ((T->getVectorKind() == VectorType::NeonVector ||
3109 T->getVectorKind() == VectorType::NeonPolyVector)) {
3110 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3111 llvm::Triple::ArchType Arch =
3112 getASTContext().getTargetInfo().getTriple().getArch();
3113 if ((Arch == llvm::Triple::aarch64 ||
3114 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
3115 mangleAArch64NeonVectorType(T);
3117 mangleNeonVectorType(T);
3120 Out << "Dv" << T->getNumElements() << '_';
3121 if (T->getVectorKind() == VectorType::AltiVecPixel)
3123 else if (T->getVectorKind() == VectorType::AltiVecBool)
3126 mangleType(T->getElementType());
3129 void CXXNameMangler::mangleType(const DependentVectorType *T) {
3130 if ((T->getVectorKind() == VectorType::NeonVector ||
3131 T->getVectorKind() == VectorType::NeonPolyVector)) {
3132 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3133 llvm::Triple::ArchType Arch =
3134 getASTContext().getTargetInfo().getTriple().getArch();
3135 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3136 !Target.isOSDarwin())
3137 mangleAArch64NeonVectorType(T);
3139 mangleNeonVectorType(T);
3144 mangleExpression(T->getSizeExpr());
3146 if (T->getVectorKind() == VectorType::AltiVecPixel)
3148 else if (T->getVectorKind() == VectorType::AltiVecBool)
3151 mangleType(T->getElementType());
3154 void CXXNameMangler::mangleType(const ExtVectorType *T) {
3155 mangleType(static_cast<const VectorType*>(T));
3157 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3159 mangleExpression(T->getSizeExpr());
3161 mangleType(T->getElementType());
3164 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3165 SplitQualType split = T->getPointeeType().split();
3166 mangleQualifiers(split.Quals, T);
3167 mangleType(QualType(split.Ty, 0));
3170 void CXXNameMangler::mangleType(const PackExpansionType *T) {
3171 // <type> ::= Dp <type> # pack expansion (C++0x)
3173 mangleType(T->getPattern());
3176 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3177 mangleSourceName(T->getDecl()->getIdentifier());
3180 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
3181 // Treat __kindof as a vendor extended type qualifier.
3182 if (T->isKindOfType())
3183 Out << "U8__kindof";
3185 if (!T->qual_empty()) {
3186 // Mangle protocol qualifiers.
3187 SmallString<64> QualStr;
3188 llvm::raw_svector_ostream QualOS(QualStr);
3189 QualOS << "objcproto";
3190 for (const auto *I : T->quals()) {
3191 StringRef name = I->getName();
3192 QualOS << name.size() << name;
3194 Out << 'U' << QualStr.size() << QualStr;
3197 mangleType(T->getBaseType());
3199 if (T->isSpecialized()) {
3200 // Mangle type arguments as I <type>+ E
3202 for (auto typeArg : T->getTypeArgs())
3203 mangleType(typeArg);
3208 void CXXNameMangler::mangleType(const BlockPointerType *T) {
3209 Out << "U13block_pointer";
3210 mangleType(T->getPointeeType());
3213 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3214 // Mangle injected class name types as if the user had written the
3215 // specialization out fully. It may not actually be possible to see
3216 // this mangling, though.
3217 mangleType(T->getInjectedSpecializationType());
3220 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3221 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
3222 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
3224 if (mangleSubstitution(QualType(T, 0)))
3227 mangleTemplatePrefix(T->getTemplateName());
3229 // FIXME: GCC does not appear to mangle the template arguments when
3230 // the template in question is a dependent template name. Should we
3231 // emulate that badness?
3232 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3233 addSubstitution(QualType(T, 0));
3237 void CXXNameMangler::mangleType(const DependentNameType *T) {
3238 // Proposal by cxx-abi-dev, 2014-03-26
3239 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3240 // # dependent elaborated type specifier using
3242 // ::= Ts <name> # dependent elaborated type specifier using
3243 // # 'struct' or 'class'
3244 // ::= Tu <name> # dependent elaborated type specifier using
3246 // ::= Te <name> # dependent elaborated type specifier using
3248 switch (T->getKeyword()) {
3264 // Typename types are always nested
3266 manglePrefix(T->getQualifier());
3267 mangleSourceName(T->getIdentifier());
3271 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3272 // Dependently-scoped template types are nested if they have a prefix.
3275 // TODO: avoid making this TemplateName.
3276 TemplateName Prefix =
3277 getASTContext().getDependentTemplateName(T->getQualifier(),
3278 T->getIdentifier());
3279 mangleTemplatePrefix(Prefix);
3281 // FIXME: GCC does not appear to mangle the template arguments when
3282 // the template in question is a dependent template name. Should we
3283 // emulate that badness?
3284 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3288 void CXXNameMangler::mangleType(const TypeOfType *T) {
3289 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3290 // "extension with parameters" mangling.
3294 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3295 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3296 // "extension with parameters" mangling.
3300 void CXXNameMangler::mangleType(const DecltypeType *T) {
3301 Expr *E = T->getUnderlyingExpr();
3303 // type ::= Dt <expression> E # decltype of an id-expression
3304 // # or class member access
3305 // ::= DT <expression> E # decltype of an expression
3307 // This purports to be an exhaustive list of id-expressions and
3308 // class member accesses. Note that we do not ignore parentheses;
3309 // parentheses change the semantics of decltype for these
3310 // expressions (and cause the mangler to use the other form).
3311 if (isa<DeclRefExpr>(E) ||
3312 isa<MemberExpr>(E) ||
3313 isa<UnresolvedLookupExpr>(E) ||
3314 isa<DependentScopeDeclRefExpr>(E) ||
3315 isa<CXXDependentScopeMemberExpr>(E) ||
3316 isa<UnresolvedMemberExpr>(E))
3320 mangleExpression(E);
3324 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3325 // If this is dependent, we need to record that. If not, we simply
3326 // mangle it as the underlying type since they are equivalent.
3327 if (T->isDependentType()) {
3330 switch (T->getUTTKind()) {
3331 case UnaryTransformType::EnumUnderlyingType:
3337 mangleType(T->getBaseType());
3340 void CXXNameMangler::mangleType(const AutoType *T) {
3341 assert(T->getDeducedType().isNull() &&
3342 "Deduced AutoType shouldn't be handled here!");
3343 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3344 "shouldn't need to mangle __auto_type!");
3345 // <builtin-type> ::= Da # auto
3346 // ::= Dc # decltype(auto)
3347 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
3350 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3351 // FIXME: This is not the right mangling. We also need to include a scope
3352 // here in some cases.
3353 QualType D = T->getDeducedType();
3355 mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
3360 void CXXNameMangler::mangleType(const AtomicType *T) {
3361 // <type> ::= U <source-name> <type> # vendor extended type qualifier
3362 // (Until there's a standardized mangling...)
3364 mangleType(T->getValueType());
3367 void CXXNameMangler::mangleType(const PipeType *T) {
3368 // Pipe type mangling rules are described in SPIR 2.0 specification
3369 // A.1 Data types and A.3 Summary of changes
3370 // <type> ::= 8ocl_pipe
3374 void CXXNameMangler::mangleIntegerLiteral(QualType T,
3375 const llvm::APSInt &Value) {
3376 // <expr-primary> ::= L <type> <value number> E # integer literal
3380 if (T->isBooleanType()) {
3381 // Boolean values are encoded as 0/1.
3382 Out << (Value.getBoolValue() ? '1' : '0');
3384 mangleNumber(Value);
3390 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3391 // Ignore member expressions involving anonymous unions.
3392 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3393 if (!RT->getDecl()->isAnonymousStructOrUnion())
3395 const auto *ME = dyn_cast<MemberExpr>(Base);
3398 Base = ME->getBase();
3399 IsArrow = ME->isArrow();
3402 if (Base->isImplicitCXXThis()) {
3403 // Note: GCC mangles member expressions to the implicit 'this' as
3404 // *this., whereas we represent them as this->. The Itanium C++ ABI
3405 // does not specify anything here, so we follow GCC.
3408 Out << (IsArrow ? "pt" : "dt");
3409 mangleExpression(Base);
3413 /// Mangles a member expression.
3414 void CXXNameMangler::mangleMemberExpr(const Expr *base,
3416 NestedNameSpecifier *qualifier,
3417 NamedDecl *firstQualifierLookup,
3418 DeclarationName member,
3419 const TemplateArgumentLoc *TemplateArgs,
3420 unsigned NumTemplateArgs,
3422 // <expression> ::= dt <expression> <unresolved-name>
3423 // ::= pt <expression> <unresolved-name>
3425 mangleMemberExprBase(base, isArrow);
3426 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
3429 /// Look at the callee of the given call expression and determine if
3430 /// it's a parenthesized id-expression which would have triggered ADL
3432 static bool isParenthesizedADLCallee(const CallExpr *call) {
3433 const Expr *callee = call->getCallee();
3434 const Expr *fn = callee->IgnoreParens();
3436 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3437 // too, but for those to appear in the callee, it would have to be
3439 if (callee == fn) return false;
3441 // Must be an unresolved lookup.
3442 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3443 if (!lookup) return false;
3445 assert(!lookup->requiresADL());
3447 // Must be an unqualified lookup.
3448 if (lookup->getQualifier()) return false;
3450 // Must not have found a class member. Note that if one is a class
3451 // member, they're all class members.
3452 if (lookup->getNumDecls() > 0 &&
3453 (*lookup->decls_begin())->isCXXClassMember())
3456 // Otherwise, ADL would have been triggered.
3460 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3461 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3462 Out << CastEncoding;
3463 mangleType(ECE->getType());
3464 mangleExpression(ECE->getSubExpr());
3467 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3468 if (auto *Syntactic = InitList->getSyntacticForm())
3469 InitList = Syntactic;
3470 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3471 mangleExpression(InitList->getInit(i));
3474 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3475 // <expression> ::= <unary operator-name> <expression>
3476 // ::= <binary operator-name> <expression> <expression>
3477 // ::= <trinary operator-name> <expression> <expression> <expression>
3478 // ::= cv <type> expression # conversion with one argument
3479 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
3480 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3481 // ::= sc <type> <expression> # static_cast<type> (expression)
3482 // ::= cc <type> <expression> # const_cast<type> (expression)
3483 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
3484 // ::= st <type> # sizeof (a type)
3485 // ::= at <type> # alignof (a type)
3486 // ::= <template-param>
3487 // ::= <function-param>
3488 // ::= sr <type> <unqualified-name> # dependent name
3489 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3490 // ::= ds <expression> <expression> # expr.*expr
3491 // ::= sZ <template-param> # size of a parameter pack
3492 // ::= sZ <function-param> # size of a function parameter pack
3493 // ::= <expr-primary>
3494 // <expr-primary> ::= L <type> <value number> E # integer literal
3495 // ::= L <type <value float> E # floating literal
3496 // ::= L <mangled-name> E # external name
3497 // ::= fpT # 'this' expression
3498 QualType ImplicitlyConvertedToType;
3501 switch (E->getStmtClass()) {
3502 case Expr::NoStmtClass:
3503 #define ABSTRACT_STMT(Type)
3504 #define EXPR(Type, Base)
3505 #define STMT(Type, Base) \
3506 case Expr::Type##Class:
3507 #include "clang/AST/StmtNodes.inc"
3510 // These all can only appear in local or variable-initialization
3511 // contexts and so should never appear in a mangling.
3512 case Expr::AddrLabelExprClass:
3513 case Expr::DesignatedInitUpdateExprClass:
3514 case Expr::ImplicitValueInitExprClass:
3515 case Expr::ArrayInitLoopExprClass:
3516 case Expr::ArrayInitIndexExprClass:
3517 case Expr::NoInitExprClass:
3518 case Expr::ParenListExprClass:
3519 case Expr::LambdaExprClass:
3520 case Expr::MSPropertyRefExprClass:
3521 case Expr::MSPropertySubscriptExprClass:
3522 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
3523 case Expr::OMPArraySectionExprClass:
3524 case Expr::CXXInheritedCtorInitExprClass:
3525 llvm_unreachable("unexpected statement kind");
3527 case Expr::ConstantExprClass:
3528 E = cast<ConstantExpr>(E)->getSubExpr();
3531 // FIXME: invent manglings for all these.
3532 case Expr::BlockExprClass:
3533 case Expr::ChooseExprClass:
3534 case Expr::CompoundLiteralExprClass:
3535 case Expr::ExtVectorElementExprClass:
3536 case Expr::GenericSelectionExprClass:
3537 case Expr::ObjCEncodeExprClass:
3538 case Expr::ObjCIsaExprClass:
3539 case Expr::ObjCIvarRefExprClass:
3540 case Expr::ObjCMessageExprClass:
3541 case Expr::ObjCPropertyRefExprClass:
3542 case Expr::ObjCProtocolExprClass:
3543 case Expr::ObjCSelectorExprClass:
3544 case Expr::ObjCStringLiteralClass:
3545 case Expr::ObjCBoxedExprClass:
3546 case Expr::ObjCArrayLiteralClass:
3547 case Expr::ObjCDictionaryLiteralClass:
3548 case Expr::ObjCSubscriptRefExprClass:
3549 case Expr::ObjCIndirectCopyRestoreExprClass:
3550 case Expr::ObjCAvailabilityCheckExprClass:
3551 case Expr::OffsetOfExprClass:
3552 case Expr::PredefinedExprClass:
3553 case Expr::ShuffleVectorExprClass:
3554 case Expr::ConvertVectorExprClass:
3555 case Expr::StmtExprClass:
3556 case Expr::TypeTraitExprClass:
3557 case Expr::ArrayTypeTraitExprClass:
3558 case Expr::ExpressionTraitExprClass:
3559 case Expr::VAArgExprClass:
3560 case Expr::CUDAKernelCallExprClass:
3561 case Expr::AsTypeExprClass:
3562 case Expr::PseudoObjectExprClass:
3563 case Expr::AtomicExprClass:
3564 case Expr::FixedPointLiteralClass:
3567 // As bad as this diagnostic is, it's better than crashing.
3568 DiagnosticsEngine &Diags = Context.getDiags();
3569 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3570 "cannot yet mangle expression type %0");
3571 Diags.Report(E->getExprLoc(), DiagID)
3572 << E->getStmtClassName() << E->getSourceRange();
3577 case Expr::CXXUuidofExprClass: {
3578 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3579 if (UE->isTypeOperand()) {
3580 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3581 Out << "u8__uuidoft";
3584 Expr *UuidExp = UE->getExprOperand();
3585 Out << "u8__uuidofz";
3586 mangleExpression(UuidExp, Arity);
3591 // Even gcc-4.5 doesn't mangle this.
3592 case Expr::BinaryConditionalOperatorClass: {
3593 DiagnosticsEngine &Diags = Context.getDiags();
3595 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3596 "?: operator with omitted middle operand cannot be mangled");
3597 Diags.Report(E->getExprLoc(), DiagID)
3598 << E->getStmtClassName() << E->getSourceRange();
3602 // These are used for internal purposes and cannot be meaningfully mangled.
3603 case Expr::OpaqueValueExprClass:
3604 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3606 case Expr::InitListExprClass: {
3608 mangleInitListElements(cast<InitListExpr>(E));
3613 case Expr::DesignatedInitExprClass: {
3614 auto *DIE = cast<DesignatedInitExpr>(E);
3615 for (const auto &Designator : DIE->designators()) {
3616 if (Designator.isFieldDesignator()) {
3618 mangleSourceName(Designator.getFieldName());
3619 } else if (Designator.isArrayDesignator()) {
3621 mangleExpression(DIE->getArrayIndex(Designator));
3623 assert(Designator.isArrayRangeDesignator() &&
3624 "unknown designator kind");
3626 mangleExpression(DIE->getArrayRangeStart(Designator));
3627 mangleExpression(DIE->getArrayRangeEnd(Designator));
3630 mangleExpression(DIE->getInit());
3634 case Expr::CXXDefaultArgExprClass:
3635 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3638 case Expr::CXXDefaultInitExprClass:
3639 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3642 case Expr::CXXStdInitializerListExprClass:
3643 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3646 case Expr::SubstNonTypeTemplateParmExprClass:
3647 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3651 case Expr::UserDefinedLiteralClass:
3652 // We follow g++'s approach of mangling a UDL as a call to the literal
3654 case Expr::CXXMemberCallExprClass: // fallthrough
3655 case Expr::CallExprClass: {
3656 const CallExpr *CE = cast<CallExpr>(E);
3658 // <expression> ::= cp <simple-id> <expression>* E
3659 // We use this mangling only when the call would use ADL except
3660 // for being parenthesized. Per discussion with David
3661 // Vandervoorde, 2011.04.25.
3662 if (isParenthesizedADLCallee(CE)) {
3664 // The callee here is a parenthesized UnresolvedLookupExpr with
3665 // no qualifier and should always get mangled as a <simple-id>
3668 // <expression> ::= cl <expression>* E
3673 unsigned CallArity = CE->getNumArgs();
3674 for (const Expr *Arg : CE->arguments())
3675 if (isa<PackExpansionExpr>(Arg))
3676 CallArity = UnknownArity;
3678 mangleExpression(CE->getCallee(), CallArity);
3679 for (const Expr *Arg : CE->arguments())
3680 mangleExpression(Arg);
3685 case Expr::CXXNewExprClass: {
3686 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3687 if (New->isGlobalNew()) Out << "gs";
3688 Out << (New->isArray() ? "na" : "nw");
3689 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3690 E = New->placement_arg_end(); I != E; ++I)
3691 mangleExpression(*I);
3693 mangleType(New->getAllocatedType());
3694 if (New->hasInitializer()) {
3695 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3699 const Expr *Init = New->getInitializer();
3700 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3701 // Directly inline the initializers.
3702 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3705 mangleExpression(*I);
3706 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3707 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3708 mangleExpression(PLE->getExpr(i));
3709 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3710 isa<InitListExpr>(Init)) {
3711 // Only take InitListExprs apart for list-initialization.
3712 mangleInitListElements(cast<InitListExpr>(Init));
3714 mangleExpression(Init);
3720 case Expr::CXXPseudoDestructorExprClass: {
3721 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3722 if (const Expr *Base = PDE->getBase())
3723 mangleMemberExprBase(Base, PDE->isArrow());
3724 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3725 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3727 mangleUnresolvedPrefix(Qualifier,
3728 /*Recursive=*/true);
3729 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3733 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3736 } else if (Qualifier) {
3737 mangleUnresolvedPrefix(Qualifier);
3739 // <base-unresolved-name> ::= dn <destructor-name>
3741 QualType DestroyedType = PDE->getDestroyedType();
3742 mangleUnresolvedTypeOrSimpleId(DestroyedType);
3746 case Expr::MemberExprClass: {
3747 const MemberExpr *ME = cast<MemberExpr>(E);
3748 mangleMemberExpr(ME->getBase(), ME->isArrow(),
3749 ME->getQualifier(), nullptr,
3750 ME->getMemberDecl()->getDeclName(),
3751 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3756 case Expr::UnresolvedMemberExprClass: {
3757 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
3758 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3759 ME->isArrow(), ME->getQualifier(), nullptr,
3760 ME->getMemberName(),
3761 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3766 case Expr::CXXDependentScopeMemberExprClass: {
3767 const CXXDependentScopeMemberExpr *ME
3768 = cast<CXXDependentScopeMemberExpr>(E);
3769 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3770 ME->isArrow(), ME->getQualifier(),
3771 ME->getFirstQualifierFoundInScope(),
3773 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3778 case Expr::UnresolvedLookupExprClass: {
3779 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
3780 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3781 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3786 case Expr::CXXUnresolvedConstructExprClass: {
3787 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3788 unsigned N = CE->arg_size();
3790 if (CE->isListInitialization()) {
3791 assert(N == 1 && "unexpected form for list initialization");
3792 auto *IL = cast<InitListExpr>(CE->getArg(0));
3794 mangleType(CE->getType());
3795 mangleInitListElements(IL);
3801 mangleType(CE->getType());
3802 if (N != 1) Out << '_';
3803 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3804 if (N != 1) Out << 'E';
3808 case Expr::CXXConstructExprClass: {
3809 const auto *CE = cast<CXXConstructExpr>(E);
3810 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
3812 CE->getNumArgs() >= 1 &&
3813 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3814 "implicit CXXConstructExpr must have one argument");
3815 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3818 for (auto *E : CE->arguments())
3819 mangleExpression(E);
3824 case Expr::CXXTemporaryObjectExprClass: {
3825 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3826 unsigned N = CE->getNumArgs();
3827 bool List = CE->isListInitialization();
3833 mangleType(CE->getType());
3834 if (!List && N != 1)
3836 if (CE->isStdInitListInitialization()) {
3837 // We implicitly created a std::initializer_list<T> for the first argument
3838 // of a constructor of type U in an expression of the form U{a, b, c}.
3839 // Strip all the semantic gunk off the initializer list.
3841 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3842 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3843 mangleInitListElements(ILE);
3845 for (auto *E : CE->arguments())
3846 mangleExpression(E);
3853 case Expr::CXXScalarValueInitExprClass:
3855 mangleType(E->getType());
3859 case Expr::CXXNoexceptExprClass:
3861 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3864 case Expr::UnaryExprOrTypeTraitExprClass: {
3865 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3867 if (!SAE->isInstantiationDependent()) {
3869 // If the operand of a sizeof or alignof operator is not
3870 // instantiation-dependent it is encoded as an integer literal
3871 // reflecting the result of the operator.
3873 // If the result of the operator is implicitly converted to a known
3874 // integer type, that type is used for the literal; otherwise, the type
3875 // of std::size_t or std::ptrdiff_t is used.
3876 QualType T = (ImplicitlyConvertedToType.isNull() ||
3877 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3878 : ImplicitlyConvertedToType;
3879 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3880 mangleIntegerLiteral(T, V);
3884 switch(SAE->getKind()) {
3888 case UETT_PreferredAlignOf:
3892 case UETT_VecStep: {
3893 DiagnosticsEngine &Diags = Context.getDiags();
3894 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3895 "cannot yet mangle vec_step expression");
3896 Diags.Report(DiagID);
3899 case UETT_OpenMPRequiredSimdAlign:
3900 DiagnosticsEngine &Diags = Context.getDiags();
3901 unsigned DiagID = Diags.getCustomDiagID(
3902 DiagnosticsEngine::Error,
3903 "cannot yet mangle __builtin_omp_required_simd_align expression");
3904 Diags.Report(DiagID);
3907 if (SAE->isArgumentType()) {
3909 mangleType(SAE->getArgumentType());
3912 mangleExpression(SAE->getArgumentExpr());
3917 case Expr::CXXThrowExprClass: {
3918 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
3919 // <expression> ::= tw <expression> # throw expression
3921 if (TE->getSubExpr()) {
3923 mangleExpression(TE->getSubExpr());
3930 case Expr::CXXTypeidExprClass: {
3931 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
3932 // <expression> ::= ti <type> # typeid (type)
3933 // ::= te <expression> # typeid (expression)
3934 if (TIE->isTypeOperand()) {
3936 mangleType(TIE->getTypeOperand(Context.getASTContext()));
3939 mangleExpression(TIE->getExprOperand());
3944 case Expr::CXXDeleteExprClass: {
3945 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
3946 // <expression> ::= [gs] dl <expression> # [::] delete expr
3947 // ::= [gs] da <expression> # [::] delete [] expr
3948 if (DE->isGlobalDelete()) Out << "gs";
3949 Out << (DE->isArrayForm() ? "da" : "dl");
3950 mangleExpression(DE->getArgument());
3954 case Expr::UnaryOperatorClass: {
3955 const UnaryOperator *UO = cast<UnaryOperator>(E);
3956 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3958 mangleExpression(UO->getSubExpr());
3962 case Expr::ArraySubscriptExprClass: {
3963 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3965 // Array subscript is treated as a syntactically weird form of
3968 mangleExpression(AE->getLHS());
3969 mangleExpression(AE->getRHS());
3973 case Expr::CompoundAssignOperatorClass: // fallthrough
3974 case Expr::BinaryOperatorClass: {
3975 const BinaryOperator *BO = cast<BinaryOperator>(E);
3976 if (BO->getOpcode() == BO_PtrMemD)
3979 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3981 mangleExpression(BO->getLHS());
3982 mangleExpression(BO->getRHS());
3986 case Expr::ConditionalOperatorClass: {
3987 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3988 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3989 mangleExpression(CO->getCond());
3990 mangleExpression(CO->getLHS(), Arity);
3991 mangleExpression(CO->getRHS(), Arity);
3995 case Expr::ImplicitCastExprClass: {
3996 ImplicitlyConvertedToType = E->getType();
3997 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4001 case Expr::ObjCBridgedCastExprClass: {
4002 // Mangle ownership casts as a vendor extended operator __bridge,
4003 // __bridge_transfer, or __bridge_retain.
4004 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
4005 Out << "v1U" << Kind.size() << Kind;
4007 // Fall through to mangle the cast itself.
4010 case Expr::CStyleCastExprClass:
4011 mangleCastExpression(E, "cv");
4014 case Expr::CXXFunctionalCastExprClass: {
4015 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4016 // FIXME: Add isImplicit to CXXConstructExpr.
4017 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4018 if (CCE->getParenOrBraceRange().isInvalid())
4019 Sub = CCE->getArg(0)->IgnoreImplicit();
4020 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4021 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4022 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4024 mangleType(E->getType());
4025 mangleInitListElements(IL);
4028 mangleCastExpression(E, "cv");
4033 case Expr::CXXStaticCastExprClass:
4034 mangleCastExpression(E, "sc");
4036 case Expr::CXXDynamicCastExprClass:
4037 mangleCastExpression(E, "dc");
4039 case Expr::CXXReinterpretCastExprClass:
4040 mangleCastExpression(E, "rc");
4042 case Expr::CXXConstCastExprClass:
4043 mangleCastExpression(E, "cc");
4046 case Expr::CXXOperatorCallExprClass: {
4047 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4048 unsigned NumArgs = CE->getNumArgs();
4049 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4050 // (the enclosing MemberExpr covers the syntactic portion).
4051 if (CE->getOperator() != OO_Arrow)
4052 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
4053 // Mangle the arguments.
4054 for (unsigned i = 0; i != NumArgs; ++i)
4055 mangleExpression(CE->getArg(i));
4059 case Expr::ParenExprClass:
4060 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
4063 case Expr::DeclRefExprClass: {
4064 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4066 switch (D->getKind()) {
4068 // <expr-primary> ::= L <mangled-name> E # external name
4075 mangleFunctionParam(cast<ParmVarDecl>(D));
4078 case Decl::EnumConstant: {
4079 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4080 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4084 case Decl::NonTypeTemplateParm: {
4085 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4086 mangleTemplateParameter(PD->getIndex());
4095 case Expr::SubstNonTypeTemplateParmPackExprClass:
4096 // FIXME: not clear how to mangle this!
4097 // template <unsigned N...> class A {
4098 // template <class U...> void foo(U (&x)[N]...);
4100 Out << "_SUBSTPACK_";
4103 case Expr::FunctionParmPackExprClass: {
4104 // FIXME: not clear how to mangle this!
4105 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4106 Out << "v110_SUBSTPACK";
4107 mangleFunctionParam(FPPE->getParameterPack());
4111 case Expr::DependentScopeDeclRefExprClass: {
4112 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
4113 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4114 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4119 case Expr::CXXBindTemporaryExprClass:
4120 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
4123 case Expr::ExprWithCleanupsClass:
4124 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4127 case Expr::FloatingLiteralClass: {
4128 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4130 mangleType(FL->getType());
4131 mangleFloat(FL->getValue());
4136 case Expr::CharacterLiteralClass:
4138 mangleType(E->getType());
4139 Out << cast<CharacterLiteral>(E)->getValue();
4143 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4144 case Expr::ObjCBoolLiteralExprClass:
4146 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4150 case Expr::CXXBoolLiteralExprClass:
4152 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4156 case Expr::IntegerLiteralClass: {
4157 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4158 if (E->getType()->isSignedIntegerType())
4159 Value.setIsSigned(true);
4160 mangleIntegerLiteral(E->getType(), Value);
4164 case Expr::ImaginaryLiteralClass: {
4165 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4166 // Mangle as if a complex literal.
4167 // Proposal from David Vandevoorde, 2010.06.30.
4169 mangleType(E->getType());
4170 if (const FloatingLiteral *Imag =
4171 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4172 // Mangle a floating-point zero of the appropriate type.
4173 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4175 mangleFloat(Imag->getValue());
4178 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4179 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4180 Value.setIsSigned(true);
4181 mangleNumber(Value);
4187 case Expr::StringLiteralClass: {
4188 // Revised proposal from David Vandervoorde, 2010.07.15.
4190 assert(isa<ConstantArrayType>(E->getType()));
4191 mangleType(E->getType());
4196 case Expr::GNUNullExprClass:
4197 // FIXME: should this really be mangled the same as nullptr?
4200 case Expr::CXXNullPtrLiteralExprClass: {
4205 case Expr::PackExpansionExprClass:
4207 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4210 case Expr::SizeOfPackExprClass: {
4211 auto *SPE = cast<SizeOfPackExpr>(E);
4212 if (SPE->isPartiallySubstituted()) {
4214 for (const auto &A : SPE->getPartialArguments())
4215 mangleTemplateArg(A);
4221 const NamedDecl *Pack = SPE->getPack();
4222 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4223 mangleTemplateParameter(TTP->getIndex());
4224 else if (const NonTypeTemplateParmDecl *NTTP
4225 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4226 mangleTemplateParameter(NTTP->getIndex());
4227 else if (const TemplateTemplateParmDecl *TempTP
4228 = dyn_cast<TemplateTemplateParmDecl>(Pack))
4229 mangleTemplateParameter(TempTP->getIndex());
4231 mangleFunctionParam(cast<ParmVarDecl>(Pack));
4235 case Expr::MaterializeTemporaryExprClass: {
4236 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
4240 case Expr::CXXFoldExprClass: {
4241 auto *FE = cast<CXXFoldExpr>(E);
4242 if (FE->isLeftFold())
4243 Out << (FE->getInit() ? "fL" : "fl");
4245 Out << (FE->getInit() ? "fR" : "fr");
4247 if (FE->getOperator() == BO_PtrMemD)
4251 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4255 mangleExpression(FE->getLHS());
4257 mangleExpression(FE->getRHS());
4261 case Expr::CXXThisExprClass:
4265 case Expr::CoawaitExprClass:
4266 // FIXME: Propose a non-vendor mangling.
4267 Out << "v18co_await";
4268 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4271 case Expr::DependentCoawaitExprClass:
4272 // FIXME: Propose a non-vendor mangling.
4273 Out << "v18co_await";
4274 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4277 case Expr::CoyieldExprClass:
4278 // FIXME: Propose a non-vendor mangling.
4279 Out << "v18co_yield";
4280 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4285 /// Mangle an expression which refers to a parameter variable.
4287 /// <expression> ::= <function-param>
4288 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4289 /// <function-param> ::= fp <top-level CV-qualifiers>
4290 /// <parameter-2 non-negative number> _ # L == 0, I > 0
4291 /// <function-param> ::= fL <L-1 non-negative number>
4292 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
4293 /// <function-param> ::= fL <L-1 non-negative number>
4294 /// p <top-level CV-qualifiers>
4295 /// <I-1 non-negative number> _ # L > 0, I > 0
4297 /// L is the nesting depth of the parameter, defined as 1 if the
4298 /// parameter comes from the innermost function prototype scope
4299 /// enclosing the current context, 2 if from the next enclosing
4300 /// function prototype scope, and so on, with one special case: if
4301 /// we've processed the full parameter clause for the innermost
4302 /// function type, then L is one less. This definition conveniently
4303 /// makes it irrelevant whether a function's result type was written
4304 /// trailing or leading, but is otherwise overly complicated; the
4305 /// numbering was first designed without considering references to
4306 /// parameter in locations other than return types, and then the
4307 /// mangling had to be generalized without changing the existing
4310 /// I is the zero-based index of the parameter within its parameter
4311 /// declaration clause. Note that the original ABI document describes
4312 /// this using 1-based ordinals.
4313 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4314 unsigned parmDepth = parm->getFunctionScopeDepth();
4315 unsigned parmIndex = parm->getFunctionScopeIndex();
4318 // parmDepth does not include the declaring function prototype.
4319 // FunctionTypeDepth does account for that.
4320 assert(parmDepth < FunctionTypeDepth.getDepth());
4321 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4322 if (FunctionTypeDepth.isInResultType())
4325 if (nestingDepth == 0) {
4328 Out << "fL" << (nestingDepth - 1) << 'p';
4331 // Top-level qualifiers. We don't have to worry about arrays here,
4332 // because parameters declared as arrays should already have been
4333 // transformed to have pointer type. FIXME: apparently these don't
4334 // get mangled if used as an rvalue of a known non-class type?
4335 assert(!parm->getType()->isArrayType()
4336 && "parameter's type is still an array type?");
4338 if (const DependentAddressSpaceType *DAST =
4339 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
4340 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
4342 mangleQualifiers(parm->getType().getQualifiers());
4346 if (parmIndex != 0) {
4347 Out << (parmIndex - 1);
4352 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4353 const CXXRecordDecl *InheritedFrom) {
4354 // <ctor-dtor-name> ::= C1 # complete object constructor
4355 // ::= C2 # base object constructor
4356 // ::= CI1 <type> # complete inheriting constructor
4357 // ::= CI2 <type> # base inheriting constructor
4359 // In addition, C5 is a comdat name with C1 and C2 in it.
4373 case Ctor_DefaultClosure:
4374 case Ctor_CopyingClosure:
4375 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
4378 mangleName(InheritedFrom);
4381 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4382 // <ctor-dtor-name> ::= D0 # deleting destructor
4383 // ::= D1 # complete object destructor
4384 // ::= D2 # base object destructor
4386 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
4403 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4404 unsigned NumTemplateArgs) {
4405 // <template-args> ::= I <template-arg>+ E
4407 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4408 mangleTemplateArg(TemplateArgs[i].getArgument());
4412 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4413 // <template-args> ::= I <template-arg>+ E
4415 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4416 mangleTemplateArg(AL[i]);
4420 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4421 unsigned NumTemplateArgs) {
4422 // <template-args> ::= I <template-arg>+ E
4424 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4425 mangleTemplateArg(TemplateArgs[i]);
4429 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4430 // <template-arg> ::= <type> # type or template
4431 // ::= X <expression> E # expression
4432 // ::= <expr-primary> # simple expressions
4433 // ::= J <template-arg>* E # argument pack
4434 if (!A.isInstantiationDependent() || A.isDependent())
4435 A = Context.getASTContext().getCanonicalTemplateArgument(A);
4437 switch (A.getKind()) {
4438 case TemplateArgument::Null:
4439 llvm_unreachable("Cannot mangle NULL template argument");
4441 case TemplateArgument::Type:
4442 mangleType(A.getAsType());
4444 case TemplateArgument::Template:
4445 // This is mangled as <type>.
4446 mangleType(A.getAsTemplate());
4448 case TemplateArgument::TemplateExpansion:
4449 // <type> ::= Dp <type> # pack expansion (C++0x)
4451 mangleType(A.getAsTemplateOrTemplatePattern());
4453 case TemplateArgument::Expression: {
4454 // It's possible to end up with a DeclRefExpr here in certain
4455 // dependent cases, in which case we should mangle as a
4457 const Expr *E = A.getAsExpr()->IgnoreParens();
4458 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4459 const ValueDecl *D = DRE->getDecl();
4460 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
4469 mangleExpression(E);
4473 case TemplateArgument::Integral:
4474 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4476 case TemplateArgument::Declaration: {
4477 // <expr-primary> ::= L <mangled-name> E # external name
4478 // Clang produces AST's where pointer-to-member-function expressions
4479 // and pointer-to-function expressions are represented as a declaration not
4480 // an expression. We compensate for it here to produce the correct mangling.
4481 ValueDecl *D = A.getAsDecl();
4482 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
4483 if (compensateMangling) {
4485 mangleOperatorName(OO_Amp, 1);
4489 // References to external entities use the mangled name; if the name would
4490 // not normally be mangled then mangle it as unqualified.
4494 if (compensateMangling)
4499 case TemplateArgument::NullPtr: {
4500 // <expr-primary> ::= L <type> 0 E
4502 mangleType(A.getNullPtrType());
4506 case TemplateArgument::Pack: {
4507 // <template-arg> ::= J <template-arg>* E
4509 for (const auto &P : A.pack_elements())
4510 mangleTemplateArg(P);
4516 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4517 // <template-param> ::= T_ # first template parameter
4518 // ::= T <parameter-2 non-negative number> _
4522 Out << 'T' << (Index - 1) << '_';
4525 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4528 else if (SeqID > 1) {
4531 // <seq-id> is encoded in base-36, using digits and upper case letters.
4532 char Buffer[7]; // log(2**32) / log(36) ~= 7
4533 MutableArrayRef<char> BufferRef(Buffer);
4534 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
4536 for (; SeqID != 0; SeqID /= 36) {
4537 unsigned C = SeqID % 36;
4538 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4541 Out.write(I.base(), I - BufferRef.rbegin());
4546 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4547 bool result = mangleSubstitution(tname);
4548 assert(result && "no existing substitution for template name");
4552 // <substitution> ::= S <seq-id> _
4554 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4555 // Try one of the standard substitutions first.
4556 if (mangleStandardSubstitution(ND))
4559 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4560 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4563 /// Determine whether the given type has any qualifiers that are relevant for
4565 static bool hasMangledSubstitutionQualifiers(QualType T) {
4566 Qualifiers Qs = T.getQualifiers();
4567 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
4570 bool CXXNameMangler::mangleSubstitution(QualType T) {
4571 if (!hasMangledSubstitutionQualifiers(T)) {
4572 if (const RecordType *RT = T->getAs<RecordType>())
4573 return mangleSubstitution(RT->getDecl());
4576 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4578 return mangleSubstitution(TypePtr);
4581 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4582 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4583 return mangleSubstitution(TD);
4585 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4586 return mangleSubstitution(
4587 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4590 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4591 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4592 if (I == Substitutions.end())
4595 unsigned SeqID = I->second;
4602 static bool isCharType(QualType T) {
4606 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4607 T->isSpecificBuiltinType(BuiltinType::Char_U);
4610 /// Returns whether a given type is a template specialization of a given name
4611 /// with a single argument of type char.
4612 static bool isCharSpecialization(QualType T, const char *Name) {
4616 const RecordType *RT = T->getAs<RecordType>();
4620 const ClassTemplateSpecializationDecl *SD =
4621 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4625 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4628 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4629 if (TemplateArgs.size() != 1)
4632 if (!isCharType(TemplateArgs[0].getAsType()))
4635 return SD->getIdentifier()->getName() == Name;
4638 template <std::size_t StrLen>
4639 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4640 const char (&Str)[StrLen]) {
4641 if (!SD->getIdentifier()->isStr(Str))
4644 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4645 if (TemplateArgs.size() != 2)
4648 if (!isCharType(TemplateArgs[0].getAsType()))
4651 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4657 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4658 // <substitution> ::= St # ::std::
4659 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4666 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4667 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4670 // <substitution> ::= Sa # ::std::allocator
4671 if (TD->getIdentifier()->isStr("allocator")) {
4676 // <<substitution> ::= Sb # ::std::basic_string
4677 if (TD->getIdentifier()->isStr("basic_string")) {
4683 if (const ClassTemplateSpecializationDecl *SD =
4684 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4685 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4688 // <substitution> ::= Ss # ::std::basic_string<char,
4689 // ::std::char_traits<char>,
4690 // ::std::allocator<char> >
4691 if (SD->getIdentifier()->isStr("basic_string")) {
4692 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4694 if (TemplateArgs.size() != 3)
4697 if (!isCharType(TemplateArgs[0].getAsType()))
4700 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4703 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4710 // <substitution> ::= Si # ::std::basic_istream<char,
4711 // ::std::char_traits<char> >
4712 if (isStreamCharSpecialization(SD, "basic_istream")) {
4717 // <substitution> ::= So # ::std::basic_ostream<char,
4718 // ::std::char_traits<char> >
4719 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4724 // <substitution> ::= Sd # ::std::basic_iostream<char,
4725 // ::std::char_traits<char> >
4726 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4734 void CXXNameMangler::addSubstitution(QualType T) {
4735 if (!hasMangledSubstitutionQualifiers(T)) {
4736 if (const RecordType *RT = T->getAs<RecordType>()) {
4737 addSubstitution(RT->getDecl());
4742 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4743 addSubstitution(TypePtr);
4746 void CXXNameMangler::addSubstitution(TemplateName Template) {
4747 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4748 return addSubstitution(TD);
4750 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4751 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4754 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4755 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4756 Substitutions[Ptr] = SeqID++;
4759 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4760 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4761 if (Other->SeqID > SeqID) {
4762 Substitutions.swap(Other->Substitutions);
4763 SeqID = Other->SeqID;
4767 CXXNameMangler::AbiTagList
4768 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4769 // When derived abi tags are disabled there is no need to make any list.
4770 if (DisableDerivedAbiTags)
4771 return AbiTagList();
4773 llvm::raw_null_ostream NullOutStream;
4774 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4775 TrackReturnTypeTags.disableDerivedAbiTags();
4777 const FunctionProtoType *Proto =
4778 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
4779 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
4780 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4781 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4782 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
4783 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
4785 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4788 CXXNameMangler::AbiTagList
4789 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4790 // When derived abi tags are disabled there is no need to make any list.
4791 if (DisableDerivedAbiTags)
4792 return AbiTagList();
4794 llvm::raw_null_ostream NullOutStream;
4795 CXXNameMangler TrackVariableType(*this, NullOutStream);
4796 TrackVariableType.disableDerivedAbiTags();
4798 TrackVariableType.mangleType(VD->getType());
4800 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4803 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4804 const VarDecl *VD) {
4805 llvm::raw_null_ostream NullOutStream;
4806 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4807 TrackAbiTags.mangle(VD);
4808 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4813 /// Mangles the name of the declaration D and emits that name to the given
4816 /// If the declaration D requires a mangled name, this routine will emit that
4817 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4818 /// and this routine will return false. In this case, the caller should just
4819 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
4821 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4823 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4824 "Invalid mangleName() call, argument is not a variable or function!");
4825 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4826 "Invalid mangleName() call on 'structor decl!");
4828 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4829 getASTContext().getSourceManager(),
4830 "Mangling declaration");
4832 CXXNameMangler Mangler(*this, Out, D);
4836 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4839 CXXNameMangler Mangler(*this, Out, D, Type);
4843 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4846 CXXNameMangler Mangler(*this, Out, D, Type);
4850 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4852 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4856 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4858 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4862 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4863 const ThunkInfo &Thunk,
4865 // <special-name> ::= T <call-offset> <base encoding>
4866 // # base is the nominal target function of thunk
4867 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4868 // # base is the nominal target function of thunk
4869 // # first call-offset is 'this' adjustment
4870 // # second call-offset is result adjustment
4872 assert(!isa<CXXDestructorDecl>(MD) &&
4873 "Use mangleCXXDtor for destructor decls!");
4874 CXXNameMangler Mangler(*this, Out);
4875 Mangler.getStream() << "_ZT";
4876 if (!Thunk.Return.isEmpty())
4877 Mangler.getStream() << 'c';
4879 // Mangle the 'this' pointer adjustment.
4880 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4881 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4883 // Mangle the return pointer adjustment if there is one.
4884 if (!Thunk.Return.isEmpty())
4885 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
4886 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4888 Mangler.mangleFunctionEncoding(MD);
4891 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4892 const CXXDestructorDecl *DD, CXXDtorType Type,
4893 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
4894 // <special-name> ::= T <call-offset> <base encoding>
4895 // # base is the nominal target function of thunk
4896 CXXNameMangler Mangler(*this, Out, DD, Type);
4897 Mangler.getStream() << "_ZT";
4899 // Mangle the 'this' pointer adjustment.
4900 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
4901 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
4903 Mangler.mangleFunctionEncoding(DD);
4906 /// Returns the mangled name for a guard variable for the passed in VarDecl.
4907 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4909 // <special-name> ::= GV <object name> # Guard variable for one-time
4911 CXXNameMangler Mangler(*this, Out);
4912 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4913 // be a bug that is fixed in trunk.
4914 Mangler.getStream() << "_ZGV";
4915 Mangler.mangleName(D);
4918 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4920 // These symbols are internal in the Itanium ABI, so the names don't matter.
4921 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4922 // avoid duplicate symbols.
4923 Out << "__cxx_global_var_init";
4926 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4928 // Prefix the mangling of D with __dtor_.
4929 CXXNameMangler Mangler(*this, Out);
4930 Mangler.getStream() << "__dtor_";
4931 if (shouldMangleDeclName(D))
4934 Mangler.getStream() << D->getName();
4937 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4938 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4939 CXXNameMangler Mangler(*this, Out);
4940 Mangler.getStream() << "__filt_";
4941 if (shouldMangleDeclName(EnclosingDecl))
4942 Mangler.mangle(EnclosingDecl);
4944 Mangler.getStream() << EnclosingDecl->getName();
4947 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4948 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4949 CXXNameMangler Mangler(*this, Out);
4950 Mangler.getStream() << "__fin_";
4951 if (shouldMangleDeclName(EnclosingDecl))
4952 Mangler.mangle(EnclosingDecl);
4954 Mangler.getStream() << EnclosingDecl->getName();
4957 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4959 // <special-name> ::= TH <object name>
4960 CXXNameMangler Mangler(*this, Out);
4961 Mangler.getStream() << "_ZTH";
4962 Mangler.mangleName(D);
4966 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4968 // <special-name> ::= TW <object name>
4969 CXXNameMangler Mangler(*this, Out);
4970 Mangler.getStream() << "_ZTW";
4971 Mangler.mangleName(D);
4974 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
4975 unsigned ManglingNumber,
4977 // We match the GCC mangling here.
4978 // <special-name> ::= GR <object name>
4979 CXXNameMangler Mangler(*this, Out);
4980 Mangler.getStream() << "_ZGR";
4981 Mangler.mangleName(D);
4982 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
4983 Mangler.mangleSeqID(ManglingNumber - 1);
4986 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4988 // <special-name> ::= TV <type> # virtual table
4989 CXXNameMangler Mangler(*this, Out);
4990 Mangler.getStream() << "_ZTV";
4991 Mangler.mangleNameOrStandardSubstitution(RD);
4994 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4996 // <special-name> ::= TT <type> # VTT structure
4997 CXXNameMangler Mangler(*this, Out);
4998 Mangler.getStream() << "_ZTT";
4999 Mangler.mangleNameOrStandardSubstitution(RD);
5002 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
5004 const CXXRecordDecl *Type,
5006 // <special-name> ::= TC <type> <offset number> _ <base type>
5007 CXXNameMangler Mangler(*this, Out);
5008 Mangler.getStream() << "_ZTC";
5009 Mangler.mangleNameOrStandardSubstitution(RD);
5010 Mangler.getStream() << Offset;
5011 Mangler.getStream() << '_';
5012 Mangler.mangleNameOrStandardSubstitution(Type);
5015 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
5016 // <special-name> ::= TI <type> # typeinfo structure
5017 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
5018 CXXNameMangler Mangler(*this, Out);
5019 Mangler.getStream() << "_ZTI";
5020 Mangler.mangleType(Ty);
5023 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
5025 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
5026 CXXNameMangler Mangler(*this, Out);
5027 Mangler.getStream() << "_ZTS";
5028 Mangler.mangleType(Ty);
5031 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
5032 mangleCXXRTTIName(Ty, Out);
5035 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
5036 llvm_unreachable("Can't mangle string literals");
5039 ItaniumMangleContext *
5040 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
5041 return new ItaniumMangleContextImpl(Context, Diags);