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"
32 using namespace clang;
36 /// \brief Retrieve the declaration context that should be used when mangling
37 /// the given declaration.
38 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
39 // The ABI assumes that lambda closure types that occur within
40 // default arguments live in the context of the function. However, due to
41 // the way in which Clang parses and creates function declarations, this is
42 // not the case: the lambda closure type ends up living in the context
43 // where the function itself resides, because the function declaration itself
44 // had not yet been created. Fix the context here.
45 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
47 if (ParmVarDecl *ContextParam =
48 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
49 return ContextParam->getDeclContext();
52 // Perform the same check for block literals.
53 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
54 if (ParmVarDecl *ContextParam =
55 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
56 return ContextParam->getDeclContext();
59 const DeclContext *DC = D->getDeclContext();
60 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
61 return getEffectiveDeclContext(CD);
66 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
67 return getEffectiveDeclContext(cast<Decl>(DC));
70 static const FunctionDecl *getStructor(const NamedDecl *ND) {
71 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
72 return FTD->getTemplatedDecl();
74 const auto *FD = cast<FunctionDecl>(ND);
75 if (const auto *FTD = FD->getPrimaryTemplate())
76 return FTD->getTemplatedDecl();
81 static bool isLambda(const NamedDecl *ND) {
82 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
86 return Record->isLambda();
89 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
90 /// Microsoft Visual C++ ABI.
91 class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
92 typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
93 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
94 llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
95 llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
96 llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds;
97 llvm::DenseMap<const NamedDecl *, unsigned> SEHFinallyIds;
100 MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags)
101 : MicrosoftMangleContext(Context, Diags) {}
102 bool shouldMangleCXXName(const NamedDecl *D) override;
103 bool shouldMangleStringLiteral(const StringLiteral *SL) override;
104 void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
105 void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
106 raw_ostream &) override;
107 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
108 raw_ostream &) override;
109 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
110 const ThisAdjustment &ThisAdjustment,
111 raw_ostream &) override;
112 void mangleCXXVFTable(const CXXRecordDecl *Derived,
113 ArrayRef<const CXXRecordDecl *> BasePath,
114 raw_ostream &Out) override;
115 void mangleCXXVBTable(const CXXRecordDecl *Derived,
116 ArrayRef<const CXXRecordDecl *> BasePath,
117 raw_ostream &Out) override;
118 void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
119 uint32_t NumEntries, raw_ostream &Out) override;
120 void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
121 raw_ostream &Out) override;
122 void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
123 CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
124 int32_t VBPtrOffset, uint32_t VBIndex,
125 raw_ostream &Out) override;
126 void mangleCXXCatchHandlerType(QualType T, uint32_t Flags,
127 raw_ostream &Out) override;
128 void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
129 void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
130 void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
131 uint32_t NVOffset, int32_t VBPtrOffset,
132 uint32_t VBTableOffset, uint32_t Flags,
133 raw_ostream &Out) override;
134 void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
135 raw_ostream &Out) override;
136 void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
137 raw_ostream &Out) override;
139 mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
140 ArrayRef<const CXXRecordDecl *> BasePath,
141 raw_ostream &Out) override;
142 void mangleTypeName(QualType T, raw_ostream &) override;
143 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
144 raw_ostream &) override;
145 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
146 raw_ostream &) override;
147 void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
148 raw_ostream &) override;
149 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
150 void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
151 raw_ostream &Out) override;
152 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
153 void mangleDynamicAtExitDestructor(const VarDecl *D,
154 raw_ostream &Out) override;
155 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
156 raw_ostream &Out) override;
157 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
158 raw_ostream &Out) override;
159 void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
160 void mangleCXXVTableBitSet(const CXXRecordDecl *RD,
161 raw_ostream &Out) override;
162 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
163 // Lambda closure types are already numbered.
167 const DeclContext *DC = getEffectiveDeclContext(ND);
168 if (!DC->isFunctionOrMethod())
171 // Use the canonical number for externally visible decls.
172 if (ND->isExternallyVisible()) {
173 disc = getASTContext().getManglingNumber(ND);
177 // Anonymous tags are already numbered.
178 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
179 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
183 // Make up a reasonable number for internal decls.
184 unsigned &discriminator = Uniquifier[ND];
186 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
187 disc = discriminator + 1;
191 unsigned getLambdaId(const CXXRecordDecl *RD) {
192 assert(RD->isLambda() && "RD must be a lambda!");
193 assert(!RD->isExternallyVisible() && "RD must not be visible!");
194 assert(RD->getLambdaManglingNumber() == 0 &&
195 "RD must not have a mangling number!");
196 std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
197 Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
198 return Result.first->second;
202 void mangleInitFiniStub(const VarDecl *D, raw_ostream &Out, char CharCode);
205 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
206 /// Microsoft Visual C++ ABI.
207 class MicrosoftCXXNameMangler {
208 MicrosoftMangleContextImpl &Context;
211 /// The "structor" is the top-level declaration being mangled, if
212 /// that's not a template specialization; otherwise it's the pattern
213 /// for that specialization.
214 const NamedDecl *Structor;
215 unsigned StructorType;
217 typedef llvm::SmallVector<std::string, 10> BackRefVec;
218 BackRefVec NameBackReferences;
220 typedef llvm::DenseMap<void *, unsigned> ArgBackRefMap;
221 ArgBackRefMap TypeBackReferences;
223 ASTContext &getASTContext() const { return Context.getASTContext(); }
225 // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
226 // this check into mangleQualifiers().
227 const bool PointersAre64Bit;
230 enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
232 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
233 : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
234 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
237 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
238 const CXXConstructorDecl *D, CXXCtorType Type)
239 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
240 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
243 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
244 const CXXDestructorDecl *D, CXXDtorType Type)
245 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
246 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
249 raw_ostream &getStream() const { return Out; }
251 void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
252 void mangleName(const NamedDecl *ND);
253 void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
254 void mangleVariableEncoding(const VarDecl *VD);
255 void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
256 void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
257 const CXXMethodDecl *MD);
258 void mangleVirtualMemPtrThunk(
259 const CXXMethodDecl *MD,
260 const MicrosoftVTableContext::MethodVFTableLocation &ML);
261 void mangleNumber(int64_t Number);
262 void mangleType(QualType T, SourceRange Range,
263 QualifierMangleMode QMM = QMM_Mangle);
264 void mangleFunctionType(const FunctionType *T,
265 const FunctionDecl *D = nullptr,
266 bool ForceThisQuals = false);
267 void mangleNestedName(const NamedDecl *ND);
270 void mangleUnqualifiedName(const NamedDecl *ND) {
271 mangleUnqualifiedName(ND, ND->getDeclName());
273 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
274 void mangleSourceName(StringRef Name);
275 void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
276 void mangleCXXDtorType(CXXDtorType T);
277 void mangleQualifiers(Qualifiers Quals, bool IsMember);
278 void mangleRefQualifier(RefQualifierKind RefQualifier);
279 void manglePointerCVQualifiers(Qualifiers Quals);
280 void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
282 void mangleUnscopedTemplateName(const TemplateDecl *ND);
284 mangleTemplateInstantiationName(const TemplateDecl *TD,
285 const TemplateArgumentList &TemplateArgs);
286 void mangleObjCMethodName(const ObjCMethodDecl *MD);
288 void mangleArgumentType(QualType T, SourceRange Range);
290 // Declare manglers for every type class.
291 #define ABSTRACT_TYPE(CLASS, PARENT)
292 #define NON_CANONICAL_TYPE(CLASS, PARENT)
293 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
296 #include "clang/AST/TypeNodes.def"
298 #undef NON_CANONICAL_TYPE
301 void mangleType(const TagDecl *TD);
302 void mangleDecayedArrayType(const ArrayType *T);
303 void mangleArrayType(const ArrayType *T);
304 void mangleFunctionClass(const FunctionDecl *FD);
305 void mangleCallingConvention(CallingConv CC);
306 void mangleCallingConvention(const FunctionType *T);
307 void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
308 void mangleExpression(const Expr *E);
309 void mangleThrowSpecification(const FunctionProtoType *T);
311 void mangleTemplateArgs(const TemplateDecl *TD,
312 const TemplateArgumentList &TemplateArgs);
313 void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
314 const NamedDecl *Parm);
318 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
319 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
320 LanguageLinkage L = FD->getLanguageLinkage();
321 // Overloadable functions need mangling.
322 if (FD->hasAttr<OverloadableAttr>())
325 // The ABI expects that we would never mangle "typical" user-defined entry
326 // points regardless of visibility or freestanding-ness.
328 // N.B. This is distinct from asking about "main". "main" has a lot of
329 // special rules associated with it in the standard while these
330 // user-defined entry points are outside of the purview of the standard.
331 // For example, there can be only one definition for "main" in a standards
332 // compliant program; however nothing forbids the existence of wmain and
333 // WinMain in the same translation unit.
334 if (FD->isMSVCRTEntryPoint())
337 // C++ functions and those whose names are not a simple identifier need
339 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
342 // C functions are not mangled.
343 if (L == CLanguageLinkage)
347 // Otherwise, no mangling is done outside C++ mode.
348 if (!getASTContext().getLangOpts().CPlusPlus)
351 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
352 // C variables are not mangled.
356 // Variables at global scope with non-internal linkage are not mangled.
357 const DeclContext *DC = getEffectiveDeclContext(D);
358 // Check for extern variable declared locally.
359 if (DC->isFunctionOrMethod() && D->hasLinkage())
360 while (!DC->isNamespace() && !DC->isTranslationUnit())
361 DC = getEffectiveParentContext(DC);
363 if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
364 !isa<VarTemplateSpecializationDecl>(D))
372 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
376 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
377 // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
378 // Therefore it's really important that we don't decorate the
379 // name with leading underscores or leading/trailing at signs. So, by
380 // default, we emit an asm marker at the start so we get the name right.
381 // Callers can override this with a custom prefix.
383 // <mangled-name> ::= ? <name> <type-encoding>
386 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
387 mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
388 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
389 mangleVariableEncoding(VD);
391 // TODO: Fields? Can MSVC even mangle them?
392 // Issue a diagnostic for now.
393 DiagnosticsEngine &Diags = Context.getDiags();
394 unsigned DiagID = Diags.getCustomDiagID(
395 DiagnosticsEngine::Error, "cannot mangle this declaration yet");
396 Diags.Report(D->getLocation(), DiagID) << D->getSourceRange();
400 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD,
402 // <type-encoding> ::= <function-class> <function-type>
404 // Since MSVC operates on the type as written and not the canonical type, it
405 // actually matters which decl we have here. MSVC appears to choose the
406 // first, since it is most likely to be the declaration in a header file.
407 FD = FD->getFirstDecl();
409 // We should never ever see a FunctionNoProtoType at this point.
410 // We don't even know how to mangle their types anyway :).
411 const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
413 // extern "C" functions can hold entities that must be mangled.
414 // As it stands, these functions still need to get expressed in the full
415 // external name. They have their class and type omitted, replaced with '9'.
417 // We would like to mangle all extern "C" functions using this additional
418 // component but this would break compatibility with MSVC's behavior.
419 // Instead, do this when we know that compatibility isn't important (in
420 // other words, when it is an overloaded extern "C" funciton).
421 if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
424 mangleFunctionClass(FD);
426 mangleFunctionType(FT, FD);
432 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
433 // <type-encoding> ::= <storage-class> <variable-type>
434 // <storage-class> ::= 0 # private static member
435 // ::= 1 # protected static member
436 // ::= 2 # public static member
438 // ::= 4 # static local
440 // The first character in the encoding (after the name) is the storage class.
441 if (VD->isStaticDataMember()) {
442 // If it's a static member, it also encodes the access level.
443 switch (VD->getAccess()) {
445 case AS_private: Out << '0'; break;
446 case AS_protected: Out << '1'; break;
447 case AS_public: Out << '2'; break;
450 else if (!VD->isStaticLocal())
454 // Now mangle the type.
455 // <variable-type> ::= <type> <cvr-qualifiers>
456 // ::= <type> <pointee-cvr-qualifiers> # pointers, references
457 // Pointers and references are odd. The type of 'int * const foo;' gets
458 // mangled as 'QAHA' instead of 'PAHB', for example.
459 SourceRange SR = VD->getSourceRange();
460 QualType Ty = VD->getType();
461 if (Ty->isPointerType() || Ty->isReferenceType() ||
462 Ty->isMemberPointerType()) {
463 mangleType(Ty, SR, QMM_Drop);
464 manglePointerExtQualifiers(
465 Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
466 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
467 mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
468 // Member pointers are suffixed with a back reference to the member
469 // pointer's class name.
470 mangleName(MPT->getClass()->getAsCXXRecordDecl());
472 mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
473 } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
474 // Global arrays are funny, too.
475 mangleDecayedArrayType(AT);
476 if (AT->getElementType()->isArrayType())
479 mangleQualifiers(Ty.getQualifiers(), false);
481 mangleType(Ty, SR, QMM_Drop);
482 mangleQualifiers(Ty.getQualifiers(), false);
486 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
487 const ValueDecl *VD) {
488 // <member-data-pointer> ::= <integer-literal>
489 // ::= $F <number> <number>
490 // ::= $G <number> <number> <number>
493 int64_t VBTableOffset;
494 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
496 FieldOffset = getASTContext().getFieldOffset(VD);
497 assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
498 "cannot take address of bitfield");
499 FieldOffset /= getASTContext().getCharWidth();
503 FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
510 case MSInheritanceAttr::Keyword_single_inheritance: Code = '0'; break;
511 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = '0'; break;
512 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'F'; break;
513 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
518 mangleNumber(FieldOffset);
520 // The C++ standard doesn't allow base-to-derived member pointer conversions
521 // in template parameter contexts, so the vbptr offset of data member pointers
523 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
525 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
526 mangleNumber(VBTableOffset);
530 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
531 const CXXMethodDecl *MD) {
532 // <member-function-pointer> ::= $1? <name>
533 // ::= $H? <name> <number>
534 // ::= $I? <name> <number> <number>
535 // ::= $J? <name> <number> <number> <number>
537 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
541 case MSInheritanceAttr::Keyword_single_inheritance: Code = '1'; break;
542 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = 'H'; break;
543 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'I'; break;
544 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
547 // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr
549 uint64_t NVOffset = 0;
550 uint64_t VBTableOffset = 0;
551 uint64_t VBPtrOffset = 0;
553 Out << '$' << Code << '?';
554 if (MD->isVirtual()) {
555 MicrosoftVTableContext *VTContext =
556 cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
557 const MicrosoftVTableContext::MethodVFTableLocation &ML =
558 VTContext->getMethodVFTableLocation(GlobalDecl(MD));
559 mangleVirtualMemPtrThunk(MD, ML);
560 NVOffset = ML.VFPtrOffset.getQuantity();
561 VBTableOffset = ML.VBTableIndex * 4;
563 const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
564 VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
568 mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
571 // Null single inheritance member functions are encoded as a simple nullptr.
572 if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
576 if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
581 if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
582 mangleNumber(NVOffset);
583 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
584 mangleNumber(VBPtrOffset);
585 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
586 mangleNumber(VBTableOffset);
589 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
590 const CXXMethodDecl *MD,
591 const MicrosoftVTableContext::MethodVFTableLocation &ML) {
592 // Get the vftable offset.
593 CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
594 getASTContext().getTargetInfo().getPointerWidth(0));
595 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
598 mangleName(MD->getParent());
600 mangleNumber(OffsetInVFTable);
602 mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>());
605 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
606 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
608 // Always start with the unqualified name.
609 mangleUnqualifiedName(ND);
611 mangleNestedName(ND);
613 // Terminate the whole name with an '@'.
617 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
618 // <non-negative integer> ::= A@ # when Number == 0
619 // ::= <decimal digit> # when 1 <= Number <= 10
620 // ::= <hex digit>+ @ # when Number >= 10
622 // <number> ::= [?] <non-negative integer>
624 uint64_t Value = static_cast<uint64_t>(Number);
632 else if (Value >= 1 && Value <= 10)
635 // Numbers that are not encoded as decimal digits are represented as nibbles
636 // in the range of ASCII characters 'A' to 'P'.
637 // The number 0x123450 would be encoded as 'BCDEFA'
638 char EncodedNumberBuffer[sizeof(uint64_t) * 2];
639 MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
640 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
641 for (; Value != 0; Value >>= 4)
642 *I++ = 'A' + (Value & 0xf);
643 Out.write(I.base(), I - BufferRef.rbegin());
648 static const TemplateDecl *
649 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
650 // Check if we have a function template.
651 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
652 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
653 TemplateArgs = FD->getTemplateSpecializationArgs();
658 // Check if we have a class template.
659 if (const ClassTemplateSpecializationDecl *Spec =
660 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
661 TemplateArgs = &Spec->getTemplateArgs();
662 return Spec->getSpecializedTemplate();
665 // Check if we have a variable template.
666 if (const VarTemplateSpecializationDecl *Spec =
667 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
668 TemplateArgs = &Spec->getTemplateArgs();
669 return Spec->getSpecializedTemplate();
675 void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
676 DeclarationName Name) {
677 // <unqualified-name> ::= <operator-name>
678 // ::= <ctor-dtor-name>
680 // ::= <template-name>
682 // Check if we have a template.
683 const TemplateArgumentList *TemplateArgs = nullptr;
684 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
685 // Function templates aren't considered for name back referencing. This
686 // makes sense since function templates aren't likely to occur multiple
687 // times in a symbol.
688 // FIXME: Test alias template mangling with MSVC 2013.
689 if (!isa<ClassTemplateDecl>(TD)) {
690 mangleTemplateInstantiationName(TD, *TemplateArgs);
695 // Here comes the tricky thing: if we need to mangle something like
696 // void foo(A::X<Y>, B::X<Y>),
697 // the X<Y> part is aliased. However, if you need to mangle
698 // void foo(A::X<A::Y>, A::X<B::Y>),
699 // the A::X<> part is not aliased.
700 // That said, from the mangler's perspective we have a structure like this:
701 // namespace[s] -> type[ -> template-parameters]
702 // but from the Clang perspective we have
703 // type [ -> template-parameters]
705 // What we do is we create a new mangler, mangle the same type (without
706 // a namespace suffix) to a string using the extra mangler and then use
707 // the mangled type name as a key to check the mangling of different types
710 llvm::SmallString<64> TemplateMangling;
711 llvm::raw_svector_ostream Stream(TemplateMangling);
712 MicrosoftCXXNameMangler Extra(Context, Stream);
713 Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
716 mangleSourceName(TemplateMangling);
720 switch (Name.getNameKind()) {
721 case DeclarationName::Identifier: {
722 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
723 mangleSourceName(II->getName());
727 // Otherwise, an anonymous entity. We must have a declaration.
728 assert(ND && "mangling empty name without declaration");
730 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
731 if (NS->isAnonymousNamespace()) {
737 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
738 // We must have an anonymous union or struct declaration.
739 const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
740 assert(RD && "expected variable decl to have a record type");
741 // Anonymous types with no tag or typedef get the name of their
742 // declarator mangled in. If they have no declarator, number them with
744 llvm::SmallString<64> Name("$S");
745 // Get a unique id for the anonymous struct.
746 Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
747 mangleSourceName(Name.str());
751 // We must have an anonymous struct.
752 const TagDecl *TD = cast<TagDecl>(ND);
753 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
754 assert(TD->getDeclContext() == D->getDeclContext() &&
755 "Typedef should not be in another decl context!");
756 assert(D->getDeclName().getAsIdentifierInfo() &&
757 "Typedef was not named!");
758 mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
762 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
763 if (Record->isLambda()) {
764 llvm::SmallString<10> Name("<lambda_");
766 if (Record->getLambdaManglingNumber())
767 LambdaId = Record->getLambdaManglingNumber();
769 LambdaId = Context.getLambdaId(Record);
771 Name += llvm::utostr(LambdaId);
774 mangleSourceName(Name);
779 llvm::SmallString<64> Name("<unnamed-type-");
780 if (TD->hasDeclaratorForAnonDecl()) {
781 // Anonymous types with no tag or typedef get the name of their
782 // declarator mangled in if they have one.
783 Name += TD->getDeclaratorForAnonDecl()->getName();
785 // Otherwise, number the types using a $S prefix.
787 Name += llvm::utostr(Context.getAnonymousStructId(TD));
790 mangleSourceName(Name.str());
794 case DeclarationName::ObjCZeroArgSelector:
795 case DeclarationName::ObjCOneArgSelector:
796 case DeclarationName::ObjCMultiArgSelector:
797 llvm_unreachable("Can't mangle Objective-C selector names here!");
799 case DeclarationName::CXXConstructorName:
800 if (Structor == getStructor(ND)) {
801 if (StructorType == Ctor_CopyingClosure) {
805 if (StructorType == Ctor_DefaultClosure) {
813 case DeclarationName::CXXDestructorName:
815 // If the named decl is the C++ destructor we're mangling,
816 // use the type we were given.
817 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
819 // Otherwise, use the base destructor name. This is relevant if a
820 // class with a destructor is declared within a destructor.
821 mangleCXXDtorType(Dtor_Base);
824 case DeclarationName::CXXConversionFunctionName:
825 // <operator-name> ::= ?B # (cast)
826 // The target type is encoded as the return type.
830 case DeclarationName::CXXOperatorName:
831 mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
834 case DeclarationName::CXXLiteralOperatorName: {
836 mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
840 case DeclarationName::CXXUsingDirective:
841 llvm_unreachable("Can't mangle a using directive name!");
845 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
846 // <postfix> ::= <unqualified-name> [<postfix>]
847 // ::= <substitution> [<postfix>]
848 const DeclContext *DC = getEffectiveDeclContext(ND);
850 while (!DC->isTranslationUnit()) {
851 if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
853 if (Context.getNextDiscriminator(ND, Disc)) {
860 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
861 DiagnosticsEngine &Diags = Context.getDiags();
863 Diags.getCustomDiagID(DiagnosticsEngine::Error,
864 "cannot mangle a local inside this block yet");
865 Diags.Report(BD->getLocation(), DiagID);
867 // FIXME: This is completely, utterly, wrong; see ItaniumMangle
868 // for how this should be done.
869 Out << "__block_invoke" << Context.getBlockId(BD, false);
872 } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
873 mangleObjCMethodName(Method);
874 } else if (isa<NamedDecl>(DC)) {
875 ND = cast<NamedDecl>(DC);
876 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
880 mangleUnqualifiedName(ND);
882 DC = DC->getParent();
886 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
887 // Microsoft uses the names on the case labels for these dtor variants. Clang
888 // uses the Itanium terminology internally. Everything in this ABI delegates
889 // towards the base dtor.
891 // <operator-name> ::= ?1 # destructor
892 case Dtor_Base: Out << "?1"; return;
893 // <operator-name> ::= ?_D # vbase destructor
894 case Dtor_Complete: Out << "?_D"; return;
895 // <operator-name> ::= ?_G # scalar deleting destructor
896 case Dtor_Deleting: Out << "?_G"; return;
897 // <operator-name> ::= ?_E # vector deleting destructor
898 // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need
901 llvm_unreachable("not expecting a COMDAT");
903 llvm_unreachable("Unsupported dtor type?");
906 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
907 SourceLocation Loc) {
911 // <operator-name> ::= ?2 # new
912 case OO_New: Out << "?2"; break;
913 // <operator-name> ::= ?3 # delete
914 case OO_Delete: Out << "?3"; break;
915 // <operator-name> ::= ?4 # =
916 case OO_Equal: Out << "?4"; break;
917 // <operator-name> ::= ?5 # >>
918 case OO_GreaterGreater: Out << "?5"; break;
919 // <operator-name> ::= ?6 # <<
920 case OO_LessLess: Out << "?6"; break;
921 // <operator-name> ::= ?7 # !
922 case OO_Exclaim: Out << "?7"; break;
923 // <operator-name> ::= ?8 # ==
924 case OO_EqualEqual: Out << "?8"; break;
925 // <operator-name> ::= ?9 # !=
926 case OO_ExclaimEqual: Out << "?9"; break;
927 // <operator-name> ::= ?A # []
928 case OO_Subscript: Out << "?A"; break;
930 // <operator-name> ::= ?C # ->
931 case OO_Arrow: Out << "?C"; break;
932 // <operator-name> ::= ?D # *
933 case OO_Star: Out << "?D"; break;
934 // <operator-name> ::= ?E # ++
935 case OO_PlusPlus: Out << "?E"; break;
936 // <operator-name> ::= ?F # --
937 case OO_MinusMinus: Out << "?F"; break;
938 // <operator-name> ::= ?G # -
939 case OO_Minus: Out << "?G"; break;
940 // <operator-name> ::= ?H # +
941 case OO_Plus: Out << "?H"; break;
942 // <operator-name> ::= ?I # &
943 case OO_Amp: Out << "?I"; break;
944 // <operator-name> ::= ?J # ->*
945 case OO_ArrowStar: Out << "?J"; break;
946 // <operator-name> ::= ?K # /
947 case OO_Slash: Out << "?K"; break;
948 // <operator-name> ::= ?L # %
949 case OO_Percent: Out << "?L"; break;
950 // <operator-name> ::= ?M # <
951 case OO_Less: Out << "?M"; break;
952 // <operator-name> ::= ?N # <=
953 case OO_LessEqual: Out << "?N"; break;
954 // <operator-name> ::= ?O # >
955 case OO_Greater: Out << "?O"; break;
956 // <operator-name> ::= ?P # >=
957 case OO_GreaterEqual: Out << "?P"; break;
958 // <operator-name> ::= ?Q # ,
959 case OO_Comma: Out << "?Q"; break;
960 // <operator-name> ::= ?R # ()
961 case OO_Call: Out << "?R"; break;
962 // <operator-name> ::= ?S # ~
963 case OO_Tilde: Out << "?S"; break;
964 // <operator-name> ::= ?T # ^
965 case OO_Caret: Out << "?T"; break;
966 // <operator-name> ::= ?U # |
967 case OO_Pipe: Out << "?U"; break;
968 // <operator-name> ::= ?V # &&
969 case OO_AmpAmp: Out << "?V"; break;
970 // <operator-name> ::= ?W # ||
971 case OO_PipePipe: Out << "?W"; break;
972 // <operator-name> ::= ?X # *=
973 case OO_StarEqual: Out << "?X"; break;
974 // <operator-name> ::= ?Y # +=
975 case OO_PlusEqual: Out << "?Y"; break;
976 // <operator-name> ::= ?Z # -=
977 case OO_MinusEqual: Out << "?Z"; break;
978 // <operator-name> ::= ?_0 # /=
979 case OO_SlashEqual: Out << "?_0"; break;
980 // <operator-name> ::= ?_1 # %=
981 case OO_PercentEqual: Out << "?_1"; break;
982 // <operator-name> ::= ?_2 # >>=
983 case OO_GreaterGreaterEqual: Out << "?_2"; break;
984 // <operator-name> ::= ?_3 # <<=
985 case OO_LessLessEqual: Out << "?_3"; break;
986 // <operator-name> ::= ?_4 # &=
987 case OO_AmpEqual: Out << "?_4"; break;
988 // <operator-name> ::= ?_5 # |=
989 case OO_PipeEqual: Out << "?_5"; break;
990 // <operator-name> ::= ?_6 # ^=
991 case OO_CaretEqual: Out << "?_6"; break;
996 // ?_B # local static guard
998 // ?_D # vbase destructor
999 // ?_E # vector deleting destructor
1000 // ?_F # default constructor closure
1001 // ?_G # scalar deleting destructor
1002 // ?_H # vector constructor iterator
1003 // ?_I # vector destructor iterator
1004 // ?_J # vector vbase constructor iterator
1005 // ?_K # virtual displacement map
1006 // ?_L # eh vector constructor iterator
1007 // ?_M # eh vector destructor iterator
1008 // ?_N # eh vector vbase constructor iterator
1009 // ?_O # copy constructor closure
1010 // ?_P<name> # udt returning <name>
1012 // ?_R0 # RTTI Type Descriptor
1013 // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
1014 // ?_R2 # RTTI Base Class Array
1015 // ?_R3 # RTTI Class Hierarchy Descriptor
1016 // ?_R4 # RTTI Complete Object Locator
1017 // ?_S # local vftable
1018 // ?_T # local vftable constructor closure
1019 // <operator-name> ::= ?_U # new[]
1020 case OO_Array_New: Out << "?_U"; break;
1021 // <operator-name> ::= ?_V # delete[]
1022 case OO_Array_Delete: Out << "?_V"; break;
1024 case OO_Conditional: {
1025 DiagnosticsEngine &Diags = Context.getDiags();
1026 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1027 "cannot mangle this conditional operator yet");
1028 Diags.Report(Loc, DiagID);
1033 case NUM_OVERLOADED_OPERATORS:
1034 llvm_unreachable("Not an overloaded operator");
1038 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1039 // <source name> ::= <identifier> @
1040 BackRefVec::iterator Found =
1041 std::find(NameBackReferences.begin(), NameBackReferences.end(), Name);
1042 if (Found == NameBackReferences.end()) {
1043 if (NameBackReferences.size() < 10)
1044 NameBackReferences.push_back(Name);
1047 Out << (Found - NameBackReferences.begin());
1051 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1052 Context.mangleObjCMethodName(MD, Out);
1055 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1056 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1057 // <template-name> ::= <unscoped-template-name> <template-args>
1058 // ::= <substitution>
1059 // Always start with the unqualified name.
1061 // Templates have their own context for back references.
1062 ArgBackRefMap OuterArgsContext;
1063 BackRefVec OuterTemplateContext;
1064 NameBackReferences.swap(OuterTemplateContext);
1065 TypeBackReferences.swap(OuterArgsContext);
1067 mangleUnscopedTemplateName(TD);
1068 mangleTemplateArgs(TD, TemplateArgs);
1070 // Restore the previous back reference contexts.
1071 NameBackReferences.swap(OuterTemplateContext);
1072 TypeBackReferences.swap(OuterArgsContext);
1076 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1077 // <unscoped-template-name> ::= ?$ <unqualified-name>
1079 mangleUnqualifiedName(TD);
1082 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1084 // <integer-literal> ::= $0 <number>
1086 // Make sure booleans are encoded as 0/1.
1087 if (IsBoolean && Value.getBoolValue())
1089 else if (Value.isSigned())
1090 mangleNumber(Value.getSExtValue());
1092 mangleNumber(Value.getZExtValue());
1095 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1096 // See if this is a constant expression.
1098 if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1099 mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1103 // Look through no-op casts like template parameter substitutions.
1104 E = E->IgnoreParenNoopCasts(Context.getASTContext());
1106 const CXXUuidofExpr *UE = nullptr;
1107 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1108 if (UO->getOpcode() == UO_AddrOf)
1109 UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1111 UE = dyn_cast<CXXUuidofExpr>(E);
1114 // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1115 // const __s_GUID _GUID_{lower case UUID with underscores}
1116 StringRef Uuid = UE->getUuidAsStringRef(Context.getASTContext());
1117 std::string Name = "_GUID_" + Uuid.lower();
1118 std::replace(Name.begin(), Name.end(), '-', '_');
1120 // If we had to peek through an address-of operator, treat this like we are
1121 // dealing with a pointer type. Otherwise, treat it like a const reference.
1123 // N.B. This matches up with the handling of TemplateArgument::Declaration
1124 // in mangleTemplateArg
1129 Out << Name << "@@3U__s_GUID@@B";
1133 // As bad as this diagnostic is, it's better than crashing.
1134 DiagnosticsEngine &Diags = Context.getDiags();
1135 unsigned DiagID = Diags.getCustomDiagID(
1136 DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1137 Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1138 << E->getSourceRange();
1141 void MicrosoftCXXNameMangler::mangleTemplateArgs(
1142 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1143 // <template-args> ::= <template-arg>+
1144 const TemplateParameterList *TPL = TD->getTemplateParameters();
1145 assert(TPL->size() == TemplateArgs.size() &&
1146 "size mismatch between args and parms!");
1149 for (const TemplateArgument &TA : TemplateArgs.asArray())
1150 mangleTemplateArg(TD, TA, TPL->getParam(Idx++));
1153 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1154 const TemplateArgument &TA,
1155 const NamedDecl *Parm) {
1156 // <template-arg> ::= <type>
1157 // ::= <integer-literal>
1158 // ::= <member-data-pointer>
1159 // ::= <member-function-pointer>
1160 // ::= $E? <name> <type-encoding>
1161 // ::= $1? <name> <type-encoding>
1163 // ::= <template-args>
1165 switch (TA.getKind()) {
1166 case TemplateArgument::Null:
1167 llvm_unreachable("Can't mangle null template arguments!");
1168 case TemplateArgument::TemplateExpansion:
1169 llvm_unreachable("Can't mangle template expansion arguments!");
1170 case TemplateArgument::Type: {
1171 QualType T = TA.getAsType();
1172 mangleType(T, SourceRange(), QMM_Escape);
1175 case TemplateArgument::Declaration: {
1176 const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
1177 if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1178 mangleMemberDataPointer(
1179 cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
1180 cast<ValueDecl>(ND));
1181 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1182 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1183 if (MD && MD->isInstance()) {
1184 mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
1188 mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1191 mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
1195 case TemplateArgument::Integral:
1196 mangleIntegerLiteral(TA.getAsIntegral(),
1197 TA.getIntegralType()->isBooleanType());
1199 case TemplateArgument::NullPtr: {
1200 QualType T = TA.getNullPtrType();
1201 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1202 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1203 if (MPT->isMemberFunctionPointerType() && isa<ClassTemplateDecl>(TD)) {
1204 mangleMemberFunctionPointer(RD, nullptr);
1207 if (MPT->isMemberDataPointer()) {
1208 mangleMemberDataPointer(RD, nullptr);
1215 case TemplateArgument::Expression:
1216 mangleExpression(TA.getAsExpr());
1218 case TemplateArgument::Pack: {
1219 ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1220 if (TemplateArgs.empty()) {
1221 if (isa<TemplateTypeParmDecl>(Parm) ||
1222 isa<TemplateTemplateParmDecl>(Parm))
1223 // MSVC 2015 changed the mangling for empty expanded template packs,
1224 // use the old mangling for link compatibility for old versions.
1225 Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1226 LangOptions::MSVC2015)
1229 else if (isa<NonTypeTemplateParmDecl>(Parm))
1232 llvm_unreachable("unexpected template parameter decl!");
1234 for (const TemplateArgument &PA : TemplateArgs)
1235 mangleTemplateArg(TD, PA, Parm);
1239 case TemplateArgument::Template: {
1240 const NamedDecl *ND =
1241 TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
1242 if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1244 } else if (isa<TypeAliasDecl>(ND)) {
1248 llvm_unreachable("unexpected template template NamedDecl!");
1255 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1257 // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1258 // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1259 // 'I' means __restrict (32/64-bit).
1260 // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1262 // <base-cvr-qualifiers> ::= A # near
1263 // ::= B # near const
1264 // ::= C # near volatile
1265 // ::= D # near const volatile
1266 // ::= E # far (16-bit)
1267 // ::= F # far const (16-bit)
1268 // ::= G # far volatile (16-bit)
1269 // ::= H # far const volatile (16-bit)
1270 // ::= I # huge (16-bit)
1271 // ::= J # huge const (16-bit)
1272 // ::= K # huge volatile (16-bit)
1273 // ::= L # huge const volatile (16-bit)
1274 // ::= M <basis> # based
1275 // ::= N <basis> # based const
1276 // ::= O <basis> # based volatile
1277 // ::= P <basis> # based const volatile
1278 // ::= Q # near member
1279 // ::= R # near const member
1280 // ::= S # near volatile member
1281 // ::= T # near const volatile member
1282 // ::= U # far member (16-bit)
1283 // ::= V # far const member (16-bit)
1284 // ::= W # far volatile member (16-bit)
1285 // ::= X # far const volatile member (16-bit)
1286 // ::= Y # huge member (16-bit)
1287 // ::= Z # huge const member (16-bit)
1288 // ::= 0 # huge volatile member (16-bit)
1289 // ::= 1 # huge const volatile member (16-bit)
1290 // ::= 2 <basis> # based member
1291 // ::= 3 <basis> # based const member
1292 // ::= 4 <basis> # based volatile member
1293 // ::= 5 <basis> # based const volatile member
1294 // ::= 6 # near function (pointers only)
1295 // ::= 7 # far function (pointers only)
1296 // ::= 8 # near method (pointers only)
1297 // ::= 9 # far method (pointers only)
1298 // ::= _A <basis> # based function (pointers only)
1299 // ::= _B <basis> # based function (far?) (pointers only)
1300 // ::= _C <basis> # based method (pointers only)
1301 // ::= _D <basis> # based method (far?) (pointers only)
1302 // ::= _E # block (Clang)
1303 // <basis> ::= 0 # __based(void)
1304 // ::= 1 # __based(segment)?
1305 // ::= 2 <name> # __based(name)
1308 // ::= 5 # not really based
1309 bool HasConst = Quals.hasConst(),
1310 HasVolatile = Quals.hasVolatile();
1313 if (HasConst && HasVolatile) {
1315 } else if (HasVolatile) {
1317 } else if (HasConst) {
1323 if (HasConst && HasVolatile) {
1325 } else if (HasVolatile) {
1327 } else if (HasConst) {
1334 // FIXME: For now, just drop all extension qualifiers on the floor.
1338 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1339 // <ref-qualifier> ::= G # lvalue reference
1340 // ::= H # rvalue-reference
1341 switch (RefQualifier) {
1355 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1356 QualType PointeeType) {
1357 bool HasRestrict = Quals.hasRestrict();
1358 if (PointersAre64Bit &&
1359 (PointeeType.isNull() || !PointeeType->isFunctionType()))
1366 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1367 // <pointer-cv-qualifiers> ::= P # no qualifiers
1370 // ::= S # const volatile
1371 bool HasConst = Quals.hasConst(),
1372 HasVolatile = Quals.hasVolatile();
1374 if (HasConst && HasVolatile) {
1376 } else if (HasVolatile) {
1378 } else if (HasConst) {
1385 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1386 SourceRange Range) {
1387 // MSVC will backreference two canonically equivalent types that have slightly
1388 // different manglings when mangled alone.
1390 // Decayed types do not match up with non-decayed versions of the same type.
1393 // void (*x)(void) will not form a backreference with void x(void)
1395 if (const auto *DT = T->getAs<DecayedType>()) {
1396 QualType OriginalType = DT->getOriginalType();
1397 // All decayed ArrayTypes should be treated identically; as-if they were
1398 // a decayed IncompleteArrayType.
1399 if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
1400 OriginalType = getASTContext().getIncompleteArrayType(
1401 AT->getElementType(), AT->getSizeModifier(),
1402 AT->getIndexTypeCVRQualifiers());
1404 TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
1405 // If the original parameter was textually written as an array,
1406 // instead treat the decayed parameter like it's const.
1409 // int [] -> int * const
1410 if (OriginalType->isArrayType())
1413 TypePtr = T.getCanonicalType().getAsOpaquePtr();
1416 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1418 if (Found == TypeBackReferences.end()) {
1419 size_t OutSizeBefore = Out.tell();
1421 mangleType(T, Range, QMM_Drop);
1423 // See if it's worth creating a back reference.
1424 // Only types longer than 1 character are considered
1425 // and only 10 back references slots are available:
1426 bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
1427 if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1428 size_t Size = TypeBackReferences.size();
1429 TypeBackReferences[TypePtr] = Size;
1432 Out << Found->second;
1436 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1437 QualifierMangleMode QMM) {
1438 // Don't use the canonical types. MSVC includes things like 'const' on
1439 // pointer arguments to function pointers that canonicalization strips away.
1440 T = T.getDesugaredType(getASTContext());
1441 Qualifiers Quals = T.getLocalQualifiers();
1442 if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1443 // If there were any Quals, getAsArrayType() pushed them onto the array
1445 if (QMM == QMM_Mangle)
1447 else if (QMM == QMM_Escape || QMM == QMM_Result)
1449 mangleArrayType(AT);
1453 bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1454 T->isReferenceType() || T->isBlockPointerType();
1460 if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1462 mangleFunctionType(FT);
1465 mangleQualifiers(Quals, false);
1468 if (!IsPointer && Quals) {
1470 mangleQualifiers(Quals, false);
1474 if ((!IsPointer && Quals) || isa<TagType>(T)) {
1476 mangleQualifiers(Quals, false);
1481 const Type *ty = T.getTypePtr();
1483 switch (ty->getTypeClass()) {
1484 #define ABSTRACT_TYPE(CLASS, PARENT)
1485 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1487 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1489 #define TYPE(CLASS, PARENT) \
1491 mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1493 #include "clang/AST/TypeNodes.def"
1494 #undef ABSTRACT_TYPE
1495 #undef NON_CANONICAL_TYPE
1500 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1501 SourceRange Range) {
1502 // <type> ::= <builtin-type>
1503 // <builtin-type> ::= X # void
1504 // ::= C # signed char
1506 // ::= E # unsigned char
1508 // ::= G # unsigned short (or wchar_t if it's not a builtin)
1510 // ::= I # unsigned int
1512 // ::= K # unsigned long
1516 // ::= O # long double (__float80 is mangled differently)
1517 // ::= _J # long long, __int64
1518 // ::= _K # unsigned long long, __int64
1519 // ::= _L # __int128
1520 // ::= _M # unsigned __int128
1522 // _O # <array in parameter>
1523 // ::= _T # __float80 (Intel)
1525 // ::= _Z # __float80 (Digital Mars)
1526 switch (T->getKind()) {
1527 case BuiltinType::Void: Out << 'X'; break;
1528 case BuiltinType::SChar: Out << 'C'; break;
1529 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
1530 case BuiltinType::UChar: Out << 'E'; break;
1531 case BuiltinType::Short: Out << 'F'; break;
1532 case BuiltinType::UShort: Out << 'G'; break;
1533 case BuiltinType::Int: Out << 'H'; break;
1534 case BuiltinType::UInt: Out << 'I'; break;
1535 case BuiltinType::Long: Out << 'J'; break;
1536 case BuiltinType::ULong: Out << 'K'; break;
1537 case BuiltinType::Float: Out << 'M'; break;
1538 case BuiltinType::Double: Out << 'N'; break;
1539 // TODO: Determine size and mangle accordingly
1540 case BuiltinType::LongDouble: Out << 'O'; break;
1541 case BuiltinType::LongLong: Out << "_J"; break;
1542 case BuiltinType::ULongLong: Out << "_K"; break;
1543 case BuiltinType::Int128: Out << "_L"; break;
1544 case BuiltinType::UInt128: Out << "_M"; break;
1545 case BuiltinType::Bool: Out << "_N"; break;
1546 case BuiltinType::Char16: Out << "_S"; break;
1547 case BuiltinType::Char32: Out << "_U"; break;
1548 case BuiltinType::WChar_S:
1549 case BuiltinType::WChar_U: Out << "_W"; break;
1551 #define BUILTIN_TYPE(Id, SingletonId)
1552 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1553 case BuiltinType::Id:
1554 #include "clang/AST/BuiltinTypes.def"
1555 case BuiltinType::Dependent:
1556 llvm_unreachable("placeholder types shouldn't get to name mangling");
1558 case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
1559 case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
1560 case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
1562 case BuiltinType::OCLImage1d: Out << "PAUocl_image1d@@"; break;
1563 case BuiltinType::OCLImage1dArray: Out << "PAUocl_image1darray@@"; break;
1564 case BuiltinType::OCLImage1dBuffer: Out << "PAUocl_image1dbuffer@@"; break;
1565 case BuiltinType::OCLImage2d: Out << "PAUocl_image2d@@"; break;
1566 case BuiltinType::OCLImage2dArray: Out << "PAUocl_image2darray@@"; break;
1567 case BuiltinType::OCLImage3d: Out << "PAUocl_image3d@@"; break;
1568 case BuiltinType::OCLSampler: Out << "PAUocl_sampler@@"; break;
1569 case BuiltinType::OCLEvent: Out << "PAUocl_event@@"; break;
1571 case BuiltinType::NullPtr: Out << "$$T"; break;
1573 case BuiltinType::Half: {
1574 DiagnosticsEngine &Diags = Context.getDiags();
1575 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1576 "cannot mangle this built-in %0 type yet");
1577 Diags.Report(Range.getBegin(), DiagID)
1578 << T->getName(Context.getASTContext().getPrintingPolicy())
1585 // <type> ::= <function-type>
1586 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
1588 // Structors only appear in decls, so at this point we know it's not a
1590 // FIXME: This may not be lambda-friendly.
1591 if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
1593 mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
1596 mangleFunctionType(T);
1599 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1600 Qualifiers, SourceRange) {
1601 llvm_unreachable("Can't mangle K&R function prototypes");
1604 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
1605 const FunctionDecl *D,
1606 bool ForceThisQuals) {
1607 // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1608 // <return-type> <argument-list> <throw-spec>
1609 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1612 if (D) Range = D->getSourceRange();
1614 bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
1615 CallingConv CC = T->getCallConv();
1616 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1617 if (MD->isInstance())
1618 HasThisQuals = true;
1619 if (isa<CXXDestructorDecl>(MD)) {
1621 } else if (isa<CXXConstructorDecl>(MD)) {
1623 IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
1624 StructorType == Ctor_DefaultClosure) &&
1625 getStructor(MD) == Structor;
1627 CC = getASTContext().getDefaultCallingConvention(
1628 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1632 // If this is a C++ instance method, mangle the CVR qualifiers for the
1635 Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
1636 manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
1637 mangleRefQualifier(Proto->getRefQualifier());
1638 mangleQualifiers(Quals, /*IsMember=*/false);
1641 mangleCallingConvention(CC);
1643 // <return-type> ::= <type>
1644 // ::= @ # structors (they have no declared return type)
1646 if (isa<CXXDestructorDecl>(D) && D == Structor &&
1647 StructorType == Dtor_Deleting) {
1648 // The scalar deleting destructor takes an extra int argument.
1649 // However, the FunctionType generated has 0 arguments.
1650 // FIXME: This is a temporary hack.
1651 // Maybe should fix the FunctionType creation instead?
1652 Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
1655 if (IsCtorClosure) {
1656 // Default constructor closure and copy constructor closure both return
1660 if (StructorType == Ctor_DefaultClosure) {
1661 // Default constructor closure always has no arguments.
1663 } else if (StructorType == Ctor_CopyingClosure) {
1664 // Copy constructor closure always takes an unqualified reference.
1665 mangleArgumentType(getASTContext().getLValueReferenceType(
1666 Proto->getParamType(0)
1667 ->getAs<LValueReferenceType>()
1669 /*SpelledAsLValue=*/true),
1673 llvm_unreachable("unexpected constructor closure!");
1680 QualType ResultType = Proto->getReturnType();
1681 if (const auto *AT =
1682 dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
1684 mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
1686 mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
1689 if (ResultType->isVoidType())
1690 ResultType = ResultType.getUnqualifiedType();
1691 mangleType(ResultType, Range, QMM_Result);
1695 // <argument-list> ::= X # void
1697 // ::= <type>* Z # varargs
1698 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
1701 // Happens for function pointer type arguments for example.
1702 for (const QualType &Arg : Proto->param_types())
1703 mangleArgumentType(Arg, Range);
1704 // <builtin-type> ::= Z # ellipsis
1705 if (Proto->isVariadic())
1711 mangleThrowSpecification(Proto);
1714 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1715 // <function-class> ::= <member-function> E? # E designates a 64-bit 'this'
1716 // # pointer. in 64-bit mode *all*
1717 // # 'this' pointers are 64-bit.
1718 // ::= <global-function>
1719 // <member-function> ::= A # private: near
1720 // ::= B # private: far
1721 // ::= C # private: static near
1722 // ::= D # private: static far
1723 // ::= E # private: virtual near
1724 // ::= F # private: virtual far
1725 // ::= I # protected: near
1726 // ::= J # protected: far
1727 // ::= K # protected: static near
1728 // ::= L # protected: static far
1729 // ::= M # protected: virtual near
1730 // ::= N # protected: virtual far
1731 // ::= Q # public: near
1732 // ::= R # public: far
1733 // ::= S # public: static near
1734 // ::= T # public: static far
1735 // ::= U # public: virtual near
1736 // ::= V # public: virtual far
1737 // <global-function> ::= Y # global near
1738 // ::= Z # global far
1739 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1740 switch (MD->getAccess()) {
1742 llvm_unreachable("Unsupported access specifier");
1746 else if (MD->isVirtual())
1754 else if (MD->isVirtual())
1762 else if (MD->isVirtual())
1771 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
1772 // <calling-convention> ::= A # __cdecl
1773 // ::= B # __export __cdecl
1775 // ::= D # __export __pascal
1776 // ::= E # __thiscall
1777 // ::= F # __export __thiscall
1778 // ::= G # __stdcall
1779 // ::= H # __export __stdcall
1780 // ::= I # __fastcall
1781 // ::= J # __export __fastcall
1782 // ::= Q # __vectorcall
1783 // The 'export' calling conventions are from a bygone era
1784 // (*cough*Win16*cough*) when functions were declared for export with
1785 // that keyword. (It didn't actually export them, it just made them so
1786 // that they could be in a DLL and somebody from another module could call
1791 llvm_unreachable("Unsupported CC for mangling");
1792 case CC_X86_64Win64:
1794 case CC_C: Out << 'A'; break;
1795 case CC_X86Pascal: Out << 'C'; break;
1796 case CC_X86ThisCall: Out << 'E'; break;
1797 case CC_X86StdCall: Out << 'G'; break;
1798 case CC_X86FastCall: Out << 'I'; break;
1799 case CC_X86VectorCall: Out << 'Q'; break;
1802 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
1803 mangleCallingConvention(T->getCallConv());
1805 void MicrosoftCXXNameMangler::mangleThrowSpecification(
1806 const FunctionProtoType *FT) {
1807 // <throw-spec> ::= Z # throw(...) (default)
1808 // ::= @ # throw() or __declspec/__attribute__((nothrow))
1810 // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1811 // all actually mangled as 'Z'. (They're ignored because their associated
1812 // functionality isn't implemented, and probably never will be.)
1816 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
1817 Qualifiers, SourceRange Range) {
1818 // Probably should be mangled as a template instantiation; need to see what
1820 DiagnosticsEngine &Diags = Context.getDiags();
1821 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1822 "cannot mangle this unresolved dependent type yet");
1823 Diags.Report(Range.getBegin(), DiagID)
1827 // <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1828 // <union-type> ::= T <name>
1829 // <struct-type> ::= U <name>
1830 // <class-type> ::= V <name>
1831 // <enum-type> ::= W4 <name>
1832 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
1834 mangleType(cast<TagType>(T)->getDecl());
1836 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
1838 mangleType(cast<TagType>(T)->getDecl());
1840 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
1841 switch (TD->getTagKind()) {
1859 // <type> ::= <array-type>
1860 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1861 // [Y <dimension-count> <dimension>+]
1862 // <element-type> # as global, E is never required
1863 // It's supposed to be the other way around, but for some strange reason, it
1864 // isn't. Today this behavior is retained for the sole purpose of backwards
1866 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
1867 // This isn't a recursive mangling, so now we have to do it all in this
1869 manglePointerCVQualifiers(T->getElementType().getQualifiers());
1870 mangleType(T->getElementType(), SourceRange());
1872 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
1874 llvm_unreachable("Should have been special cased");
1876 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
1878 llvm_unreachable("Should have been special cased");
1880 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
1881 Qualifiers, SourceRange) {
1882 llvm_unreachable("Should have been special cased");
1884 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
1885 Qualifiers, SourceRange) {
1886 llvm_unreachable("Should have been special cased");
1888 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
1889 QualType ElementTy(T, 0);
1890 SmallVector<llvm::APInt, 3> Dimensions;
1892 if (ElementTy->isConstantArrayType()) {
1893 const ConstantArrayType *CAT =
1894 getASTContext().getAsConstantArrayType(ElementTy);
1895 Dimensions.push_back(CAT->getSize());
1896 ElementTy = CAT->getElementType();
1897 } else if (ElementTy->isIncompleteArrayType()) {
1898 const IncompleteArrayType *IAT =
1899 getASTContext().getAsIncompleteArrayType(ElementTy);
1900 Dimensions.push_back(llvm::APInt(32, 0));
1901 ElementTy = IAT->getElementType();
1902 } else if (ElementTy->isVariableArrayType()) {
1903 const VariableArrayType *VAT =
1904 getASTContext().getAsVariableArrayType(ElementTy);
1905 Dimensions.push_back(llvm::APInt(32, 0));
1906 ElementTy = VAT->getElementType();
1907 } else if (ElementTy->isDependentSizedArrayType()) {
1908 // The dependent expression has to be folded into a constant (TODO).
1909 const DependentSizedArrayType *DSAT =
1910 getASTContext().getAsDependentSizedArrayType(ElementTy);
1911 DiagnosticsEngine &Diags = Context.getDiags();
1912 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1913 "cannot mangle this dependent-length array yet");
1914 Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
1915 << DSAT->getBracketsRange();
1922 // <dimension-count> ::= <number> # number of extra dimensions
1923 mangleNumber(Dimensions.size());
1924 for (const llvm::APInt &Dimension : Dimensions)
1925 mangleNumber(Dimension.getLimitedValue());
1926 mangleType(ElementTy, SourceRange(), QMM_Escape);
1929 // <type> ::= <pointer-to-member-type>
1930 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1931 // <class name> <type>
1932 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, Qualifiers Quals,
1933 SourceRange Range) {
1934 QualType PointeeType = T->getPointeeType();
1935 manglePointerCVQualifiers(Quals);
1936 manglePointerExtQualifiers(Quals, PointeeType);
1937 if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
1939 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1940 mangleFunctionType(FPT, nullptr, true);
1942 mangleQualifiers(PointeeType.getQualifiers(), true);
1943 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1944 mangleType(PointeeType, Range, QMM_Drop);
1948 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
1949 Qualifiers, SourceRange Range) {
1950 DiagnosticsEngine &Diags = Context.getDiags();
1951 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1952 "cannot mangle this template type parameter type yet");
1953 Diags.Report(Range.getBegin(), DiagID)
1957 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
1958 Qualifiers, SourceRange Range) {
1959 DiagnosticsEngine &Diags = Context.getDiags();
1960 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1961 "cannot mangle this substituted parameter pack yet");
1962 Diags.Report(Range.getBegin(), DiagID)
1966 // <type> ::= <pointer-type>
1967 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
1968 // # the E is required for 64-bit non-static pointers
1969 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
1970 SourceRange Range) {
1971 QualType PointeeType = T->getPointeeType();
1972 manglePointerCVQualifiers(Quals);
1973 manglePointerExtQualifiers(Quals, PointeeType);
1974 mangleType(PointeeType, Range);
1976 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
1977 Qualifiers Quals, SourceRange Range) {
1978 QualType PointeeType = T->getPointeeType();
1979 manglePointerCVQualifiers(Quals);
1980 manglePointerExtQualifiers(Quals, PointeeType);
1981 // Object pointers never have qualifiers.
1983 mangleType(PointeeType, Range);
1986 // <type> ::= <reference-type>
1987 // <reference-type> ::= A E? <cvr-qualifiers> <type>
1988 // # the E is required for 64-bit non-static lvalue references
1989 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
1990 Qualifiers Quals, SourceRange Range) {
1991 QualType PointeeType = T->getPointeeType();
1992 Out << (Quals.hasVolatile() ? 'B' : 'A');
1993 manglePointerExtQualifiers(Quals, PointeeType);
1994 mangleType(PointeeType, Range);
1997 // <type> ::= <r-value-reference-type>
1998 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
1999 // # the E is required for 64-bit non-static rvalue references
2000 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2001 Qualifiers Quals, SourceRange Range) {
2002 QualType PointeeType = T->getPointeeType();
2003 Out << (Quals.hasVolatile() ? "$$R" : "$$Q");
2004 manglePointerExtQualifiers(Quals, PointeeType);
2005 mangleType(PointeeType, Range);
2008 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
2009 SourceRange Range) {
2010 DiagnosticsEngine &Diags = Context.getDiags();
2011 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2012 "cannot mangle this complex number type yet");
2013 Diags.Report(Range.getBegin(), DiagID)
2017 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
2018 SourceRange Range) {
2019 const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
2020 assert(ET && "vectors with non-builtin elements are unsupported");
2021 uint64_t Width = getASTContext().getTypeSize(T);
2022 // Pattern match exactly the typedefs in our intrinsic headers. Anything that
2023 // doesn't match the Intel types uses a custom mangling below.
2024 bool IntelVector = true;
2025 if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
2027 } else if (Width == 128 || Width == 256) {
2028 if (ET->getKind() == BuiltinType::Float)
2029 Out << "T__m" << Width;
2030 else if (ET->getKind() == BuiltinType::LongLong)
2031 Out << "T__m" << Width << 'i';
2032 else if (ET->getKind() == BuiltinType::Double)
2033 Out << "U__m" << Width << 'd';
2035 IntelVector = false;
2037 IntelVector = false;
2041 // The MS ABI doesn't have a special mangling for vector types, so we define
2042 // our own mangling to handle uses of __vector_size__ on user-specified
2043 // types, and for extensions like __v4sf.
2044 Out << "T__clang_vec" << T->getNumElements() << '_';
2045 mangleType(ET, Quals, Range);
2051 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T, Qualifiers,
2052 SourceRange Range) {
2053 DiagnosticsEngine &Diags = Context.getDiags();
2054 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2055 "cannot mangle this extended vector type yet");
2056 Diags.Report(Range.getBegin(), DiagID)
2059 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
2060 Qualifiers, SourceRange Range) {
2061 DiagnosticsEngine &Diags = Context.getDiags();
2062 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2063 "cannot mangle this dependent-sized extended vector type yet");
2064 Diags.Report(Range.getBegin(), DiagID)
2068 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
2070 // ObjC interfaces have structs underlying them.
2072 mangleName(T->getDecl());
2075 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, Qualifiers,
2076 SourceRange Range) {
2077 // We don't allow overloading by different protocol qualification,
2078 // so mangling them isn't necessary.
2079 mangleType(T->getBaseType(), Range);
2082 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
2083 Qualifiers Quals, SourceRange Range) {
2084 QualType PointeeType = T->getPointeeType();
2085 manglePointerCVQualifiers(Quals);
2086 manglePointerExtQualifiers(Quals, PointeeType);
2090 mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
2093 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
2094 Qualifiers, SourceRange) {
2095 llvm_unreachable("Cannot mangle injected class name type.");
2098 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
2099 Qualifiers, SourceRange Range) {
2100 DiagnosticsEngine &Diags = Context.getDiags();
2101 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2102 "cannot mangle this template specialization type yet");
2103 Diags.Report(Range.getBegin(), DiagID)
2107 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
2108 SourceRange Range) {
2109 DiagnosticsEngine &Diags = Context.getDiags();
2110 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2111 "cannot mangle this dependent name type yet");
2112 Diags.Report(Range.getBegin(), DiagID)
2116 void MicrosoftCXXNameMangler::mangleType(
2117 const DependentTemplateSpecializationType *T, Qualifiers,
2118 SourceRange Range) {
2119 DiagnosticsEngine &Diags = Context.getDiags();
2120 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2121 "cannot mangle this dependent template specialization type yet");
2122 Diags.Report(Range.getBegin(), DiagID)
2126 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
2127 SourceRange Range) {
2128 DiagnosticsEngine &Diags = Context.getDiags();
2129 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2130 "cannot mangle this pack expansion yet");
2131 Diags.Report(Range.getBegin(), DiagID)
2135 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
2136 SourceRange Range) {
2137 DiagnosticsEngine &Diags = Context.getDiags();
2138 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2139 "cannot mangle this typeof(type) yet");
2140 Diags.Report(Range.getBegin(), DiagID)
2144 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
2145 SourceRange Range) {
2146 DiagnosticsEngine &Diags = Context.getDiags();
2147 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2148 "cannot mangle this typeof(expression) yet");
2149 Diags.Report(Range.getBegin(), DiagID)
2153 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
2154 SourceRange Range) {
2155 DiagnosticsEngine &Diags = Context.getDiags();
2156 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2157 "cannot mangle this decltype() yet");
2158 Diags.Report(Range.getBegin(), DiagID)
2162 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2163 Qualifiers, SourceRange Range) {
2164 DiagnosticsEngine &Diags = Context.getDiags();
2165 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2166 "cannot mangle this unary transform type yet");
2167 Diags.Report(Range.getBegin(), DiagID)
2171 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
2172 SourceRange Range) {
2173 assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2175 DiagnosticsEngine &Diags = Context.getDiags();
2176 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2177 "cannot mangle this 'auto' type yet");
2178 Diags.Report(Range.getBegin(), DiagID)
2182 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
2183 SourceRange Range) {
2184 DiagnosticsEngine &Diags = Context.getDiags();
2185 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2186 "cannot mangle this C11 atomic type yet");
2187 Diags.Report(Range.getBegin(), DiagID)
2191 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2193 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2194 "Invalid mangleName() call, argument is not a variable or function!");
2195 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2196 "Invalid mangleName() call on 'structor decl!");
2198 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2199 getASTContext().getSourceManager(),
2200 "Mangling declaration");
2202 MicrosoftCXXNameMangler Mangler(*this, Out);
2203 return Mangler.mangle(D);
2206 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2207 // <virtual-adjustment>
2208 // <no-adjustment> ::= A # private near
2209 // ::= B # private far
2210 // ::= I # protected near
2211 // ::= J # protected far
2212 // ::= Q # public near
2213 // ::= R # public far
2214 // <static-adjustment> ::= G <static-offset> # private near
2215 // ::= H <static-offset> # private far
2216 // ::= O <static-offset> # protected near
2217 // ::= P <static-offset> # protected far
2218 // ::= W <static-offset> # public near
2219 // ::= X <static-offset> # public far
2220 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2221 // ::= $1 <virtual-shift> <static-offset> # private far
2222 // ::= $2 <virtual-shift> <static-offset> # protected near
2223 // ::= $3 <virtual-shift> <static-offset> # protected far
2224 // ::= $4 <virtual-shift> <static-offset> # public near
2225 // ::= $5 <virtual-shift> <static-offset> # public far
2226 // <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift>
2227 // <vtordisp-shift> ::= <offset-to-vtordisp>
2228 // <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset>
2229 // <offset-to-vtordisp>
2230 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2231 const ThisAdjustment &Adjustment,
2232 MicrosoftCXXNameMangler &Mangler,
2234 if (!Adjustment.Virtual.isEmpty()) {
2237 switch (MD->getAccess()) {
2239 llvm_unreachable("Unsupported access specifier");
2249 if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2250 Out << 'R' << AccessSpec;
2251 Mangler.mangleNumber(
2252 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2253 Mangler.mangleNumber(
2254 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2255 Mangler.mangleNumber(
2256 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2257 Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2260 Mangler.mangleNumber(
2261 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2262 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2264 } else if (Adjustment.NonVirtual != 0) {
2265 switch (MD->getAccess()) {
2267 llvm_unreachable("Unsupported access specifier");
2277 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2279 switch (MD->getAccess()) {
2281 llvm_unreachable("Unsupported access specifier");
2295 MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
2297 MicrosoftVTableContext *VTContext =
2298 cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
2299 const MicrosoftVTableContext::MethodVFTableLocation &ML =
2300 VTContext->getMethodVFTableLocation(GlobalDecl(MD));
2302 MicrosoftCXXNameMangler Mangler(*this, Out);
2303 Mangler.getStream() << "\01?";
2304 Mangler.mangleVirtualMemPtrThunk(MD, ML);
2307 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2308 const ThunkInfo &Thunk,
2310 MicrosoftCXXNameMangler Mangler(*this, Out);
2312 Mangler.mangleName(MD);
2313 mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
2314 if (!Thunk.Return.isEmpty())
2315 assert(Thunk.Method != nullptr &&
2316 "Thunk info should hold the overridee decl");
2318 const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2319 Mangler.mangleFunctionType(
2320 DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
2323 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2324 const CXXDestructorDecl *DD, CXXDtorType Type,
2325 const ThisAdjustment &Adjustment, raw_ostream &Out) {
2326 // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2327 // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2328 // mangling manually until we support both deleting dtor types.
2329 assert(Type == Dtor_Deleting);
2330 MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
2332 Mangler.mangleName(DD->getParent());
2333 mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
2334 Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
2337 void MicrosoftMangleContextImpl::mangleCXXVFTable(
2338 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2340 // <mangled-name> ::= ?_7 <class-name> <storage-class>
2341 // <cvr-qualifiers> [<name>] @
2342 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2343 // is always '6' for vftables.
2344 MicrosoftCXXNameMangler Mangler(*this, Out);
2345 Mangler.getStream() << "\01??_7";
2346 Mangler.mangleName(Derived);
2347 Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2348 for (const CXXRecordDecl *RD : BasePath)
2349 Mangler.mangleName(RD);
2350 Mangler.getStream() << '@';
2353 void MicrosoftMangleContextImpl::mangleCXXVBTable(
2354 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2356 // <mangled-name> ::= ?_8 <class-name> <storage-class>
2357 // <cvr-qualifiers> [<name>] @
2358 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2359 // is always '7' for vbtables.
2360 MicrosoftCXXNameMangler Mangler(*this, Out);
2361 Mangler.getStream() << "\01??_8";
2362 Mangler.mangleName(Derived);
2363 Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const.
2364 for (const CXXRecordDecl *RD : BasePath)
2365 Mangler.mangleName(RD);
2366 Mangler.getStream() << '@';
2369 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
2370 MicrosoftCXXNameMangler Mangler(*this, Out);
2371 Mangler.getStream() << "\01??_R0";
2372 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2373 Mangler.getStream() << "@8";
2376 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
2378 MicrosoftCXXNameMangler Mangler(*this, Out);
2379 Mangler.getStream() << '.';
2380 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2383 void MicrosoftMangleContextImpl::mangleCXXCatchHandlerType(QualType T,
2386 MicrosoftCXXNameMangler Mangler(*this, Out);
2387 Mangler.getStream() << "llvm.eh.handlertype.";
2388 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2389 Mangler.getStream() << '.' << Flags;
2392 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T,
2395 uint32_t NumEntries,
2397 MicrosoftCXXNameMangler Mangler(*this, Out);
2398 Mangler.getStream() << "_TI";
2400 Mangler.getStream() << 'C';
2402 Mangler.getStream() << 'V';
2403 Mangler.getStream() << NumEntries;
2404 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2407 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
2408 QualType T, uint32_t NumEntries, raw_ostream &Out) {
2409 MicrosoftCXXNameMangler Mangler(*this, Out);
2410 Mangler.getStream() << "_CTA";
2411 Mangler.getStream() << NumEntries;
2412 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2415 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
2416 QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
2417 uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
2419 MicrosoftCXXNameMangler Mangler(*this, Out);
2420 Mangler.getStream() << "_CT";
2422 llvm::SmallString<64> RTTIMangling;
2424 llvm::raw_svector_ostream Stream(RTTIMangling);
2425 mangleCXXRTTI(T, Stream);
2427 Mangler.getStream() << RTTIMangling.substr(1);
2429 // VS2015 CTP6 omits the copy-constructor in the mangled name. This name is,
2430 // in fact, superfluous but I'm not sure the change was made consciously.
2431 // TODO: Revisit this when VS2015 gets released.
2432 llvm::SmallString<64> CopyCtorMangling;
2434 llvm::raw_svector_ostream Stream(CopyCtorMangling);
2435 mangleCXXCtor(CD, CT, Stream);
2437 Mangler.getStream() << CopyCtorMangling.substr(1);
2439 Mangler.getStream() << Size;
2440 if (VBPtrOffset == -1) {
2442 Mangler.getStream() << NVOffset;
2445 Mangler.getStream() << NVOffset;
2446 Mangler.getStream() << VBPtrOffset;
2447 Mangler.getStream() << VBIndex;
2451 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
2452 const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
2453 uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
2454 MicrosoftCXXNameMangler Mangler(*this, Out);
2455 Mangler.getStream() << "\01??_R1";
2456 Mangler.mangleNumber(NVOffset);
2457 Mangler.mangleNumber(VBPtrOffset);
2458 Mangler.mangleNumber(VBTableOffset);
2459 Mangler.mangleNumber(Flags);
2460 Mangler.mangleName(Derived);
2461 Mangler.getStream() << "8";
2464 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
2465 const CXXRecordDecl *Derived, raw_ostream &Out) {
2466 MicrosoftCXXNameMangler Mangler(*this, Out);
2467 Mangler.getStream() << "\01??_R2";
2468 Mangler.mangleName(Derived);
2469 Mangler.getStream() << "8";
2472 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
2473 const CXXRecordDecl *Derived, raw_ostream &Out) {
2474 MicrosoftCXXNameMangler Mangler(*this, Out);
2475 Mangler.getStream() << "\01??_R3";
2476 Mangler.mangleName(Derived);
2477 Mangler.getStream() << "8";
2480 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
2481 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2483 // <mangled-name> ::= ?_R4 <class-name> <storage-class>
2484 // <cvr-qualifiers> [<name>] @
2485 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2486 // is always '6' for vftables.
2487 MicrosoftCXXNameMangler Mangler(*this, Out);
2488 Mangler.getStream() << "\01??_R4";
2489 Mangler.mangleName(Derived);
2490 Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2491 for (const CXXRecordDecl *RD : BasePath)
2492 Mangler.mangleName(RD);
2493 Mangler.getStream() << '@';
2496 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
2497 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2498 MicrosoftCXXNameMangler Mangler(*this, Out);
2499 // The function body is in the same comdat as the function with the handler,
2500 // so the numbering here doesn't have to be the same across TUs.
2502 // <mangled-name> ::= ?filt$ <filter-number> @0
2503 Mangler.getStream() << "\01?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
2504 Mangler.mangleName(EnclosingDecl);
2507 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
2508 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2509 MicrosoftCXXNameMangler Mangler(*this, Out);
2510 // The function body is in the same comdat as the function with the handler,
2511 // so the numbering here doesn't have to be the same across TUs.
2513 // <mangled-name> ::= ?fin$ <filter-number> @0
2514 Mangler.getStream() << "\01?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
2515 Mangler.mangleName(EnclosingDecl);
2518 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
2519 // This is just a made up unique string for the purposes of tbaa. undname
2520 // does *not* know how to demangle it.
2521 MicrosoftCXXNameMangler Mangler(*this, Out);
2522 Mangler.getStream() << '?';
2523 Mangler.mangleType(T, SourceRange());
2526 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
2529 MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
2533 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
2536 MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
2540 void MicrosoftMangleContextImpl::mangleReferenceTemporary(const VarDecl *VD,
2543 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2544 "cannot mangle this reference temporary yet");
2545 getDiags().Report(VD->getLocation(), DiagID);
2548 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
2549 const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
2550 MicrosoftCXXNameMangler Mangler(*this, Out);
2552 Mangler.getStream() << "\01?$TSS" << GuardNum << '@';
2553 Mangler.mangleNestedName(VD);
2556 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
2558 // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
2559 // ::= ?__J <postfix> @5 <scope-depth>
2560 // ::= ?$S <guard-num> @ <postfix> @4IA
2562 // The first mangling is what MSVC uses to guard static locals in inline
2563 // functions. It uses a different mangling in external functions to support
2564 // guarding more than 32 variables. MSVC rejects inline functions with more
2565 // than 32 static locals. We don't fully implement the second mangling
2566 // because those guards are not externally visible, and instead use LLVM's
2567 // default renaming when creating a new guard variable.
2568 MicrosoftCXXNameMangler Mangler(*this, Out);
2570 bool Visible = VD->isExternallyVisible();
2572 Mangler.getStream() << (VD->getTLSKind() ? "\01??__J" : "\01??_B");
2574 Mangler.getStream() << "\01?$S1@";
2576 unsigned ScopeDepth = 0;
2577 if (Visible && !getNextDiscriminator(VD, ScopeDepth))
2578 // If we do not have a discriminator and are emitting a guard variable for
2579 // use at global scope, then mangling the nested name will not be enough to
2580 // remove ambiguities.
2581 Mangler.mangle(VD, "");
2583 Mangler.mangleNestedName(VD);
2584 Mangler.getStream() << (Visible ? "@5" : "@4IA");
2586 Mangler.mangleNumber(ScopeDepth);
2589 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
2592 MicrosoftCXXNameMangler Mangler(*this, Out);
2593 Mangler.getStream() << "\01??__" << CharCode;
2594 Mangler.mangleName(D);
2595 if (D->isStaticDataMember()) {
2596 Mangler.mangleVariableEncoding(D);
2597 Mangler.getStream() << '@';
2599 // This is the function class mangling. These stubs are global, non-variadic,
2600 // cdecl functions that return void and take no args.
2601 Mangler.getStream() << "YAXXZ";
2604 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
2606 // <initializer-name> ::= ?__E <name> YAXXZ
2607 mangleInitFiniStub(D, Out, 'E');
2611 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
2613 // <destructor-name> ::= ?__F <name> YAXXZ
2614 mangleInitFiniStub(D, Out, 'F');
2617 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
2619 // <char-type> ::= 0 # char
2621 // ::= ??? # char16_t/char32_t will need a mangling too...
2623 // <literal-length> ::= <non-negative integer> # the length of the literal
2625 // <encoded-crc> ::= <hex digit>+ @ # crc of the literal including
2626 // # null-terminator
2628 // <encoded-string> ::= <simple character> # uninteresting character
2629 // ::= '?$' <hex digit> <hex digit> # these two nibbles
2630 // # encode the byte for the
2632 // ::= '?' [a-z] # \xe1 - \xfa
2633 // ::= '?' [A-Z] # \xc1 - \xda
2634 // ::= '?' [0-9] # [,/\:. \n\t'-]
2636 // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
2637 // <encoded-string> '@'
2638 MicrosoftCXXNameMangler Mangler(*this, Out);
2639 Mangler.getStream() << "\01??_C@_";
2641 // <char-type>: The "kind" of string literal is encoded into the mangled name.
2643 Mangler.getStream() << '1';
2645 Mangler.getStream() << '0';
2647 // <literal-length>: The next part of the mangled name consists of the length
2649 // The StringLiteral does not consider the NUL terminator byte(s) but the
2651 // N.B. The length is in terms of bytes, not characters.
2652 Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
2654 // We will use the "Rocksoft^tm Model CRC Algorithm" to describe the
2655 // properties of our CRC:
2661 // XorOut : 00000000
2663 uint32_t CRC = 0xFFFFFFFFU;
2665 auto UpdateCRC = [&CRC](char Byte) {
2666 for (unsigned i = 0; i < 8; ++i) {
2667 bool Bit = CRC & 0x80000000U;
2668 if (Byte & (1U << i))
2676 auto GetLittleEndianByte = [&Mangler, &SL](unsigned Index) {
2677 unsigned CharByteWidth = SL->getCharByteWidth();
2678 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2679 unsigned OffsetInCodeUnit = Index % CharByteWidth;
2680 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2683 auto GetBigEndianByte = [&Mangler, &SL](unsigned Index) {
2684 unsigned CharByteWidth = SL->getCharByteWidth();
2685 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2686 unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
2687 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2690 // CRC all the bytes of the StringLiteral.
2691 for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
2692 UpdateCRC(GetLittleEndianByte(I));
2694 // The NUL terminator byte(s) were not present earlier,
2695 // we need to manually process those bytes into the CRC.
2696 for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2700 // The literature refers to the process of reversing the bits in the final CRC
2701 // output as "reflection".
2702 CRC = llvm::reverseBits(CRC);
2704 // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
2706 Mangler.mangleNumber(CRC);
2708 // <encoded-string>: The mangled name also contains the first 32 _characters_
2709 // (including null-terminator bytes) of the StringLiteral.
2710 // Each character is encoded by splitting them into bytes and then encoding
2711 // the constituent bytes.
2712 auto MangleByte = [&Mangler](char Byte) {
2713 // There are five different manglings for characters:
2714 // - [a-zA-Z0-9_$]: A one-to-one mapping.
2715 // - ?[a-z]: The range from \xe1 to \xfa.
2716 // - ?[A-Z]: The range from \xc1 to \xda.
2717 // - ?[0-9]: The set of [,/\:. \n\t'-].
2718 // - ?$XX: A fallback which maps nibbles.
2719 if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
2720 Mangler.getStream() << Byte;
2721 } else if (isLetter(Byte & 0x7f)) {
2722 Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
2724 const char SpecialChars[] = {',', '/', '\\', ':', '.',
2725 ' ', '\n', '\t', '\'', '-'};
2727 std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
2728 if (Pos != std::end(SpecialChars)) {
2729 Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
2731 Mangler.getStream() << "?$";
2732 Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
2733 Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
2738 // Enforce our 32 character max.
2739 unsigned NumCharsToMangle = std::min(32U, SL->getLength());
2740 for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E;
2743 MangleByte(GetBigEndianByte(I));
2745 MangleByte(GetLittleEndianByte(I));
2747 // Encode the NUL terminator if there is room.
2748 if (NumCharsToMangle < 32)
2749 for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2753 Mangler.getStream() << '@';
2756 void MicrosoftMangleContextImpl::mangleCXXVTableBitSet(const CXXRecordDecl *RD,
2758 llvm::report_fatal_error("Cannot mangle bitsets yet");
2761 MicrosoftMangleContext *
2762 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
2763 return new MicrosoftMangleContextImpl(Context, Diags);