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 mangleCXXCatchHandlerType(QualType T, uint32_t Flags,
131 raw_ostream &Out) override;
132 void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
133 void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
134 void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
135 uint32_t NVOffset, int32_t VBPtrOffset,
136 uint32_t VBTableOffset, uint32_t Flags,
137 raw_ostream &Out) override;
138 void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
139 raw_ostream &Out) override;
140 void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
141 raw_ostream &Out) override;
143 mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
144 ArrayRef<const CXXRecordDecl *> BasePath,
145 raw_ostream &Out) override;
146 void mangleTypeName(QualType T, raw_ostream &) override;
147 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
148 raw_ostream &) override;
149 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
150 raw_ostream &) override;
151 void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
152 raw_ostream &) override;
153 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
154 void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
155 raw_ostream &Out) override;
156 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
157 void mangleDynamicAtExitDestructor(const VarDecl *D,
158 raw_ostream &Out) override;
159 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
160 raw_ostream &Out) override;
161 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
162 raw_ostream &Out) override;
163 void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
164 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
165 // Lambda closure types are already numbered.
169 const DeclContext *DC = getEffectiveDeclContext(ND);
170 if (!DC->isFunctionOrMethod())
173 // Use the canonical number for externally visible decls.
174 if (ND->isExternallyVisible()) {
175 disc = getASTContext().getManglingNumber(ND);
179 // Anonymous tags are already numbered.
180 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
181 if (!Tag->hasNameForLinkage() &&
182 !getASTContext().getDeclaratorForUnnamedTagDecl(Tag) &&
183 !getASTContext().getTypedefNameForUnnamedTagDecl(Tag))
187 // Make up a reasonable number for internal decls.
188 unsigned &discriminator = Uniquifier[ND];
190 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
191 disc = discriminator + 1;
195 unsigned getLambdaId(const CXXRecordDecl *RD) {
196 assert(RD->isLambda() && "RD must be a lambda!");
197 assert(!RD->isExternallyVisible() && "RD must not be visible!");
198 assert(RD->getLambdaManglingNumber() == 0 &&
199 "RD must not have a mangling number!");
200 std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
201 Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
202 return Result.first->second;
206 void mangleInitFiniStub(const VarDecl *D, raw_ostream &Out, char CharCode);
209 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
210 /// Microsoft Visual C++ ABI.
211 class MicrosoftCXXNameMangler {
212 MicrosoftMangleContextImpl &Context;
215 /// The "structor" is the top-level declaration being mangled, if
216 /// that's not a template specialization; otherwise it's the pattern
217 /// for that specialization.
218 const NamedDecl *Structor;
219 unsigned StructorType;
221 typedef llvm::SmallVector<std::string, 10> BackRefVec;
222 BackRefVec NameBackReferences;
224 typedef llvm::DenseMap<void *, unsigned> ArgBackRefMap;
225 ArgBackRefMap TypeBackReferences;
227 typedef std::set<int> PassObjectSizeArgsSet;
228 PassObjectSizeArgsSet PassObjectSizeArgs;
230 ASTContext &getASTContext() const { return Context.getASTContext(); }
232 // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
233 // this check into mangleQualifiers().
234 const bool PointersAre64Bit;
237 enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
239 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
240 : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
241 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
244 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
245 const CXXConstructorDecl *D, CXXCtorType Type)
246 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
247 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
250 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
251 const CXXDestructorDecl *D, CXXDtorType Type)
252 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
253 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
256 raw_ostream &getStream() const { return Out; }
258 void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
259 void mangleName(const NamedDecl *ND);
260 void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
261 void mangleVariableEncoding(const VarDecl *VD);
262 void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
263 void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
264 const CXXMethodDecl *MD);
265 void mangleVirtualMemPtrThunk(
266 const CXXMethodDecl *MD,
267 const MicrosoftVTableContext::MethodVFTableLocation &ML);
268 void mangleNumber(int64_t Number);
269 void mangleTagTypeKind(TagTypeKind TK);
270 void mangleArtificalTagType(TagTypeKind TK, StringRef UnqualifiedName,
271 ArrayRef<StringRef> NestedNames = None);
272 void mangleType(QualType T, SourceRange Range,
273 QualifierMangleMode QMM = QMM_Mangle);
274 void mangleFunctionType(const FunctionType *T,
275 const FunctionDecl *D = nullptr,
276 bool ForceThisQuals = false);
277 void mangleNestedName(const NamedDecl *ND);
280 void mangleUnqualifiedName(const NamedDecl *ND) {
281 mangleUnqualifiedName(ND, ND->getDeclName());
283 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
284 void mangleSourceName(StringRef Name);
285 void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
286 void mangleCXXDtorType(CXXDtorType T);
287 void mangleQualifiers(Qualifiers Quals, bool IsMember);
288 void mangleRefQualifier(RefQualifierKind RefQualifier);
289 void manglePointerCVQualifiers(Qualifiers Quals);
290 void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
292 void mangleUnscopedTemplateName(const TemplateDecl *ND);
294 mangleTemplateInstantiationName(const TemplateDecl *TD,
295 const TemplateArgumentList &TemplateArgs);
296 void mangleObjCMethodName(const ObjCMethodDecl *MD);
298 void mangleArgumentType(QualType T, SourceRange Range);
299 void manglePassObjectSizeArg(const PassObjectSizeAttr *POSA);
301 // Declare manglers for every type class.
302 #define ABSTRACT_TYPE(CLASS, PARENT)
303 #define NON_CANONICAL_TYPE(CLASS, PARENT)
304 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
307 #include "clang/AST/TypeNodes.def"
309 #undef NON_CANONICAL_TYPE
312 void mangleType(const TagDecl *TD);
313 void mangleDecayedArrayType(const ArrayType *T);
314 void mangleArrayType(const ArrayType *T);
315 void mangleFunctionClass(const FunctionDecl *FD);
316 void mangleCallingConvention(CallingConv CC);
317 void mangleCallingConvention(const FunctionType *T);
318 void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
319 void mangleExpression(const Expr *E);
320 void mangleThrowSpecification(const FunctionProtoType *T);
322 void mangleTemplateArgs(const TemplateDecl *TD,
323 const TemplateArgumentList &TemplateArgs);
324 void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
325 const NamedDecl *Parm);
329 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
330 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
331 LanguageLinkage L = FD->getLanguageLinkage();
332 // Overloadable functions need mangling.
333 if (FD->hasAttr<OverloadableAttr>())
336 // The ABI expects that we would never mangle "typical" user-defined entry
337 // points regardless of visibility or freestanding-ness.
339 // N.B. This is distinct from asking about "main". "main" has a lot of
340 // special rules associated with it in the standard while these
341 // user-defined entry points are outside of the purview of the standard.
342 // For example, there can be only one definition for "main" in a standards
343 // compliant program; however nothing forbids the existence of wmain and
344 // WinMain in the same translation unit.
345 if (FD->isMSVCRTEntryPoint())
348 // C++ functions and those whose names are not a simple identifier need
350 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
353 // C functions are not mangled.
354 if (L == CLanguageLinkage)
358 // Otherwise, no mangling is done outside C++ mode.
359 if (!getASTContext().getLangOpts().CPlusPlus)
362 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
363 // C variables are not mangled.
367 // Variables at global scope with non-internal linkage are not mangled.
368 const DeclContext *DC = getEffectiveDeclContext(D);
369 // Check for extern variable declared locally.
370 if (DC->isFunctionOrMethod() && D->hasLinkage())
371 while (!DC->isNamespace() && !DC->isTranslationUnit())
372 DC = getEffectiveParentContext(DC);
374 if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
375 !isa<VarTemplateSpecializationDecl>(D) &&
376 D->getIdentifier() != nullptr)
384 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
388 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
389 // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
390 // Therefore it's really important that we don't decorate the
391 // name with leading underscores or leading/trailing at signs. So, by
392 // default, we emit an asm marker at the start so we get the name right.
393 // Callers can override this with a custom prefix.
395 // <mangled-name> ::= ? <name> <type-encoding>
398 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
399 mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
400 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
401 mangleVariableEncoding(VD);
403 llvm_unreachable("Tried to mangle unexpected NamedDecl!");
406 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD,
408 // <type-encoding> ::= <function-class> <function-type>
410 // Since MSVC operates on the type as written and not the canonical type, it
411 // actually matters which decl we have here. MSVC appears to choose the
412 // first, since it is most likely to be the declaration in a header file.
413 FD = FD->getFirstDecl();
415 // We should never ever see a FunctionNoProtoType at this point.
416 // We don't even know how to mangle their types anyway :).
417 const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
419 // extern "C" functions can hold entities that must be mangled.
420 // As it stands, these functions still need to get expressed in the full
421 // external name. They have their class and type omitted, replaced with '9'.
423 // We would like to mangle all extern "C" functions using this additional
424 // component but this would break compatibility with MSVC's behavior.
425 // Instead, do this when we know that compatibility isn't important (in
426 // other words, when it is an overloaded extern "C" function).
427 if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
430 mangleFunctionClass(FD);
432 mangleFunctionType(FT, FD);
438 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
439 // <type-encoding> ::= <storage-class> <variable-type>
440 // <storage-class> ::= 0 # private static member
441 // ::= 1 # protected static member
442 // ::= 2 # public static member
444 // ::= 4 # static local
446 // The first character in the encoding (after the name) is the storage class.
447 if (VD->isStaticDataMember()) {
448 // If it's a static member, it also encodes the access level.
449 switch (VD->getAccess()) {
451 case AS_private: Out << '0'; break;
452 case AS_protected: Out << '1'; break;
453 case AS_public: Out << '2'; break;
456 else if (!VD->isStaticLocal())
460 // Now mangle the type.
461 // <variable-type> ::= <type> <cvr-qualifiers>
462 // ::= <type> <pointee-cvr-qualifiers> # pointers, references
463 // Pointers and references are odd. The type of 'int * const foo;' gets
464 // mangled as 'QAHA' instead of 'PAHB', for example.
465 SourceRange SR = VD->getSourceRange();
466 QualType Ty = VD->getType();
467 if (Ty->isPointerType() || Ty->isReferenceType() ||
468 Ty->isMemberPointerType()) {
469 mangleType(Ty, SR, QMM_Drop);
470 manglePointerExtQualifiers(
471 Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
472 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
473 mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
474 // Member pointers are suffixed with a back reference to the member
475 // pointer's class name.
476 mangleName(MPT->getClass()->getAsCXXRecordDecl());
478 mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
479 } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
480 // Global arrays are funny, too.
481 mangleDecayedArrayType(AT);
482 if (AT->getElementType()->isArrayType())
485 mangleQualifiers(Ty.getQualifiers(), false);
487 mangleType(Ty, SR, QMM_Drop);
488 mangleQualifiers(Ty.getQualifiers(), false);
492 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
493 const ValueDecl *VD) {
494 // <member-data-pointer> ::= <integer-literal>
495 // ::= $F <number> <number>
496 // ::= $G <number> <number> <number>
499 int64_t VBTableOffset;
500 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
502 FieldOffset = getASTContext().getFieldOffset(VD);
503 assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
504 "cannot take address of bitfield");
505 FieldOffset /= getASTContext().getCharWidth();
509 if (IM == MSInheritanceAttr::Keyword_virtual_inheritance)
510 FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
512 FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
519 case MSInheritanceAttr::Keyword_single_inheritance: Code = '0'; break;
520 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = '0'; break;
521 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'F'; break;
522 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
527 mangleNumber(FieldOffset);
529 // The C++ standard doesn't allow base-to-derived member pointer conversions
530 // in template parameter contexts, so the vbptr offset of data member pointers
532 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
534 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
535 mangleNumber(VBTableOffset);
539 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
540 const CXXMethodDecl *MD) {
541 // <member-function-pointer> ::= $1? <name>
542 // ::= $H? <name> <number>
543 // ::= $I? <name> <number> <number>
544 // ::= $J? <name> <number> <number> <number>
546 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
550 case MSInheritanceAttr::Keyword_single_inheritance: Code = '1'; break;
551 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = 'H'; break;
552 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'I'; break;
553 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
556 // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr
558 uint64_t NVOffset = 0;
559 uint64_t VBTableOffset = 0;
560 uint64_t VBPtrOffset = 0;
562 Out << '$' << Code << '?';
563 if (MD->isVirtual()) {
564 MicrosoftVTableContext *VTContext =
565 cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
566 const MicrosoftVTableContext::MethodVFTableLocation &ML =
567 VTContext->getMethodVFTableLocation(GlobalDecl(MD));
568 mangleVirtualMemPtrThunk(MD, ML);
569 NVOffset = ML.VFPtrOffset.getQuantity();
570 VBTableOffset = ML.VBTableIndex * 4;
572 const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
573 VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
577 mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
580 if (VBTableOffset == 0 &&
581 IM == MSInheritanceAttr::Keyword_virtual_inheritance)
582 NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
584 // Null single inheritance member functions are encoded as a simple nullptr.
585 if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
589 if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
594 if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
595 mangleNumber(static_cast<uint32_t>(NVOffset));
596 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
597 mangleNumber(VBPtrOffset);
598 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
599 mangleNumber(VBTableOffset);
602 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
603 const CXXMethodDecl *MD,
604 const MicrosoftVTableContext::MethodVFTableLocation &ML) {
605 // Get the vftable offset.
606 CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
607 getASTContext().getTargetInfo().getPointerWidth(0));
608 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
611 mangleName(MD->getParent());
613 mangleNumber(OffsetInVFTable);
615 mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>());
618 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
619 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
621 // Always start with the unqualified name.
622 mangleUnqualifiedName(ND);
624 mangleNestedName(ND);
626 // Terminate the whole name with an '@'.
630 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
631 // <non-negative integer> ::= A@ # when Number == 0
632 // ::= <decimal digit> # when 1 <= Number <= 10
633 // ::= <hex digit>+ @ # when Number >= 10
635 // <number> ::= [?] <non-negative integer>
637 uint64_t Value = static_cast<uint64_t>(Number);
645 else if (Value >= 1 && Value <= 10)
648 // Numbers that are not encoded as decimal digits are represented as nibbles
649 // in the range of ASCII characters 'A' to 'P'.
650 // The number 0x123450 would be encoded as 'BCDEFA'
651 char EncodedNumberBuffer[sizeof(uint64_t) * 2];
652 MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
653 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
654 for (; Value != 0; Value >>= 4)
655 *I++ = 'A' + (Value & 0xf);
656 Out.write(I.base(), I - BufferRef.rbegin());
661 static const TemplateDecl *
662 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
663 // Check if we have a function template.
664 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
665 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
666 TemplateArgs = FD->getTemplateSpecializationArgs();
671 // Check if we have a class template.
672 if (const ClassTemplateSpecializationDecl *Spec =
673 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
674 TemplateArgs = &Spec->getTemplateArgs();
675 return Spec->getSpecializedTemplate();
678 // Check if we have a variable template.
679 if (const VarTemplateSpecializationDecl *Spec =
680 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
681 TemplateArgs = &Spec->getTemplateArgs();
682 return Spec->getSpecializedTemplate();
688 void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
689 DeclarationName Name) {
690 // <unqualified-name> ::= <operator-name>
691 // ::= <ctor-dtor-name>
693 // ::= <template-name>
695 // Check if we have a template.
696 const TemplateArgumentList *TemplateArgs = nullptr;
697 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
698 // Function templates aren't considered for name back referencing. This
699 // makes sense since function templates aren't likely to occur multiple
700 // times in a symbol.
701 if (isa<FunctionTemplateDecl>(TD)) {
702 mangleTemplateInstantiationName(TD, *TemplateArgs);
707 // Here comes the tricky thing: if we need to mangle something like
708 // void foo(A::X<Y>, B::X<Y>),
709 // the X<Y> part is aliased. However, if you need to mangle
710 // void foo(A::X<A::Y>, A::X<B::Y>),
711 // the A::X<> part is not aliased.
712 // That said, from the mangler's perspective we have a structure like this:
713 // namespace[s] -> type[ -> template-parameters]
714 // but from the Clang perspective we have
715 // type [ -> template-parameters]
717 // What we do is we create a new mangler, mangle the same type (without
718 // a namespace suffix) to a string using the extra mangler and then use
719 // the mangled type name as a key to check the mangling of different types
722 llvm::SmallString<64> TemplateMangling;
723 llvm::raw_svector_ostream Stream(TemplateMangling);
724 MicrosoftCXXNameMangler Extra(Context, Stream);
725 Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
727 mangleSourceName(TemplateMangling);
731 switch (Name.getNameKind()) {
732 case DeclarationName::Identifier: {
733 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
734 mangleSourceName(II->getName());
738 // Otherwise, an anonymous entity. We must have a declaration.
739 assert(ND && "mangling empty name without declaration");
741 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
742 if (NS->isAnonymousNamespace()) {
748 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
749 // We must have an anonymous union or struct declaration.
750 const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
751 assert(RD && "expected variable decl to have a record type");
752 // Anonymous types with no tag or typedef get the name of their
753 // declarator mangled in. If they have no declarator, number them with
755 llvm::SmallString<64> Name("$S");
756 // Get a unique id for the anonymous struct.
757 Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
758 mangleSourceName(Name.str());
762 // We must have an anonymous struct.
763 const TagDecl *TD = cast<TagDecl>(ND);
764 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
765 assert(TD->getDeclContext() == D->getDeclContext() &&
766 "Typedef should not be in another decl context!");
767 assert(D->getDeclName().getAsIdentifierInfo() &&
768 "Typedef was not named!");
769 mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
773 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
774 if (Record->isLambda()) {
775 llvm::SmallString<10> Name("<lambda_");
777 if (Record->getLambdaManglingNumber())
778 LambdaId = Record->getLambdaManglingNumber();
780 LambdaId = Context.getLambdaId(Record);
782 Name += llvm::utostr(LambdaId);
785 mangleSourceName(Name);
790 llvm::SmallString<64> Name("<unnamed-type-");
791 if (DeclaratorDecl *DD =
792 Context.getASTContext().getDeclaratorForUnnamedTagDecl(TD)) {
793 // Anonymous types without a name for linkage purposes have their
794 // declarator mangled in if they have one.
795 Name += DD->getName();
796 } else if (TypedefNameDecl *TND =
797 Context.getASTContext().getTypedefNameForUnnamedTagDecl(
799 // Anonymous types without a name for linkage purposes have their
800 // associate typedef mangled in if they have one.
801 Name += TND->getName();
803 // Otherwise, number the types using a $S prefix.
805 Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1);
808 mangleSourceName(Name.str());
812 case DeclarationName::ObjCZeroArgSelector:
813 case DeclarationName::ObjCOneArgSelector:
814 case DeclarationName::ObjCMultiArgSelector:
815 llvm_unreachable("Can't mangle Objective-C selector names here!");
817 case DeclarationName::CXXConstructorName:
818 if (Structor == getStructor(ND)) {
819 if (StructorType == Ctor_CopyingClosure) {
823 if (StructorType == Ctor_DefaultClosure) {
831 case DeclarationName::CXXDestructorName:
833 // If the named decl is the C++ destructor we're mangling,
834 // use the type we were given.
835 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
837 // Otherwise, use the base destructor name. This is relevant if a
838 // class with a destructor is declared within a destructor.
839 mangleCXXDtorType(Dtor_Base);
842 case DeclarationName::CXXConversionFunctionName:
843 // <operator-name> ::= ?B # (cast)
844 // The target type is encoded as the return type.
848 case DeclarationName::CXXOperatorName:
849 mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
852 case DeclarationName::CXXLiteralOperatorName: {
854 mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
858 case DeclarationName::CXXUsingDirective:
859 llvm_unreachable("Can't mangle a using directive name!");
863 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
864 // <postfix> ::= <unqualified-name> [<postfix>]
865 // ::= <substitution> [<postfix>]
866 const DeclContext *DC = getEffectiveDeclContext(ND);
868 while (!DC->isTranslationUnit()) {
869 if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
871 if (Context.getNextDiscriminator(ND, Disc)) {
878 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
879 DiagnosticsEngine &Diags = Context.getDiags();
881 Diags.getCustomDiagID(DiagnosticsEngine::Error,
882 "cannot mangle a local inside this block yet");
883 Diags.Report(BD->getLocation(), DiagID);
885 // FIXME: This is completely, utterly, wrong; see ItaniumMangle
886 // for how this should be done.
887 Out << "__block_invoke" << Context.getBlockId(BD, false);
890 } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
891 mangleObjCMethodName(Method);
892 } else if (isa<NamedDecl>(DC)) {
893 ND = cast<NamedDecl>(DC);
894 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
898 mangleUnqualifiedName(ND);
900 DC = DC->getParent();
904 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
905 // Microsoft uses the names on the case labels for these dtor variants. Clang
906 // uses the Itanium terminology internally. Everything in this ABI delegates
907 // towards the base dtor.
909 // <operator-name> ::= ?1 # destructor
910 case Dtor_Base: Out << "?1"; return;
911 // <operator-name> ::= ?_D # vbase destructor
912 case Dtor_Complete: Out << "?_D"; return;
913 // <operator-name> ::= ?_G # scalar deleting destructor
914 case Dtor_Deleting: Out << "?_G"; return;
915 // <operator-name> ::= ?_E # vector deleting destructor
916 // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need
919 llvm_unreachable("not expecting a COMDAT");
921 llvm_unreachable("Unsupported dtor type?");
924 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
925 SourceLocation Loc) {
929 // <operator-name> ::= ?2 # new
930 case OO_New: Out << "?2"; break;
931 // <operator-name> ::= ?3 # delete
932 case OO_Delete: Out << "?3"; break;
933 // <operator-name> ::= ?4 # =
934 case OO_Equal: Out << "?4"; break;
935 // <operator-name> ::= ?5 # >>
936 case OO_GreaterGreater: Out << "?5"; break;
937 // <operator-name> ::= ?6 # <<
938 case OO_LessLess: Out << "?6"; break;
939 // <operator-name> ::= ?7 # !
940 case OO_Exclaim: Out << "?7"; break;
941 // <operator-name> ::= ?8 # ==
942 case OO_EqualEqual: Out << "?8"; break;
943 // <operator-name> ::= ?9 # !=
944 case OO_ExclaimEqual: Out << "?9"; break;
945 // <operator-name> ::= ?A # []
946 case OO_Subscript: Out << "?A"; break;
948 // <operator-name> ::= ?C # ->
949 case OO_Arrow: Out << "?C"; break;
950 // <operator-name> ::= ?D # *
951 case OO_Star: Out << "?D"; break;
952 // <operator-name> ::= ?E # ++
953 case OO_PlusPlus: Out << "?E"; break;
954 // <operator-name> ::= ?F # --
955 case OO_MinusMinus: Out << "?F"; break;
956 // <operator-name> ::= ?G # -
957 case OO_Minus: Out << "?G"; break;
958 // <operator-name> ::= ?H # +
959 case OO_Plus: Out << "?H"; break;
960 // <operator-name> ::= ?I # &
961 case OO_Amp: Out << "?I"; break;
962 // <operator-name> ::= ?J # ->*
963 case OO_ArrowStar: Out << "?J"; break;
964 // <operator-name> ::= ?K # /
965 case OO_Slash: Out << "?K"; break;
966 // <operator-name> ::= ?L # %
967 case OO_Percent: Out << "?L"; break;
968 // <operator-name> ::= ?M # <
969 case OO_Less: Out << "?M"; break;
970 // <operator-name> ::= ?N # <=
971 case OO_LessEqual: Out << "?N"; break;
972 // <operator-name> ::= ?O # >
973 case OO_Greater: Out << "?O"; break;
974 // <operator-name> ::= ?P # >=
975 case OO_GreaterEqual: Out << "?P"; break;
976 // <operator-name> ::= ?Q # ,
977 case OO_Comma: Out << "?Q"; break;
978 // <operator-name> ::= ?R # ()
979 case OO_Call: Out << "?R"; break;
980 // <operator-name> ::= ?S # ~
981 case OO_Tilde: Out << "?S"; break;
982 // <operator-name> ::= ?T # ^
983 case OO_Caret: Out << "?T"; break;
984 // <operator-name> ::= ?U # |
985 case OO_Pipe: Out << "?U"; break;
986 // <operator-name> ::= ?V # &&
987 case OO_AmpAmp: Out << "?V"; break;
988 // <operator-name> ::= ?W # ||
989 case OO_PipePipe: Out << "?W"; break;
990 // <operator-name> ::= ?X # *=
991 case OO_StarEqual: Out << "?X"; break;
992 // <operator-name> ::= ?Y # +=
993 case OO_PlusEqual: Out << "?Y"; break;
994 // <operator-name> ::= ?Z # -=
995 case OO_MinusEqual: Out << "?Z"; break;
996 // <operator-name> ::= ?_0 # /=
997 case OO_SlashEqual: Out << "?_0"; break;
998 // <operator-name> ::= ?_1 # %=
999 case OO_PercentEqual: Out << "?_1"; break;
1000 // <operator-name> ::= ?_2 # >>=
1001 case OO_GreaterGreaterEqual: Out << "?_2"; break;
1002 // <operator-name> ::= ?_3 # <<=
1003 case OO_LessLessEqual: Out << "?_3"; break;
1004 // <operator-name> ::= ?_4 # &=
1005 case OO_AmpEqual: Out << "?_4"; break;
1006 // <operator-name> ::= ?_5 # |=
1007 case OO_PipeEqual: Out << "?_5"; break;
1008 // <operator-name> ::= ?_6 # ^=
1009 case OO_CaretEqual: Out << "?_6"; break;
1014 // ?_B # local static guard
1016 // ?_D # vbase destructor
1017 // ?_E # vector deleting destructor
1018 // ?_F # default constructor closure
1019 // ?_G # scalar deleting destructor
1020 // ?_H # vector constructor iterator
1021 // ?_I # vector destructor iterator
1022 // ?_J # vector vbase constructor iterator
1023 // ?_K # virtual displacement map
1024 // ?_L # eh vector constructor iterator
1025 // ?_M # eh vector destructor iterator
1026 // ?_N # eh vector vbase constructor iterator
1027 // ?_O # copy constructor closure
1028 // ?_P<name> # udt returning <name>
1030 // ?_R0 # RTTI Type Descriptor
1031 // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
1032 // ?_R2 # RTTI Base Class Array
1033 // ?_R3 # RTTI Class Hierarchy Descriptor
1034 // ?_R4 # RTTI Complete Object Locator
1035 // ?_S # local vftable
1036 // ?_T # local vftable constructor closure
1037 // <operator-name> ::= ?_U # new[]
1038 case OO_Array_New: Out << "?_U"; break;
1039 // <operator-name> ::= ?_V # delete[]
1040 case OO_Array_Delete: Out << "?_V"; break;
1042 case OO_Conditional: {
1043 DiagnosticsEngine &Diags = Context.getDiags();
1044 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1045 "cannot mangle this conditional operator yet");
1046 Diags.Report(Loc, DiagID);
1051 DiagnosticsEngine &Diags = Context.getDiags();
1052 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1053 "cannot mangle this operator co_await yet");
1054 Diags.Report(Loc, DiagID);
1059 case NUM_OVERLOADED_OPERATORS:
1060 llvm_unreachable("Not an overloaded operator");
1064 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1065 // <source name> ::= <identifier> @
1066 BackRefVec::iterator Found =
1067 std::find(NameBackReferences.begin(), NameBackReferences.end(), Name);
1068 if (Found == NameBackReferences.end()) {
1069 if (NameBackReferences.size() < 10)
1070 NameBackReferences.push_back(Name);
1073 Out << (Found - NameBackReferences.begin());
1077 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1078 Context.mangleObjCMethodName(MD, Out);
1081 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1082 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1083 // <template-name> ::= <unscoped-template-name> <template-args>
1084 // ::= <substitution>
1085 // Always start with the unqualified name.
1087 // Templates have their own context for back references.
1088 ArgBackRefMap OuterArgsContext;
1089 BackRefVec OuterTemplateContext;
1090 PassObjectSizeArgsSet OuterPassObjectSizeArgs;
1091 NameBackReferences.swap(OuterTemplateContext);
1092 TypeBackReferences.swap(OuterArgsContext);
1093 PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1095 mangleUnscopedTemplateName(TD);
1096 mangleTemplateArgs(TD, TemplateArgs);
1098 // Restore the previous back reference contexts.
1099 NameBackReferences.swap(OuterTemplateContext);
1100 TypeBackReferences.swap(OuterArgsContext);
1101 PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1105 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1106 // <unscoped-template-name> ::= ?$ <unqualified-name>
1108 mangleUnqualifiedName(TD);
1111 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1113 // <integer-literal> ::= $0 <number>
1115 // Make sure booleans are encoded as 0/1.
1116 if (IsBoolean && Value.getBoolValue())
1118 else if (Value.isSigned())
1119 mangleNumber(Value.getSExtValue());
1121 mangleNumber(Value.getZExtValue());
1124 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1125 // See if this is a constant expression.
1127 if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1128 mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1132 // Look through no-op casts like template parameter substitutions.
1133 E = E->IgnoreParenNoopCasts(Context.getASTContext());
1135 const CXXUuidofExpr *UE = nullptr;
1136 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1137 if (UO->getOpcode() == UO_AddrOf)
1138 UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1140 UE = dyn_cast<CXXUuidofExpr>(E);
1143 // If we had to peek through an address-of operator, treat this like we are
1144 // dealing with a pointer type. Otherwise, treat it like a const reference.
1146 // N.B. This matches up with the handling of TemplateArgument::Declaration
1147 // in mangleTemplateArg
1153 // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1154 // const __s_GUID _GUID_{lower case UUID with underscores}
1155 StringRef Uuid = UE->getUuidAsStringRef(Context.getASTContext());
1156 std::string Name = "_GUID_" + Uuid.lower();
1157 std::replace(Name.begin(), Name.end(), '-', '_');
1159 mangleSourceName(Name);
1160 // Terminate the whole name with an '@'.
1162 // It's a global variable.
1164 // It's a struct called __s_GUID.
1165 mangleArtificalTagType(TTK_Struct, "__s_GUID");
1171 // As bad as this diagnostic is, it's better than crashing.
1172 DiagnosticsEngine &Diags = Context.getDiags();
1173 unsigned DiagID = Diags.getCustomDiagID(
1174 DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1175 Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1176 << E->getSourceRange();
1179 void MicrosoftCXXNameMangler::mangleTemplateArgs(
1180 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1181 // <template-args> ::= <template-arg>+
1182 const TemplateParameterList *TPL = TD->getTemplateParameters();
1183 assert(TPL->size() == TemplateArgs.size() &&
1184 "size mismatch between args and parms!");
1187 for (const TemplateArgument &TA : TemplateArgs.asArray())
1188 mangleTemplateArg(TD, TA, TPL->getParam(Idx++));
1191 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1192 const TemplateArgument &TA,
1193 const NamedDecl *Parm) {
1194 // <template-arg> ::= <type>
1195 // ::= <integer-literal>
1196 // ::= <member-data-pointer>
1197 // ::= <member-function-pointer>
1198 // ::= $E? <name> <type-encoding>
1199 // ::= $1? <name> <type-encoding>
1201 // ::= <template-args>
1203 switch (TA.getKind()) {
1204 case TemplateArgument::Null:
1205 llvm_unreachable("Can't mangle null template arguments!");
1206 case TemplateArgument::TemplateExpansion:
1207 llvm_unreachable("Can't mangle template expansion arguments!");
1208 case TemplateArgument::Type: {
1209 QualType T = TA.getAsType();
1210 mangleType(T, SourceRange(), QMM_Escape);
1213 case TemplateArgument::Declaration: {
1214 const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
1215 if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1216 mangleMemberDataPointer(
1217 cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
1218 cast<ValueDecl>(ND));
1219 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1220 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1221 if (MD && MD->isInstance()) {
1222 mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
1226 mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1229 mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
1233 case TemplateArgument::Integral:
1234 mangleIntegerLiteral(TA.getAsIntegral(),
1235 TA.getIntegralType()->isBooleanType());
1237 case TemplateArgument::NullPtr: {
1238 QualType T = TA.getNullPtrType();
1239 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1240 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1241 if (MPT->isMemberFunctionPointerType() &&
1242 !isa<FunctionTemplateDecl>(TD)) {
1243 mangleMemberFunctionPointer(RD, nullptr);
1246 if (MPT->isMemberDataPointer()) {
1247 if (!isa<FunctionTemplateDecl>(TD)) {
1248 mangleMemberDataPointer(RD, nullptr);
1251 // nullptr data pointers are always represented with a single field
1252 // which is initialized with either 0 or -1. Why -1? Well, we need to
1253 // distinguish the case where the data member is at offset zero in the
1255 // However, we are free to use 0 *if* we would use multiple fields for
1256 // non-nullptr member pointers.
1257 if (!RD->nullFieldOffsetIsZero()) {
1258 mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false);
1263 mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false);
1266 case TemplateArgument::Expression:
1267 mangleExpression(TA.getAsExpr());
1269 case TemplateArgument::Pack: {
1270 ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1271 if (TemplateArgs.empty()) {
1272 if (isa<TemplateTypeParmDecl>(Parm) ||
1273 isa<TemplateTemplateParmDecl>(Parm))
1274 // MSVC 2015 changed the mangling for empty expanded template packs,
1275 // use the old mangling for link compatibility for old versions.
1276 Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1277 LangOptions::MSVC2015)
1280 else if (isa<NonTypeTemplateParmDecl>(Parm))
1283 llvm_unreachable("unexpected template parameter decl!");
1285 for (const TemplateArgument &PA : TemplateArgs)
1286 mangleTemplateArg(TD, PA, Parm);
1290 case TemplateArgument::Template: {
1291 const NamedDecl *ND =
1292 TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
1293 if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1295 } else if (isa<TypeAliasDecl>(ND)) {
1299 llvm_unreachable("unexpected template template NamedDecl!");
1306 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1308 // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1309 // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1310 // 'I' means __restrict (32/64-bit).
1311 // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1313 // <base-cvr-qualifiers> ::= A # near
1314 // ::= B # near const
1315 // ::= C # near volatile
1316 // ::= D # near const volatile
1317 // ::= E # far (16-bit)
1318 // ::= F # far const (16-bit)
1319 // ::= G # far volatile (16-bit)
1320 // ::= H # far const volatile (16-bit)
1321 // ::= I # huge (16-bit)
1322 // ::= J # huge const (16-bit)
1323 // ::= K # huge volatile (16-bit)
1324 // ::= L # huge const volatile (16-bit)
1325 // ::= M <basis> # based
1326 // ::= N <basis> # based const
1327 // ::= O <basis> # based volatile
1328 // ::= P <basis> # based const volatile
1329 // ::= Q # near member
1330 // ::= R # near const member
1331 // ::= S # near volatile member
1332 // ::= T # near const volatile member
1333 // ::= U # far member (16-bit)
1334 // ::= V # far const member (16-bit)
1335 // ::= W # far volatile member (16-bit)
1336 // ::= X # far const volatile member (16-bit)
1337 // ::= Y # huge member (16-bit)
1338 // ::= Z # huge const member (16-bit)
1339 // ::= 0 # huge volatile member (16-bit)
1340 // ::= 1 # huge const volatile member (16-bit)
1341 // ::= 2 <basis> # based member
1342 // ::= 3 <basis> # based const member
1343 // ::= 4 <basis> # based volatile member
1344 // ::= 5 <basis> # based const volatile member
1345 // ::= 6 # near function (pointers only)
1346 // ::= 7 # far function (pointers only)
1347 // ::= 8 # near method (pointers only)
1348 // ::= 9 # far method (pointers only)
1349 // ::= _A <basis> # based function (pointers only)
1350 // ::= _B <basis> # based function (far?) (pointers only)
1351 // ::= _C <basis> # based method (pointers only)
1352 // ::= _D <basis> # based method (far?) (pointers only)
1353 // ::= _E # block (Clang)
1354 // <basis> ::= 0 # __based(void)
1355 // ::= 1 # __based(segment)?
1356 // ::= 2 <name> # __based(name)
1359 // ::= 5 # not really based
1360 bool HasConst = Quals.hasConst(),
1361 HasVolatile = Quals.hasVolatile();
1364 if (HasConst && HasVolatile) {
1366 } else if (HasVolatile) {
1368 } else if (HasConst) {
1374 if (HasConst && HasVolatile) {
1376 } else if (HasVolatile) {
1378 } else if (HasConst) {
1385 // FIXME: For now, just drop all extension qualifiers on the floor.
1389 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1390 // <ref-qualifier> ::= G # lvalue reference
1391 // ::= H # rvalue-reference
1392 switch (RefQualifier) {
1406 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1407 QualType PointeeType) {
1408 bool HasRestrict = Quals.hasRestrict();
1409 if (PointersAre64Bit &&
1410 (PointeeType.isNull() || !PointeeType->isFunctionType()))
1417 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1418 // <pointer-cv-qualifiers> ::= P # no qualifiers
1421 // ::= S # const volatile
1422 bool HasConst = Quals.hasConst(),
1423 HasVolatile = Quals.hasVolatile();
1425 if (HasConst && HasVolatile) {
1427 } else if (HasVolatile) {
1429 } else if (HasConst) {
1436 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1437 SourceRange Range) {
1438 // MSVC will backreference two canonically equivalent types that have slightly
1439 // different manglings when mangled alone.
1441 // Decayed types do not match up with non-decayed versions of the same type.
1444 // void (*x)(void) will not form a backreference with void x(void)
1446 if (const auto *DT = T->getAs<DecayedType>()) {
1447 QualType OriginalType = DT->getOriginalType();
1448 // All decayed ArrayTypes should be treated identically; as-if they were
1449 // a decayed IncompleteArrayType.
1450 if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
1451 OriginalType = getASTContext().getIncompleteArrayType(
1452 AT->getElementType(), AT->getSizeModifier(),
1453 AT->getIndexTypeCVRQualifiers());
1455 TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
1456 // If the original parameter was textually written as an array,
1457 // instead treat the decayed parameter like it's const.
1460 // int [] -> int * const
1461 if (OriginalType->isArrayType())
1464 TypePtr = T.getCanonicalType().getAsOpaquePtr();
1467 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1469 if (Found == TypeBackReferences.end()) {
1470 size_t OutSizeBefore = Out.tell();
1472 mangleType(T, Range, QMM_Drop);
1474 // See if it's worth creating a back reference.
1475 // Only types longer than 1 character are considered
1476 // and only 10 back references slots are available:
1477 bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
1478 if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1479 size_t Size = TypeBackReferences.size();
1480 TypeBackReferences[TypePtr] = Size;
1483 Out << Found->second;
1487 void MicrosoftCXXNameMangler::manglePassObjectSizeArg(
1488 const PassObjectSizeAttr *POSA) {
1489 int Type = POSA->getType();
1491 auto Iter = PassObjectSizeArgs.insert(Type).first;
1492 void *TypePtr = (void *)&*Iter;
1493 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1495 if (Found == TypeBackReferences.end()) {
1496 mangleArtificalTagType(TTK_Enum, "__pass_object_size" + llvm::utostr(Type),
1499 if (TypeBackReferences.size() < 10) {
1500 size_t Size = TypeBackReferences.size();
1501 TypeBackReferences[TypePtr] = Size;
1504 Out << Found->second;
1508 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1509 QualifierMangleMode QMM) {
1510 // Don't use the canonical types. MSVC includes things like 'const' on
1511 // pointer arguments to function pointers that canonicalization strips away.
1512 T = T.getDesugaredType(getASTContext());
1513 Qualifiers Quals = T.getLocalQualifiers();
1514 if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1515 // If there were any Quals, getAsArrayType() pushed them onto the array
1517 if (QMM == QMM_Mangle)
1519 else if (QMM == QMM_Escape || QMM == QMM_Result)
1521 mangleArrayType(AT);
1525 bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1526 T->isReferenceType() || T->isBlockPointerType();
1532 if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1534 mangleFunctionType(FT);
1537 mangleQualifiers(Quals, false);
1540 if (!IsPointer && Quals) {
1542 mangleQualifiers(Quals, false);
1546 if ((!IsPointer && Quals) || isa<TagType>(T)) {
1548 mangleQualifiers(Quals, false);
1553 const Type *ty = T.getTypePtr();
1555 switch (ty->getTypeClass()) {
1556 #define ABSTRACT_TYPE(CLASS, PARENT)
1557 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1559 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1561 #define TYPE(CLASS, PARENT) \
1563 mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1565 #include "clang/AST/TypeNodes.def"
1566 #undef ABSTRACT_TYPE
1567 #undef NON_CANONICAL_TYPE
1572 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1573 SourceRange Range) {
1574 // <type> ::= <builtin-type>
1575 // <builtin-type> ::= X # void
1576 // ::= C # signed char
1578 // ::= E # unsigned char
1580 // ::= G # unsigned short (or wchar_t if it's not a builtin)
1582 // ::= I # unsigned int
1584 // ::= K # unsigned long
1588 // ::= O # long double (__float80 is mangled differently)
1589 // ::= _J # long long, __int64
1590 // ::= _K # unsigned long long, __int64
1591 // ::= _L # __int128
1592 // ::= _M # unsigned __int128
1594 // _O # <array in parameter>
1595 // ::= _T # __float80 (Intel)
1597 // ::= _Z # __float80 (Digital Mars)
1598 switch (T->getKind()) {
1599 case BuiltinType::Void:
1602 case BuiltinType::SChar:
1605 case BuiltinType::Char_U:
1606 case BuiltinType::Char_S:
1609 case BuiltinType::UChar:
1612 case BuiltinType::Short:
1615 case BuiltinType::UShort:
1618 case BuiltinType::Int:
1621 case BuiltinType::UInt:
1624 case BuiltinType::Long:
1627 case BuiltinType::ULong:
1630 case BuiltinType::Float:
1633 case BuiltinType::Double:
1636 // TODO: Determine size and mangle accordingly
1637 case BuiltinType::LongDouble:
1640 case BuiltinType::LongLong:
1643 case BuiltinType::ULongLong:
1646 case BuiltinType::Int128:
1649 case BuiltinType::UInt128:
1652 case BuiltinType::Bool:
1655 case BuiltinType::Char16:
1658 case BuiltinType::Char32:
1661 case BuiltinType::WChar_S:
1662 case BuiltinType::WChar_U:
1666 #define BUILTIN_TYPE(Id, SingletonId)
1667 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1668 case BuiltinType::Id:
1669 #include "clang/AST/BuiltinTypes.def"
1670 case BuiltinType::Dependent:
1671 llvm_unreachable("placeholder types shouldn't get to name mangling");
1673 case BuiltinType::ObjCId:
1675 mangleArtificalTagType(TTK_Struct, "objc_object");
1677 case BuiltinType::ObjCClass:
1679 mangleArtificalTagType(TTK_Struct, "objc_class");
1681 case BuiltinType::ObjCSel:
1683 mangleArtificalTagType(TTK_Struct, "objc_selector");
1686 case BuiltinType::OCLImage1d:
1688 mangleArtificalTagType(TTK_Struct, "ocl_image1d");
1690 case BuiltinType::OCLImage1dArray:
1692 mangleArtificalTagType(TTK_Struct, "ocl_image1darray");
1694 case BuiltinType::OCLImage1dBuffer:
1696 mangleArtificalTagType(TTK_Struct, "ocl_image1dbuffer");
1698 case BuiltinType::OCLImage2d:
1700 mangleArtificalTagType(TTK_Struct, "ocl_image2d");
1702 case BuiltinType::OCLImage2dArray:
1704 mangleArtificalTagType(TTK_Struct, "ocl_image2darray");
1706 case BuiltinType::OCLImage2dDepth:
1708 mangleArtificalTagType(TTK_Struct, "ocl_image2ddepth");
1710 case BuiltinType::OCLImage2dArrayDepth:
1712 mangleArtificalTagType(TTK_Struct, "ocl_image2darraydepth");
1714 case BuiltinType::OCLImage2dMSAA:
1716 mangleArtificalTagType(TTK_Struct, "ocl_image2dmsaa");
1718 case BuiltinType::OCLImage2dArrayMSAA:
1720 mangleArtificalTagType(TTK_Struct, "ocl_image2darraymsaa");
1722 case BuiltinType::OCLImage2dMSAADepth:
1724 mangleArtificalTagType(TTK_Struct, "ocl_image2dmsaadepth");
1726 case BuiltinType::OCLImage2dArrayMSAADepth:
1728 mangleArtificalTagType(TTK_Struct, "ocl_image2darraymsaadepth");
1730 case BuiltinType::OCLImage3d:
1732 mangleArtificalTagType(TTK_Struct, "ocl_image3d");
1734 case BuiltinType::OCLSampler:
1736 mangleArtificalTagType(TTK_Struct, "ocl_sampler");
1738 case BuiltinType::OCLEvent:
1740 mangleArtificalTagType(TTK_Struct, "ocl_event");
1742 case BuiltinType::OCLClkEvent:
1744 mangleArtificalTagType(TTK_Struct, "ocl_clkevent");
1746 case BuiltinType::OCLQueue:
1748 mangleArtificalTagType(TTK_Struct, "ocl_queue");
1750 case BuiltinType::OCLNDRange:
1752 mangleArtificalTagType(TTK_Struct, "ocl_ndrange");
1754 case BuiltinType::OCLReserveID:
1756 mangleArtificalTagType(TTK_Struct, "ocl_reserveid");
1759 case BuiltinType::NullPtr:
1763 case BuiltinType::Half: {
1764 DiagnosticsEngine &Diags = Context.getDiags();
1765 unsigned DiagID = Diags.getCustomDiagID(
1766 DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
1767 Diags.Report(Range.getBegin(), DiagID)
1768 << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
1774 // <type> ::= <function-type>
1775 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
1777 // Structors only appear in decls, so at this point we know it's not a
1779 // FIXME: This may not be lambda-friendly.
1780 if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
1782 mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
1785 mangleFunctionType(T);
1788 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1789 Qualifiers, SourceRange) {
1791 mangleFunctionType(T);
1794 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
1795 const FunctionDecl *D,
1796 bool ForceThisQuals) {
1797 // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1798 // <return-type> <argument-list> <throw-spec>
1799 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
1802 if (D) Range = D->getSourceRange();
1804 bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
1805 CallingConv CC = T->getCallConv();
1806 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1807 if (MD->isInstance())
1808 HasThisQuals = true;
1809 if (isa<CXXDestructorDecl>(MD)) {
1811 } else if (isa<CXXConstructorDecl>(MD)) {
1813 IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
1814 StructorType == Ctor_DefaultClosure) &&
1815 getStructor(MD) == Structor;
1817 CC = getASTContext().getDefaultCallingConvention(
1818 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1822 // If this is a C++ instance method, mangle the CVR qualifiers for the
1825 Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
1826 manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
1827 mangleRefQualifier(Proto->getRefQualifier());
1828 mangleQualifiers(Quals, /*IsMember=*/false);
1831 mangleCallingConvention(CC);
1833 // <return-type> ::= <type>
1834 // ::= @ # structors (they have no declared return type)
1836 if (isa<CXXDestructorDecl>(D) && D == Structor &&
1837 StructorType == Dtor_Deleting) {
1838 // The scalar deleting destructor takes an extra int argument.
1839 // However, the FunctionType generated has 0 arguments.
1840 // FIXME: This is a temporary hack.
1841 // Maybe should fix the FunctionType creation instead?
1842 Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
1845 if (IsCtorClosure) {
1846 // Default constructor closure and copy constructor closure both return
1850 if (StructorType == Ctor_DefaultClosure) {
1851 // Default constructor closure always has no arguments.
1853 } else if (StructorType == Ctor_CopyingClosure) {
1854 // Copy constructor closure always takes an unqualified reference.
1855 mangleArgumentType(getASTContext().getLValueReferenceType(
1856 Proto->getParamType(0)
1857 ->getAs<LValueReferenceType>()
1859 /*SpelledAsLValue=*/true),
1863 llvm_unreachable("unexpected constructor closure!");
1870 QualType ResultType = T->getReturnType();
1871 if (const auto *AT =
1872 dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
1874 mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
1876 assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
1877 "shouldn't need to mangle __auto_type!");
1878 mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
1881 if (ResultType->isVoidType())
1882 ResultType = ResultType.getUnqualifiedType();
1883 mangleType(ResultType, Range, QMM_Result);
1887 // <argument-list> ::= X # void
1889 // ::= <type>* Z # varargs
1891 // Function types without prototypes can arise when mangling a function type
1892 // within an overloadable function in C. We mangle these as the absence of
1893 // any parameter types (not even an empty parameter list).
1895 } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
1898 // Happens for function pointer type arguments for example.
1899 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
1900 mangleArgumentType(Proto->getParamType(I), Range);
1901 // Mangle each pass_object_size parameter as if it's a paramater of enum
1902 // type passed directly after the parameter with the pass_object_size
1903 // attribute. The aforementioned enum's name is __pass_object_size, and we
1904 // pretend it resides in a top-level namespace called __clang.
1906 // FIXME: Is there a defined extension notation for the MS ABI, or is it
1907 // necessary to just cross our fingers and hope this type+namespace
1908 // combination doesn't conflict with anything?
1910 if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
1911 manglePassObjectSizeArg(P);
1913 // <builtin-type> ::= Z # ellipsis
1914 if (Proto->isVariadic())
1920 mangleThrowSpecification(Proto);
1923 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1924 // <function-class> ::= <member-function> E? # E designates a 64-bit 'this'
1925 // # pointer. in 64-bit mode *all*
1926 // # 'this' pointers are 64-bit.
1927 // ::= <global-function>
1928 // <member-function> ::= A # private: near
1929 // ::= B # private: far
1930 // ::= C # private: static near
1931 // ::= D # private: static far
1932 // ::= E # private: virtual near
1933 // ::= F # private: virtual far
1934 // ::= I # protected: near
1935 // ::= J # protected: far
1936 // ::= K # protected: static near
1937 // ::= L # protected: static far
1938 // ::= M # protected: virtual near
1939 // ::= N # protected: virtual far
1940 // ::= Q # public: near
1941 // ::= R # public: far
1942 // ::= S # public: static near
1943 // ::= T # public: static far
1944 // ::= U # public: virtual near
1945 // ::= V # public: virtual far
1946 // <global-function> ::= Y # global near
1947 // ::= Z # global far
1948 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1949 switch (MD->getAccess()) {
1951 llvm_unreachable("Unsupported access specifier");
1955 else if (MD->isVirtual())
1963 else if (MD->isVirtual())
1971 else if (MD->isVirtual())
1980 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
1981 // <calling-convention> ::= A # __cdecl
1982 // ::= B # __export __cdecl
1984 // ::= D # __export __pascal
1985 // ::= E # __thiscall
1986 // ::= F # __export __thiscall
1987 // ::= G # __stdcall
1988 // ::= H # __export __stdcall
1989 // ::= I # __fastcall
1990 // ::= J # __export __fastcall
1991 // ::= Q # __vectorcall
1992 // The 'export' calling conventions are from a bygone era
1993 // (*cough*Win16*cough*) when functions were declared for export with
1994 // that keyword. (It didn't actually export them, it just made them so
1995 // that they could be in a DLL and somebody from another module could call
2000 llvm_unreachable("Unsupported CC for mangling");
2001 case CC_X86_64Win64:
2003 case CC_C: Out << 'A'; break;
2004 case CC_X86Pascal: Out << 'C'; break;
2005 case CC_X86ThisCall: Out << 'E'; break;
2006 case CC_X86StdCall: Out << 'G'; break;
2007 case CC_X86FastCall: Out << 'I'; break;
2008 case CC_X86VectorCall: Out << 'Q'; break;
2011 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2012 mangleCallingConvention(T->getCallConv());
2014 void MicrosoftCXXNameMangler::mangleThrowSpecification(
2015 const FunctionProtoType *FT) {
2016 // <throw-spec> ::= Z # throw(...) (default)
2017 // ::= @ # throw() or __declspec/__attribute__((nothrow))
2019 // NOTE: Since the Microsoft compiler ignores throw specifications, they are
2020 // all actually mangled as 'Z'. (They're ignored because their associated
2021 // functionality isn't implemented, and probably never will be.)
2025 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2026 Qualifiers, SourceRange Range) {
2027 // Probably should be mangled as a template instantiation; need to see what
2029 DiagnosticsEngine &Diags = Context.getDiags();
2030 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2031 "cannot mangle this unresolved dependent type yet");
2032 Diags.Report(Range.getBegin(), DiagID)
2036 // <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2037 // <union-type> ::= T <name>
2038 // <struct-type> ::= U <name>
2039 // <class-type> ::= V <name>
2040 // <enum-type> ::= W4 <name>
2041 void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2058 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2060 mangleType(cast<TagType>(T)->getDecl());
2062 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2064 mangleType(cast<TagType>(T)->getDecl());
2066 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2067 mangleTagTypeKind(TD->getTagKind());
2070 void MicrosoftCXXNameMangler::mangleArtificalTagType(
2071 TagTypeKind TK, StringRef UnqualifiedName, ArrayRef<StringRef> NestedNames) {
2072 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2073 mangleTagTypeKind(TK);
2075 // Always start with the unqualified name.
2076 mangleSourceName(UnqualifiedName);
2078 for (auto I = NestedNames.rbegin(), E = NestedNames.rend(); I != E; ++I)
2079 mangleSourceName(*I);
2081 // Terminate the whole name with an '@'.
2085 // <type> ::= <array-type>
2086 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2087 // [Y <dimension-count> <dimension>+]
2088 // <element-type> # as global, E is never required
2089 // It's supposed to be the other way around, but for some strange reason, it
2090 // isn't. Today this behavior is retained for the sole purpose of backwards
2092 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2093 // This isn't a recursive mangling, so now we have to do it all in this
2095 manglePointerCVQualifiers(T->getElementType().getQualifiers());
2096 mangleType(T->getElementType(), SourceRange());
2098 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2100 llvm_unreachable("Should have been special cased");
2102 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2104 llvm_unreachable("Should have been special cased");
2106 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2107 Qualifiers, SourceRange) {
2108 llvm_unreachable("Should have been special cased");
2110 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2111 Qualifiers, SourceRange) {
2112 llvm_unreachable("Should have been special cased");
2114 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2115 QualType ElementTy(T, 0);
2116 SmallVector<llvm::APInt, 3> Dimensions;
2118 if (ElementTy->isConstantArrayType()) {
2119 const ConstantArrayType *CAT =
2120 getASTContext().getAsConstantArrayType(ElementTy);
2121 Dimensions.push_back(CAT->getSize());
2122 ElementTy = CAT->getElementType();
2123 } else if (ElementTy->isIncompleteArrayType()) {
2124 const IncompleteArrayType *IAT =
2125 getASTContext().getAsIncompleteArrayType(ElementTy);
2126 Dimensions.push_back(llvm::APInt(32, 0));
2127 ElementTy = IAT->getElementType();
2128 } else if (ElementTy->isVariableArrayType()) {
2129 const VariableArrayType *VAT =
2130 getASTContext().getAsVariableArrayType(ElementTy);
2131 Dimensions.push_back(llvm::APInt(32, 0));
2132 ElementTy = VAT->getElementType();
2133 } else if (ElementTy->isDependentSizedArrayType()) {
2134 // The dependent expression has to be folded into a constant (TODO).
2135 const DependentSizedArrayType *DSAT =
2136 getASTContext().getAsDependentSizedArrayType(ElementTy);
2137 DiagnosticsEngine &Diags = Context.getDiags();
2138 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2139 "cannot mangle this dependent-length array yet");
2140 Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2141 << DSAT->getBracketsRange();
2148 // <dimension-count> ::= <number> # number of extra dimensions
2149 mangleNumber(Dimensions.size());
2150 for (const llvm::APInt &Dimension : Dimensions)
2151 mangleNumber(Dimension.getLimitedValue());
2152 mangleType(ElementTy, SourceRange(), QMM_Escape);
2155 // <type> ::= <pointer-to-member-type>
2156 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2157 // <class name> <type>
2158 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, Qualifiers Quals,
2159 SourceRange Range) {
2160 QualType PointeeType = T->getPointeeType();
2161 manglePointerCVQualifiers(Quals);
2162 manglePointerExtQualifiers(Quals, PointeeType);
2163 if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2165 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2166 mangleFunctionType(FPT, nullptr, true);
2168 mangleQualifiers(PointeeType.getQualifiers(), true);
2169 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2170 mangleType(PointeeType, Range, QMM_Drop);
2174 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2175 Qualifiers, SourceRange Range) {
2176 DiagnosticsEngine &Diags = Context.getDiags();
2177 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2178 "cannot mangle this template type parameter type yet");
2179 Diags.Report(Range.getBegin(), DiagID)
2183 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2184 Qualifiers, SourceRange Range) {
2185 DiagnosticsEngine &Diags = Context.getDiags();
2186 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2187 "cannot mangle this substituted parameter pack yet");
2188 Diags.Report(Range.getBegin(), DiagID)
2192 // <type> ::= <pointer-type>
2193 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2194 // # the E is required for 64-bit non-static pointers
2195 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2196 SourceRange Range) {
2197 QualType PointeeType = T->getPointeeType();
2198 manglePointerCVQualifiers(Quals);
2199 manglePointerExtQualifiers(Quals, PointeeType);
2200 mangleType(PointeeType, Range);
2202 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2203 Qualifiers Quals, SourceRange Range) {
2204 QualType PointeeType = T->getPointeeType();
2205 manglePointerCVQualifiers(Quals);
2206 manglePointerExtQualifiers(Quals, PointeeType);
2207 // Object pointers never have qualifiers.
2209 mangleType(PointeeType, Range);
2212 // <type> ::= <reference-type>
2213 // <reference-type> ::= A E? <cvr-qualifiers> <type>
2214 // # the E is required for 64-bit non-static lvalue references
2215 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
2216 Qualifiers Quals, SourceRange Range) {
2217 QualType PointeeType = T->getPointeeType();
2218 Out << (Quals.hasVolatile() ? 'B' : 'A');
2219 manglePointerExtQualifiers(Quals, PointeeType);
2220 mangleType(PointeeType, Range);
2223 // <type> ::= <r-value-reference-type>
2224 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
2225 // # the E is required for 64-bit non-static rvalue references
2226 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2227 Qualifiers Quals, SourceRange Range) {
2228 QualType PointeeType = T->getPointeeType();
2229 Out << (Quals.hasVolatile() ? "$$R" : "$$Q");
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 MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2433 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2434 "Invalid mangleName() call, argument is not a variable or function!");
2435 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2436 "Invalid mangleName() call on 'structor decl!");
2438 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2439 getASTContext().getSourceManager(),
2440 "Mangling declaration");
2442 MicrosoftCXXNameMangler Mangler(*this, Out);
2443 return Mangler.mangle(D);
2446 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2447 // <virtual-adjustment>
2448 // <no-adjustment> ::= A # private near
2449 // ::= B # private far
2450 // ::= I # protected near
2451 // ::= J # protected far
2452 // ::= Q # public near
2453 // ::= R # public far
2454 // <static-adjustment> ::= G <static-offset> # private near
2455 // ::= H <static-offset> # private far
2456 // ::= O <static-offset> # protected near
2457 // ::= P <static-offset> # protected far
2458 // ::= W <static-offset> # public near
2459 // ::= X <static-offset> # public far
2460 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2461 // ::= $1 <virtual-shift> <static-offset> # private far
2462 // ::= $2 <virtual-shift> <static-offset> # protected near
2463 // ::= $3 <virtual-shift> <static-offset> # protected far
2464 // ::= $4 <virtual-shift> <static-offset> # public near
2465 // ::= $5 <virtual-shift> <static-offset> # public far
2466 // <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift>
2467 // <vtordisp-shift> ::= <offset-to-vtordisp>
2468 // <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset>
2469 // <offset-to-vtordisp>
2470 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2471 const ThisAdjustment &Adjustment,
2472 MicrosoftCXXNameMangler &Mangler,
2474 if (!Adjustment.Virtual.isEmpty()) {
2477 switch (MD->getAccess()) {
2479 llvm_unreachable("Unsupported access specifier");
2489 if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2490 Out << 'R' << AccessSpec;
2491 Mangler.mangleNumber(
2492 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2493 Mangler.mangleNumber(
2494 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2495 Mangler.mangleNumber(
2496 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2497 Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2500 Mangler.mangleNumber(
2501 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2502 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2504 } else if (Adjustment.NonVirtual != 0) {
2505 switch (MD->getAccess()) {
2507 llvm_unreachable("Unsupported access specifier");
2517 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2519 switch (MD->getAccess()) {
2521 llvm_unreachable("Unsupported access specifier");
2535 MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
2537 MicrosoftVTableContext *VTContext =
2538 cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
2539 const MicrosoftVTableContext::MethodVFTableLocation &ML =
2540 VTContext->getMethodVFTableLocation(GlobalDecl(MD));
2542 MicrosoftCXXNameMangler Mangler(*this, Out);
2543 Mangler.getStream() << "\01?";
2544 Mangler.mangleVirtualMemPtrThunk(MD, ML);
2547 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2548 const ThunkInfo &Thunk,
2550 MicrosoftCXXNameMangler Mangler(*this, Out);
2552 Mangler.mangleName(MD);
2553 mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
2554 if (!Thunk.Return.isEmpty())
2555 assert(Thunk.Method != nullptr &&
2556 "Thunk info should hold the overridee decl");
2558 const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2559 Mangler.mangleFunctionType(
2560 DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
2563 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2564 const CXXDestructorDecl *DD, CXXDtorType Type,
2565 const ThisAdjustment &Adjustment, raw_ostream &Out) {
2566 // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2567 // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2568 // mangling manually until we support both deleting dtor types.
2569 assert(Type == Dtor_Deleting);
2570 MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
2572 Mangler.mangleName(DD->getParent());
2573 mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
2574 Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
2577 void MicrosoftMangleContextImpl::mangleCXXVFTable(
2578 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2580 // <mangled-name> ::= ?_7 <class-name> <storage-class>
2581 // <cvr-qualifiers> [<name>] @
2582 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2583 // is always '6' for vftables.
2584 MicrosoftCXXNameMangler Mangler(*this, Out);
2585 Mangler.getStream() << "\01??_7";
2586 Mangler.mangleName(Derived);
2587 Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2588 for (const CXXRecordDecl *RD : BasePath)
2589 Mangler.mangleName(RD);
2590 Mangler.getStream() << '@';
2593 void MicrosoftMangleContextImpl::mangleCXXVBTable(
2594 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2596 // <mangled-name> ::= ?_8 <class-name> <storage-class>
2597 // <cvr-qualifiers> [<name>] @
2598 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2599 // is always '7' for vbtables.
2600 MicrosoftCXXNameMangler Mangler(*this, Out);
2601 Mangler.getStream() << "\01??_8";
2602 Mangler.mangleName(Derived);
2603 Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const.
2604 for (const CXXRecordDecl *RD : BasePath)
2605 Mangler.mangleName(RD);
2606 Mangler.getStream() << '@';
2609 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
2610 MicrosoftCXXNameMangler Mangler(*this, Out);
2611 Mangler.getStream() << "\01??_R0";
2612 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2613 Mangler.getStream() << "@8";
2616 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
2618 MicrosoftCXXNameMangler Mangler(*this, Out);
2619 Mangler.getStream() << '.';
2620 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2623 void MicrosoftMangleContextImpl::mangleCXXCatchHandlerType(QualType T,
2626 MicrosoftCXXNameMangler Mangler(*this, Out);
2627 Mangler.getStream() << "llvm.eh.handlertype.";
2628 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2629 Mangler.getStream() << '.' << Flags;
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);