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/DeclOpenMP.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/VTableBuilder.h"
27 #include "clang/Basic/ABI.h"
28 #include "clang/Basic/DiagnosticOptions.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/Support/JamCRC.h"
32 #include "llvm/Support/xxhash.h"
33 #include "llvm/Support/MD5.h"
34 #include "llvm/Support/MathExtras.h"
36 using namespace clang;
40 struct msvc_hashing_ostream : public llvm::raw_svector_ostream {
42 llvm::SmallString<64> Buffer;
44 msvc_hashing_ostream(raw_ostream &OS)
45 : llvm::raw_svector_ostream(Buffer), OS(OS) {}
46 ~msvc_hashing_ostream() override {
47 StringRef MangledName = str();
48 bool StartsWithEscape = MangledName.startswith("\01");
50 MangledName = MangledName.drop_front(1);
51 if (MangledName.size() <= 4096) {
57 llvm::MD5::MD5Result Hash;
58 Hasher.update(MangledName);
61 SmallString<32> HexString;
62 llvm::MD5::stringifyResult(Hash, HexString);
66 OS << "??@" << HexString << '@';
70 static const DeclContext *
71 getLambdaDefaultArgumentDeclContext(const Decl *D) {
72 if (const auto *RD = dyn_cast<CXXRecordDecl>(D))
74 if (const auto *Parm =
75 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
76 return Parm->getDeclContext();
80 /// Retrieve the declaration context that should be used when mangling
81 /// the given declaration.
82 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
83 // The ABI assumes that lambda closure types that occur within
84 // default arguments live in the context of the function. However, due to
85 // the way in which Clang parses and creates function declarations, this is
86 // not the case: the lambda closure type ends up living in the context
87 // where the function itself resides, because the function declaration itself
88 // had not yet been created. Fix the context here.
89 if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(D))
92 // Perform the same check for block literals.
93 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
94 if (ParmVarDecl *ContextParam =
95 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
96 return ContextParam->getDeclContext();
99 const DeclContext *DC = D->getDeclContext();
100 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
101 return getEffectiveDeclContext(cast<Decl>(DC));
104 return DC->getRedeclContext();
107 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
108 return getEffectiveDeclContext(cast<Decl>(DC));
111 static const FunctionDecl *getStructor(const NamedDecl *ND) {
112 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
113 return FTD->getTemplatedDecl()->getCanonicalDecl();
115 const auto *FD = cast<FunctionDecl>(ND);
116 if (const auto *FTD = FD->getPrimaryTemplate())
117 return FTD->getTemplatedDecl()->getCanonicalDecl();
119 return FD->getCanonicalDecl();
122 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
123 /// Microsoft Visual C++ ABI.
124 class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
125 typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
126 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
127 llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
128 llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
129 llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds;
130 llvm::DenseMap<const NamedDecl *, unsigned> SEHFinallyIds;
131 SmallString<16> AnonymousNamespaceHash;
134 MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags);
135 bool shouldMangleCXXName(const NamedDecl *D) override;
136 bool shouldMangleStringLiteral(const StringLiteral *SL) override;
137 void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
138 void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
139 const MethodVFTableLocation &ML,
140 raw_ostream &Out) override;
141 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
142 raw_ostream &) override;
143 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
144 const ThisAdjustment &ThisAdjustment,
145 raw_ostream &) override;
146 void mangleCXXVFTable(const CXXRecordDecl *Derived,
147 ArrayRef<const CXXRecordDecl *> BasePath,
148 raw_ostream &Out) override;
149 void mangleCXXVBTable(const CXXRecordDecl *Derived,
150 ArrayRef<const CXXRecordDecl *> BasePath,
151 raw_ostream &Out) override;
152 void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
153 const CXXRecordDecl *DstRD,
154 raw_ostream &Out) override;
155 void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
156 bool IsUnaligned, uint32_t NumEntries,
157 raw_ostream &Out) override;
158 void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
159 raw_ostream &Out) override;
160 void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
161 CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
162 int32_t VBPtrOffset, uint32_t VBIndex,
163 raw_ostream &Out) override;
164 void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
165 void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
166 void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
167 uint32_t NVOffset, int32_t VBPtrOffset,
168 uint32_t VBTableOffset, uint32_t Flags,
169 raw_ostream &Out) override;
170 void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
171 raw_ostream &Out) override;
172 void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
173 raw_ostream &Out) override;
175 mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
176 ArrayRef<const CXXRecordDecl *> BasePath,
177 raw_ostream &Out) override;
178 void mangleTypeName(QualType T, raw_ostream &) override;
179 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
180 raw_ostream &) override;
181 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
182 raw_ostream &) override;
183 void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
184 raw_ostream &) override;
185 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
186 void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
187 raw_ostream &Out) override;
188 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
189 void mangleDynamicAtExitDestructor(const VarDecl *D,
190 raw_ostream &Out) override;
191 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
192 raw_ostream &Out) override;
193 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
194 raw_ostream &Out) override;
195 void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
196 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
197 const DeclContext *DC = getEffectiveDeclContext(ND);
198 if (!DC->isFunctionOrMethod())
201 // Lambda closure types are already numbered, give out a phony number so
202 // that they demangle nicely.
203 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
204 if (RD->isLambda()) {
210 // Use the canonical number for externally visible decls.
211 if (ND->isExternallyVisible()) {
212 disc = getASTContext().getManglingNumber(ND);
216 // Anonymous tags are already numbered.
217 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
218 if (!Tag->hasNameForLinkage() &&
219 !getASTContext().getDeclaratorForUnnamedTagDecl(Tag) &&
220 !getASTContext().getTypedefNameForUnnamedTagDecl(Tag))
224 // Make up a reasonable number for internal decls.
225 unsigned &discriminator = Uniquifier[ND];
227 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
228 disc = discriminator + 1;
232 unsigned getLambdaId(const CXXRecordDecl *RD) {
233 assert(RD->isLambda() && "RD must be a lambda!");
234 assert(!RD->isExternallyVisible() && "RD must not be visible!");
235 assert(RD->getLambdaManglingNumber() == 0 &&
236 "RD must not have a mangling number!");
237 std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
238 Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
239 return Result.first->second;
242 /// Return a character sequence that is (somewhat) unique to the TU suitable
243 /// for mangling anonymous namespaces.
244 StringRef getAnonymousNamespaceHash() const {
245 return AnonymousNamespaceHash;
249 void mangleInitFiniStub(const VarDecl *D, char CharCode, raw_ostream &Out);
252 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
253 /// Microsoft Visual C++ ABI.
254 class MicrosoftCXXNameMangler {
255 MicrosoftMangleContextImpl &Context;
258 /// The "structor" is the top-level declaration being mangled, if
259 /// that's not a template specialization; otherwise it's the pattern
260 /// for that specialization.
261 const NamedDecl *Structor;
262 unsigned StructorType;
264 typedef llvm::SmallVector<std::string, 10> BackRefVec;
265 BackRefVec NameBackReferences;
267 typedef llvm::DenseMap<const void *, unsigned> ArgBackRefMap;
268 ArgBackRefMap TypeBackReferences;
270 typedef std::set<int> PassObjectSizeArgsSet;
271 PassObjectSizeArgsSet PassObjectSizeArgs;
273 ASTContext &getASTContext() const { return Context.getASTContext(); }
275 // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
276 // this check into mangleQualifiers().
277 const bool PointersAre64Bit;
280 enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
282 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
283 : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
284 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
287 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
288 const CXXConstructorDecl *D, CXXCtorType Type)
289 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
290 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
293 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
294 const CXXDestructorDecl *D, CXXDtorType Type)
295 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
296 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
299 raw_ostream &getStream() const { return Out; }
301 void mangle(const NamedDecl *D, StringRef Prefix = "?");
302 void mangleName(const NamedDecl *ND);
303 void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
304 void mangleVariableEncoding(const VarDecl *VD);
305 void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
306 void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
307 const CXXMethodDecl *MD);
308 void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
309 const MethodVFTableLocation &ML);
310 void mangleNumber(int64_t Number);
311 void mangleTagTypeKind(TagTypeKind TK);
312 void mangleArtificialTagType(TagTypeKind TK, StringRef UnqualifiedName,
313 ArrayRef<StringRef> NestedNames = None);
314 void mangleAddressSpaceType(QualType T, Qualifiers Quals, SourceRange Range);
315 void mangleType(QualType T, SourceRange Range,
316 QualifierMangleMode QMM = QMM_Mangle);
317 void mangleFunctionType(const FunctionType *T,
318 const FunctionDecl *D = nullptr,
319 bool ForceThisQuals = false,
320 bool MangleExceptionSpec = true);
321 void mangleNestedName(const NamedDecl *ND);
324 bool isStructorDecl(const NamedDecl *ND) const {
325 return ND == Structor || getStructor(ND) == Structor;
328 void mangleUnqualifiedName(const NamedDecl *ND) {
329 mangleUnqualifiedName(ND, ND->getDeclName());
331 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
332 void mangleSourceName(StringRef Name);
333 void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
334 void mangleCXXDtorType(CXXDtorType T);
335 void mangleQualifiers(Qualifiers Quals, bool IsMember);
336 void mangleRefQualifier(RefQualifierKind RefQualifier);
337 void manglePointerCVQualifiers(Qualifiers Quals);
338 void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
340 void mangleUnscopedTemplateName(const TemplateDecl *ND);
342 mangleTemplateInstantiationName(const TemplateDecl *TD,
343 const TemplateArgumentList &TemplateArgs);
344 void mangleObjCMethodName(const ObjCMethodDecl *MD);
346 void mangleArgumentType(QualType T, SourceRange Range);
347 void manglePassObjectSizeArg(const PassObjectSizeAttr *POSA);
349 bool isArtificialTagType(QualType T) const;
351 // Declare manglers for every type class.
352 #define ABSTRACT_TYPE(CLASS, PARENT)
353 #define NON_CANONICAL_TYPE(CLASS, PARENT)
354 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
357 #include "clang/AST/TypeNodes.def"
359 #undef NON_CANONICAL_TYPE
362 void mangleType(const TagDecl *TD);
363 void mangleDecayedArrayType(const ArrayType *T);
364 void mangleArrayType(const ArrayType *T);
365 void mangleFunctionClass(const FunctionDecl *FD);
366 void mangleCallingConvention(CallingConv CC);
367 void mangleCallingConvention(const FunctionType *T);
368 void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
369 void mangleExpression(const Expr *E);
370 void mangleThrowSpecification(const FunctionProtoType *T);
372 void mangleTemplateArgs(const TemplateDecl *TD,
373 const TemplateArgumentList &TemplateArgs);
374 void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
375 const NamedDecl *Parm);
377 void mangleObjCProtocol(const ObjCProtocolDecl *PD);
378 void mangleObjCLifetime(const QualType T, Qualifiers Quals,
380 void mangleObjCKindOfType(const ObjCObjectType *T, Qualifiers Quals,
385 MicrosoftMangleContextImpl::MicrosoftMangleContextImpl(ASTContext &Context,
386 DiagnosticsEngine &Diags)
387 : MicrosoftMangleContext(Context, Diags) {
388 // To mangle anonymous namespaces, hash the path to the main source file. The
389 // path should be whatever (probably relative) path was passed on the command
390 // line. The goal is for the compiler to produce the same output regardless of
391 // working directory, so use the uncanonicalized relative path.
393 // It's important to make the mangled names unique because, when CodeView
394 // debug info is in use, the debugger uses mangled type names to distinguish
395 // between otherwise identically named types in anonymous namespaces.
397 // These symbols are always internal, so there is no need for the hash to
398 // match what MSVC produces. For the same reason, clang is free to change the
399 // hash at any time without breaking compatibility with old versions of clang.
400 // The generated names are intended to look similar to what MSVC generates,
401 // which are something like "?A0x01234567@".
402 SourceManager &SM = Context.getSourceManager();
403 if (const FileEntry *FE = SM.getFileEntryForID(SM.getMainFileID())) {
404 // Truncate the hash so we get 8 characters of hexadecimal.
405 uint32_t TruncatedHash = uint32_t(xxHash64(FE->getName()));
406 AnonymousNamespaceHash = llvm::utohexstr(TruncatedHash);
408 // If we don't have a path to the main file, we'll just use 0.
409 AnonymousNamespaceHash = "0";
413 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
414 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
415 LanguageLinkage L = FD->getLanguageLinkage();
416 // Overloadable functions need mangling.
417 if (FD->hasAttr<OverloadableAttr>())
420 // The ABI expects that we would never mangle "typical" user-defined entry
421 // points regardless of visibility or freestanding-ness.
423 // N.B. This is distinct from asking about "main". "main" has a lot of
424 // special rules associated with it in the standard while these
425 // user-defined entry points are outside of the purview of the standard.
426 // For example, there can be only one definition for "main" in a standards
427 // compliant program; however nothing forbids the existence of wmain and
428 // WinMain in the same translation unit.
429 if (FD->isMSVCRTEntryPoint())
432 // C++ functions and those whose names are not a simple identifier need
434 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
437 // C functions are not mangled.
438 if (L == CLanguageLinkage)
442 // Otherwise, no mangling is done outside C++ mode.
443 if (!getASTContext().getLangOpts().CPlusPlus)
446 const VarDecl *VD = dyn_cast<VarDecl>(D);
447 if (VD && !isa<DecompositionDecl>(D)) {
448 // C variables are not mangled.
452 // Variables at global scope with non-internal linkage are not mangled.
453 const DeclContext *DC = getEffectiveDeclContext(D);
454 // Check for extern variable declared locally.
455 if (DC->isFunctionOrMethod() && D->hasLinkage())
456 while (!DC->isNamespace() && !DC->isTranslationUnit())
457 DC = getEffectiveParentContext(DC);
459 if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
460 !isa<VarTemplateSpecializationDecl>(D) &&
461 D->getIdentifier() != nullptr)
469 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
473 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
474 // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
475 // Therefore it's really important that we don't decorate the
476 // name with leading underscores or leading/trailing at signs. So, by
477 // default, we emit an asm marker at the start so we get the name right.
478 // Callers can override this with a custom prefix.
480 // <mangled-name> ::= ? <name> <type-encoding>
483 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
484 mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
485 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
486 mangleVariableEncoding(VD);
488 llvm_unreachable("Tried to mangle unexpected NamedDecl!");
491 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD,
493 // <type-encoding> ::= <function-class> <function-type>
495 // Since MSVC operates on the type as written and not the canonical type, it
496 // actually matters which decl we have here. MSVC appears to choose the
497 // first, since it is most likely to be the declaration in a header file.
498 FD = FD->getFirstDecl();
500 // We should never ever see a FunctionNoProtoType at this point.
501 // We don't even know how to mangle their types anyway :).
502 const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
504 // extern "C" functions can hold entities that must be mangled.
505 // As it stands, these functions still need to get expressed in the full
506 // external name. They have their class and type omitted, replaced with '9'.
508 // We would like to mangle all extern "C" functions using this additional
509 // component but this would break compatibility with MSVC's behavior.
510 // Instead, do this when we know that compatibility isn't important (in
511 // other words, when it is an overloaded extern "C" function).
512 if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
515 mangleFunctionClass(FD);
517 mangleFunctionType(FT, FD, false, false);
523 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
524 // <type-encoding> ::= <storage-class> <variable-type>
525 // <storage-class> ::= 0 # private static member
526 // ::= 1 # protected static member
527 // ::= 2 # public static member
529 // ::= 4 # static local
531 // The first character in the encoding (after the name) is the storage class.
532 if (VD->isStaticDataMember()) {
533 // If it's a static member, it also encodes the access level.
534 switch (VD->getAccess()) {
536 case AS_private: Out << '0'; break;
537 case AS_protected: Out << '1'; break;
538 case AS_public: Out << '2'; break;
541 else if (!VD->isStaticLocal())
545 // Now mangle the type.
546 // <variable-type> ::= <type> <cvr-qualifiers>
547 // ::= <type> <pointee-cvr-qualifiers> # pointers, references
548 // Pointers and references are odd. The type of 'int * const foo;' gets
549 // mangled as 'QAHA' instead of 'PAHB', for example.
550 SourceRange SR = VD->getSourceRange();
551 QualType Ty = VD->getType();
552 if (Ty->isPointerType() || Ty->isReferenceType() ||
553 Ty->isMemberPointerType()) {
554 mangleType(Ty, SR, QMM_Drop);
555 manglePointerExtQualifiers(
556 Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
557 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
558 mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
559 // Member pointers are suffixed with a back reference to the member
560 // pointer's class name.
561 mangleName(MPT->getClass()->getAsCXXRecordDecl());
563 mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
564 } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
565 // Global arrays are funny, too.
566 mangleDecayedArrayType(AT);
567 if (AT->getElementType()->isArrayType())
570 mangleQualifiers(Ty.getQualifiers(), false);
572 mangleType(Ty, SR, QMM_Drop);
573 mangleQualifiers(Ty.getQualifiers(), false);
577 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
578 const ValueDecl *VD) {
579 // <member-data-pointer> ::= <integer-literal>
580 // ::= $F <number> <number>
581 // ::= $G <number> <number> <number>
584 int64_t VBTableOffset;
585 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
587 FieldOffset = getASTContext().getFieldOffset(VD);
588 assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
589 "cannot take address of bitfield");
590 FieldOffset /= getASTContext().getCharWidth();
594 if (IM == MSInheritanceAttr::Keyword_virtual_inheritance)
595 FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
597 FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
604 case MSInheritanceAttr::Keyword_single_inheritance: Code = '0'; break;
605 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = '0'; break;
606 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'F'; break;
607 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
612 mangleNumber(FieldOffset);
614 // The C++ standard doesn't allow base-to-derived member pointer conversions
615 // in template parameter contexts, so the vbptr offset of data member pointers
617 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
619 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
620 mangleNumber(VBTableOffset);
624 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
625 const CXXMethodDecl *MD) {
626 // <member-function-pointer> ::= $1? <name>
627 // ::= $H? <name> <number>
628 // ::= $I? <name> <number> <number>
629 // ::= $J? <name> <number> <number> <number>
631 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
635 case MSInheritanceAttr::Keyword_single_inheritance: Code = '1'; break;
636 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = 'H'; break;
637 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'I'; break;
638 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
641 // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr
643 uint64_t NVOffset = 0;
644 uint64_t VBTableOffset = 0;
645 uint64_t VBPtrOffset = 0;
647 Out << '$' << Code << '?';
648 if (MD->isVirtual()) {
649 MicrosoftVTableContext *VTContext =
650 cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
651 MethodVFTableLocation ML =
652 VTContext->getMethodVFTableLocation(GlobalDecl(MD));
653 mangleVirtualMemPtrThunk(MD, ML);
654 NVOffset = ML.VFPtrOffset.getQuantity();
655 VBTableOffset = ML.VBTableIndex * 4;
657 const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
658 VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
662 mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
665 if (VBTableOffset == 0 &&
666 IM == MSInheritanceAttr::Keyword_virtual_inheritance)
667 NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
669 // Null single inheritance member functions are encoded as a simple nullptr.
670 if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
674 if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
679 if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
680 mangleNumber(static_cast<uint32_t>(NVOffset));
681 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
682 mangleNumber(VBPtrOffset);
683 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
684 mangleNumber(VBTableOffset);
687 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
688 const CXXMethodDecl *MD, const MethodVFTableLocation &ML) {
689 // Get the vftable offset.
690 CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
691 getASTContext().getTargetInfo().getPointerWidth(0));
692 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
695 mangleName(MD->getParent());
697 mangleNumber(OffsetInVFTable);
699 mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>());
702 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
703 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
705 // Always start with the unqualified name.
706 mangleUnqualifiedName(ND);
708 mangleNestedName(ND);
710 // Terminate the whole name with an '@'.
714 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
715 // <non-negative integer> ::= A@ # when Number == 0
716 // ::= <decimal digit> # when 1 <= Number <= 10
717 // ::= <hex digit>+ @ # when Number >= 10
719 // <number> ::= [?] <non-negative integer>
721 uint64_t Value = static_cast<uint64_t>(Number);
729 else if (Value >= 1 && Value <= 10)
732 // Numbers that are not encoded as decimal digits are represented as nibbles
733 // in the range of ASCII characters 'A' to 'P'.
734 // The number 0x123450 would be encoded as 'BCDEFA'
735 char EncodedNumberBuffer[sizeof(uint64_t) * 2];
736 MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
737 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
738 for (; Value != 0; Value >>= 4)
739 *I++ = 'A' + (Value & 0xf);
740 Out.write(I.base(), I - BufferRef.rbegin());
745 static const TemplateDecl *
746 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
747 // Check if we have a function template.
748 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
749 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
750 TemplateArgs = FD->getTemplateSpecializationArgs();
755 // Check if we have a class template.
756 if (const ClassTemplateSpecializationDecl *Spec =
757 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
758 TemplateArgs = &Spec->getTemplateArgs();
759 return Spec->getSpecializedTemplate();
762 // Check if we have a variable template.
763 if (const VarTemplateSpecializationDecl *Spec =
764 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
765 TemplateArgs = &Spec->getTemplateArgs();
766 return Spec->getSpecializedTemplate();
772 void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
773 DeclarationName Name) {
774 // <unqualified-name> ::= <operator-name>
775 // ::= <ctor-dtor-name>
777 // ::= <template-name>
779 // Check if we have a template.
780 const TemplateArgumentList *TemplateArgs = nullptr;
781 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
782 // Function templates aren't considered for name back referencing. This
783 // makes sense since function templates aren't likely to occur multiple
784 // times in a symbol.
785 if (isa<FunctionTemplateDecl>(TD)) {
786 mangleTemplateInstantiationName(TD, *TemplateArgs);
791 // Here comes the tricky thing: if we need to mangle something like
792 // void foo(A::X<Y>, B::X<Y>),
793 // the X<Y> part is aliased. However, if you need to mangle
794 // void foo(A::X<A::Y>, A::X<B::Y>),
795 // the A::X<> part is not aliased.
796 // That said, from the mangler's perspective we have a structure like this:
797 // namespace[s] -> type[ -> template-parameters]
798 // but from the Clang perspective we have
799 // type [ -> template-parameters]
801 // What we do is we create a new mangler, mangle the same type (without
802 // a namespace suffix) to a string using the extra mangler and then use
803 // the mangled type name as a key to check the mangling of different types
806 llvm::SmallString<64> TemplateMangling;
807 llvm::raw_svector_ostream Stream(TemplateMangling);
808 MicrosoftCXXNameMangler Extra(Context, Stream);
809 Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
811 mangleSourceName(TemplateMangling);
815 switch (Name.getNameKind()) {
816 case DeclarationName::Identifier: {
817 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
818 mangleSourceName(II->getName());
822 // Otherwise, an anonymous entity. We must have a declaration.
823 assert(ND && "mangling empty name without declaration");
825 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
826 if (NS->isAnonymousNamespace()) {
827 Out << "?A0x" << Context.getAnonymousNamespaceHash() << '@';
832 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(ND)) {
833 // FIXME: Invented mangling for decomposition declarations:
835 // where X,Y,Z are the names of the bindings.
836 llvm::SmallString<128> Name("[");
837 for (auto *BD : DD->bindings()) {
840 Name += BD->getDeclName().getAsIdentifierInfo()->getName();
843 mangleSourceName(Name);
847 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
848 // We must have an anonymous union or struct declaration.
849 const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
850 assert(RD && "expected variable decl to have a record type");
851 // Anonymous types with no tag or typedef get the name of their
852 // declarator mangled in. If they have no declarator, number them with
854 llvm::SmallString<64> Name("$S");
855 // Get a unique id for the anonymous struct.
856 Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
857 mangleSourceName(Name.str());
861 // We must have an anonymous struct.
862 const TagDecl *TD = cast<TagDecl>(ND);
863 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
864 assert(TD->getDeclContext() == D->getDeclContext() &&
865 "Typedef should not be in another decl context!");
866 assert(D->getDeclName().getAsIdentifierInfo() &&
867 "Typedef was not named!");
868 mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
872 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
873 if (Record->isLambda()) {
874 llvm::SmallString<10> Name("<lambda_");
876 Decl *LambdaContextDecl = Record->getLambdaContextDecl();
877 unsigned LambdaManglingNumber = Record->getLambdaManglingNumber();
879 const ParmVarDecl *Parm =
880 dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
881 const FunctionDecl *Func =
882 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
885 unsigned DefaultArgNo =
886 Func->getNumParams() - Parm->getFunctionScopeIndex();
887 Name += llvm::utostr(DefaultArgNo);
891 if (LambdaManglingNumber)
892 LambdaId = LambdaManglingNumber;
894 LambdaId = Context.getLambdaId(Record);
896 Name += llvm::utostr(LambdaId);
899 mangleSourceName(Name);
901 // If the context of a closure type is an initializer for a class
902 // member (static or nonstatic), it is encoded in a qualified name.
903 if (LambdaManglingNumber && LambdaContextDecl) {
904 if ((isa<VarDecl>(LambdaContextDecl) ||
905 isa<FieldDecl>(LambdaContextDecl)) &&
906 LambdaContextDecl->getDeclContext()->isRecord()) {
907 mangleUnqualifiedName(cast<NamedDecl>(LambdaContextDecl));
914 llvm::SmallString<64> Name;
915 if (DeclaratorDecl *DD =
916 Context.getASTContext().getDeclaratorForUnnamedTagDecl(TD)) {
917 // Anonymous types without a name for linkage purposes have their
918 // declarator mangled in if they have one.
919 Name += "<unnamed-type-";
920 Name += DD->getName();
921 } else if (TypedefNameDecl *TND =
922 Context.getASTContext().getTypedefNameForUnnamedTagDecl(
924 // Anonymous types without a name for linkage purposes have their
925 // associate typedef mangled in if they have one.
926 Name += "<unnamed-type-";
927 Name += TND->getName();
928 } else if (isa<EnumDecl>(TD) &&
929 cast<EnumDecl>(TD)->enumerator_begin() !=
930 cast<EnumDecl>(TD)->enumerator_end()) {
931 // Anonymous non-empty enums mangle in the first enumerator.
932 auto *ED = cast<EnumDecl>(TD);
933 Name += "<unnamed-enum-";
934 Name += ED->enumerator_begin()->getName();
936 // Otherwise, number the types using a $S prefix.
937 Name += "<unnamed-type-$S";
938 Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1);
941 mangleSourceName(Name.str());
945 case DeclarationName::ObjCZeroArgSelector:
946 case DeclarationName::ObjCOneArgSelector:
947 case DeclarationName::ObjCMultiArgSelector: {
948 // This is reachable only when constructing an outlined SEH finally
949 // block. Nothing depends on this mangling and it's used only with
950 // functinos with internal linkage.
951 llvm::SmallString<64> Name;
952 mangleSourceName(Name.str());
956 case DeclarationName::CXXConstructorName:
957 if (isStructorDecl(ND)) {
958 if (StructorType == Ctor_CopyingClosure) {
962 if (StructorType == Ctor_DefaultClosure) {
970 case DeclarationName::CXXDestructorName:
971 if (isStructorDecl(ND))
972 // If the named decl is the C++ destructor we're mangling,
973 // use the type we were given.
974 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
976 // Otherwise, use the base destructor name. This is relevant if a
977 // class with a destructor is declared within a destructor.
978 mangleCXXDtorType(Dtor_Base);
981 case DeclarationName::CXXConversionFunctionName:
982 // <operator-name> ::= ?B # (cast)
983 // The target type is encoded as the return type.
987 case DeclarationName::CXXOperatorName:
988 mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
991 case DeclarationName::CXXLiteralOperatorName: {
993 mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
997 case DeclarationName::CXXDeductionGuideName:
998 llvm_unreachable("Can't mangle a deduction guide name!");
1000 case DeclarationName::CXXUsingDirective:
1001 llvm_unreachable("Can't mangle a using directive name!");
1005 // <postfix> ::= <unqualified-name> [<postfix>]
1006 // ::= <substitution> [<postfix>]
1007 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
1008 const DeclContext *DC = getEffectiveDeclContext(ND);
1009 while (!DC->isTranslationUnit()) {
1010 if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
1012 if (Context.getNextDiscriminator(ND, Disc)) {
1019 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
1021 [](StringRef Name, const unsigned Discriminator,
1022 const unsigned ParameterDiscriminator) -> std::string {
1024 llvm::raw_string_ostream Stream(Buffer);
1027 Stream << '_' << Discriminator;
1028 if (ParameterDiscriminator)
1029 Stream << '_' << ParameterDiscriminator;
1030 return Stream.str();
1033 unsigned Discriminator = BD->getBlockManglingNumber();
1035 Discriminator = Context.getBlockId(BD, /*Local=*/false);
1037 // Mangle the parameter position as a discriminator to deal with unnamed
1038 // parameters. Rather than mangling the unqualified parameter name,
1039 // always use the position to give a uniform mangling.
1040 unsigned ParameterDiscriminator = 0;
1041 if (const auto *MC = BD->getBlockManglingContextDecl())
1042 if (const auto *P = dyn_cast<ParmVarDecl>(MC))
1043 if (const auto *F = dyn_cast<FunctionDecl>(P->getDeclContext()))
1044 ParameterDiscriminator =
1045 F->getNumParams() - P->getFunctionScopeIndex();
1047 DC = getEffectiveDeclContext(BD);
1050 mangleSourceName(Discriminate("_block_invoke", Discriminator,
1051 ParameterDiscriminator));
1052 // If we have a block mangling context, encode that now. This allows us
1053 // to discriminate between named static data initializers in the same
1054 // scope. This is handled differently from parameters, which use
1055 // positions to discriminate between multiple instances.
1056 if (const auto *MC = BD->getBlockManglingContextDecl())
1057 if (!isa<ParmVarDecl>(MC))
1058 if (const auto *ND = dyn_cast<NamedDecl>(MC))
1059 mangleUnqualifiedName(ND);
1060 // MS ABI and Itanium manglings are in inverted scopes. In the case of a
1061 // RecordDecl, mangle the entire scope hierarchy at this point rather than
1062 // just the unqualified name to get the ordering correct.
1063 if (const auto *RD = dyn_cast<RecordDecl>(DC))
1069 // struct __block_literal *
1072 if (PointersAre64Bit)
1075 mangleArtificialTagType(TTK_Struct,
1076 Discriminate("__block_literal", Discriminator,
1077 ParameterDiscriminator));
1080 // If the effective context was a Record, we have fully mangled the
1081 // qualified name and do not need to continue.
1082 if (isa<RecordDecl>(DC))
1085 } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
1086 mangleObjCMethodName(Method);
1087 } else if (isa<NamedDecl>(DC)) {
1088 ND = cast<NamedDecl>(DC);
1089 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1093 mangleUnqualifiedName(ND);
1094 // Lambdas in default arguments conceptually belong to the function the
1095 // parameter corresponds to.
1096 if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(ND)) {
1102 DC = DC->getParent();
1106 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
1107 // Microsoft uses the names on the case labels for these dtor variants. Clang
1108 // uses the Itanium terminology internally. Everything in this ABI delegates
1109 // towards the base dtor.
1111 // <operator-name> ::= ?1 # destructor
1112 case Dtor_Base: Out << "?1"; return;
1113 // <operator-name> ::= ?_D # vbase destructor
1114 case Dtor_Complete: Out << "?_D"; return;
1115 // <operator-name> ::= ?_G # scalar deleting destructor
1116 case Dtor_Deleting: Out << "?_G"; return;
1117 // <operator-name> ::= ?_E # vector deleting destructor
1118 // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need
1121 llvm_unreachable("not expecting a COMDAT");
1123 llvm_unreachable("Unsupported dtor type?");
1126 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
1127 SourceLocation Loc) {
1131 // <operator-name> ::= ?2 # new
1132 case OO_New: Out << "?2"; break;
1133 // <operator-name> ::= ?3 # delete
1134 case OO_Delete: Out << "?3"; break;
1135 // <operator-name> ::= ?4 # =
1136 case OO_Equal: Out << "?4"; break;
1137 // <operator-name> ::= ?5 # >>
1138 case OO_GreaterGreater: Out << "?5"; break;
1139 // <operator-name> ::= ?6 # <<
1140 case OO_LessLess: Out << "?6"; break;
1141 // <operator-name> ::= ?7 # !
1142 case OO_Exclaim: Out << "?7"; break;
1143 // <operator-name> ::= ?8 # ==
1144 case OO_EqualEqual: Out << "?8"; break;
1145 // <operator-name> ::= ?9 # !=
1146 case OO_ExclaimEqual: Out << "?9"; break;
1147 // <operator-name> ::= ?A # []
1148 case OO_Subscript: Out << "?A"; break;
1150 // <operator-name> ::= ?C # ->
1151 case OO_Arrow: Out << "?C"; break;
1152 // <operator-name> ::= ?D # *
1153 case OO_Star: Out << "?D"; break;
1154 // <operator-name> ::= ?E # ++
1155 case OO_PlusPlus: Out << "?E"; break;
1156 // <operator-name> ::= ?F # --
1157 case OO_MinusMinus: Out << "?F"; break;
1158 // <operator-name> ::= ?G # -
1159 case OO_Minus: Out << "?G"; break;
1160 // <operator-name> ::= ?H # +
1161 case OO_Plus: Out << "?H"; break;
1162 // <operator-name> ::= ?I # &
1163 case OO_Amp: Out << "?I"; break;
1164 // <operator-name> ::= ?J # ->*
1165 case OO_ArrowStar: Out << "?J"; break;
1166 // <operator-name> ::= ?K # /
1167 case OO_Slash: Out << "?K"; break;
1168 // <operator-name> ::= ?L # %
1169 case OO_Percent: Out << "?L"; break;
1170 // <operator-name> ::= ?M # <
1171 case OO_Less: Out << "?M"; break;
1172 // <operator-name> ::= ?N # <=
1173 case OO_LessEqual: Out << "?N"; break;
1174 // <operator-name> ::= ?O # >
1175 case OO_Greater: Out << "?O"; break;
1176 // <operator-name> ::= ?P # >=
1177 case OO_GreaterEqual: Out << "?P"; break;
1178 // <operator-name> ::= ?Q # ,
1179 case OO_Comma: Out << "?Q"; break;
1180 // <operator-name> ::= ?R # ()
1181 case OO_Call: Out << "?R"; break;
1182 // <operator-name> ::= ?S # ~
1183 case OO_Tilde: Out << "?S"; break;
1184 // <operator-name> ::= ?T # ^
1185 case OO_Caret: Out << "?T"; break;
1186 // <operator-name> ::= ?U # |
1187 case OO_Pipe: Out << "?U"; break;
1188 // <operator-name> ::= ?V # &&
1189 case OO_AmpAmp: Out << "?V"; break;
1190 // <operator-name> ::= ?W # ||
1191 case OO_PipePipe: Out << "?W"; break;
1192 // <operator-name> ::= ?X # *=
1193 case OO_StarEqual: Out << "?X"; break;
1194 // <operator-name> ::= ?Y # +=
1195 case OO_PlusEqual: Out << "?Y"; break;
1196 // <operator-name> ::= ?Z # -=
1197 case OO_MinusEqual: Out << "?Z"; break;
1198 // <operator-name> ::= ?_0 # /=
1199 case OO_SlashEqual: Out << "?_0"; break;
1200 // <operator-name> ::= ?_1 # %=
1201 case OO_PercentEqual: Out << "?_1"; break;
1202 // <operator-name> ::= ?_2 # >>=
1203 case OO_GreaterGreaterEqual: Out << "?_2"; break;
1204 // <operator-name> ::= ?_3 # <<=
1205 case OO_LessLessEqual: Out << "?_3"; break;
1206 // <operator-name> ::= ?_4 # &=
1207 case OO_AmpEqual: Out << "?_4"; break;
1208 // <operator-name> ::= ?_5 # |=
1209 case OO_PipeEqual: Out << "?_5"; break;
1210 // <operator-name> ::= ?_6 # ^=
1211 case OO_CaretEqual: Out << "?_6"; break;
1216 // ?_B # local static guard
1218 // ?_D # vbase destructor
1219 // ?_E # vector deleting destructor
1220 // ?_F # default constructor closure
1221 // ?_G # scalar deleting destructor
1222 // ?_H # vector constructor iterator
1223 // ?_I # vector destructor iterator
1224 // ?_J # vector vbase constructor iterator
1225 // ?_K # virtual displacement map
1226 // ?_L # eh vector constructor iterator
1227 // ?_M # eh vector destructor iterator
1228 // ?_N # eh vector vbase constructor iterator
1229 // ?_O # copy constructor closure
1230 // ?_P<name> # udt returning <name>
1232 // ?_R0 # RTTI Type Descriptor
1233 // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
1234 // ?_R2 # RTTI Base Class Array
1235 // ?_R3 # RTTI Class Hierarchy Descriptor
1236 // ?_R4 # RTTI Complete Object Locator
1237 // ?_S # local vftable
1238 // ?_T # local vftable constructor closure
1239 // <operator-name> ::= ?_U # new[]
1240 case OO_Array_New: Out << "?_U"; break;
1241 // <operator-name> ::= ?_V # delete[]
1242 case OO_Array_Delete: Out << "?_V"; break;
1243 // <operator-name> ::= ?__L # co_await
1244 case OO_Coawait: Out << "?__L"; break;
1246 case OO_Spaceship: {
1247 // FIXME: Once MS picks a mangling, use it.
1248 DiagnosticsEngine &Diags = Context.getDiags();
1249 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1250 "cannot mangle this three-way comparison operator yet");
1251 Diags.Report(Loc, DiagID);
1255 case OO_Conditional: {
1256 DiagnosticsEngine &Diags = Context.getDiags();
1257 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1258 "cannot mangle this conditional operator yet");
1259 Diags.Report(Loc, DiagID);
1264 case NUM_OVERLOADED_OPERATORS:
1265 llvm_unreachable("Not an overloaded operator");
1269 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1270 // <source name> ::= <identifier> @
1271 BackRefVec::iterator Found =
1272 std::find(NameBackReferences.begin(), NameBackReferences.end(), Name);
1273 if (Found == NameBackReferences.end()) {
1274 if (NameBackReferences.size() < 10)
1275 NameBackReferences.push_back(Name);
1278 Out << (Found - NameBackReferences.begin());
1282 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1283 Context.mangleObjCMethodName(MD, Out);
1286 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1287 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1288 // <template-name> ::= <unscoped-template-name> <template-args>
1289 // ::= <substitution>
1290 // Always start with the unqualified name.
1292 // Templates have their own context for back references.
1293 ArgBackRefMap OuterArgsContext;
1294 BackRefVec OuterTemplateContext;
1295 PassObjectSizeArgsSet OuterPassObjectSizeArgs;
1296 NameBackReferences.swap(OuterTemplateContext);
1297 TypeBackReferences.swap(OuterArgsContext);
1298 PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1300 mangleUnscopedTemplateName(TD);
1301 mangleTemplateArgs(TD, TemplateArgs);
1303 // Restore the previous back reference contexts.
1304 NameBackReferences.swap(OuterTemplateContext);
1305 TypeBackReferences.swap(OuterArgsContext);
1306 PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1310 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1311 // <unscoped-template-name> ::= ?$ <unqualified-name>
1313 mangleUnqualifiedName(TD);
1316 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1318 // <integer-literal> ::= $0 <number>
1320 // Make sure booleans are encoded as 0/1.
1321 if (IsBoolean && Value.getBoolValue())
1323 else if (Value.isSigned())
1324 mangleNumber(Value.getSExtValue());
1326 mangleNumber(Value.getZExtValue());
1329 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1330 // See if this is a constant expression.
1332 if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1333 mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1337 // Look through no-op casts like template parameter substitutions.
1338 E = E->IgnoreParenNoopCasts(Context.getASTContext());
1340 const CXXUuidofExpr *UE = nullptr;
1341 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1342 if (UO->getOpcode() == UO_AddrOf)
1343 UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1345 UE = dyn_cast<CXXUuidofExpr>(E);
1348 // If we had to peek through an address-of operator, treat this like we are
1349 // dealing with a pointer type. Otherwise, treat it like a const reference.
1351 // N.B. This matches up with the handling of TemplateArgument::Declaration
1352 // in mangleTemplateArg
1358 // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1359 // const __s_GUID _GUID_{lower case UUID with underscores}
1360 StringRef Uuid = UE->getUuidStr();
1361 std::string Name = "_GUID_" + Uuid.lower();
1362 std::replace(Name.begin(), Name.end(), '-', '_');
1364 mangleSourceName(Name);
1365 // Terminate the whole name with an '@'.
1367 // It's a global variable.
1369 // It's a struct called __s_GUID.
1370 mangleArtificialTagType(TTK_Struct, "__s_GUID");
1376 // As bad as this diagnostic is, it's better than crashing.
1377 DiagnosticsEngine &Diags = Context.getDiags();
1378 unsigned DiagID = Diags.getCustomDiagID(
1379 DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1380 Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1381 << E->getSourceRange();
1384 void MicrosoftCXXNameMangler::mangleTemplateArgs(
1385 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1386 // <template-args> ::= <template-arg>+
1387 const TemplateParameterList *TPL = TD->getTemplateParameters();
1388 assert(TPL->size() == TemplateArgs.size() &&
1389 "size mismatch between args and parms!");
1391 for (size_t i = 0; i < TemplateArgs.size(); ++i) {
1392 const TemplateArgument &TA = TemplateArgs[i];
1394 // Separate consecutive packs by $$Z.
1395 if (i > 0 && TA.getKind() == TemplateArgument::Pack &&
1396 TemplateArgs[i - 1].getKind() == TemplateArgument::Pack)
1399 mangleTemplateArg(TD, TA, TPL->getParam(i));
1403 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1404 const TemplateArgument &TA,
1405 const NamedDecl *Parm) {
1406 // <template-arg> ::= <type>
1407 // ::= <integer-literal>
1408 // ::= <member-data-pointer>
1409 // ::= <member-function-pointer>
1410 // ::= $E? <name> <type-encoding>
1411 // ::= $1? <name> <type-encoding>
1413 // ::= <template-args>
1415 switch (TA.getKind()) {
1416 case TemplateArgument::Null:
1417 llvm_unreachable("Can't mangle null template arguments!");
1418 case TemplateArgument::TemplateExpansion:
1419 llvm_unreachable("Can't mangle template expansion arguments!");
1420 case TemplateArgument::Type: {
1421 QualType T = TA.getAsType();
1422 mangleType(T, SourceRange(), QMM_Escape);
1425 case TemplateArgument::Declaration: {
1426 const NamedDecl *ND = TA.getAsDecl();
1427 if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1428 mangleMemberDataPointer(cast<CXXRecordDecl>(ND->getDeclContext())
1429 ->getMostRecentNonInjectedDecl(),
1430 cast<ValueDecl>(ND));
1431 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1432 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1433 if (MD && MD->isInstance()) {
1434 mangleMemberFunctionPointer(
1435 MD->getParent()->getMostRecentNonInjectedDecl(), MD);
1439 mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1442 mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
1446 case TemplateArgument::Integral:
1447 mangleIntegerLiteral(TA.getAsIntegral(),
1448 TA.getIntegralType()->isBooleanType());
1450 case TemplateArgument::NullPtr: {
1451 QualType T = TA.getNullPtrType();
1452 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1453 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1454 if (MPT->isMemberFunctionPointerType() &&
1455 !isa<FunctionTemplateDecl>(TD)) {
1456 mangleMemberFunctionPointer(RD, nullptr);
1459 if (MPT->isMemberDataPointer()) {
1460 if (!isa<FunctionTemplateDecl>(TD)) {
1461 mangleMemberDataPointer(RD, nullptr);
1464 // nullptr data pointers are always represented with a single field
1465 // which is initialized with either 0 or -1. Why -1? Well, we need to
1466 // distinguish the case where the data member is at offset zero in the
1468 // However, we are free to use 0 *if* we would use multiple fields for
1469 // non-nullptr member pointers.
1470 if (!RD->nullFieldOffsetIsZero()) {
1471 mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false);
1476 mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false);
1479 case TemplateArgument::Expression:
1480 mangleExpression(TA.getAsExpr());
1482 case TemplateArgument::Pack: {
1483 ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1484 if (TemplateArgs.empty()) {
1485 if (isa<TemplateTypeParmDecl>(Parm) ||
1486 isa<TemplateTemplateParmDecl>(Parm))
1487 // MSVC 2015 changed the mangling for empty expanded template packs,
1488 // use the old mangling for link compatibility for old versions.
1489 Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1490 LangOptions::MSVC2015)
1493 else if (isa<NonTypeTemplateParmDecl>(Parm))
1496 llvm_unreachable("unexpected template parameter decl!");
1498 for (const TemplateArgument &PA : TemplateArgs)
1499 mangleTemplateArg(TD, PA, Parm);
1503 case TemplateArgument::Template: {
1504 const NamedDecl *ND =
1505 TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
1506 if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1508 } else if (isa<TypeAliasDecl>(ND)) {
1512 llvm_unreachable("unexpected template template NamedDecl!");
1519 void MicrosoftCXXNameMangler::mangleObjCProtocol(const ObjCProtocolDecl *PD) {
1520 llvm::SmallString<64> TemplateMangling;
1521 llvm::raw_svector_ostream Stream(TemplateMangling);
1522 MicrosoftCXXNameMangler Extra(Context, Stream);
1525 Extra.mangleSourceName("Protocol");
1526 Extra.mangleArtificialTagType(TTK_Struct, PD->getName());
1528 mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1531 void MicrosoftCXXNameMangler::mangleObjCLifetime(const QualType Type,
1533 SourceRange Range) {
1534 llvm::SmallString<64> TemplateMangling;
1535 llvm::raw_svector_ostream Stream(TemplateMangling);
1536 MicrosoftCXXNameMangler Extra(Context, Stream);
1539 switch (Quals.getObjCLifetime()) {
1540 case Qualifiers::OCL_None:
1541 case Qualifiers::OCL_ExplicitNone:
1543 case Qualifiers::OCL_Autoreleasing:
1544 Extra.mangleSourceName("Autoreleasing");
1546 case Qualifiers::OCL_Strong:
1547 Extra.mangleSourceName("Strong");
1549 case Qualifiers::OCL_Weak:
1550 Extra.mangleSourceName("Weak");
1553 Extra.manglePointerCVQualifiers(Quals);
1554 Extra.manglePointerExtQualifiers(Quals, Type);
1555 Extra.mangleType(Type, Range);
1557 mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1560 void MicrosoftCXXNameMangler::mangleObjCKindOfType(const ObjCObjectType *T,
1562 SourceRange Range) {
1563 llvm::SmallString<64> TemplateMangling;
1564 llvm::raw_svector_ostream Stream(TemplateMangling);
1565 MicrosoftCXXNameMangler Extra(Context, Stream);
1568 Extra.mangleSourceName("KindOf");
1569 Extra.mangleType(QualType(T, 0)
1570 .stripObjCKindOfType(getASTContext())
1571 ->getAs<ObjCObjectType>(),
1574 mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1577 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1579 // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1580 // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1581 // 'I' means __restrict (32/64-bit).
1582 // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1584 // <base-cvr-qualifiers> ::= A # near
1585 // ::= B # near const
1586 // ::= C # near volatile
1587 // ::= D # near const volatile
1588 // ::= E # far (16-bit)
1589 // ::= F # far const (16-bit)
1590 // ::= G # far volatile (16-bit)
1591 // ::= H # far const volatile (16-bit)
1592 // ::= I # huge (16-bit)
1593 // ::= J # huge const (16-bit)
1594 // ::= K # huge volatile (16-bit)
1595 // ::= L # huge const volatile (16-bit)
1596 // ::= M <basis> # based
1597 // ::= N <basis> # based const
1598 // ::= O <basis> # based volatile
1599 // ::= P <basis> # based const volatile
1600 // ::= Q # near member
1601 // ::= R # near const member
1602 // ::= S # near volatile member
1603 // ::= T # near const volatile member
1604 // ::= U # far member (16-bit)
1605 // ::= V # far const member (16-bit)
1606 // ::= W # far volatile member (16-bit)
1607 // ::= X # far const volatile member (16-bit)
1608 // ::= Y # huge member (16-bit)
1609 // ::= Z # huge const member (16-bit)
1610 // ::= 0 # huge volatile member (16-bit)
1611 // ::= 1 # huge const volatile member (16-bit)
1612 // ::= 2 <basis> # based member
1613 // ::= 3 <basis> # based const member
1614 // ::= 4 <basis> # based volatile member
1615 // ::= 5 <basis> # based const volatile member
1616 // ::= 6 # near function (pointers only)
1617 // ::= 7 # far function (pointers only)
1618 // ::= 8 # near method (pointers only)
1619 // ::= 9 # far method (pointers only)
1620 // ::= _A <basis> # based function (pointers only)
1621 // ::= _B <basis> # based function (far?) (pointers only)
1622 // ::= _C <basis> # based method (pointers only)
1623 // ::= _D <basis> # based method (far?) (pointers only)
1624 // ::= _E # block (Clang)
1625 // <basis> ::= 0 # __based(void)
1626 // ::= 1 # __based(segment)?
1627 // ::= 2 <name> # __based(name)
1630 // ::= 5 # not really based
1631 bool HasConst = Quals.hasConst(),
1632 HasVolatile = Quals.hasVolatile();
1635 if (HasConst && HasVolatile) {
1637 } else if (HasVolatile) {
1639 } else if (HasConst) {
1645 if (HasConst && HasVolatile) {
1647 } else if (HasVolatile) {
1649 } else if (HasConst) {
1656 // FIXME: For now, just drop all extension qualifiers on the floor.
1660 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1661 // <ref-qualifier> ::= G # lvalue reference
1662 // ::= H # rvalue-reference
1663 switch (RefQualifier) {
1677 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1678 QualType PointeeType) {
1679 if (PointersAre64Bit &&
1680 (PointeeType.isNull() || !PointeeType->isFunctionType()))
1683 if (Quals.hasRestrict())
1686 if (Quals.hasUnaligned() ||
1687 (!PointeeType.isNull() && PointeeType.getLocalQualifiers().hasUnaligned()))
1691 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1692 // <pointer-cv-qualifiers> ::= P # no qualifiers
1695 // ::= S # const volatile
1696 bool HasConst = Quals.hasConst(),
1697 HasVolatile = Quals.hasVolatile();
1699 if (HasConst && HasVolatile) {
1701 } else if (HasVolatile) {
1703 } else if (HasConst) {
1710 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1711 SourceRange Range) {
1712 // MSVC will backreference two canonically equivalent types that have slightly
1713 // different manglings when mangled alone.
1715 // Decayed types do not match up with non-decayed versions of the same type.
1718 // void (*x)(void) will not form a backreference with void x(void)
1720 if (const auto *DT = T->getAs<DecayedType>()) {
1721 QualType OriginalType = DT->getOriginalType();
1722 // All decayed ArrayTypes should be treated identically; as-if they were
1723 // a decayed IncompleteArrayType.
1724 if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
1725 OriginalType = getASTContext().getIncompleteArrayType(
1726 AT->getElementType(), AT->getSizeModifier(),
1727 AT->getIndexTypeCVRQualifiers());
1729 TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
1730 // If the original parameter was textually written as an array,
1731 // instead treat the decayed parameter like it's const.
1734 // int [] -> int * const
1735 if (OriginalType->isArrayType())
1738 TypePtr = T.getCanonicalType().getAsOpaquePtr();
1741 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1743 if (Found == TypeBackReferences.end()) {
1744 size_t OutSizeBefore = Out.tell();
1746 mangleType(T, Range, QMM_Drop);
1748 // See if it's worth creating a back reference.
1749 // Only types longer than 1 character are considered
1750 // and only 10 back references slots are available:
1751 bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
1752 if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1753 size_t Size = TypeBackReferences.size();
1754 TypeBackReferences[TypePtr] = Size;
1757 Out << Found->second;
1761 void MicrosoftCXXNameMangler::manglePassObjectSizeArg(
1762 const PassObjectSizeAttr *POSA) {
1763 int Type = POSA->getType();
1765 auto Iter = PassObjectSizeArgs.insert(Type).first;
1766 auto *TypePtr = (const void *)&*Iter;
1767 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1769 if (Found == TypeBackReferences.end()) {
1770 mangleArtificialTagType(TTK_Enum, "__pass_object_size" + llvm::utostr(Type),
1773 if (TypeBackReferences.size() < 10) {
1774 size_t Size = TypeBackReferences.size();
1775 TypeBackReferences[TypePtr] = Size;
1778 Out << Found->second;
1782 void MicrosoftCXXNameMangler::mangleAddressSpaceType(QualType T,
1784 SourceRange Range) {
1785 // Address space is mangled as an unqualified templated type in the __clang
1786 // namespace. The demangled version of this is:
1787 // In the case of a language specific address space:
1788 // __clang::struct _AS[language_addr_space]<Type>
1790 // <language_addr_space> ::= <OpenCL-addrspace> | <CUDA-addrspace>
1791 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
1792 // "private"| "generic" ]
1793 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1794 // Note that the above were chosen to match the Itanium mangling for this.
1796 // In the case of a non-language specific address space:
1797 // __clang::struct _AS<TargetAS, Type>
1798 assert(Quals.hasAddressSpace() && "Not valid without address space");
1799 llvm::SmallString<32> ASMangling;
1800 llvm::raw_svector_ostream Stream(ASMangling);
1801 MicrosoftCXXNameMangler Extra(Context, Stream);
1804 LangAS AS = Quals.getAddressSpace();
1805 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1806 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1807 Extra.mangleSourceName("_AS");
1808 Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(TargetAS),
1809 /*IsBoolean*/ false);
1813 llvm_unreachable("Not a language specific address space");
1814 case LangAS::opencl_global:
1815 Extra.mangleSourceName("_ASCLglobal");
1817 case LangAS::opencl_local:
1818 Extra.mangleSourceName("_ASCLlocal");
1820 case LangAS::opencl_constant:
1821 Extra.mangleSourceName("_ASCLconstant");
1823 case LangAS::opencl_private:
1824 Extra.mangleSourceName("_ASCLprivate");
1826 case LangAS::opencl_generic:
1827 Extra.mangleSourceName("_ASCLgeneric");
1829 case LangAS::cuda_device:
1830 Extra.mangleSourceName("_ASCUdevice");
1832 case LangAS::cuda_constant:
1833 Extra.mangleSourceName("_ASCUconstant");
1835 case LangAS::cuda_shared:
1836 Extra.mangleSourceName("_ASCUshared");
1841 Extra.mangleType(T, Range, QMM_Escape);
1842 mangleQualifiers(Qualifiers(), false);
1843 mangleArtificialTagType(TTK_Struct, ASMangling, {"__clang"});
1846 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1847 QualifierMangleMode QMM) {
1848 // Don't use the canonical types. MSVC includes things like 'const' on
1849 // pointer arguments to function pointers that canonicalization strips away.
1850 T = T.getDesugaredType(getASTContext());
1851 Qualifiers Quals = T.getLocalQualifiers();
1853 if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1854 // If there were any Quals, getAsArrayType() pushed them onto the array
1856 if (QMM == QMM_Mangle)
1858 else if (QMM == QMM_Escape || QMM == QMM_Result)
1860 mangleArrayType(AT);
1864 bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1865 T->isReferenceType() || T->isBlockPointerType();
1869 if (Quals.hasObjCLifetime())
1870 Quals = Quals.withoutObjCLifetime();
1873 if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1875 mangleFunctionType(FT);
1878 mangleQualifiers(Quals, false);
1881 if (!IsPointer && Quals) {
1883 mangleQualifiers(Quals, false);
1887 // Presence of __unaligned qualifier shouldn't affect mangling here.
1888 Quals.removeUnaligned();
1889 if (Quals.hasObjCLifetime())
1890 Quals = Quals.withoutObjCLifetime();
1891 if ((!IsPointer && Quals) || isa<TagType>(T) || isArtificialTagType(T)) {
1893 mangleQualifiers(Quals, false);
1898 const Type *ty = T.getTypePtr();
1900 switch (ty->getTypeClass()) {
1901 #define ABSTRACT_TYPE(CLASS, PARENT)
1902 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1904 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1906 #define TYPE(CLASS, PARENT) \
1908 mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1910 #include "clang/AST/TypeNodes.def"
1911 #undef ABSTRACT_TYPE
1912 #undef NON_CANONICAL_TYPE
1917 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1918 SourceRange Range) {
1919 // <type> ::= <builtin-type>
1920 // <builtin-type> ::= X # void
1921 // ::= C # signed char
1923 // ::= E # unsigned char
1925 // ::= G # unsigned short (or wchar_t if it's not a builtin)
1927 // ::= I # unsigned int
1929 // ::= K # unsigned long
1933 // ::= O # long double (__float80 is mangled differently)
1934 // ::= _J # long long, __int64
1935 // ::= _K # unsigned long long, __int64
1936 // ::= _L # __int128
1937 // ::= _M # unsigned __int128
1939 // _O # <array in parameter>
1940 // ::= _T # __float80 (Intel)
1941 // ::= _S # char16_t
1942 // ::= _U # char32_t
1944 // ::= _Z # __float80 (Digital Mars)
1945 switch (T->getKind()) {
1946 case BuiltinType::Void:
1949 case BuiltinType::SChar:
1952 case BuiltinType::Char_U:
1953 case BuiltinType::Char_S:
1956 case BuiltinType::UChar:
1959 case BuiltinType::Short:
1962 case BuiltinType::UShort:
1965 case BuiltinType::Int:
1968 case BuiltinType::UInt:
1971 case BuiltinType::Long:
1974 case BuiltinType::ULong:
1977 case BuiltinType::Float:
1980 case BuiltinType::Double:
1983 // TODO: Determine size and mangle accordingly
1984 case BuiltinType::LongDouble:
1987 case BuiltinType::LongLong:
1990 case BuiltinType::ULongLong:
1993 case BuiltinType::Int128:
1996 case BuiltinType::UInt128:
1999 case BuiltinType::Bool:
2002 case BuiltinType::Char16:
2005 case BuiltinType::Char32:
2008 case BuiltinType::WChar_S:
2009 case BuiltinType::WChar_U:
2013 #define BUILTIN_TYPE(Id, SingletonId)
2014 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2015 case BuiltinType::Id:
2016 #include "clang/AST/BuiltinTypes.def"
2017 case BuiltinType::Dependent:
2018 llvm_unreachable("placeholder types shouldn't get to name mangling");
2020 case BuiltinType::ObjCId:
2021 mangleArtificialTagType(TTK_Struct, "objc_object");
2023 case BuiltinType::ObjCClass:
2024 mangleArtificialTagType(TTK_Struct, "objc_class");
2026 case BuiltinType::ObjCSel:
2027 mangleArtificialTagType(TTK_Struct, "objc_selector");
2030 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2031 case BuiltinType::Id: \
2032 Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \
2034 #include "clang/Basic/OpenCLImageTypes.def"
2035 case BuiltinType::OCLSampler:
2037 mangleArtificialTagType(TTK_Struct, "ocl_sampler");
2039 case BuiltinType::OCLEvent:
2041 mangleArtificialTagType(TTK_Struct, "ocl_event");
2043 case BuiltinType::OCLClkEvent:
2045 mangleArtificialTagType(TTK_Struct, "ocl_clkevent");
2047 case BuiltinType::OCLQueue:
2049 mangleArtificialTagType(TTK_Struct, "ocl_queue");
2051 case BuiltinType::OCLReserveID:
2053 mangleArtificialTagType(TTK_Struct, "ocl_reserveid");
2055 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2056 case BuiltinType::Id: \
2057 mangleArtificialTagType(TTK_Struct, "ocl_" #ExtType); \
2059 #include "clang/Basic/OpenCLExtensionTypes.def"
2061 case BuiltinType::NullPtr:
2065 case BuiltinType::Float16:
2066 mangleArtificialTagType(TTK_Struct, "_Float16", {"__clang"});
2069 case BuiltinType::Half:
2070 mangleArtificialTagType(TTK_Struct, "_Half", {"__clang"});
2073 case BuiltinType::ShortAccum:
2074 case BuiltinType::Accum:
2075 case BuiltinType::LongAccum:
2076 case BuiltinType::UShortAccum:
2077 case BuiltinType::UAccum:
2078 case BuiltinType::ULongAccum:
2079 case BuiltinType::ShortFract:
2080 case BuiltinType::Fract:
2081 case BuiltinType::LongFract:
2082 case BuiltinType::UShortFract:
2083 case BuiltinType::UFract:
2084 case BuiltinType::ULongFract:
2085 case BuiltinType::SatShortAccum:
2086 case BuiltinType::SatAccum:
2087 case BuiltinType::SatLongAccum:
2088 case BuiltinType::SatUShortAccum:
2089 case BuiltinType::SatUAccum:
2090 case BuiltinType::SatULongAccum:
2091 case BuiltinType::SatShortFract:
2092 case BuiltinType::SatFract:
2093 case BuiltinType::SatLongFract:
2094 case BuiltinType::SatUShortFract:
2095 case BuiltinType::SatUFract:
2096 case BuiltinType::SatULongFract:
2097 case BuiltinType::Char8:
2098 case BuiltinType::Float128: {
2099 DiagnosticsEngine &Diags = Context.getDiags();
2100 unsigned DiagID = Diags.getCustomDiagID(
2101 DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
2102 Diags.Report(Range.getBegin(), DiagID)
2103 << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
2109 // <type> ::= <function-type>
2110 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
2112 // Structors only appear in decls, so at this point we know it's not a
2114 // FIXME: This may not be lambda-friendly.
2115 if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
2117 mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
2120 mangleFunctionType(T);
2123 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
2124 Qualifiers, SourceRange) {
2126 mangleFunctionType(T);
2129 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
2130 const FunctionDecl *D,
2131 bool ForceThisQuals,
2132 bool MangleExceptionSpec) {
2133 // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
2134 // <return-type> <argument-list> <throw-spec>
2135 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
2138 if (D) Range = D->getSourceRange();
2140 bool IsInLambda = false;
2141 bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
2142 CallingConv CC = T->getCallConv();
2143 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
2144 if (MD->getParent()->isLambda())
2146 if (MD->isInstance())
2147 HasThisQuals = true;
2148 if (isa<CXXDestructorDecl>(MD)) {
2150 } else if (isa<CXXConstructorDecl>(MD)) {
2152 IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
2153 StructorType == Ctor_DefaultClosure) &&
2156 CC = getASTContext().getDefaultCallingConvention(
2157 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
2161 // If this is a C++ instance method, mangle the CVR qualifiers for the
2164 Qualifiers Quals = Proto->getTypeQuals();
2165 manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
2166 mangleRefQualifier(Proto->getRefQualifier());
2167 mangleQualifiers(Quals, /*IsMember=*/false);
2170 mangleCallingConvention(CC);
2172 // <return-type> ::= <type>
2173 // ::= @ # structors (they have no declared return type)
2175 if (isa<CXXDestructorDecl>(D) && isStructorDecl(D)) {
2176 // The scalar deleting destructor takes an extra int argument which is not
2177 // reflected in the AST.
2178 if (StructorType == Dtor_Deleting) {
2179 Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
2182 // The vbase destructor returns void which is not reflected in the AST.
2183 if (StructorType == Dtor_Complete) {
2188 if (IsCtorClosure) {
2189 // Default constructor closure and copy constructor closure both return
2193 if (StructorType == Ctor_DefaultClosure) {
2194 // Default constructor closure always has no arguments.
2196 } else if (StructorType == Ctor_CopyingClosure) {
2197 // Copy constructor closure always takes an unqualified reference.
2198 mangleArgumentType(getASTContext().getLValueReferenceType(
2199 Proto->getParamType(0)
2200 ->getAs<LValueReferenceType>()
2202 /*SpelledAsLValue=*/true),
2206 llvm_unreachable("unexpected constructor closure!");
2213 QualType ResultType = T->getReturnType();
2214 if (const auto *AT =
2215 dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
2217 mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
2219 assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2220 "shouldn't need to mangle __auto_type!");
2221 mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
2223 } else if (IsInLambda) {
2226 if (ResultType->isVoidType())
2227 ResultType = ResultType.getUnqualifiedType();
2228 mangleType(ResultType, Range, QMM_Result);
2232 // <argument-list> ::= X # void
2234 // ::= <type>* Z # varargs
2236 // Function types without prototypes can arise when mangling a function type
2237 // within an overloadable function in C. We mangle these as the absence of
2238 // any parameter types (not even an empty parameter list).
2240 } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2243 // Happens for function pointer type arguments for example.
2244 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2245 mangleArgumentType(Proto->getParamType(I), Range);
2246 // Mangle each pass_object_size parameter as if it's a parameter of enum
2247 // type passed directly after the parameter with the pass_object_size
2248 // attribute. The aforementioned enum's name is __pass_object_size, and we
2249 // pretend it resides in a top-level namespace called __clang.
2251 // FIXME: Is there a defined extension notation for the MS ABI, or is it
2252 // necessary to just cross our fingers and hope this type+namespace
2253 // combination doesn't conflict with anything?
2255 if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
2256 manglePassObjectSizeArg(P);
2258 // <builtin-type> ::= Z # ellipsis
2259 if (Proto->isVariadic())
2265 if (MangleExceptionSpec && getASTContext().getLangOpts().CPlusPlus17 &&
2266 getASTContext().getLangOpts().isCompatibleWithMSVC(
2267 LangOptions::MSVC2017_5))
2268 mangleThrowSpecification(Proto);
2273 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
2274 // <function-class> ::= <member-function> E? # E designates a 64-bit 'this'
2275 // # pointer. in 64-bit mode *all*
2276 // # 'this' pointers are 64-bit.
2277 // ::= <global-function>
2278 // <member-function> ::= A # private: near
2279 // ::= B # private: far
2280 // ::= C # private: static near
2281 // ::= D # private: static far
2282 // ::= E # private: virtual near
2283 // ::= F # private: virtual far
2284 // ::= I # protected: near
2285 // ::= J # protected: far
2286 // ::= K # protected: static near
2287 // ::= L # protected: static far
2288 // ::= M # protected: virtual near
2289 // ::= N # protected: virtual far
2290 // ::= Q # public: near
2291 // ::= R # public: far
2292 // ::= S # public: static near
2293 // ::= T # public: static far
2294 // ::= U # public: virtual near
2295 // ::= V # public: virtual far
2296 // <global-function> ::= Y # global near
2297 // ::= Z # global far
2298 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2299 bool IsVirtual = MD->isVirtual();
2300 // When mangling vbase destructor variants, ignore whether or not the
2301 // underlying destructor was defined to be virtual.
2302 if (isa<CXXDestructorDecl>(MD) && isStructorDecl(MD) &&
2303 StructorType == Dtor_Complete) {
2306 switch (MD->getAccess()) {
2308 llvm_unreachable("Unsupported access specifier");
2337 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
2338 // <calling-convention> ::= A # __cdecl
2339 // ::= B # __export __cdecl
2341 // ::= D # __export __pascal
2342 // ::= E # __thiscall
2343 // ::= F # __export __thiscall
2344 // ::= G # __stdcall
2345 // ::= H # __export __stdcall
2346 // ::= I # __fastcall
2347 // ::= J # __export __fastcall
2348 // ::= Q # __vectorcall
2349 // ::= w # __regcall
2350 // The 'export' calling conventions are from a bygone era
2351 // (*cough*Win16*cough*) when functions were declared for export with
2352 // that keyword. (It didn't actually export them, it just made them so
2353 // that they could be in a DLL and somebody from another module could call
2358 llvm_unreachable("Unsupported CC for mangling");
2361 case CC_C: Out << 'A'; break;
2362 case CC_X86Pascal: Out << 'C'; break;
2363 case CC_X86ThisCall: Out << 'E'; break;
2364 case CC_X86StdCall: Out << 'G'; break;
2365 case CC_X86FastCall: Out << 'I'; break;
2366 case CC_X86VectorCall: Out << 'Q'; break;
2367 case CC_Swift: Out << 'S'; break;
2368 case CC_PreserveMost: Out << 'U'; break;
2369 case CC_X86RegCall: Out << 'w'; break;
2372 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2373 mangleCallingConvention(T->getCallConv());
2376 void MicrosoftCXXNameMangler::mangleThrowSpecification(
2377 const FunctionProtoType *FT) {
2378 // <throw-spec> ::= Z # (default)
2379 // ::= _E # noexcept
2386 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2387 Qualifiers, SourceRange Range) {
2388 // Probably should be mangled as a template instantiation; need to see what
2390 DiagnosticsEngine &Diags = Context.getDiags();
2391 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2392 "cannot mangle this unresolved dependent type yet");
2393 Diags.Report(Range.getBegin(), DiagID)
2397 // <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2398 // <union-type> ::= T <name>
2399 // <struct-type> ::= U <name>
2400 // <class-type> ::= V <name>
2401 // <enum-type> ::= W4 <name>
2402 void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2419 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2421 mangleType(cast<TagType>(T)->getDecl());
2423 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2425 mangleType(cast<TagType>(T)->getDecl());
2427 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2428 mangleTagTypeKind(TD->getTagKind());
2432 // If you add a call to this, consider updating isArtificialTagType() too.
2433 void MicrosoftCXXNameMangler::mangleArtificialTagType(
2434 TagTypeKind TK, StringRef UnqualifiedName,
2435 ArrayRef<StringRef> NestedNames) {
2436 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2437 mangleTagTypeKind(TK);
2439 // Always start with the unqualified name.
2440 mangleSourceName(UnqualifiedName);
2442 for (auto I = NestedNames.rbegin(), E = NestedNames.rend(); I != E; ++I)
2443 mangleSourceName(*I);
2445 // Terminate the whole name with an '@'.
2449 // <type> ::= <array-type>
2450 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2451 // [Y <dimension-count> <dimension>+]
2452 // <element-type> # as global, E is never required
2453 // It's supposed to be the other way around, but for some strange reason, it
2454 // isn't. Today this behavior is retained for the sole purpose of backwards
2456 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2457 // This isn't a recursive mangling, so now we have to do it all in this
2459 manglePointerCVQualifiers(T->getElementType().getQualifiers());
2460 mangleType(T->getElementType(), SourceRange());
2462 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2464 llvm_unreachable("Should have been special cased");
2466 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2468 llvm_unreachable("Should have been special cased");
2470 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2471 Qualifiers, SourceRange) {
2472 llvm_unreachable("Should have been special cased");
2474 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2475 Qualifiers, SourceRange) {
2476 llvm_unreachable("Should have been special cased");
2478 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2479 QualType ElementTy(T, 0);
2480 SmallVector<llvm::APInt, 3> Dimensions;
2482 if (ElementTy->isConstantArrayType()) {
2483 const ConstantArrayType *CAT =
2484 getASTContext().getAsConstantArrayType(ElementTy);
2485 Dimensions.push_back(CAT->getSize());
2486 ElementTy = CAT->getElementType();
2487 } else if (ElementTy->isIncompleteArrayType()) {
2488 const IncompleteArrayType *IAT =
2489 getASTContext().getAsIncompleteArrayType(ElementTy);
2490 Dimensions.push_back(llvm::APInt(32, 0));
2491 ElementTy = IAT->getElementType();
2492 } else if (ElementTy->isVariableArrayType()) {
2493 const VariableArrayType *VAT =
2494 getASTContext().getAsVariableArrayType(ElementTy);
2495 Dimensions.push_back(llvm::APInt(32, 0));
2496 ElementTy = VAT->getElementType();
2497 } else if (ElementTy->isDependentSizedArrayType()) {
2498 // The dependent expression has to be folded into a constant (TODO).
2499 const DependentSizedArrayType *DSAT =
2500 getASTContext().getAsDependentSizedArrayType(ElementTy);
2501 DiagnosticsEngine &Diags = Context.getDiags();
2502 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2503 "cannot mangle this dependent-length array yet");
2504 Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2505 << DSAT->getBracketsRange();
2512 // <dimension-count> ::= <number> # number of extra dimensions
2513 mangleNumber(Dimensions.size());
2514 for (const llvm::APInt &Dimension : Dimensions)
2515 mangleNumber(Dimension.getLimitedValue());
2516 mangleType(ElementTy, SourceRange(), QMM_Escape);
2519 // <type> ::= <pointer-to-member-type>
2520 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2521 // <class name> <type>
2522 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
2523 Qualifiers Quals, SourceRange Range) {
2524 QualType PointeeType = T->getPointeeType();
2525 manglePointerCVQualifiers(Quals);
2526 manglePointerExtQualifiers(Quals, PointeeType);
2527 if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2529 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2530 mangleFunctionType(FPT, nullptr, true);
2532 mangleQualifiers(PointeeType.getQualifiers(), true);
2533 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2534 mangleType(PointeeType, Range, QMM_Drop);
2538 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2539 Qualifiers, SourceRange Range) {
2540 DiagnosticsEngine &Diags = Context.getDiags();
2541 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2542 "cannot mangle this template type parameter type yet");
2543 Diags.Report(Range.getBegin(), DiagID)
2547 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2548 Qualifiers, SourceRange Range) {
2549 DiagnosticsEngine &Diags = Context.getDiags();
2550 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2551 "cannot mangle this substituted parameter pack yet");
2552 Diags.Report(Range.getBegin(), DiagID)
2556 // <type> ::= <pointer-type>
2557 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2558 // # the E is required for 64-bit non-static pointers
2559 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2560 SourceRange Range) {
2561 QualType PointeeType = T->getPointeeType();
2562 manglePointerCVQualifiers(Quals);
2563 manglePointerExtQualifiers(Quals, PointeeType);
2565 if (PointeeType.getQualifiers().hasAddressSpace())
2566 mangleAddressSpaceType(PointeeType, PointeeType.getQualifiers(), Range);
2568 mangleType(PointeeType, Range);
2571 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2572 Qualifiers Quals, SourceRange Range) {
2573 QualType PointeeType = T->getPointeeType();
2574 switch (Quals.getObjCLifetime()) {
2575 case Qualifiers::OCL_None:
2576 case Qualifiers::OCL_ExplicitNone:
2578 case Qualifiers::OCL_Autoreleasing:
2579 case Qualifiers::OCL_Strong:
2580 case Qualifiers::OCL_Weak:
2581 return mangleObjCLifetime(PointeeType, Quals, Range);
2583 manglePointerCVQualifiers(Quals);
2584 manglePointerExtQualifiers(Quals, PointeeType);
2585 mangleType(PointeeType, Range);
2588 // <type> ::= <reference-type>
2589 // <reference-type> ::= A E? <cvr-qualifiers> <type>
2590 // # the E is required for 64-bit non-static lvalue references
2591 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
2592 Qualifiers Quals, SourceRange Range) {
2593 QualType PointeeType = T->getPointeeType();
2594 assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2596 manglePointerExtQualifiers(Quals, PointeeType);
2597 mangleType(PointeeType, Range);
2600 // <type> ::= <r-value-reference-type>
2601 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
2602 // # the E is required for 64-bit non-static rvalue references
2603 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2604 Qualifiers Quals, SourceRange Range) {
2605 QualType PointeeType = T->getPointeeType();
2606 assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2608 manglePointerExtQualifiers(Quals, PointeeType);
2609 mangleType(PointeeType, Range);
2612 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
2613 SourceRange Range) {
2614 QualType ElementType = T->getElementType();
2616 llvm::SmallString<64> TemplateMangling;
2617 llvm::raw_svector_ostream Stream(TemplateMangling);
2618 MicrosoftCXXNameMangler Extra(Context, Stream);
2620 Extra.mangleSourceName("_Complex");
2621 Extra.mangleType(ElementType, Range, QMM_Escape);
2623 mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
2626 // Returns true for types that mangleArtificialTagType() gets called for with
2627 // TTK_Union, TTK_Struct, TTK_Class and where compatibility with MSVC's
2628 // mangling matters.
2629 // (It doesn't matter for Objective-C types and the like that cl.exe doesn't
2631 bool MicrosoftCXXNameMangler::isArtificialTagType(QualType T) const {
2632 const Type *ty = T.getTypePtr();
2633 switch (ty->getTypeClass()) {
2637 case Type::Vector: {
2638 // For ABI compatibility only __m64, __m128(id), and __m256(id) matter,
2639 // but since mangleType(VectorType*) always calls mangleArtificialTagType()
2640 // just always return true (the other vector types are clang-only).
2646 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
2647 SourceRange Range) {
2648 const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
2649 assert(ET && "vectors with non-builtin elements are unsupported");
2650 uint64_t Width = getASTContext().getTypeSize(T);
2651 // Pattern match exactly the typedefs in our intrinsic headers. Anything that
2652 // doesn't match the Intel types uses a custom mangling below.
2653 size_t OutSizeBefore = Out.tell();
2654 if (!isa<ExtVectorType>(T)) {
2655 llvm::Triple::ArchType AT =
2656 getASTContext().getTargetInfo().getTriple().getArch();
2657 if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) {
2658 if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
2659 mangleArtificialTagType(TTK_Union, "__m64");
2660 } else if (Width >= 128) {
2661 if (ET->getKind() == BuiltinType::Float)
2662 mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width));
2663 else if (ET->getKind() == BuiltinType::LongLong)
2664 mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i');
2665 else if (ET->getKind() == BuiltinType::Double)
2666 mangleArtificialTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd');
2671 bool IsBuiltin = Out.tell() != OutSizeBefore;
2673 // The MS ABI doesn't have a special mangling for vector types, so we define
2674 // our own mangling to handle uses of __vector_size__ on user-specified
2675 // types, and for extensions like __v4sf.
2677 llvm::SmallString<64> TemplateMangling;
2678 llvm::raw_svector_ostream Stream(TemplateMangling);
2679 MicrosoftCXXNameMangler Extra(Context, Stream);
2681 Extra.mangleSourceName("__vector");
2682 Extra.mangleType(QualType(ET, 0), Range, QMM_Escape);
2683 Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()),
2684 /*IsBoolean=*/false);
2686 mangleArtificialTagType(TTK_Union, TemplateMangling, {"__clang"});
2690 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
2691 Qualifiers Quals, SourceRange Range) {
2692 mangleType(static_cast<const VectorType *>(T), Quals, Range);
2695 void MicrosoftCXXNameMangler::mangleType(const DependentVectorType *T,
2696 Qualifiers, SourceRange Range) {
2697 DiagnosticsEngine &Diags = Context.getDiags();
2698 unsigned DiagID = Diags.getCustomDiagID(
2699 DiagnosticsEngine::Error,
2700 "cannot mangle this dependent-sized vector type yet");
2701 Diags.Report(Range.getBegin(), DiagID) << Range;
2704 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
2705 Qualifiers, SourceRange Range) {
2706 DiagnosticsEngine &Diags = Context.getDiags();
2707 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2708 "cannot mangle this dependent-sized extended vector type yet");
2709 Diags.Report(Range.getBegin(), DiagID)
2713 void MicrosoftCXXNameMangler::mangleType(const DependentAddressSpaceType *T,
2714 Qualifiers, SourceRange Range) {
2715 DiagnosticsEngine &Diags = Context.getDiags();
2716 unsigned DiagID = Diags.getCustomDiagID(
2717 DiagnosticsEngine::Error,
2718 "cannot mangle this dependent address space type yet");
2719 Diags.Report(Range.getBegin(), DiagID) << Range;
2722 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
2724 // ObjC interfaces have structs underlying them.
2725 mangleTagTypeKind(TTK_Struct);
2726 mangleName(T->getDecl());
2729 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
2730 Qualifiers Quals, SourceRange Range) {
2731 if (T->isKindOfType())
2732 return mangleObjCKindOfType(T, Quals, Range);
2734 if (T->qual_empty() && !T->isSpecialized())
2735 return mangleType(T->getBaseType(), Range, QMM_Drop);
2737 ArgBackRefMap OuterArgsContext;
2738 BackRefVec OuterTemplateContext;
2740 TypeBackReferences.swap(OuterArgsContext);
2741 NameBackReferences.swap(OuterTemplateContext);
2743 mangleTagTypeKind(TTK_Struct);
2747 mangleSourceName("objc_object");
2748 else if (T->isObjCClass())
2749 mangleSourceName("objc_class");
2751 mangleSourceName(T->getInterface()->getName());
2753 for (const auto &Q : T->quals())
2754 mangleObjCProtocol(Q);
2756 if (T->isSpecialized())
2757 for (const auto &TA : T->getTypeArgs())
2758 mangleType(TA, Range, QMM_Drop);
2764 TypeBackReferences.swap(OuterArgsContext);
2765 NameBackReferences.swap(OuterTemplateContext);
2768 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
2769 Qualifiers Quals, SourceRange Range) {
2770 QualType PointeeType = T->getPointeeType();
2771 manglePointerCVQualifiers(Quals);
2772 manglePointerExtQualifiers(Quals, PointeeType);
2776 mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
2779 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
2780 Qualifiers, SourceRange) {
2781 llvm_unreachable("Cannot mangle injected class name type.");
2784 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
2785 Qualifiers, SourceRange Range) {
2786 DiagnosticsEngine &Diags = Context.getDiags();
2787 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2788 "cannot mangle this template specialization type yet");
2789 Diags.Report(Range.getBegin(), DiagID)
2793 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
2794 SourceRange Range) {
2795 DiagnosticsEngine &Diags = Context.getDiags();
2796 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2797 "cannot mangle this dependent name type yet");
2798 Diags.Report(Range.getBegin(), DiagID)
2802 void MicrosoftCXXNameMangler::mangleType(
2803 const DependentTemplateSpecializationType *T, Qualifiers,
2804 SourceRange Range) {
2805 DiagnosticsEngine &Diags = Context.getDiags();
2806 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2807 "cannot mangle this dependent template specialization type yet");
2808 Diags.Report(Range.getBegin(), DiagID)
2812 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
2813 SourceRange Range) {
2814 DiagnosticsEngine &Diags = Context.getDiags();
2815 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2816 "cannot mangle this pack expansion yet");
2817 Diags.Report(Range.getBegin(), DiagID)
2821 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
2822 SourceRange Range) {
2823 DiagnosticsEngine &Diags = Context.getDiags();
2824 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2825 "cannot mangle this typeof(type) yet");
2826 Diags.Report(Range.getBegin(), DiagID)
2830 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
2831 SourceRange Range) {
2832 DiagnosticsEngine &Diags = Context.getDiags();
2833 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2834 "cannot mangle this typeof(expression) yet");
2835 Diags.Report(Range.getBegin(), DiagID)
2839 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
2840 SourceRange Range) {
2841 DiagnosticsEngine &Diags = Context.getDiags();
2842 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2843 "cannot mangle this decltype() yet");
2844 Diags.Report(Range.getBegin(), DiagID)
2848 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2849 Qualifiers, SourceRange Range) {
2850 DiagnosticsEngine &Diags = Context.getDiags();
2851 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2852 "cannot mangle this unary transform type yet");
2853 Diags.Report(Range.getBegin(), DiagID)
2857 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
2858 SourceRange Range) {
2859 assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2861 DiagnosticsEngine &Diags = Context.getDiags();
2862 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2863 "cannot mangle this 'auto' type yet");
2864 Diags.Report(Range.getBegin(), DiagID)
2868 void MicrosoftCXXNameMangler::mangleType(
2869 const DeducedTemplateSpecializationType *T, Qualifiers, SourceRange Range) {
2870 assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2872 DiagnosticsEngine &Diags = Context.getDiags();
2873 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2874 "cannot mangle this deduced class template specialization type yet");
2875 Diags.Report(Range.getBegin(), DiagID)
2879 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
2880 SourceRange Range) {
2881 QualType ValueType = T->getValueType();
2883 llvm::SmallString<64> TemplateMangling;
2884 llvm::raw_svector_ostream Stream(TemplateMangling);
2885 MicrosoftCXXNameMangler Extra(Context, Stream);
2887 Extra.mangleSourceName("_Atomic");
2888 Extra.mangleType(ValueType, Range, QMM_Escape);
2890 mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
2893 void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
2894 SourceRange Range) {
2895 DiagnosticsEngine &Diags = Context.getDiags();
2896 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2897 "cannot mangle this OpenCL pipe type yet");
2898 Diags.Report(Range.getBegin(), DiagID)
2902 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2904 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2905 "Invalid mangleName() call, argument is not a variable or function!");
2906 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2907 "Invalid mangleName() call on 'structor decl!");
2909 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2910 getASTContext().getSourceManager(),
2911 "Mangling declaration");
2913 msvc_hashing_ostream MHO(Out);
2914 MicrosoftCXXNameMangler Mangler(*this, MHO);
2915 return Mangler.mangle(D);
2918 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2919 // <virtual-adjustment>
2920 // <no-adjustment> ::= A # private near
2921 // ::= B # private far
2922 // ::= I # protected near
2923 // ::= J # protected far
2924 // ::= Q # public near
2925 // ::= R # public far
2926 // <static-adjustment> ::= G <static-offset> # private near
2927 // ::= H <static-offset> # private far
2928 // ::= O <static-offset> # protected near
2929 // ::= P <static-offset> # protected far
2930 // ::= W <static-offset> # public near
2931 // ::= X <static-offset> # public far
2932 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2933 // ::= $1 <virtual-shift> <static-offset> # private far
2934 // ::= $2 <virtual-shift> <static-offset> # protected near
2935 // ::= $3 <virtual-shift> <static-offset> # protected far
2936 // ::= $4 <virtual-shift> <static-offset> # public near
2937 // ::= $5 <virtual-shift> <static-offset> # public far
2938 // <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift>
2939 // <vtordisp-shift> ::= <offset-to-vtordisp>
2940 // <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset>
2941 // <offset-to-vtordisp>
2942 static void mangleThunkThisAdjustment(AccessSpecifier AS,
2943 const ThisAdjustment &Adjustment,
2944 MicrosoftCXXNameMangler &Mangler,
2946 if (!Adjustment.Virtual.isEmpty()) {
2951 llvm_unreachable("Unsupported access specifier");
2961 if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2962 Out << 'R' << AccessSpec;
2963 Mangler.mangleNumber(
2964 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2965 Mangler.mangleNumber(
2966 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2967 Mangler.mangleNumber(
2968 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2969 Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2972 Mangler.mangleNumber(
2973 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2974 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2976 } else if (Adjustment.NonVirtual != 0) {
2979 llvm_unreachable("Unsupported access specifier");
2989 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2993 llvm_unreachable("Unsupported access specifier");
3006 void MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(
3007 const CXXMethodDecl *MD, const MethodVFTableLocation &ML,
3009 msvc_hashing_ostream MHO(Out);
3010 MicrosoftCXXNameMangler Mangler(*this, MHO);
3011 Mangler.getStream() << '?';
3012 Mangler.mangleVirtualMemPtrThunk(MD, ML);
3015 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3016 const ThunkInfo &Thunk,
3018 msvc_hashing_ostream MHO(Out);
3019 MicrosoftCXXNameMangler Mangler(*this, MHO);
3020 Mangler.getStream() << '?';
3021 Mangler.mangleName(MD);
3023 // Usually the thunk uses the access specifier of the new method, but if this
3024 // is a covariant return thunk, then MSVC always uses the public access
3025 // specifier, and we do the same.
3026 AccessSpecifier AS = Thunk.Return.isEmpty() ? MD->getAccess() : AS_public;
3027 mangleThunkThisAdjustment(AS, Thunk.This, Mangler, MHO);
3029 if (!Thunk.Return.isEmpty())
3030 assert(Thunk.Method != nullptr &&
3031 "Thunk info should hold the overridee decl");
3033 const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
3034 Mangler.mangleFunctionType(
3035 DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
3038 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
3039 const CXXDestructorDecl *DD, CXXDtorType Type,
3040 const ThisAdjustment &Adjustment, raw_ostream &Out) {
3041 // FIXME: Actually, the dtor thunk should be emitted for vector deleting
3042 // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
3043 // mangling manually until we support both deleting dtor types.
3044 assert(Type == Dtor_Deleting);
3045 msvc_hashing_ostream MHO(Out);
3046 MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type);
3047 Mangler.getStream() << "??_E";
3048 Mangler.mangleName(DD->getParent());
3049 mangleThunkThisAdjustment(DD->getAccess(), Adjustment, Mangler, MHO);
3050 Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
3053 void MicrosoftMangleContextImpl::mangleCXXVFTable(
3054 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3056 // <mangled-name> ::= ?_7 <class-name> <storage-class>
3057 // <cvr-qualifiers> [<name>] @
3058 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3059 // is always '6' for vftables.
3060 msvc_hashing_ostream MHO(Out);
3061 MicrosoftCXXNameMangler Mangler(*this, MHO);
3062 if (Derived->hasAttr<DLLImportAttr>())
3063 Mangler.getStream() << "??_S";
3065 Mangler.getStream() << "??_7";
3066 Mangler.mangleName(Derived);
3067 Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
3068 for (const CXXRecordDecl *RD : BasePath)
3069 Mangler.mangleName(RD);
3070 Mangler.getStream() << '@';
3073 void MicrosoftMangleContextImpl::mangleCXXVBTable(
3074 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3076 // <mangled-name> ::= ?_8 <class-name> <storage-class>
3077 // <cvr-qualifiers> [<name>] @
3078 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3079 // is always '7' for vbtables.
3080 msvc_hashing_ostream MHO(Out);
3081 MicrosoftCXXNameMangler Mangler(*this, MHO);
3082 Mangler.getStream() << "??_8";
3083 Mangler.mangleName(Derived);
3084 Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const.
3085 for (const CXXRecordDecl *RD : BasePath)
3086 Mangler.mangleName(RD);
3087 Mangler.getStream() << '@';
3090 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
3091 msvc_hashing_ostream MHO(Out);
3092 MicrosoftCXXNameMangler Mangler(*this, MHO);
3093 Mangler.getStream() << "??_R0";
3094 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3095 Mangler.getStream() << "@8";
3098 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
3100 MicrosoftCXXNameMangler Mangler(*this, Out);
3101 Mangler.getStream() << '.';
3102 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3105 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
3106 const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
3107 msvc_hashing_ostream MHO(Out);
3108 MicrosoftCXXNameMangler Mangler(*this, MHO);
3109 Mangler.getStream() << "??_K";
3110 Mangler.mangleName(SrcRD);
3111 Mangler.getStream() << "$C";
3112 Mangler.mangleName(DstRD);
3115 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst,
3118 uint32_t NumEntries,
3120 msvc_hashing_ostream MHO(Out);
3121 MicrosoftCXXNameMangler Mangler(*this, MHO);
3122 Mangler.getStream() << "_TI";
3124 Mangler.getStream() << 'C';
3126 Mangler.getStream() << 'V';
3128 Mangler.getStream() << 'U';
3129 Mangler.getStream() << NumEntries;
3130 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3133 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
3134 QualType T, uint32_t NumEntries, raw_ostream &Out) {
3135 msvc_hashing_ostream MHO(Out);
3136 MicrosoftCXXNameMangler Mangler(*this, MHO);
3137 Mangler.getStream() << "_CTA";
3138 Mangler.getStream() << NumEntries;
3139 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3142 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
3143 QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
3144 uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
3146 MicrosoftCXXNameMangler Mangler(*this, Out);
3147 Mangler.getStream() << "_CT";
3149 llvm::SmallString<64> RTTIMangling;
3151 llvm::raw_svector_ostream Stream(RTTIMangling);
3152 msvc_hashing_ostream MHO(Stream);
3153 mangleCXXRTTI(T, MHO);
3155 Mangler.getStream() << RTTIMangling;
3157 // VS2015 CTP6 omits the copy-constructor in the mangled name. This name is,
3158 // in fact, superfluous but I'm not sure the change was made consciously.
3159 llvm::SmallString<64> CopyCtorMangling;
3160 if (!getASTContext().getLangOpts().isCompatibleWithMSVC(
3161 LangOptions::MSVC2015) &&
3163 llvm::raw_svector_ostream Stream(CopyCtorMangling);
3164 msvc_hashing_ostream MHO(Stream);
3165 mangleCXXCtor(CD, CT, MHO);
3167 Mangler.getStream() << CopyCtorMangling;
3169 Mangler.getStream() << Size;
3170 if (VBPtrOffset == -1) {
3172 Mangler.getStream() << NVOffset;
3175 Mangler.getStream() << NVOffset;
3176 Mangler.getStream() << VBPtrOffset;
3177 Mangler.getStream() << VBIndex;
3181 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
3182 const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
3183 uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
3184 msvc_hashing_ostream MHO(Out);
3185 MicrosoftCXXNameMangler Mangler(*this, MHO);
3186 Mangler.getStream() << "??_R1";
3187 Mangler.mangleNumber(NVOffset);
3188 Mangler.mangleNumber(VBPtrOffset);
3189 Mangler.mangleNumber(VBTableOffset);
3190 Mangler.mangleNumber(Flags);
3191 Mangler.mangleName(Derived);
3192 Mangler.getStream() << "8";
3195 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
3196 const CXXRecordDecl *Derived, raw_ostream &Out) {
3197 msvc_hashing_ostream MHO(Out);
3198 MicrosoftCXXNameMangler Mangler(*this, MHO);
3199 Mangler.getStream() << "??_R2";
3200 Mangler.mangleName(Derived);
3201 Mangler.getStream() << "8";
3204 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
3205 const CXXRecordDecl *Derived, raw_ostream &Out) {
3206 msvc_hashing_ostream MHO(Out);
3207 MicrosoftCXXNameMangler Mangler(*this, MHO);
3208 Mangler.getStream() << "??_R3";
3209 Mangler.mangleName(Derived);
3210 Mangler.getStream() << "8";
3213 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
3214 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3216 // <mangled-name> ::= ?_R4 <class-name> <storage-class>
3217 // <cvr-qualifiers> [<name>] @
3218 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3219 // is always '6' for vftables.
3220 llvm::SmallString<64> VFTableMangling;
3221 llvm::raw_svector_ostream Stream(VFTableMangling);
3222 mangleCXXVFTable(Derived, BasePath, Stream);
3224 if (VFTableMangling.startswith("??@")) {
3225 assert(VFTableMangling.endswith("@"));
3226 Out << VFTableMangling << "??_R4@";
3230 assert(VFTableMangling.startswith("??_7") ||
3231 VFTableMangling.startswith("??_S"));
3233 Out << "??_R4" << StringRef(VFTableMangling).drop_front(4);
3236 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
3237 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3238 msvc_hashing_ostream MHO(Out);
3239 MicrosoftCXXNameMangler Mangler(*this, MHO);
3240 // The function body is in the same comdat as the function with the handler,
3241 // so the numbering here doesn't have to be the same across TUs.
3243 // <mangled-name> ::= ?filt$ <filter-number> @0
3244 Mangler.getStream() << "?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
3245 Mangler.mangleName(EnclosingDecl);
3248 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
3249 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3250 msvc_hashing_ostream MHO(Out);
3251 MicrosoftCXXNameMangler Mangler(*this, MHO);
3252 // The function body is in the same comdat as the function with the handler,
3253 // so the numbering here doesn't have to be the same across TUs.
3255 // <mangled-name> ::= ?fin$ <filter-number> @0
3256 Mangler.getStream() << "?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
3257 Mangler.mangleName(EnclosingDecl);
3260 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
3261 // This is just a made up unique string for the purposes of tbaa. undname
3262 // does *not* know how to demangle it.
3263 MicrosoftCXXNameMangler Mangler(*this, Out);
3264 Mangler.getStream() << '?';
3265 Mangler.mangleType(T, SourceRange());
3268 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3271 msvc_hashing_ostream MHO(Out);
3272 MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
3276 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3279 msvc_hashing_ostream MHO(Out);
3280 MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
3284 void MicrosoftMangleContextImpl::mangleReferenceTemporary(
3285 const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
3286 msvc_hashing_ostream MHO(Out);
3287 MicrosoftCXXNameMangler Mangler(*this, MHO);
3289 Mangler.getStream() << "?$RT" << ManglingNumber << '@';
3290 Mangler.mangle(VD, "");
3293 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
3294 const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
3295 msvc_hashing_ostream MHO(Out);
3296 MicrosoftCXXNameMangler Mangler(*this, MHO);
3298 Mangler.getStream() << "?$TSS" << GuardNum << '@';
3299 Mangler.mangleNestedName(VD);
3300 Mangler.getStream() << "@4HA";
3303 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
3305 // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
3306 // ::= ?__J <postfix> @5 <scope-depth>
3307 // ::= ?$S <guard-num> @ <postfix> @4IA
3309 // The first mangling is what MSVC uses to guard static locals in inline
3310 // functions. It uses a different mangling in external functions to support
3311 // guarding more than 32 variables. MSVC rejects inline functions with more
3312 // than 32 static locals. We don't fully implement the second mangling
3313 // because those guards are not externally visible, and instead use LLVM's
3314 // default renaming when creating a new guard variable.
3315 msvc_hashing_ostream MHO(Out);
3316 MicrosoftCXXNameMangler Mangler(*this, MHO);
3318 bool Visible = VD->isExternallyVisible();
3320 Mangler.getStream() << (VD->getTLSKind() ? "??__J" : "??_B");
3322 Mangler.getStream() << "?$S1@";
3324 unsigned ScopeDepth = 0;
3325 if (Visible && !getNextDiscriminator(VD, ScopeDepth))
3326 // If we do not have a discriminator and are emitting a guard variable for
3327 // use at global scope, then mangling the nested name will not be enough to
3328 // remove ambiguities.
3329 Mangler.mangle(VD, "");
3331 Mangler.mangleNestedName(VD);
3332 Mangler.getStream() << (Visible ? "@5" : "@4IA");
3334 Mangler.mangleNumber(ScopeDepth);
3337 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
3340 msvc_hashing_ostream MHO(Out);
3341 MicrosoftCXXNameMangler Mangler(*this, MHO);
3342 Mangler.getStream() << "??__" << CharCode;
3343 if (D->isStaticDataMember()) {
3344 Mangler.getStream() << '?';
3345 Mangler.mangleName(D);
3346 Mangler.mangleVariableEncoding(D);
3347 Mangler.getStream() << "@@";
3349 Mangler.mangleName(D);
3351 // This is the function class mangling. These stubs are global, non-variadic,
3352 // cdecl functions that return void and take no args.
3353 Mangler.getStream() << "YAXXZ";
3356 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
3358 // <initializer-name> ::= ?__E <name> YAXXZ
3359 mangleInitFiniStub(D, 'E', Out);
3363 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3365 // <destructor-name> ::= ?__F <name> YAXXZ
3366 mangleInitFiniStub(D, 'F', Out);
3369 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
3371 // <char-type> ::= 0 # char, char16_t, char32_t
3372 // # (little endian char data in mangling)
3373 // ::= 1 # wchar_t (big endian char data in mangling)
3375 // <literal-length> ::= <non-negative integer> # the length of the literal
3377 // <encoded-crc> ::= <hex digit>+ @ # crc of the literal including
3378 // # trailing null bytes
3380 // <encoded-string> ::= <simple character> # uninteresting character
3381 // ::= '?$' <hex digit> <hex digit> # these two nibbles
3382 // # encode the byte for the
3384 // ::= '?' [a-z] # \xe1 - \xfa
3385 // ::= '?' [A-Z] # \xc1 - \xda
3386 // ::= '?' [0-9] # [,/\:. \n\t'-]
3388 // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
3389 // <encoded-string> '@'
3390 MicrosoftCXXNameMangler Mangler(*this, Out);
3391 Mangler.getStream() << "??_C@_";
3393 // The actual string length might be different from that of the string literal
3395 // char foo[3] = "foobar";
3396 // char bar[42] = "foobar";
3397 // Where it is truncated or zero-padded to fit the array. This is the length
3398 // used for mangling, and any trailing null-bytes also need to be mangled.
3399 unsigned StringLength = getASTContext()
3400 .getAsConstantArrayType(SL->getType())
3403 unsigned StringByteLength = StringLength * SL->getCharByteWidth();
3405 // <char-type>: The "kind" of string literal is encoded into the mangled name.
3407 Mangler.getStream() << '1';
3409 Mangler.getStream() << '0';
3411 // <literal-length>: The next part of the mangled name consists of the length
3412 // of the string in bytes.
3413 Mangler.mangleNumber(StringByteLength);
3415 auto GetLittleEndianByte = [&SL](unsigned Index) {
3416 unsigned CharByteWidth = SL->getCharByteWidth();
3417 if (Index / CharByteWidth >= SL->getLength())
3418 return static_cast<char>(0);
3419 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3420 unsigned OffsetInCodeUnit = Index % CharByteWidth;
3421 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3424 auto GetBigEndianByte = [&SL](unsigned Index) {
3425 unsigned CharByteWidth = SL->getCharByteWidth();
3426 if (Index / CharByteWidth >= SL->getLength())
3427 return static_cast<char>(0);
3428 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3429 unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
3430 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3433 // CRC all the bytes of the StringLiteral.
3435 for (unsigned I = 0, E = StringByteLength; I != E; ++I)
3436 JC.update(GetLittleEndianByte(I));
3438 // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
3440 Mangler.mangleNumber(JC.getCRC());
3442 // <encoded-string>: The mangled name also contains the first 32 bytes
3443 // (including null-terminator bytes) of the encoded StringLiteral.
3444 // Each character is encoded by splitting them into bytes and then encoding
3445 // the constituent bytes.
3446 auto MangleByte = [&Mangler](char Byte) {
3447 // There are five different manglings for characters:
3448 // - [a-zA-Z0-9_$]: A one-to-one mapping.
3449 // - ?[a-z]: The range from \xe1 to \xfa.
3450 // - ?[A-Z]: The range from \xc1 to \xda.
3451 // - ?[0-9]: The set of [,/\:. \n\t'-].
3452 // - ?$XX: A fallback which maps nibbles.
3453 if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
3454 Mangler.getStream() << Byte;
3455 } else if (isLetter(Byte & 0x7f)) {
3456 Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
3458 const char SpecialChars[] = {',', '/', '\\', ':', '.',
3459 ' ', '\n', '\t', '\'', '-'};
3461 std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
3462 if (Pos != std::end(SpecialChars)) {
3463 Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
3465 Mangler.getStream() << "?$";
3466 Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
3467 Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
3472 // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead.
3473 unsigned MaxBytesToMangle = SL->isWide() ? 64U : 32U;
3474 unsigned NumBytesToMangle = std::min(MaxBytesToMangle, StringByteLength);
3475 for (unsigned I = 0; I != NumBytesToMangle; ++I) {
3477 MangleByte(GetBigEndianByte(I));
3479 MangleByte(GetLittleEndianByte(I));
3482 Mangler.getStream() << '@';
3485 MicrosoftMangleContext *
3486 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
3487 return new MicrosoftMangleContextImpl(Context, Diags);