1 //===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
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 // This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/Mangle.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/VTableBuilder.h"
26 #include "clang/Basic/ABI.h"
27 #include "clang/Basic/DiagnosticOptions.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/JamCRC.h"
33 using namespace clang;
37 /// \brief Retrieve the declaration context that should be used when mangling
38 /// the given declaration.
39 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
40 // The ABI assumes that lambda closure types that occur within
41 // default arguments live in the context of the function. However, due to
42 // the way in which Clang parses and creates function declarations, this is
43 // not the case: the lambda closure type ends up living in the context
44 // where the function itself resides, because the function declaration itself
45 // had not yet been created. Fix the context here.
46 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
48 if (ParmVarDecl *ContextParam =
49 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
50 return ContextParam->getDeclContext();
53 // Perform the same check for block literals.
54 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
55 if (ParmVarDecl *ContextParam =
56 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
57 return ContextParam->getDeclContext();
60 const DeclContext *DC = D->getDeclContext();
61 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
62 return getEffectiveDeclContext(CD);
67 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
68 return getEffectiveDeclContext(cast<Decl>(DC));
71 static const FunctionDecl *getStructor(const NamedDecl *ND) {
72 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
73 return FTD->getTemplatedDecl();
75 const auto *FD = cast<FunctionDecl>(ND);
76 if (const auto *FTD = FD->getPrimaryTemplate())
77 return FTD->getTemplatedDecl();
82 static bool isLambda(const NamedDecl *ND) {
83 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
87 return Record->isLambda();
90 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
91 /// Microsoft Visual C++ ABI.
92 class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
93 typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
94 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
95 llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
96 llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
97 llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds;
98 llvm::DenseMap<const NamedDecl *, unsigned> SEHFinallyIds;
101 MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags)
102 : MicrosoftMangleContext(Context, Diags) {}
103 bool shouldMangleCXXName(const NamedDecl *D) override;
104 bool shouldMangleStringLiteral(const StringLiteral *SL) override;
105 void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
106 void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
107 raw_ostream &) override;
108 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
109 raw_ostream &) override;
110 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
111 const ThisAdjustment &ThisAdjustment,
112 raw_ostream &) override;
113 void mangleCXXVFTable(const CXXRecordDecl *Derived,
114 ArrayRef<const CXXRecordDecl *> BasePath,
115 raw_ostream &Out) override;
116 void mangleCXXVBTable(const CXXRecordDecl *Derived,
117 ArrayRef<const CXXRecordDecl *> BasePath,
118 raw_ostream &Out) override;
119 void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
120 const CXXRecordDecl *DstRD,
121 raw_ostream &Out) override;
122 void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
123 uint32_t NumEntries, raw_ostream &Out) override;
124 void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
125 raw_ostream &Out) override;
126 void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
127 CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
128 int32_t VBPtrOffset, uint32_t VBIndex,
129 raw_ostream &Out) override;
130 void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
131 void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
132 void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
133 uint32_t NVOffset, int32_t VBPtrOffset,
134 uint32_t VBTableOffset, uint32_t Flags,
135 raw_ostream &Out) override;
136 void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
137 raw_ostream &Out) override;
138 void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
139 raw_ostream &Out) override;
141 mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
142 ArrayRef<const CXXRecordDecl *> BasePath,
143 raw_ostream &Out) override;
144 void mangleTypeName(QualType T, raw_ostream &) override;
145 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
146 raw_ostream &) override;
147 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
148 raw_ostream &) override;
149 void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
150 raw_ostream &) override;
151 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
152 void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
153 raw_ostream &Out) override;
154 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
155 void mangleDynamicAtExitDestructor(const VarDecl *D,
156 raw_ostream &Out) override;
157 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
158 raw_ostream &Out) override;
159 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
160 raw_ostream &Out) override;
161 void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
162 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
163 // Lambda closure types are already numbered.
167 const DeclContext *DC = getEffectiveDeclContext(ND);
168 if (!DC->isFunctionOrMethod())
171 // Use the canonical number for externally visible decls.
172 if (ND->isExternallyVisible()) {
173 disc = getASTContext().getManglingNumber(ND);
177 // Anonymous tags are already numbered.
178 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
179 if (!Tag->hasNameForLinkage() &&
180 !getASTContext().getDeclaratorForUnnamedTagDecl(Tag) &&
181 !getASTContext().getTypedefNameForUnnamedTagDecl(Tag))
185 // Make up a reasonable number for internal decls.
186 unsigned &discriminator = Uniquifier[ND];
188 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
189 disc = discriminator + 1;
193 unsigned getLambdaId(const CXXRecordDecl *RD) {
194 assert(RD->isLambda() && "RD must be a lambda!");
195 assert(!RD->isExternallyVisible() && "RD must not be visible!");
196 assert(RD->getLambdaManglingNumber() == 0 &&
197 "RD must not have a mangling number!");
198 std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
199 Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
200 return Result.first->second;
204 void mangleInitFiniStub(const VarDecl *D, raw_ostream &Out, char CharCode);
207 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
208 /// Microsoft Visual C++ ABI.
209 class MicrosoftCXXNameMangler {
210 MicrosoftMangleContextImpl &Context;
213 /// The "structor" is the top-level declaration being mangled, if
214 /// that's not a template specialization; otherwise it's the pattern
215 /// for that specialization.
216 const NamedDecl *Structor;
217 unsigned StructorType;
219 typedef llvm::SmallVector<std::string, 10> BackRefVec;
220 BackRefVec NameBackReferences;
222 typedef llvm::DenseMap<const void *, unsigned> ArgBackRefMap;
223 ArgBackRefMap TypeBackReferences;
225 typedef std::set<int> PassObjectSizeArgsSet;
226 PassObjectSizeArgsSet PassObjectSizeArgs;
228 ASTContext &getASTContext() const { return Context.getASTContext(); }
230 // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
231 // this check into mangleQualifiers().
232 const bool PointersAre64Bit;
235 enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
237 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
238 : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
239 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
242 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
243 const CXXConstructorDecl *D, CXXCtorType Type)
244 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
245 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
248 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
249 const CXXDestructorDecl *D, CXXDtorType Type)
250 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
251 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
254 raw_ostream &getStream() const { return Out; }
256 void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
257 void mangleName(const NamedDecl *ND);
258 void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
259 void mangleVariableEncoding(const VarDecl *VD);
260 void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
261 void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
262 const CXXMethodDecl *MD);
263 void mangleVirtualMemPtrThunk(
264 const CXXMethodDecl *MD,
265 const MicrosoftVTableContext::MethodVFTableLocation &ML);
266 void mangleNumber(int64_t Number);
267 void mangleTagTypeKind(TagTypeKind TK);
268 void mangleArtificalTagType(TagTypeKind TK, StringRef UnqualifiedName,
269 ArrayRef<StringRef> NestedNames = None);
270 void mangleType(QualType T, SourceRange Range,
271 QualifierMangleMode QMM = QMM_Mangle);
272 void mangleFunctionType(const FunctionType *T,
273 const FunctionDecl *D = nullptr,
274 bool ForceThisQuals = false);
275 void mangleNestedName(const NamedDecl *ND);
278 void mangleUnqualifiedName(const NamedDecl *ND) {
279 mangleUnqualifiedName(ND, ND->getDeclName());
281 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
282 void mangleSourceName(StringRef Name);
283 void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
284 void mangleCXXDtorType(CXXDtorType T);
285 void mangleQualifiers(Qualifiers Quals, bool IsMember);
286 void mangleRefQualifier(RefQualifierKind RefQualifier);
287 void manglePointerCVQualifiers(Qualifiers Quals);
288 void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
290 void mangleUnscopedTemplateName(const TemplateDecl *ND);
292 mangleTemplateInstantiationName(const TemplateDecl *TD,
293 const TemplateArgumentList &TemplateArgs);
294 void mangleObjCMethodName(const ObjCMethodDecl *MD);
296 void mangleArgumentType(QualType T, SourceRange Range);
297 void manglePassObjectSizeArg(const PassObjectSizeAttr *POSA);
299 // Declare manglers for every type class.
300 #define ABSTRACT_TYPE(CLASS, PARENT)
301 #define NON_CANONICAL_TYPE(CLASS, PARENT)
302 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
305 #include "clang/AST/TypeNodes.def"
307 #undef NON_CANONICAL_TYPE
310 void mangleType(const TagDecl *TD);
311 void mangleDecayedArrayType(const ArrayType *T);
312 void mangleArrayType(const ArrayType *T);
313 void mangleFunctionClass(const FunctionDecl *FD);
314 void mangleCallingConvention(CallingConv CC);
315 void mangleCallingConvention(const FunctionType *T);
316 void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
317 void mangleExpression(const Expr *E);
318 void mangleThrowSpecification(const FunctionProtoType *T);
320 void mangleTemplateArgs(const TemplateDecl *TD,
321 const TemplateArgumentList &TemplateArgs);
322 void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
323 const NamedDecl *Parm);
327 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
328 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
329 LanguageLinkage L = FD->getLanguageLinkage();
330 // Overloadable functions need mangling.
331 if (FD->hasAttr<OverloadableAttr>())
334 // The ABI expects that we would never mangle "typical" user-defined entry
335 // points regardless of visibility or freestanding-ness.
337 // N.B. This is distinct from asking about "main". "main" has a lot of
338 // special rules associated with it in the standard while these
339 // user-defined entry points are outside of the purview of the standard.
340 // For example, there can be only one definition for "main" in a standards
341 // compliant program; however nothing forbids the existence of wmain and
342 // WinMain in the same translation unit.
343 if (FD->isMSVCRTEntryPoint())
346 // C++ functions and those whose names are not a simple identifier need
348 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
351 // C functions are not mangled.
352 if (L == CLanguageLinkage)
356 // Otherwise, no mangling is done outside C++ mode.
357 if (!getASTContext().getLangOpts().CPlusPlus)
360 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
361 // C variables are not mangled.
365 // Variables at global scope with non-internal linkage are not mangled.
366 const DeclContext *DC = getEffectiveDeclContext(D);
367 // Check for extern variable declared locally.
368 if (DC->isFunctionOrMethod() && D->hasLinkage())
369 while (!DC->isNamespace() && !DC->isTranslationUnit())
370 DC = getEffectiveParentContext(DC);
372 if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
373 !isa<VarTemplateSpecializationDecl>(D) &&
374 D->getIdentifier() != nullptr)
382 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
386 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
387 // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
388 // Therefore it's really important that we don't decorate the
389 // name with leading underscores or leading/trailing at signs. So, by
390 // default, we emit an asm marker at the start so we get the name right.
391 // Callers can override this with a custom prefix.
393 // <mangled-name> ::= ? <name> <type-encoding>
396 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
397 mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
398 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
399 mangleVariableEncoding(VD);
401 llvm_unreachable("Tried to mangle unexpected NamedDecl!");
404 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD,
406 // <type-encoding> ::= <function-class> <function-type>
408 // Since MSVC operates on the type as written and not the canonical type, it
409 // actually matters which decl we have here. MSVC appears to choose the
410 // first, since it is most likely to be the declaration in a header file.
411 FD = FD->getFirstDecl();
413 // We should never ever see a FunctionNoProtoType at this point.
414 // We don't even know how to mangle their types anyway :).
415 const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
417 // extern "C" functions can hold entities that must be mangled.
418 // As it stands, these functions still need to get expressed in the full
419 // external name. They have their class and type omitted, replaced with '9'.
421 // We would like to mangle all extern "C" functions using this additional
422 // component but this would break compatibility with MSVC's behavior.
423 // Instead, do this when we know that compatibility isn't important (in
424 // other words, when it is an overloaded extern "C" function).
425 if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
428 mangleFunctionClass(FD);
430 mangleFunctionType(FT, FD);
436 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
437 // <type-encoding> ::= <storage-class> <variable-type>
438 // <storage-class> ::= 0 # private static member
439 // ::= 1 # protected static member
440 // ::= 2 # public static member
442 // ::= 4 # static local
444 // The first character in the encoding (after the name) is the storage class.
445 if (VD->isStaticDataMember()) {
446 // If it's a static member, it also encodes the access level.
447 switch (VD->getAccess()) {
449 case AS_private: Out << '0'; break;
450 case AS_protected: Out << '1'; break;
451 case AS_public: Out << '2'; break;
454 else if (!VD->isStaticLocal())
458 // Now mangle the type.
459 // <variable-type> ::= <type> <cvr-qualifiers>
460 // ::= <type> <pointee-cvr-qualifiers> # pointers, references
461 // Pointers and references are odd. The type of 'int * const foo;' gets
462 // mangled as 'QAHA' instead of 'PAHB', for example.
463 SourceRange SR = VD->getSourceRange();
464 QualType Ty = VD->getType();
465 if (Ty->isPointerType() || Ty->isReferenceType() ||
466 Ty->isMemberPointerType()) {
467 mangleType(Ty, SR, QMM_Drop);
468 manglePointerExtQualifiers(
469 Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
470 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
471 mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
472 // Member pointers are suffixed with a back reference to the member
473 // pointer's class name.
474 mangleName(MPT->getClass()->getAsCXXRecordDecl());
476 mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
477 } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
478 // Global arrays are funny, too.
479 mangleDecayedArrayType(AT);
480 if (AT->getElementType()->isArrayType())
483 mangleQualifiers(Ty.getQualifiers(), false);
485 mangleType(Ty, SR, QMM_Drop);
486 mangleQualifiers(Ty.getQualifiers(), false);
490 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
491 const ValueDecl *VD) {
492 // <member-data-pointer> ::= <integer-literal>
493 // ::= $F <number> <number>
494 // ::= $G <number> <number> <number>
497 int64_t VBTableOffset;
498 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
500 FieldOffset = getASTContext().getFieldOffset(VD);
501 assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
502 "cannot take address of bitfield");
503 FieldOffset /= getASTContext().getCharWidth();
507 if (IM == MSInheritanceAttr::Keyword_virtual_inheritance)
508 FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
510 FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
517 case MSInheritanceAttr::Keyword_single_inheritance: Code = '0'; break;
518 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = '0'; break;
519 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'F'; break;
520 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
525 mangleNumber(FieldOffset);
527 // The C++ standard doesn't allow base-to-derived member pointer conversions
528 // in template parameter contexts, so the vbptr offset of data member pointers
530 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
532 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
533 mangleNumber(VBTableOffset);
537 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
538 const CXXMethodDecl *MD) {
539 // <member-function-pointer> ::= $1? <name>
540 // ::= $H? <name> <number>
541 // ::= $I? <name> <number> <number>
542 // ::= $J? <name> <number> <number> <number>
544 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
548 case MSInheritanceAttr::Keyword_single_inheritance: Code = '1'; break;
549 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = 'H'; break;
550 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'I'; break;
551 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
554 // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr
556 uint64_t NVOffset = 0;
557 uint64_t VBTableOffset = 0;
558 uint64_t VBPtrOffset = 0;
560 Out << '$' << Code << '?';
561 if (MD->isVirtual()) {
562 MicrosoftVTableContext *VTContext =
563 cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
564 const MicrosoftVTableContext::MethodVFTableLocation &ML =
565 VTContext->getMethodVFTableLocation(GlobalDecl(MD));
566 mangleVirtualMemPtrThunk(MD, ML);
567 NVOffset = ML.VFPtrOffset.getQuantity();
568 VBTableOffset = ML.VBTableIndex * 4;
570 const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
571 VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
575 mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
578 if (VBTableOffset == 0 &&
579 IM == MSInheritanceAttr::Keyword_virtual_inheritance)
580 NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
582 // Null single inheritance member functions are encoded as a simple nullptr.
583 if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
587 if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
592 if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
593 mangleNumber(static_cast<uint32_t>(NVOffset));
594 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
595 mangleNumber(VBPtrOffset);
596 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
597 mangleNumber(VBTableOffset);
600 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
601 const CXXMethodDecl *MD,
602 const MicrosoftVTableContext::MethodVFTableLocation &ML) {
603 // Get the vftable offset.
604 CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
605 getASTContext().getTargetInfo().getPointerWidth(0));
606 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
609 mangleName(MD->getParent());
611 mangleNumber(OffsetInVFTable);
613 mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>());
616 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
617 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
619 // Always start with the unqualified name.
620 mangleUnqualifiedName(ND);
622 mangleNestedName(ND);
624 // Terminate the whole name with an '@'.
628 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
629 // <non-negative integer> ::= A@ # when Number == 0
630 // ::= <decimal digit> # when 1 <= Number <= 10
631 // ::= <hex digit>+ @ # when Number >= 10
633 // <number> ::= [?] <non-negative integer>
635 uint64_t Value = static_cast<uint64_t>(Number);
643 else if (Value >= 1 && Value <= 10)
646 // Numbers that are not encoded as decimal digits are represented as nibbles
647 // in the range of ASCII characters 'A' to 'P'.
648 // The number 0x123450 would be encoded as 'BCDEFA'
649 char EncodedNumberBuffer[sizeof(uint64_t) * 2];
650 MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
651 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
652 for (; Value != 0; Value >>= 4)
653 *I++ = 'A' + (Value & 0xf);
654 Out.write(I.base(), I - BufferRef.rbegin());
659 static const TemplateDecl *
660 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
661 // Check if we have a function template.
662 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
663 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
664 TemplateArgs = FD->getTemplateSpecializationArgs();
669 // Check if we have a class template.
670 if (const ClassTemplateSpecializationDecl *Spec =
671 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
672 TemplateArgs = &Spec->getTemplateArgs();
673 return Spec->getSpecializedTemplate();
676 // Check if we have a variable template.
677 if (const VarTemplateSpecializationDecl *Spec =
678 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
679 TemplateArgs = &Spec->getTemplateArgs();
680 return Spec->getSpecializedTemplate();
686 void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
687 DeclarationName Name) {
688 // <unqualified-name> ::= <operator-name>
689 // ::= <ctor-dtor-name>
691 // ::= <template-name>
693 // Check if we have a template.
694 const TemplateArgumentList *TemplateArgs = nullptr;
695 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
696 // Function templates aren't considered for name back referencing. This
697 // makes sense since function templates aren't likely to occur multiple
698 // times in a symbol.
699 if (isa<FunctionTemplateDecl>(TD)) {
700 mangleTemplateInstantiationName(TD, *TemplateArgs);
705 // Here comes the tricky thing: if we need to mangle something like
706 // void foo(A::X<Y>, B::X<Y>),
707 // the X<Y> part is aliased. However, if you need to mangle
708 // void foo(A::X<A::Y>, A::X<B::Y>),
709 // the A::X<> part is not aliased.
710 // That said, from the mangler's perspective we have a structure like this:
711 // namespace[s] -> type[ -> template-parameters]
712 // but from the Clang perspective we have
713 // type [ -> template-parameters]
715 // What we do is we create a new mangler, mangle the same type (without
716 // a namespace suffix) to a string using the extra mangler and then use
717 // the mangled type name as a key to check the mangling of different types
720 llvm::SmallString<64> TemplateMangling;
721 llvm::raw_svector_ostream Stream(TemplateMangling);
722 MicrosoftCXXNameMangler Extra(Context, Stream);
723 Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
725 mangleSourceName(TemplateMangling);
729 switch (Name.getNameKind()) {
730 case DeclarationName::Identifier: {
731 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
732 mangleSourceName(II->getName());
736 // Otherwise, an anonymous entity. We must have a declaration.
737 assert(ND && "mangling empty name without declaration");
739 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
740 if (NS->isAnonymousNamespace()) {
746 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
747 // We must have an anonymous union or struct declaration.
748 const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
749 assert(RD && "expected variable decl to have a record type");
750 // Anonymous types with no tag or typedef get the name of their
751 // declarator mangled in. If they have no declarator, number them with
753 llvm::SmallString<64> Name("$S");
754 // Get a unique id for the anonymous struct.
755 Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
756 mangleSourceName(Name.str());
760 // We must have an anonymous struct.
761 const TagDecl *TD = cast<TagDecl>(ND);
762 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
763 assert(TD->getDeclContext() == D->getDeclContext() &&
764 "Typedef should not be in another decl context!");
765 assert(D->getDeclName().getAsIdentifierInfo() &&
766 "Typedef was not named!");
767 mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
771 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
772 if (Record->isLambda()) {
773 llvm::SmallString<10> Name("<lambda_");
775 if (Record->getLambdaManglingNumber())
776 LambdaId = Record->getLambdaManglingNumber();
778 LambdaId = Context.getLambdaId(Record);
780 Name += llvm::utostr(LambdaId);
783 mangleSourceName(Name);
788 llvm::SmallString<64> Name("<unnamed-type-");
789 if (DeclaratorDecl *DD =
790 Context.getASTContext().getDeclaratorForUnnamedTagDecl(TD)) {
791 // Anonymous types without a name for linkage purposes have their
792 // declarator mangled in if they have one.
793 Name += DD->getName();
794 } else if (TypedefNameDecl *TND =
795 Context.getASTContext().getTypedefNameForUnnamedTagDecl(
797 // Anonymous types without a name for linkage purposes have their
798 // associate typedef mangled in if they have one.
799 Name += TND->getName();
801 // Otherwise, number the types using a $S prefix.
803 Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1);
806 mangleSourceName(Name.str());
810 case DeclarationName::ObjCZeroArgSelector:
811 case DeclarationName::ObjCOneArgSelector:
812 case DeclarationName::ObjCMultiArgSelector:
813 llvm_unreachable("Can't mangle Objective-C selector names here!");
815 case DeclarationName::CXXConstructorName:
816 if (Structor == getStructor(ND)) {
817 if (StructorType == Ctor_CopyingClosure) {
821 if (StructorType == Ctor_DefaultClosure) {
829 case DeclarationName::CXXDestructorName:
831 // If the named decl is the C++ destructor we're mangling,
832 // use the type we were given.
833 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
835 // Otherwise, use the base destructor name. This is relevant if a
836 // class with a destructor is declared within a destructor.
837 mangleCXXDtorType(Dtor_Base);
840 case DeclarationName::CXXConversionFunctionName:
841 // <operator-name> ::= ?B # (cast)
842 // The target type is encoded as the return type.
846 case DeclarationName::CXXOperatorName:
847 mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
850 case DeclarationName::CXXLiteralOperatorName: {
852 mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
856 case DeclarationName::CXXUsingDirective:
857 llvm_unreachable("Can't mangle a using directive name!");
861 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
862 // <postfix> ::= <unqualified-name> [<postfix>]
863 // ::= <substitution> [<postfix>]
864 const DeclContext *DC = getEffectiveDeclContext(ND);
866 while (!DC->isTranslationUnit()) {
867 if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
869 if (Context.getNextDiscriminator(ND, Disc)) {
876 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
877 DiagnosticsEngine &Diags = Context.getDiags();
879 Diags.getCustomDiagID(DiagnosticsEngine::Error,
880 "cannot mangle a local inside this block yet");
881 Diags.Report(BD->getLocation(), DiagID);
883 // FIXME: This is completely, utterly, wrong; see ItaniumMangle
884 // for how this should be done.
885 Out << "__block_invoke" << Context.getBlockId(BD, false);
888 } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
889 mangleObjCMethodName(Method);
890 } else if (isa<NamedDecl>(DC)) {
891 ND = cast<NamedDecl>(DC);
892 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
896 mangleUnqualifiedName(ND);
898 DC = DC->getParent();
902 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
903 // Microsoft uses the names on the case labels for these dtor variants. Clang
904 // uses the Itanium terminology internally. Everything in this ABI delegates
905 // towards the base dtor.
907 // <operator-name> ::= ?1 # destructor
908 case Dtor_Base: Out << "?1"; return;
909 // <operator-name> ::= ?_D # vbase destructor
910 case Dtor_Complete: Out << "?_D"; return;
911 // <operator-name> ::= ?_G # scalar deleting destructor
912 case Dtor_Deleting: Out << "?_G"; return;
913 // <operator-name> ::= ?_E # vector deleting destructor
914 // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need
917 llvm_unreachable("not expecting a COMDAT");
919 llvm_unreachable("Unsupported dtor type?");
922 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
923 SourceLocation Loc) {
927 // <operator-name> ::= ?2 # new
928 case OO_New: Out << "?2"; break;
929 // <operator-name> ::= ?3 # delete
930 case OO_Delete: Out << "?3"; break;
931 // <operator-name> ::= ?4 # =
932 case OO_Equal: Out << "?4"; break;
933 // <operator-name> ::= ?5 # >>
934 case OO_GreaterGreater: Out << "?5"; break;
935 // <operator-name> ::= ?6 # <<
936 case OO_LessLess: Out << "?6"; break;
937 // <operator-name> ::= ?7 # !
938 case OO_Exclaim: Out << "?7"; break;
939 // <operator-name> ::= ?8 # ==
940 case OO_EqualEqual: Out << "?8"; break;
941 // <operator-name> ::= ?9 # !=
942 case OO_ExclaimEqual: Out << "?9"; break;
943 // <operator-name> ::= ?A # []
944 case OO_Subscript: Out << "?A"; break;
946 // <operator-name> ::= ?C # ->
947 case OO_Arrow: Out << "?C"; break;
948 // <operator-name> ::= ?D # *
949 case OO_Star: Out << "?D"; break;
950 // <operator-name> ::= ?E # ++
951 case OO_PlusPlus: Out << "?E"; break;
952 // <operator-name> ::= ?F # --
953 case OO_MinusMinus: Out << "?F"; break;
954 // <operator-name> ::= ?G # -
955 case OO_Minus: Out << "?G"; break;
956 // <operator-name> ::= ?H # +
957 case OO_Plus: Out << "?H"; break;
958 // <operator-name> ::= ?I # &
959 case OO_Amp: Out << "?I"; break;
960 // <operator-name> ::= ?J # ->*
961 case OO_ArrowStar: Out << "?J"; break;
962 // <operator-name> ::= ?K # /
963 case OO_Slash: Out << "?K"; break;
964 // <operator-name> ::= ?L # %
965 case OO_Percent: Out << "?L"; break;
966 // <operator-name> ::= ?M # <
967 case OO_Less: Out << "?M"; break;
968 // <operator-name> ::= ?N # <=
969 case OO_LessEqual: Out << "?N"; break;
970 // <operator-name> ::= ?O # >
971 case OO_Greater: Out << "?O"; break;
972 // <operator-name> ::= ?P # >=
973 case OO_GreaterEqual: Out << "?P"; break;
974 // <operator-name> ::= ?Q # ,
975 case OO_Comma: Out << "?Q"; break;
976 // <operator-name> ::= ?R # ()
977 case OO_Call: Out << "?R"; break;
978 // <operator-name> ::= ?S # ~
979 case OO_Tilde: Out << "?S"; break;
980 // <operator-name> ::= ?T # ^
981 case OO_Caret: Out << "?T"; break;
982 // <operator-name> ::= ?U # |
983 case OO_Pipe: Out << "?U"; break;
984 // <operator-name> ::= ?V # &&
985 case OO_AmpAmp: Out << "?V"; break;
986 // <operator-name> ::= ?W # ||
987 case OO_PipePipe: Out << "?W"; break;
988 // <operator-name> ::= ?X # *=
989 case OO_StarEqual: Out << "?X"; break;
990 // <operator-name> ::= ?Y # +=
991 case OO_PlusEqual: Out << "?Y"; break;
992 // <operator-name> ::= ?Z # -=
993 case OO_MinusEqual: Out << "?Z"; break;
994 // <operator-name> ::= ?_0 # /=
995 case OO_SlashEqual: Out << "?_0"; break;
996 // <operator-name> ::= ?_1 # %=
997 case OO_PercentEqual: Out << "?_1"; break;
998 // <operator-name> ::= ?_2 # >>=
999 case OO_GreaterGreaterEqual: Out << "?_2"; break;
1000 // <operator-name> ::= ?_3 # <<=
1001 case OO_LessLessEqual: Out << "?_3"; break;
1002 // <operator-name> ::= ?_4 # &=
1003 case OO_AmpEqual: Out << "?_4"; break;
1004 // <operator-name> ::= ?_5 # |=
1005 case OO_PipeEqual: Out << "?_5"; break;
1006 // <operator-name> ::= ?_6 # ^=
1007 case OO_CaretEqual: Out << "?_6"; break;
1012 // ?_B # local static guard
1014 // ?_D # vbase destructor
1015 // ?_E # vector deleting destructor
1016 // ?_F # default constructor closure
1017 // ?_G # scalar deleting destructor
1018 // ?_H # vector constructor iterator
1019 // ?_I # vector destructor iterator
1020 // ?_J # vector vbase constructor iterator
1021 // ?_K # virtual displacement map
1022 // ?_L # eh vector constructor iterator
1023 // ?_M # eh vector destructor iterator
1024 // ?_N # eh vector vbase constructor iterator
1025 // ?_O # copy constructor closure
1026 // ?_P<name> # udt returning <name>
1028 // ?_R0 # RTTI Type Descriptor
1029 // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
1030 // ?_R2 # RTTI Base Class Array
1031 // ?_R3 # RTTI Class Hierarchy Descriptor
1032 // ?_R4 # RTTI Complete Object Locator
1033 // ?_S # local vftable
1034 // ?_T # local vftable constructor closure
1035 // <operator-name> ::= ?_U # new[]
1036 case OO_Array_New: Out << "?_U"; break;
1037 // <operator-name> ::= ?_V # delete[]
1038 case OO_Array_Delete: Out << "?_V"; break;
1040 case OO_Conditional: {
1041 DiagnosticsEngine &Diags = Context.getDiags();
1042 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1043 "cannot mangle this conditional operator yet");
1044 Diags.Report(Loc, DiagID);
1049 DiagnosticsEngine &Diags = Context.getDiags();
1050 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1051 "cannot mangle this operator co_await yet");
1052 Diags.Report(Loc, DiagID);
1057 case NUM_OVERLOADED_OPERATORS:
1058 llvm_unreachable("Not an overloaded operator");
1062 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1063 // <source name> ::= <identifier> @
1064 BackRefVec::iterator Found =
1065 std::find(NameBackReferences.begin(), NameBackReferences.end(), Name);
1066 if (Found == NameBackReferences.end()) {
1067 if (NameBackReferences.size() < 10)
1068 NameBackReferences.push_back(Name);
1071 Out << (Found - NameBackReferences.begin());
1075 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1076 Context.mangleObjCMethodName(MD, Out);
1079 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1080 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1081 // <template-name> ::= <unscoped-template-name> <template-args>
1082 // ::= <substitution>
1083 // Always start with the unqualified name.
1085 // Templates have their own context for back references.
1086 ArgBackRefMap OuterArgsContext;
1087 BackRefVec OuterTemplateContext;
1088 PassObjectSizeArgsSet OuterPassObjectSizeArgs;
1089 NameBackReferences.swap(OuterTemplateContext);
1090 TypeBackReferences.swap(OuterArgsContext);
1091 PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1093 mangleUnscopedTemplateName(TD);
1094 mangleTemplateArgs(TD, TemplateArgs);
1096 // Restore the previous back reference contexts.
1097 NameBackReferences.swap(OuterTemplateContext);
1098 TypeBackReferences.swap(OuterArgsContext);
1099 PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1103 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1104 // <unscoped-template-name> ::= ?$ <unqualified-name>
1106 mangleUnqualifiedName(TD);
1109 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1111 // <integer-literal> ::= $0 <number>
1113 // Make sure booleans are encoded as 0/1.
1114 if (IsBoolean && Value.getBoolValue())
1116 else if (Value.isSigned())
1117 mangleNumber(Value.getSExtValue());
1119 mangleNumber(Value.getZExtValue());
1122 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1123 // See if this is a constant expression.
1125 if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1126 mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1130 // Look through no-op casts like template parameter substitutions.
1131 E = E->IgnoreParenNoopCasts(Context.getASTContext());
1133 const CXXUuidofExpr *UE = nullptr;
1134 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1135 if (UO->getOpcode() == UO_AddrOf)
1136 UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1138 UE = dyn_cast<CXXUuidofExpr>(E);
1141 // If we had to peek through an address-of operator, treat this like we are
1142 // dealing with a pointer type. Otherwise, treat it like a const reference.
1144 // N.B. This matches up with the handling of TemplateArgument::Declaration
1145 // in mangleTemplateArg
1151 // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1152 // const __s_GUID _GUID_{lower case UUID with underscores}
1153 StringRef Uuid = UE->getUuidAsStringRef(Context.getASTContext());
1154 std::string Name = "_GUID_" + Uuid.lower();
1155 std::replace(Name.begin(), Name.end(), '-', '_');
1157 mangleSourceName(Name);
1158 // Terminate the whole name with an '@'.
1160 // It's a global variable.
1162 // It's a struct called __s_GUID.
1163 mangleArtificalTagType(TTK_Struct, "__s_GUID");
1169 // As bad as this diagnostic is, it's better than crashing.
1170 DiagnosticsEngine &Diags = Context.getDiags();
1171 unsigned DiagID = Diags.getCustomDiagID(
1172 DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1173 Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1174 << E->getSourceRange();
1177 void MicrosoftCXXNameMangler::mangleTemplateArgs(
1178 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1179 // <template-args> ::= <template-arg>+
1180 const TemplateParameterList *TPL = TD->getTemplateParameters();
1181 assert(TPL->size() == TemplateArgs.size() &&
1182 "size mismatch between args and parms!");
1185 for (const TemplateArgument &TA : TemplateArgs.asArray())
1186 mangleTemplateArg(TD, TA, TPL->getParam(Idx++));
1189 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1190 const TemplateArgument &TA,
1191 const NamedDecl *Parm) {
1192 // <template-arg> ::= <type>
1193 // ::= <integer-literal>
1194 // ::= <member-data-pointer>
1195 // ::= <member-function-pointer>
1196 // ::= $E? <name> <type-encoding>
1197 // ::= $1? <name> <type-encoding>
1199 // ::= <template-args>
1201 switch (TA.getKind()) {
1202 case TemplateArgument::Null:
1203 llvm_unreachable("Can't mangle null template arguments!");
1204 case TemplateArgument::TemplateExpansion:
1205 llvm_unreachable("Can't mangle template expansion arguments!");
1206 case TemplateArgument::Type: {
1207 QualType T = TA.getAsType();
1208 mangleType(T, SourceRange(), QMM_Escape);
1211 case TemplateArgument::Declaration: {
1212 const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
1213 if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1214 mangleMemberDataPointer(
1215 cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
1216 cast<ValueDecl>(ND));
1217 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1218 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1219 if (MD && MD->isInstance()) {
1220 mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
1224 mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1227 mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
1231 case TemplateArgument::Integral:
1232 mangleIntegerLiteral(TA.getAsIntegral(),
1233 TA.getIntegralType()->isBooleanType());
1235 case TemplateArgument::NullPtr: {
1236 QualType T = TA.getNullPtrType();
1237 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1238 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1239 if (MPT->isMemberFunctionPointerType() &&
1240 !isa<FunctionTemplateDecl>(TD)) {
1241 mangleMemberFunctionPointer(RD, nullptr);
1244 if (MPT->isMemberDataPointer()) {
1245 if (!isa<FunctionTemplateDecl>(TD)) {
1246 mangleMemberDataPointer(RD, nullptr);
1249 // nullptr data pointers are always represented with a single field
1250 // which is initialized with either 0 or -1. Why -1? Well, we need to
1251 // distinguish the case where the data member is at offset zero in the
1253 // However, we are free to use 0 *if* we would use multiple fields for
1254 // non-nullptr member pointers.
1255 if (!RD->nullFieldOffsetIsZero()) {
1256 mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false);
1261 mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false);
1264 case TemplateArgument::Expression:
1265 mangleExpression(TA.getAsExpr());
1267 case TemplateArgument::Pack: {
1268 ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1269 if (TemplateArgs.empty()) {
1270 if (isa<TemplateTypeParmDecl>(Parm) ||
1271 isa<TemplateTemplateParmDecl>(Parm))
1272 // MSVC 2015 changed the mangling for empty expanded template packs,
1273 // use the old mangling for link compatibility for old versions.
1274 Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1275 LangOptions::MSVC2015)
1278 else if (isa<NonTypeTemplateParmDecl>(Parm))
1281 llvm_unreachable("unexpected template parameter decl!");
1283 for (const TemplateArgument &PA : TemplateArgs)
1284 mangleTemplateArg(TD, PA, Parm);
1288 case TemplateArgument::Template: {
1289 const NamedDecl *ND =
1290 TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
1291 if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1293 } else if (isa<TypeAliasDecl>(ND)) {
1297 llvm_unreachable("unexpected template template NamedDecl!");
1304 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1306 // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1307 // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1308 // 'I' means __restrict (32/64-bit).
1309 // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1311 // <base-cvr-qualifiers> ::= A # near
1312 // ::= B # near const
1313 // ::= C # near volatile
1314 // ::= D # near const volatile
1315 // ::= E # far (16-bit)
1316 // ::= F # far const (16-bit)
1317 // ::= G # far volatile (16-bit)
1318 // ::= H # far const volatile (16-bit)
1319 // ::= I # huge (16-bit)
1320 // ::= J # huge const (16-bit)
1321 // ::= K # huge volatile (16-bit)
1322 // ::= L # huge const volatile (16-bit)
1323 // ::= M <basis> # based
1324 // ::= N <basis> # based const
1325 // ::= O <basis> # based volatile
1326 // ::= P <basis> # based const volatile
1327 // ::= Q # near member
1328 // ::= R # near const member
1329 // ::= S # near volatile member
1330 // ::= T # near const volatile member
1331 // ::= U # far member (16-bit)
1332 // ::= V # far const member (16-bit)
1333 // ::= W # far volatile member (16-bit)
1334 // ::= X # far const volatile member (16-bit)
1335 // ::= Y # huge member (16-bit)
1336 // ::= Z # huge const member (16-bit)
1337 // ::= 0 # huge volatile member (16-bit)
1338 // ::= 1 # huge const volatile member (16-bit)
1339 // ::= 2 <basis> # based member
1340 // ::= 3 <basis> # based const member
1341 // ::= 4 <basis> # based volatile member
1342 // ::= 5 <basis> # based const volatile member
1343 // ::= 6 # near function (pointers only)
1344 // ::= 7 # far function (pointers only)
1345 // ::= 8 # near method (pointers only)
1346 // ::= 9 # far method (pointers only)
1347 // ::= _A <basis> # based function (pointers only)
1348 // ::= _B <basis> # based function (far?) (pointers only)
1349 // ::= _C <basis> # based method (pointers only)
1350 // ::= _D <basis> # based method (far?) (pointers only)
1351 // ::= _E # block (Clang)
1352 // <basis> ::= 0 # __based(void)
1353 // ::= 1 # __based(segment)?
1354 // ::= 2 <name> # __based(name)
1357 // ::= 5 # not really based
1358 bool HasConst = Quals.hasConst(),
1359 HasVolatile = Quals.hasVolatile();
1362 if (HasConst && HasVolatile) {
1364 } else if (HasVolatile) {
1366 } else if (HasConst) {
1372 if (HasConst && HasVolatile) {
1374 } else if (HasVolatile) {
1376 } else if (HasConst) {
1383 // FIXME: For now, just drop all extension qualifiers on the floor.
1387 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1388 // <ref-qualifier> ::= G # lvalue reference
1389 // ::= H # rvalue-reference
1390 switch (RefQualifier) {
1404 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1405 QualType PointeeType) {
1406 bool HasRestrict = Quals.hasRestrict();
1407 if (PointersAre64Bit &&
1408 (PointeeType.isNull() || !PointeeType->isFunctionType()))
1415 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1416 // <pointer-cv-qualifiers> ::= P # no qualifiers
1419 // ::= S # const volatile
1420 bool HasConst = Quals.hasConst(),
1421 HasVolatile = Quals.hasVolatile();
1423 if (HasConst && HasVolatile) {
1425 } else if (HasVolatile) {
1427 } else if (HasConst) {
1434 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1435 SourceRange Range) {
1436 // MSVC will backreference two canonically equivalent types that have slightly
1437 // different manglings when mangled alone.
1439 // Decayed types do not match up with non-decayed versions of the same type.
1442 // void (*x)(void) will not form a backreference with void x(void)
1444 if (const auto *DT = T->getAs<DecayedType>()) {
1445 QualType OriginalType = DT->getOriginalType();
1446 // All decayed ArrayTypes should be treated identically; as-if they were
1447 // a decayed IncompleteArrayType.
1448 if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
1449 OriginalType = getASTContext().getIncompleteArrayType(
1450 AT->getElementType(), AT->getSizeModifier(),
1451 AT->getIndexTypeCVRQualifiers());
1453 TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
1454 // If the original parameter was textually written as an array,
1455 // instead treat the decayed parameter like it's const.
1458 // int [] -> int * const
1459 if (OriginalType->isArrayType())
1462 TypePtr = T.getCanonicalType().getAsOpaquePtr();
1465 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1467 if (Found == TypeBackReferences.end()) {
1468 size_t OutSizeBefore = Out.tell();
1470 mangleType(T, Range, QMM_Drop);
1472 // See if it's worth creating a back reference.
1473 // Only types longer than 1 character are considered
1474 // and only 10 back references slots are available:
1475 bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
1476 if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1477 size_t Size = TypeBackReferences.size();
1478 TypeBackReferences[TypePtr] = Size;
1481 Out << Found->second;
1485 void MicrosoftCXXNameMangler::manglePassObjectSizeArg(
1486 const PassObjectSizeAttr *POSA) {
1487 int Type = POSA->getType();
1489 auto Iter = PassObjectSizeArgs.insert(Type).first;
1490 auto *TypePtr = (const void *)&*Iter;
1491 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1493 if (Found == TypeBackReferences.end()) {
1494 mangleArtificalTagType(TTK_Enum, "__pass_object_size" + llvm::utostr(Type),
1497 if (TypeBackReferences.size() < 10) {
1498 size_t Size = TypeBackReferences.size();
1499 TypeBackReferences[TypePtr] = Size;
1502 Out << Found->second;
1506 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1507 QualifierMangleMode QMM) {
1508 // Don't use the canonical types. MSVC includes things like 'const' on
1509 // pointer arguments to function pointers that canonicalization strips away.
1510 T = T.getDesugaredType(getASTContext());
1511 Qualifiers Quals = T.getLocalQualifiers();
1512 if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1513 // If there were any Quals, getAsArrayType() pushed them onto the array
1515 if (QMM == QMM_Mangle)
1517 else if (QMM == QMM_Escape || QMM == QMM_Result)
1519 mangleArrayType(AT);
1523 bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1524 T->isReferenceType() || T->isBlockPointerType();
1530 if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1532 mangleFunctionType(FT);
1535 mangleQualifiers(Quals, false);
1538 if (!IsPointer && Quals) {
1540 mangleQualifiers(Quals, false);
1544 if ((!IsPointer && Quals) || isa<TagType>(T)) {
1546 mangleQualifiers(Quals, false);
1551 const Type *ty = T.getTypePtr();
1553 switch (ty->getTypeClass()) {
1554 #define ABSTRACT_TYPE(CLASS, PARENT)
1555 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1557 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1559 #define TYPE(CLASS, PARENT) \
1561 mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1563 #include "clang/AST/TypeNodes.def"
1564 #undef ABSTRACT_TYPE
1565 #undef NON_CANONICAL_TYPE
1570 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1571 SourceRange Range) {
1572 // <type> ::= <builtin-type>
1573 // <builtin-type> ::= X # void
1574 // ::= C # signed char
1576 // ::= E # unsigned char
1578 // ::= G # unsigned short (or wchar_t if it's not a builtin)
1580 // ::= I # unsigned int
1582 // ::= K # unsigned long
1586 // ::= O # long double (__float80 is mangled differently)
1587 // ::= _J # long long, __int64
1588 // ::= _K # unsigned long long, __int64
1589 // ::= _L # __int128
1590 // ::= _M # unsigned __int128
1592 // _O # <array in parameter>
1593 // ::= _T # __float80 (Intel)
1595 // ::= _Z # __float80 (Digital Mars)
1596 switch (T->getKind()) {
1597 case BuiltinType::Void:
1600 case BuiltinType::SChar:
1603 case BuiltinType::Char_U:
1604 case BuiltinType::Char_S:
1607 case BuiltinType::UChar:
1610 case BuiltinType::Short:
1613 case BuiltinType::UShort:
1616 case BuiltinType::Int:
1619 case BuiltinType::UInt:
1622 case BuiltinType::Long:
1625 case BuiltinType::ULong:
1628 case BuiltinType::Float:
1631 case BuiltinType::Double:
1634 // TODO: Determine size and mangle accordingly
1635 case BuiltinType::LongDouble:
1638 case BuiltinType::LongLong:
1641 case BuiltinType::ULongLong:
1644 case BuiltinType::Int128:
1647 case BuiltinType::UInt128:
1650 case BuiltinType::Bool:
1653 case BuiltinType::Char16:
1656 case BuiltinType::Char32:
1659 case BuiltinType::WChar_S:
1660 case BuiltinType::WChar_U:
1664 #define BUILTIN_TYPE(Id, SingletonId)
1665 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1666 case BuiltinType::Id:
1667 #include "clang/AST/BuiltinTypes.def"
1668 case BuiltinType::Dependent:
1669 llvm_unreachable("placeholder types shouldn't get to name mangling");
1671 case BuiltinType::ObjCId:
1673 mangleArtificalTagType(TTK_Struct, "objc_object");
1675 case BuiltinType::ObjCClass:
1677 mangleArtificalTagType(TTK_Struct, "objc_class");
1679 case BuiltinType::ObjCSel:
1681 mangleArtificalTagType(TTK_Struct, "objc_selector");
1684 case BuiltinType::OCLImage1d:
1686 mangleArtificalTagType(TTK_Struct, "ocl_image1d");
1688 case BuiltinType::OCLImage1dArray:
1690 mangleArtificalTagType(TTK_Struct, "ocl_image1darray");
1692 case BuiltinType::OCLImage1dBuffer:
1694 mangleArtificalTagType(TTK_Struct, "ocl_image1dbuffer");
1696 case BuiltinType::OCLImage2d:
1698 mangleArtificalTagType(TTK_Struct, "ocl_image2d");
1700 case BuiltinType::OCLImage2dArray:
1702 mangleArtificalTagType(TTK_Struct, "ocl_image2darray");
1704 case BuiltinType::OCLImage2dDepth:
1706 mangleArtificalTagType(TTK_Struct, "ocl_image2ddepth");
1708 case BuiltinType::OCLImage2dArrayDepth:
1710 mangleArtificalTagType(TTK_Struct, "ocl_image2darraydepth");
1712 case BuiltinType::OCLImage2dMSAA:
1714 mangleArtificalTagType(TTK_Struct, "ocl_image2dmsaa");
1716 case BuiltinType::OCLImage2dArrayMSAA:
1718 mangleArtificalTagType(TTK_Struct, "ocl_image2darraymsaa");
1720 case BuiltinType::OCLImage2dMSAADepth:
1722 mangleArtificalTagType(TTK_Struct, "ocl_image2dmsaadepth");
1724 case BuiltinType::OCLImage2dArrayMSAADepth:
1726 mangleArtificalTagType(TTK_Struct, "ocl_image2darraymsaadepth");
1728 case BuiltinType::OCLImage3d:
1730 mangleArtificalTagType(TTK_Struct, "ocl_image3d");
1732 case BuiltinType::OCLSampler:
1734 mangleArtificalTagType(TTK_Struct, "ocl_sampler");
1736 case BuiltinType::OCLEvent:
1738 mangleArtificalTagType(TTK_Struct, "ocl_event");
1740 case BuiltinType::OCLClkEvent:
1742 mangleArtificalTagType(TTK_Struct, "ocl_clkevent");
1744 case BuiltinType::OCLQueue:
1746 mangleArtificalTagType(TTK_Struct, "ocl_queue");
1748 case BuiltinType::OCLNDRange:
1750 mangleArtificalTagType(TTK_Struct, "ocl_ndrange");
1752 case BuiltinType::OCLReserveID:
1754 mangleArtificalTagType(TTK_Struct, "ocl_reserveid");
1757 case BuiltinType::NullPtr:
1761 case BuiltinType::Half: {
1762 DiagnosticsEngine &Diags = Context.getDiags();
1763 unsigned DiagID = Diags.getCustomDiagID(
1764 DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
1765 Diags.Report(Range.getBegin(), DiagID)
1766 << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
1772 // <type> ::= <function-type>
1773 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
1775 // Structors only appear in decls, so at this point we know it's not a
1777 // FIXME: This may not be lambda-friendly.
1778 if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
1780 mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
1783 mangleFunctionType(T);
1786 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1787 Qualifiers, SourceRange) {
1789 mangleFunctionType(T);
1792 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
1793 const FunctionDecl *D,
1794 bool ForceThisQuals) {
1795 // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1796 // <return-type> <argument-list> <throw-spec>
1797 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
1800 if (D) Range = D->getSourceRange();
1802 bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
1803 CallingConv CC = T->getCallConv();
1804 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1805 if (MD->isInstance())
1806 HasThisQuals = true;
1807 if (isa<CXXDestructorDecl>(MD)) {
1809 } else if (isa<CXXConstructorDecl>(MD)) {
1811 IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
1812 StructorType == Ctor_DefaultClosure) &&
1813 getStructor(MD) == Structor;
1815 CC = getASTContext().getDefaultCallingConvention(
1816 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1820 // If this is a C++ instance method, mangle the CVR qualifiers for the
1823 Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
1824 manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
1825 mangleRefQualifier(Proto->getRefQualifier());
1826 mangleQualifiers(Quals, /*IsMember=*/false);
1829 mangleCallingConvention(CC);
1831 // <return-type> ::= <type>
1832 // ::= @ # structors (they have no declared return type)
1834 if (isa<CXXDestructorDecl>(D) && D == Structor &&
1835 StructorType == Dtor_Deleting) {
1836 // The scalar deleting destructor takes an extra int argument.
1837 // However, the FunctionType generated has 0 arguments.
1838 // FIXME: This is a temporary hack.
1839 // Maybe should fix the FunctionType creation instead?
1840 Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
1843 if (IsCtorClosure) {
1844 // Default constructor closure and copy constructor closure both return
1848 if (StructorType == Ctor_DefaultClosure) {
1849 // Default constructor closure always has no arguments.
1851 } else if (StructorType == Ctor_CopyingClosure) {
1852 // Copy constructor closure always takes an unqualified reference.
1853 mangleArgumentType(getASTContext().getLValueReferenceType(
1854 Proto->getParamType(0)
1855 ->getAs<LValueReferenceType>()
1857 /*SpelledAsLValue=*/true),
1861 llvm_unreachable("unexpected constructor closure!");
1868 QualType ResultType = T->getReturnType();
1869 if (const auto *AT =
1870 dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
1872 mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
1874 assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
1875 "shouldn't need to mangle __auto_type!");
1876 mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
1879 if (ResultType->isVoidType())
1880 ResultType = ResultType.getUnqualifiedType();
1881 mangleType(ResultType, Range, QMM_Result);
1885 // <argument-list> ::= X # void
1887 // ::= <type>* Z # varargs
1889 // Function types without prototypes can arise when mangling a function type
1890 // within an overloadable function in C. We mangle these as the absence of
1891 // any parameter types (not even an empty parameter list).
1893 } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
1896 // Happens for function pointer type arguments for example.
1897 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
1898 mangleArgumentType(Proto->getParamType(I), Range);
1899 // Mangle each pass_object_size parameter as if it's a paramater of enum
1900 // type passed directly after the parameter with the pass_object_size
1901 // attribute. The aforementioned enum's name is __pass_object_size, and we
1902 // pretend it resides in a top-level namespace called __clang.
1904 // FIXME: Is there a defined extension notation for the MS ABI, or is it
1905 // necessary to just cross our fingers and hope this type+namespace
1906 // combination doesn't conflict with anything?
1908 if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
1909 manglePassObjectSizeArg(P);
1911 // <builtin-type> ::= Z # ellipsis
1912 if (Proto->isVariadic())
1918 mangleThrowSpecification(Proto);
1921 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1922 // <function-class> ::= <member-function> E? # E designates a 64-bit 'this'
1923 // # pointer. in 64-bit mode *all*
1924 // # 'this' pointers are 64-bit.
1925 // ::= <global-function>
1926 // <member-function> ::= A # private: near
1927 // ::= B # private: far
1928 // ::= C # private: static near
1929 // ::= D # private: static far
1930 // ::= E # private: virtual near
1931 // ::= F # private: virtual far
1932 // ::= I # protected: near
1933 // ::= J # protected: far
1934 // ::= K # protected: static near
1935 // ::= L # protected: static far
1936 // ::= M # protected: virtual near
1937 // ::= N # protected: virtual far
1938 // ::= Q # public: near
1939 // ::= R # public: far
1940 // ::= S # public: static near
1941 // ::= T # public: static far
1942 // ::= U # public: virtual near
1943 // ::= V # public: virtual far
1944 // <global-function> ::= Y # global near
1945 // ::= Z # global far
1946 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1947 switch (MD->getAccess()) {
1949 llvm_unreachable("Unsupported access specifier");
1953 else if (MD->isVirtual())
1961 else if (MD->isVirtual())
1969 else if (MD->isVirtual())
1978 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
1979 // <calling-convention> ::= A # __cdecl
1980 // ::= B # __export __cdecl
1982 // ::= D # __export __pascal
1983 // ::= E # __thiscall
1984 // ::= F # __export __thiscall
1985 // ::= G # __stdcall
1986 // ::= H # __export __stdcall
1987 // ::= I # __fastcall
1988 // ::= J # __export __fastcall
1989 // ::= Q # __vectorcall
1990 // The 'export' calling conventions are from a bygone era
1991 // (*cough*Win16*cough*) when functions were declared for export with
1992 // that keyword. (It didn't actually export them, it just made them so
1993 // that they could be in a DLL and somebody from another module could call
1998 llvm_unreachable("Unsupported CC for mangling");
1999 case CC_X86_64Win64:
2001 case CC_C: Out << 'A'; break;
2002 case CC_X86Pascal: Out << 'C'; break;
2003 case CC_X86ThisCall: Out << 'E'; break;
2004 case CC_X86StdCall: Out << 'G'; break;
2005 case CC_X86FastCall: Out << 'I'; break;
2006 case CC_X86VectorCall: Out << 'Q'; break;
2009 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2010 mangleCallingConvention(T->getCallConv());
2012 void MicrosoftCXXNameMangler::mangleThrowSpecification(
2013 const FunctionProtoType *FT) {
2014 // <throw-spec> ::= Z # throw(...) (default)
2015 // ::= @ # throw() or __declspec/__attribute__((nothrow))
2017 // NOTE: Since the Microsoft compiler ignores throw specifications, they are
2018 // all actually mangled as 'Z'. (They're ignored because their associated
2019 // functionality isn't implemented, and probably never will be.)
2023 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2024 Qualifiers, SourceRange Range) {
2025 // Probably should be mangled as a template instantiation; need to see what
2027 DiagnosticsEngine &Diags = Context.getDiags();
2028 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2029 "cannot mangle this unresolved dependent type yet");
2030 Diags.Report(Range.getBegin(), DiagID)
2034 // <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2035 // <union-type> ::= T <name>
2036 // <struct-type> ::= U <name>
2037 // <class-type> ::= V <name>
2038 // <enum-type> ::= W4 <name>
2039 void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2056 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2058 mangleType(cast<TagType>(T)->getDecl());
2060 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2062 mangleType(cast<TagType>(T)->getDecl());
2064 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2065 mangleTagTypeKind(TD->getTagKind());
2068 void MicrosoftCXXNameMangler::mangleArtificalTagType(
2069 TagTypeKind TK, StringRef UnqualifiedName, ArrayRef<StringRef> NestedNames) {
2070 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2071 mangleTagTypeKind(TK);
2073 // Always start with the unqualified name.
2074 mangleSourceName(UnqualifiedName);
2076 for (auto I = NestedNames.rbegin(), E = NestedNames.rend(); I != E; ++I)
2077 mangleSourceName(*I);
2079 // Terminate the whole name with an '@'.
2083 // <type> ::= <array-type>
2084 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2085 // [Y <dimension-count> <dimension>+]
2086 // <element-type> # as global, E is never required
2087 // It's supposed to be the other way around, but for some strange reason, it
2088 // isn't. Today this behavior is retained for the sole purpose of backwards
2090 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2091 // This isn't a recursive mangling, so now we have to do it all in this
2093 manglePointerCVQualifiers(T->getElementType().getQualifiers());
2094 mangleType(T->getElementType(), SourceRange());
2096 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2098 llvm_unreachable("Should have been special cased");
2100 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2102 llvm_unreachable("Should have been special cased");
2104 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2105 Qualifiers, SourceRange) {
2106 llvm_unreachable("Should have been special cased");
2108 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2109 Qualifiers, SourceRange) {
2110 llvm_unreachable("Should have been special cased");
2112 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2113 QualType ElementTy(T, 0);
2114 SmallVector<llvm::APInt, 3> Dimensions;
2116 if (ElementTy->isConstantArrayType()) {
2117 const ConstantArrayType *CAT =
2118 getASTContext().getAsConstantArrayType(ElementTy);
2119 Dimensions.push_back(CAT->getSize());
2120 ElementTy = CAT->getElementType();
2121 } else if (ElementTy->isIncompleteArrayType()) {
2122 const IncompleteArrayType *IAT =
2123 getASTContext().getAsIncompleteArrayType(ElementTy);
2124 Dimensions.push_back(llvm::APInt(32, 0));
2125 ElementTy = IAT->getElementType();
2126 } else if (ElementTy->isVariableArrayType()) {
2127 const VariableArrayType *VAT =
2128 getASTContext().getAsVariableArrayType(ElementTy);
2129 Dimensions.push_back(llvm::APInt(32, 0));
2130 ElementTy = VAT->getElementType();
2131 } else if (ElementTy->isDependentSizedArrayType()) {
2132 // The dependent expression has to be folded into a constant (TODO).
2133 const DependentSizedArrayType *DSAT =
2134 getASTContext().getAsDependentSizedArrayType(ElementTy);
2135 DiagnosticsEngine &Diags = Context.getDiags();
2136 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2137 "cannot mangle this dependent-length array yet");
2138 Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2139 << DSAT->getBracketsRange();
2146 // <dimension-count> ::= <number> # number of extra dimensions
2147 mangleNumber(Dimensions.size());
2148 for (const llvm::APInt &Dimension : Dimensions)
2149 mangleNumber(Dimension.getLimitedValue());
2150 mangleType(ElementTy, SourceRange(), QMM_Escape);
2153 // <type> ::= <pointer-to-member-type>
2154 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2155 // <class name> <type>
2156 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, Qualifiers Quals,
2157 SourceRange Range) {
2158 QualType PointeeType = T->getPointeeType();
2159 manglePointerCVQualifiers(Quals);
2160 manglePointerExtQualifiers(Quals, PointeeType);
2161 if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2163 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2164 mangleFunctionType(FPT, nullptr, true);
2166 mangleQualifiers(PointeeType.getQualifiers(), true);
2167 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2168 mangleType(PointeeType, Range, QMM_Drop);
2172 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2173 Qualifiers, SourceRange Range) {
2174 DiagnosticsEngine &Diags = Context.getDiags();
2175 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2176 "cannot mangle this template type parameter type yet");
2177 Diags.Report(Range.getBegin(), DiagID)
2181 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2182 Qualifiers, SourceRange Range) {
2183 DiagnosticsEngine &Diags = Context.getDiags();
2184 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2185 "cannot mangle this substituted parameter pack yet");
2186 Diags.Report(Range.getBegin(), DiagID)
2190 // <type> ::= <pointer-type>
2191 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2192 // # the E is required for 64-bit non-static pointers
2193 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2194 SourceRange Range) {
2195 QualType PointeeType = T->getPointeeType();
2196 manglePointerCVQualifiers(Quals);
2197 manglePointerExtQualifiers(Quals, PointeeType);
2198 mangleType(PointeeType, Range);
2200 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2201 Qualifiers Quals, SourceRange Range) {
2202 QualType PointeeType = T->getPointeeType();
2203 manglePointerCVQualifiers(Quals);
2204 manglePointerExtQualifiers(Quals, PointeeType);
2205 // Object pointers never have qualifiers.
2207 mangleType(PointeeType, Range);
2210 // <type> ::= <reference-type>
2211 // <reference-type> ::= A E? <cvr-qualifiers> <type>
2212 // # the E is required for 64-bit non-static lvalue references
2213 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
2214 Qualifiers Quals, SourceRange Range) {
2215 QualType PointeeType = T->getPointeeType();
2216 assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2218 manglePointerExtQualifiers(Quals, PointeeType);
2219 mangleType(PointeeType, Range);
2222 // <type> ::= <r-value-reference-type>
2223 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
2224 // # the E is required for 64-bit non-static rvalue references
2225 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2226 Qualifiers Quals, SourceRange Range) {
2227 QualType PointeeType = T->getPointeeType();
2228 assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2230 manglePointerExtQualifiers(Quals, PointeeType);
2231 mangleType(PointeeType, Range);
2234 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
2235 SourceRange Range) {
2236 QualType ElementType = T->getElementType();
2238 llvm::SmallString<64> TemplateMangling;
2239 llvm::raw_svector_ostream Stream(TemplateMangling);
2240 MicrosoftCXXNameMangler Extra(Context, Stream);
2242 Extra.mangleSourceName("_Complex");
2243 Extra.mangleType(ElementType, Range, QMM_Escape);
2245 mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__clang"});
2248 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
2249 SourceRange Range) {
2250 const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
2251 assert(ET && "vectors with non-builtin elements are unsupported");
2252 uint64_t Width = getASTContext().getTypeSize(T);
2253 // Pattern match exactly the typedefs in our intrinsic headers. Anything that
2254 // doesn't match the Intel types uses a custom mangling below.
2255 size_t OutSizeBefore = Out.tell();
2256 llvm::Triple::ArchType AT =
2257 getASTContext().getTargetInfo().getTriple().getArch();
2258 if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) {
2259 if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
2260 mangleArtificalTagType(TTK_Union, "__m64");
2261 } else if (Width >= 128) {
2262 if (ET->getKind() == BuiltinType::Float)
2263 mangleArtificalTagType(TTK_Union, "__m" + llvm::utostr(Width));
2264 else if (ET->getKind() == BuiltinType::LongLong)
2265 mangleArtificalTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i');
2266 else if (ET->getKind() == BuiltinType::Double)
2267 mangleArtificalTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd');
2271 bool IsBuiltin = Out.tell() != OutSizeBefore;
2273 // The MS ABI doesn't have a special mangling for vector types, so we define
2274 // our own mangling to handle uses of __vector_size__ on user-specified
2275 // types, and for extensions like __v4sf.
2277 llvm::SmallString<64> TemplateMangling;
2278 llvm::raw_svector_ostream Stream(TemplateMangling);
2279 MicrosoftCXXNameMangler Extra(Context, Stream);
2281 Extra.mangleSourceName("__vector");
2282 Extra.mangleType(QualType(ET, 0), Range, QMM_Escape);
2283 Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()),
2284 /*IsBoolean=*/false);
2286 mangleArtificalTagType(TTK_Union, TemplateMangling, {"__clang"});
2290 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
2291 Qualifiers Quals, SourceRange Range) {
2292 mangleType(static_cast<const VectorType *>(T), Quals, Range);
2294 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
2295 Qualifiers, SourceRange Range) {
2296 DiagnosticsEngine &Diags = Context.getDiags();
2297 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2298 "cannot mangle this dependent-sized extended vector type yet");
2299 Diags.Report(Range.getBegin(), DiagID)
2303 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
2305 // ObjC interfaces have structs underlying them.
2306 mangleTagTypeKind(TTK_Struct);
2307 mangleName(T->getDecl());
2310 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, Qualifiers,
2311 SourceRange Range) {
2312 // We don't allow overloading by different protocol qualification,
2313 // so mangling them isn't necessary.
2314 mangleType(T->getBaseType(), Range);
2317 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
2318 Qualifiers Quals, SourceRange Range) {
2319 QualType PointeeType = T->getPointeeType();
2320 manglePointerCVQualifiers(Quals);
2321 manglePointerExtQualifiers(Quals, PointeeType);
2325 mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
2328 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
2329 Qualifiers, SourceRange) {
2330 llvm_unreachable("Cannot mangle injected class name type.");
2333 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
2334 Qualifiers, SourceRange Range) {
2335 DiagnosticsEngine &Diags = Context.getDiags();
2336 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2337 "cannot mangle this template specialization type yet");
2338 Diags.Report(Range.getBegin(), DiagID)
2342 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
2343 SourceRange Range) {
2344 DiagnosticsEngine &Diags = Context.getDiags();
2345 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2346 "cannot mangle this dependent name type yet");
2347 Diags.Report(Range.getBegin(), DiagID)
2351 void MicrosoftCXXNameMangler::mangleType(
2352 const DependentTemplateSpecializationType *T, Qualifiers,
2353 SourceRange Range) {
2354 DiagnosticsEngine &Diags = Context.getDiags();
2355 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2356 "cannot mangle this dependent template specialization type yet");
2357 Diags.Report(Range.getBegin(), DiagID)
2361 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
2362 SourceRange Range) {
2363 DiagnosticsEngine &Diags = Context.getDiags();
2364 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2365 "cannot mangle this pack expansion yet");
2366 Diags.Report(Range.getBegin(), DiagID)
2370 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
2371 SourceRange Range) {
2372 DiagnosticsEngine &Diags = Context.getDiags();
2373 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2374 "cannot mangle this typeof(type) yet");
2375 Diags.Report(Range.getBegin(), DiagID)
2379 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
2380 SourceRange Range) {
2381 DiagnosticsEngine &Diags = Context.getDiags();
2382 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2383 "cannot mangle this typeof(expression) yet");
2384 Diags.Report(Range.getBegin(), DiagID)
2388 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
2389 SourceRange Range) {
2390 DiagnosticsEngine &Diags = Context.getDiags();
2391 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2392 "cannot mangle this decltype() yet");
2393 Diags.Report(Range.getBegin(), DiagID)
2397 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2398 Qualifiers, SourceRange Range) {
2399 DiagnosticsEngine &Diags = Context.getDiags();
2400 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2401 "cannot mangle this unary transform type yet");
2402 Diags.Report(Range.getBegin(), DiagID)
2406 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
2407 SourceRange Range) {
2408 assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2410 DiagnosticsEngine &Diags = Context.getDiags();
2411 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2412 "cannot mangle this 'auto' type yet");
2413 Diags.Report(Range.getBegin(), DiagID)
2417 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
2418 SourceRange Range) {
2419 QualType ValueType = T->getValueType();
2421 llvm::SmallString<64> TemplateMangling;
2422 llvm::raw_svector_ostream Stream(TemplateMangling);
2423 MicrosoftCXXNameMangler Extra(Context, Stream);
2425 Extra.mangleSourceName("_Atomic");
2426 Extra.mangleType(ValueType, Range, QMM_Escape);
2428 mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__clang"});
2431 void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
2432 SourceRange Range) {
2433 DiagnosticsEngine &Diags = Context.getDiags();
2434 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2435 "cannot mangle this OpenCL pipe type yet");
2436 Diags.Report(Range.getBegin(), DiagID)
2440 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2442 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2443 "Invalid mangleName() call, argument is not a variable or function!");
2444 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2445 "Invalid mangleName() call on 'structor decl!");
2447 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2448 getASTContext().getSourceManager(),
2449 "Mangling declaration");
2451 MicrosoftCXXNameMangler Mangler(*this, Out);
2452 return Mangler.mangle(D);
2455 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2456 // <virtual-adjustment>
2457 // <no-adjustment> ::= A # private near
2458 // ::= B # private far
2459 // ::= I # protected near
2460 // ::= J # protected far
2461 // ::= Q # public near
2462 // ::= R # public far
2463 // <static-adjustment> ::= G <static-offset> # private near
2464 // ::= H <static-offset> # private far
2465 // ::= O <static-offset> # protected near
2466 // ::= P <static-offset> # protected far
2467 // ::= W <static-offset> # public near
2468 // ::= X <static-offset> # public far
2469 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2470 // ::= $1 <virtual-shift> <static-offset> # private far
2471 // ::= $2 <virtual-shift> <static-offset> # protected near
2472 // ::= $3 <virtual-shift> <static-offset> # protected far
2473 // ::= $4 <virtual-shift> <static-offset> # public near
2474 // ::= $5 <virtual-shift> <static-offset> # public far
2475 // <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift>
2476 // <vtordisp-shift> ::= <offset-to-vtordisp>
2477 // <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset>
2478 // <offset-to-vtordisp>
2479 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2480 const ThisAdjustment &Adjustment,
2481 MicrosoftCXXNameMangler &Mangler,
2483 if (!Adjustment.Virtual.isEmpty()) {
2486 switch (MD->getAccess()) {
2488 llvm_unreachable("Unsupported access specifier");
2498 if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2499 Out << 'R' << AccessSpec;
2500 Mangler.mangleNumber(
2501 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2502 Mangler.mangleNumber(
2503 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2504 Mangler.mangleNumber(
2505 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2506 Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2509 Mangler.mangleNumber(
2510 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2511 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2513 } else if (Adjustment.NonVirtual != 0) {
2514 switch (MD->getAccess()) {
2516 llvm_unreachable("Unsupported access specifier");
2526 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2528 switch (MD->getAccess()) {
2530 llvm_unreachable("Unsupported access specifier");
2544 MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
2546 MicrosoftVTableContext *VTContext =
2547 cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
2548 const MicrosoftVTableContext::MethodVFTableLocation &ML =
2549 VTContext->getMethodVFTableLocation(GlobalDecl(MD));
2551 MicrosoftCXXNameMangler Mangler(*this, Out);
2552 Mangler.getStream() << "\01?";
2553 Mangler.mangleVirtualMemPtrThunk(MD, ML);
2556 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2557 const ThunkInfo &Thunk,
2559 MicrosoftCXXNameMangler Mangler(*this, Out);
2561 Mangler.mangleName(MD);
2562 mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
2563 if (!Thunk.Return.isEmpty())
2564 assert(Thunk.Method != nullptr &&
2565 "Thunk info should hold the overridee decl");
2567 const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2568 Mangler.mangleFunctionType(
2569 DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
2572 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2573 const CXXDestructorDecl *DD, CXXDtorType Type,
2574 const ThisAdjustment &Adjustment, raw_ostream &Out) {
2575 // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2576 // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2577 // mangling manually until we support both deleting dtor types.
2578 assert(Type == Dtor_Deleting);
2579 MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
2581 Mangler.mangleName(DD->getParent());
2582 mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
2583 Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
2586 void MicrosoftMangleContextImpl::mangleCXXVFTable(
2587 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2589 // <mangled-name> ::= ?_7 <class-name> <storage-class>
2590 // <cvr-qualifiers> [<name>] @
2591 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2592 // is always '6' for vftables.
2593 MicrosoftCXXNameMangler Mangler(*this, Out);
2594 Mangler.getStream() << "\01??_7";
2595 Mangler.mangleName(Derived);
2596 Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2597 for (const CXXRecordDecl *RD : BasePath)
2598 Mangler.mangleName(RD);
2599 Mangler.getStream() << '@';
2602 void MicrosoftMangleContextImpl::mangleCXXVBTable(
2603 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2605 // <mangled-name> ::= ?_8 <class-name> <storage-class>
2606 // <cvr-qualifiers> [<name>] @
2607 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2608 // is always '7' for vbtables.
2609 MicrosoftCXXNameMangler Mangler(*this, Out);
2610 Mangler.getStream() << "\01??_8";
2611 Mangler.mangleName(Derived);
2612 Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const.
2613 for (const CXXRecordDecl *RD : BasePath)
2614 Mangler.mangleName(RD);
2615 Mangler.getStream() << '@';
2618 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
2619 MicrosoftCXXNameMangler Mangler(*this, Out);
2620 Mangler.getStream() << "\01??_R0";
2621 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2622 Mangler.getStream() << "@8";
2625 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
2627 MicrosoftCXXNameMangler Mangler(*this, Out);
2628 Mangler.getStream() << '.';
2629 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2632 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
2633 const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
2634 MicrosoftCXXNameMangler Mangler(*this, Out);
2635 Mangler.getStream() << "\01??_K";
2636 Mangler.mangleName(SrcRD);
2637 Mangler.getStream() << "$C";
2638 Mangler.mangleName(DstRD);
2641 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T,
2644 uint32_t NumEntries,
2646 MicrosoftCXXNameMangler Mangler(*this, Out);
2647 Mangler.getStream() << "_TI";
2649 Mangler.getStream() << 'C';
2651 Mangler.getStream() << 'V';
2652 Mangler.getStream() << NumEntries;
2653 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2656 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
2657 QualType T, uint32_t NumEntries, raw_ostream &Out) {
2658 MicrosoftCXXNameMangler Mangler(*this, Out);
2659 Mangler.getStream() << "_CTA";
2660 Mangler.getStream() << NumEntries;
2661 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2664 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
2665 QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
2666 uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
2668 MicrosoftCXXNameMangler Mangler(*this, Out);
2669 Mangler.getStream() << "_CT";
2671 llvm::SmallString<64> RTTIMangling;
2673 llvm::raw_svector_ostream Stream(RTTIMangling);
2674 mangleCXXRTTI(T, Stream);
2676 Mangler.getStream() << RTTIMangling.substr(1);
2678 // VS2015 CTP6 omits the copy-constructor in the mangled name. This name is,
2679 // in fact, superfluous but I'm not sure the change was made consciously.
2680 // TODO: Revisit this when VS2015 gets released.
2681 llvm::SmallString<64> CopyCtorMangling;
2683 llvm::raw_svector_ostream Stream(CopyCtorMangling);
2684 mangleCXXCtor(CD, CT, Stream);
2686 Mangler.getStream() << CopyCtorMangling.substr(1);
2688 Mangler.getStream() << Size;
2689 if (VBPtrOffset == -1) {
2691 Mangler.getStream() << NVOffset;
2694 Mangler.getStream() << NVOffset;
2695 Mangler.getStream() << VBPtrOffset;
2696 Mangler.getStream() << VBIndex;
2700 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
2701 const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
2702 uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
2703 MicrosoftCXXNameMangler Mangler(*this, Out);
2704 Mangler.getStream() << "\01??_R1";
2705 Mangler.mangleNumber(NVOffset);
2706 Mangler.mangleNumber(VBPtrOffset);
2707 Mangler.mangleNumber(VBTableOffset);
2708 Mangler.mangleNumber(Flags);
2709 Mangler.mangleName(Derived);
2710 Mangler.getStream() << "8";
2713 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
2714 const CXXRecordDecl *Derived, raw_ostream &Out) {
2715 MicrosoftCXXNameMangler Mangler(*this, Out);
2716 Mangler.getStream() << "\01??_R2";
2717 Mangler.mangleName(Derived);
2718 Mangler.getStream() << "8";
2721 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
2722 const CXXRecordDecl *Derived, raw_ostream &Out) {
2723 MicrosoftCXXNameMangler Mangler(*this, Out);
2724 Mangler.getStream() << "\01??_R3";
2725 Mangler.mangleName(Derived);
2726 Mangler.getStream() << "8";
2729 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
2730 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2732 // <mangled-name> ::= ?_R4 <class-name> <storage-class>
2733 // <cvr-qualifiers> [<name>] @
2734 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2735 // is always '6' for vftables.
2736 MicrosoftCXXNameMangler Mangler(*this, Out);
2737 Mangler.getStream() << "\01??_R4";
2738 Mangler.mangleName(Derived);
2739 Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2740 for (const CXXRecordDecl *RD : BasePath)
2741 Mangler.mangleName(RD);
2742 Mangler.getStream() << '@';
2745 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
2746 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2747 MicrosoftCXXNameMangler Mangler(*this, Out);
2748 // The function body is in the same comdat as the function with the handler,
2749 // so the numbering here doesn't have to be the same across TUs.
2751 // <mangled-name> ::= ?filt$ <filter-number> @0
2752 Mangler.getStream() << "\01?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
2753 Mangler.mangleName(EnclosingDecl);
2756 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
2757 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2758 MicrosoftCXXNameMangler Mangler(*this, Out);
2759 // The function body is in the same comdat as the function with the handler,
2760 // so the numbering here doesn't have to be the same across TUs.
2762 // <mangled-name> ::= ?fin$ <filter-number> @0
2763 Mangler.getStream() << "\01?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
2764 Mangler.mangleName(EnclosingDecl);
2767 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
2768 // This is just a made up unique string for the purposes of tbaa. undname
2769 // does *not* know how to demangle it.
2770 MicrosoftCXXNameMangler Mangler(*this, Out);
2771 Mangler.getStream() << '?';
2772 Mangler.mangleType(T, SourceRange());
2775 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
2778 MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
2782 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
2785 MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
2789 void MicrosoftMangleContextImpl::mangleReferenceTemporary(
2790 const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
2791 MicrosoftCXXNameMangler Mangler(*this, Out);
2793 Mangler.getStream() << "\01?$RT" << ManglingNumber << '@';
2794 Mangler.mangle(VD, "");
2797 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
2798 const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
2799 MicrosoftCXXNameMangler Mangler(*this, Out);
2801 Mangler.getStream() << "\01?$TSS" << GuardNum << '@';
2802 Mangler.mangleNestedName(VD);
2805 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
2807 // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
2808 // ::= ?__J <postfix> @5 <scope-depth>
2809 // ::= ?$S <guard-num> @ <postfix> @4IA
2811 // The first mangling is what MSVC uses to guard static locals in inline
2812 // functions. It uses a different mangling in external functions to support
2813 // guarding more than 32 variables. MSVC rejects inline functions with more
2814 // than 32 static locals. We don't fully implement the second mangling
2815 // because those guards are not externally visible, and instead use LLVM's
2816 // default renaming when creating a new guard variable.
2817 MicrosoftCXXNameMangler Mangler(*this, Out);
2819 bool Visible = VD->isExternallyVisible();
2821 Mangler.getStream() << (VD->getTLSKind() ? "\01??__J" : "\01??_B");
2823 Mangler.getStream() << "\01?$S1@";
2825 unsigned ScopeDepth = 0;
2826 if (Visible && !getNextDiscriminator(VD, ScopeDepth))
2827 // If we do not have a discriminator and are emitting a guard variable for
2828 // use at global scope, then mangling the nested name will not be enough to
2829 // remove ambiguities.
2830 Mangler.mangle(VD, "");
2832 Mangler.mangleNestedName(VD);
2833 Mangler.getStream() << (Visible ? "@5" : "@4IA");
2835 Mangler.mangleNumber(ScopeDepth);
2838 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
2841 MicrosoftCXXNameMangler Mangler(*this, Out);
2842 Mangler.getStream() << "\01??__" << CharCode;
2843 Mangler.mangleName(D);
2844 if (D->isStaticDataMember()) {
2845 Mangler.mangleVariableEncoding(D);
2846 Mangler.getStream() << '@';
2848 // This is the function class mangling. These stubs are global, non-variadic,
2849 // cdecl functions that return void and take no args.
2850 Mangler.getStream() << "YAXXZ";
2853 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
2855 // <initializer-name> ::= ?__E <name> YAXXZ
2856 mangleInitFiniStub(D, Out, 'E');
2860 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
2862 // <destructor-name> ::= ?__F <name> YAXXZ
2863 mangleInitFiniStub(D, Out, 'F');
2866 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
2868 // <char-type> ::= 0 # char
2870 // ::= ??? # char16_t/char32_t will need a mangling too...
2872 // <literal-length> ::= <non-negative integer> # the length of the literal
2874 // <encoded-crc> ::= <hex digit>+ @ # crc of the literal including
2875 // # null-terminator
2877 // <encoded-string> ::= <simple character> # uninteresting character
2878 // ::= '?$' <hex digit> <hex digit> # these two nibbles
2879 // # encode the byte for the
2881 // ::= '?' [a-z] # \xe1 - \xfa
2882 // ::= '?' [A-Z] # \xc1 - \xda
2883 // ::= '?' [0-9] # [,/\:. \n\t'-]
2885 // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
2886 // <encoded-string> '@'
2887 MicrosoftCXXNameMangler Mangler(*this, Out);
2888 Mangler.getStream() << "\01??_C@_";
2890 // <char-type>: The "kind" of string literal is encoded into the mangled name.
2892 Mangler.getStream() << '1';
2894 Mangler.getStream() << '0';
2896 // <literal-length>: The next part of the mangled name consists of the length
2898 // The StringLiteral does not consider the NUL terminator byte(s) but the
2900 // N.B. The length is in terms of bytes, not characters.
2901 Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
2903 auto GetLittleEndianByte = [&Mangler, &SL](unsigned Index) {
2904 unsigned CharByteWidth = SL->getCharByteWidth();
2905 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2906 unsigned OffsetInCodeUnit = Index % CharByteWidth;
2907 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2910 auto GetBigEndianByte = [&Mangler, &SL](unsigned Index) {
2911 unsigned CharByteWidth = SL->getCharByteWidth();
2912 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2913 unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
2914 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2917 // CRC all the bytes of the StringLiteral.
2919 for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
2920 JC.update(GetLittleEndianByte(I));
2922 // The NUL terminator byte(s) were not present earlier,
2923 // we need to manually process those bytes into the CRC.
2924 for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2928 // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
2930 Mangler.mangleNumber(JC.getCRC());
2932 // <encoded-string>: The mangled name also contains the first 32 _characters_
2933 // (including null-terminator bytes) of the StringLiteral.
2934 // Each character is encoded by splitting them into bytes and then encoding
2935 // the constituent bytes.
2936 auto MangleByte = [&Mangler](char Byte) {
2937 // There are five different manglings for characters:
2938 // - [a-zA-Z0-9_$]: A one-to-one mapping.
2939 // - ?[a-z]: The range from \xe1 to \xfa.
2940 // - ?[A-Z]: The range from \xc1 to \xda.
2941 // - ?[0-9]: The set of [,/\:. \n\t'-].
2942 // - ?$XX: A fallback which maps nibbles.
2943 if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
2944 Mangler.getStream() << Byte;
2945 } else if (isLetter(Byte & 0x7f)) {
2946 Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
2948 const char SpecialChars[] = {',', '/', '\\', ':', '.',
2949 ' ', '\n', '\t', '\'', '-'};
2951 std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
2952 if (Pos != std::end(SpecialChars)) {
2953 Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
2955 Mangler.getStream() << "?$";
2956 Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
2957 Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
2962 // Enforce our 32 character max.
2963 unsigned NumCharsToMangle = std::min(32U, SL->getLength());
2964 for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E;
2967 MangleByte(GetBigEndianByte(I));
2969 MangleByte(GetLittleEndianByte(I));
2971 // Encode the NUL terminator if there is room.
2972 if (NumCharsToMangle < 32)
2973 for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2977 Mangler.getStream() << '@';
2980 MicrosoftMangleContext *
2981 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
2982 return new MicrosoftMangleContextImpl(Context, Diags);