1 //===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This provides C++ name mangling targeting the Microsoft Visual C++ ABI. 11 // 12 //===----------------------------------------------------------------------===// 13 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/MD5.h" 33 #include "llvm/Support/MathExtras.h" 34 35 using namespace clang; 36 37 namespace { 38 39 struct msvc_hashing_ostream : public llvm::raw_svector_ostream { 40 raw_ostream &OS; 41 llvm::SmallString<64> Buffer; 42 43 msvc_hashing_ostream(raw_ostream &OS) 44 : llvm::raw_svector_ostream(Buffer), OS(OS) {} 45 ~msvc_hashing_ostream() override { 46 StringRef MangledName = str(); 47 bool StartsWithEscape = MangledName.startswith("\01"); 48 if (StartsWithEscape) 49 MangledName = MangledName.drop_front(1); 50 if (MangledName.size() <= 4096) { 51 OS << str(); 52 return; 53 } 54 55 llvm::MD5 Hasher; 56 llvm::MD5::MD5Result Hash; 57 Hasher.update(MangledName); 58 Hasher.final(Hash); 59 60 SmallString<32> HexString; 61 llvm::MD5::stringifyResult(Hash, HexString); 62 63 if (StartsWithEscape) 64 OS << '\01'; 65 OS << "??@" << HexString << '@'; 66 } 67 }; 68 69 static const DeclContext * 70 getLambdaDefaultArgumentDeclContext(const Decl *D) { 71 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) 72 if (RD->isLambda()) 73 if (const auto *Parm = 74 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl())) 75 return Parm->getDeclContext(); 76 return nullptr; 77 } 78 79 /// \brief Retrieve the declaration context that should be used when mangling 80 /// the given declaration. 81 static const DeclContext *getEffectiveDeclContext(const Decl *D) { 82 // The ABI assumes that lambda closure types that occur within 83 // default arguments live in the context of the function. However, due to 84 // the way in which Clang parses and creates function declarations, this is 85 // not the case: the lambda closure type ends up living in the context 86 // where the function itself resides, because the function declaration itself 87 // had not yet been created. Fix the context here. 88 if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(D)) 89 return LDADC; 90 91 // Perform the same check for block literals. 92 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 93 if (ParmVarDecl *ContextParam = 94 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) 95 return ContextParam->getDeclContext(); 96 } 97 98 const DeclContext *DC = D->getDeclContext(); 99 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) { 100 return getEffectiveDeclContext(cast<Decl>(DC)); 101 } 102 103 return DC->getRedeclContext(); 104 } 105 106 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) { 107 return getEffectiveDeclContext(cast<Decl>(DC)); 108 } 109 110 static const FunctionDecl *getStructor(const NamedDecl *ND) { 111 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 112 return FTD->getTemplatedDecl()->getCanonicalDecl(); 113 114 const auto *FD = cast<FunctionDecl>(ND); 115 if (const auto *FTD = FD->getPrimaryTemplate()) 116 return FTD->getTemplatedDecl()->getCanonicalDecl(); 117 118 return FD->getCanonicalDecl(); 119 } 120 121 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the 122 /// Microsoft Visual C++ ABI. 123 class MicrosoftMangleContextImpl : public MicrosoftMangleContext { 124 typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy; 125 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator; 126 llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier; 127 llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds; 128 llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds; 129 llvm::DenseMap<const NamedDecl *, unsigned> SEHFinallyIds; 130 131 public: 132 MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags) 133 : MicrosoftMangleContext(Context, Diags) {} 134 bool shouldMangleCXXName(const NamedDecl *D) override; 135 bool shouldMangleStringLiteral(const StringLiteral *SL) override; 136 void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override; 137 void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD, 138 raw_ostream &) override; 139 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, 140 raw_ostream &) override; 141 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type, 142 const ThisAdjustment &ThisAdjustment, 143 raw_ostream &) override; 144 void mangleCXXVFTable(const CXXRecordDecl *Derived, 145 ArrayRef<const CXXRecordDecl *> BasePath, 146 raw_ostream &Out) override; 147 void mangleCXXVBTable(const CXXRecordDecl *Derived, 148 ArrayRef<const CXXRecordDecl *> BasePath, 149 raw_ostream &Out) override; 150 void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD, 151 const CXXRecordDecl *DstRD, 152 raw_ostream &Out) override; 153 void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile, 154 bool IsUnaligned, uint32_t NumEntries, 155 raw_ostream &Out) override; 156 void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries, 157 raw_ostream &Out) override; 158 void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD, 159 CXXCtorType CT, uint32_t Size, uint32_t NVOffset, 160 int32_t VBPtrOffset, uint32_t VBIndex, 161 raw_ostream &Out) override; 162 void mangleCXXRTTI(QualType T, raw_ostream &Out) override; 163 void mangleCXXRTTIName(QualType T, raw_ostream &Out) override; 164 void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived, 165 uint32_t NVOffset, int32_t VBPtrOffset, 166 uint32_t VBTableOffset, uint32_t Flags, 167 raw_ostream &Out) override; 168 void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived, 169 raw_ostream &Out) override; 170 void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived, 171 raw_ostream &Out) override; 172 void 173 mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived, 174 ArrayRef<const CXXRecordDecl *> BasePath, 175 raw_ostream &Out) override; 176 void mangleTypeName(QualType T, raw_ostream &) override; 177 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type, 178 raw_ostream &) override; 179 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type, 180 raw_ostream &) override; 181 void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber, 182 raw_ostream &) override; 183 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override; 184 void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum, 185 raw_ostream &Out) override; 186 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override; 187 void mangleDynamicAtExitDestructor(const VarDecl *D, 188 raw_ostream &Out) override; 189 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl, 190 raw_ostream &Out) override; 191 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl, 192 raw_ostream &Out) override; 193 void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override; 194 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) { 195 const DeclContext *DC = getEffectiveDeclContext(ND); 196 if (!DC->isFunctionOrMethod()) 197 return false; 198 199 // Lambda closure types are already numbered, give out a phony number so 200 // that they demangle nicely. 201 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) { 202 if (RD->isLambda()) { 203 disc = 1; 204 return true; 205 } 206 } 207 208 // Use the canonical number for externally visible decls. 209 if (ND->isExternallyVisible()) { 210 disc = getASTContext().getManglingNumber(ND); 211 return true; 212 } 213 214 // Anonymous tags are already numbered. 215 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) { 216 if (!Tag->hasNameForLinkage() && 217 !getASTContext().getDeclaratorForUnnamedTagDecl(Tag) && 218 !getASTContext().getTypedefNameForUnnamedTagDecl(Tag)) 219 return false; 220 } 221 222 // Make up a reasonable number for internal decls. 223 unsigned &discriminator = Uniquifier[ND]; 224 if (!discriminator) 225 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())]; 226 disc = discriminator + 1; 227 return true; 228 } 229 230 unsigned getLambdaId(const CXXRecordDecl *RD) { 231 assert(RD->isLambda() && "RD must be a lambda!"); 232 assert(!RD->isExternallyVisible() && "RD must not be visible!"); 233 assert(RD->getLambdaManglingNumber() == 0 && 234 "RD must not have a mangling number!"); 235 std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool> 236 Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size())); 237 return Result.first->second; 238 } 239 240 private: 241 void mangleInitFiniStub(const VarDecl *D, char CharCode, raw_ostream &Out); 242 }; 243 244 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the 245 /// Microsoft Visual C++ ABI. 246 class MicrosoftCXXNameMangler { 247 MicrosoftMangleContextImpl &Context; 248 raw_ostream &Out; 249 250 /// The "structor" is the top-level declaration being mangled, if 251 /// that's not a template specialization; otherwise it's the pattern 252 /// for that specialization. 253 const NamedDecl *Structor; 254 unsigned StructorType; 255 256 typedef llvm::SmallVector<std::string, 10> BackRefVec; 257 BackRefVec NameBackReferences; 258 259 typedef llvm::DenseMap<const void *, unsigned> ArgBackRefMap; 260 ArgBackRefMap TypeBackReferences; 261 262 typedef std::set<int> PassObjectSizeArgsSet; 263 PassObjectSizeArgsSet PassObjectSizeArgs; 264 265 ASTContext &getASTContext() const { return Context.getASTContext(); } 266 267 // FIXME: If we add support for __ptr32/64 qualifiers, then we should push 268 // this check into mangleQualifiers(). 269 const bool PointersAre64Bit; 270 271 public: 272 enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result }; 273 274 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_) 275 : Context(C), Out(Out_), Structor(nullptr), StructorType(-1), 276 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) == 277 64) {} 278 279 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_, 280 const CXXConstructorDecl *D, CXXCtorType Type) 281 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), 282 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) == 283 64) {} 284 285 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_, 286 const CXXDestructorDecl *D, CXXDtorType Type) 287 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), 288 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) == 289 64) {} 290 291 raw_ostream &getStream() const { return Out; } 292 293 void mangle(const NamedDecl *D, StringRef Prefix = "\01?"); 294 void mangleName(const NamedDecl *ND); 295 void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle); 296 void mangleVariableEncoding(const VarDecl *VD); 297 void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD); 298 void mangleMemberFunctionPointer(const CXXRecordDecl *RD, 299 const CXXMethodDecl *MD); 300 void mangleVirtualMemPtrThunk( 301 const CXXMethodDecl *MD, 302 const MicrosoftVTableContext::MethodVFTableLocation &ML); 303 void mangleNumber(int64_t Number); 304 void mangleTagTypeKind(TagTypeKind TK); 305 void mangleArtificalTagType(TagTypeKind TK, StringRef UnqualifiedName, 306 ArrayRef<StringRef> NestedNames = None); 307 void mangleType(QualType T, SourceRange Range, 308 QualifierMangleMode QMM = QMM_Mangle); 309 void mangleFunctionType(const FunctionType *T, 310 const FunctionDecl *D = nullptr, 311 bool ForceThisQuals = false); 312 void mangleNestedName(const NamedDecl *ND); 313 314 private: 315 bool isStructorDecl(const NamedDecl *ND) const { 316 return ND == Structor || getStructor(ND) == Structor; 317 } 318 319 void mangleUnqualifiedName(const NamedDecl *ND) { 320 mangleUnqualifiedName(ND, ND->getDeclName()); 321 } 322 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name); 323 void mangleSourceName(StringRef Name); 324 void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc); 325 void mangleCXXDtorType(CXXDtorType T); 326 void mangleQualifiers(Qualifiers Quals, bool IsMember); 327 void mangleRefQualifier(RefQualifierKind RefQualifier); 328 void manglePointerCVQualifiers(Qualifiers Quals); 329 void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType); 330 331 void mangleUnscopedTemplateName(const TemplateDecl *ND); 332 void 333 mangleTemplateInstantiationName(const TemplateDecl *TD, 334 const TemplateArgumentList &TemplateArgs); 335 void mangleObjCMethodName(const ObjCMethodDecl *MD); 336 337 void mangleArgumentType(QualType T, SourceRange Range); 338 void manglePassObjectSizeArg(const PassObjectSizeAttr *POSA); 339 340 // Declare manglers for every type class. 341 #define ABSTRACT_TYPE(CLASS, PARENT) 342 #define NON_CANONICAL_TYPE(CLASS, PARENT) 343 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \ 344 Qualifiers Quals, \ 345 SourceRange Range); 346 #include "clang/AST/TypeNodes.def" 347 #undef ABSTRACT_TYPE 348 #undef NON_CANONICAL_TYPE 349 #undef TYPE 350 351 void mangleType(const TagDecl *TD); 352 void mangleDecayedArrayType(const ArrayType *T); 353 void mangleArrayType(const ArrayType *T); 354 void mangleFunctionClass(const FunctionDecl *FD); 355 void mangleCallingConvention(CallingConv CC); 356 void mangleCallingConvention(const FunctionType *T); 357 void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean); 358 void mangleExpression(const Expr *E); 359 void mangleThrowSpecification(const FunctionProtoType *T); 360 361 void mangleTemplateArgs(const TemplateDecl *TD, 362 const TemplateArgumentList &TemplateArgs); 363 void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA, 364 const NamedDecl *Parm); 365 366 void mangleObjCProtocol(const ObjCProtocolDecl *PD); 367 void mangleObjCLifetime(const QualType T, Qualifiers Quals, 368 SourceRange Range); 369 }; 370 } 371 372 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) { 373 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 374 LanguageLinkage L = FD->getLanguageLinkage(); 375 // Overloadable functions need mangling. 376 if (FD->hasAttr<OverloadableAttr>()) 377 return true; 378 379 // The ABI expects that we would never mangle "typical" user-defined entry 380 // points regardless of visibility or freestanding-ness. 381 // 382 // N.B. This is distinct from asking about "main". "main" has a lot of 383 // special rules associated with it in the standard while these 384 // user-defined entry points are outside of the purview of the standard. 385 // For example, there can be only one definition for "main" in a standards 386 // compliant program; however nothing forbids the existence of wmain and 387 // WinMain in the same translation unit. 388 if (FD->isMSVCRTEntryPoint()) 389 return false; 390 391 // C++ functions and those whose names are not a simple identifier need 392 // mangling. 393 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage) 394 return true; 395 396 // C functions are not mangled. 397 if (L == CLanguageLinkage) 398 return false; 399 } 400 401 // Otherwise, no mangling is done outside C++ mode. 402 if (!getASTContext().getLangOpts().CPlusPlus) 403 return false; 404 405 const VarDecl *VD = dyn_cast<VarDecl>(D); 406 if (VD && !isa<DecompositionDecl>(D)) { 407 // C variables are not mangled. 408 if (VD->isExternC()) 409 return false; 410 411 // Variables at global scope with non-internal linkage are not mangled. 412 const DeclContext *DC = getEffectiveDeclContext(D); 413 // Check for extern variable declared locally. 414 if (DC->isFunctionOrMethod() && D->hasLinkage()) 415 while (!DC->isNamespace() && !DC->isTranslationUnit()) 416 DC = getEffectiveParentContext(DC); 417 418 if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage && 419 !isa<VarTemplateSpecializationDecl>(D) && 420 D->getIdentifier() != nullptr) 421 return false; 422 } 423 424 return true; 425 } 426 427 bool 428 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) { 429 return true; 430 } 431 432 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) { 433 // MSVC doesn't mangle C++ names the same way it mangles extern "C" names. 434 // Therefore it's really important that we don't decorate the 435 // name with leading underscores or leading/trailing at signs. So, by 436 // default, we emit an asm marker at the start so we get the name right. 437 // Callers can override this with a custom prefix. 438 439 // <mangled-name> ::= ? <name> <type-encoding> 440 Out << Prefix; 441 mangleName(D); 442 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 443 mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD)); 444 else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 445 mangleVariableEncoding(VD); 446 else 447 llvm_unreachable("Tried to mangle unexpected NamedDecl!"); 448 } 449 450 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD, 451 bool ShouldMangle) { 452 // <type-encoding> ::= <function-class> <function-type> 453 454 // Since MSVC operates on the type as written and not the canonical type, it 455 // actually matters which decl we have here. MSVC appears to choose the 456 // first, since it is most likely to be the declaration in a header file. 457 FD = FD->getFirstDecl(); 458 459 // We should never ever see a FunctionNoProtoType at this point. 460 // We don't even know how to mangle their types anyway :). 461 const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>(); 462 463 // extern "C" functions can hold entities that must be mangled. 464 // As it stands, these functions still need to get expressed in the full 465 // external name. They have their class and type omitted, replaced with '9'. 466 if (ShouldMangle) { 467 // We would like to mangle all extern "C" functions using this additional 468 // component but this would break compatibility with MSVC's behavior. 469 // Instead, do this when we know that compatibility isn't important (in 470 // other words, when it is an overloaded extern "C" function). 471 if (FD->isExternC() && FD->hasAttr<OverloadableAttr>()) 472 Out << "$$J0"; 473 474 mangleFunctionClass(FD); 475 476 mangleFunctionType(FT, FD); 477 } else { 478 Out << '9'; 479 } 480 } 481 482 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) { 483 // <type-encoding> ::= <storage-class> <variable-type> 484 // <storage-class> ::= 0 # private static member 485 // ::= 1 # protected static member 486 // ::= 2 # public static member 487 // ::= 3 # global 488 // ::= 4 # static local 489 490 // The first character in the encoding (after the name) is the storage class. 491 if (VD->isStaticDataMember()) { 492 // If it's a static member, it also encodes the access level. 493 switch (VD->getAccess()) { 494 default: 495 case AS_private: Out << '0'; break; 496 case AS_protected: Out << '1'; break; 497 case AS_public: Out << '2'; break; 498 } 499 } 500 else if (!VD->isStaticLocal()) 501 Out << '3'; 502 else 503 Out << '4'; 504 // Now mangle the type. 505 // <variable-type> ::= <type> <cvr-qualifiers> 506 // ::= <type> <pointee-cvr-qualifiers> # pointers, references 507 // Pointers and references are odd. The type of 'int * const foo;' gets 508 // mangled as 'QAHA' instead of 'PAHB', for example. 509 SourceRange SR = VD->getSourceRange(); 510 QualType Ty = VD->getType(); 511 if (Ty->isPointerType() || Ty->isReferenceType() || 512 Ty->isMemberPointerType()) { 513 mangleType(Ty, SR, QMM_Drop); 514 manglePointerExtQualifiers( 515 Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType()); 516 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) { 517 mangleQualifiers(MPT->getPointeeType().getQualifiers(), true); 518 // Member pointers are suffixed with a back reference to the member 519 // pointer's class name. 520 mangleName(MPT->getClass()->getAsCXXRecordDecl()); 521 } else 522 mangleQualifiers(Ty->getPointeeType().getQualifiers(), false); 523 } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) { 524 // Global arrays are funny, too. 525 mangleDecayedArrayType(AT); 526 if (AT->getElementType()->isArrayType()) 527 Out << 'A'; 528 else 529 mangleQualifiers(Ty.getQualifiers(), false); 530 } else { 531 mangleType(Ty, SR, QMM_Drop); 532 mangleQualifiers(Ty.getQualifiers(), false); 533 } 534 } 535 536 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD, 537 const ValueDecl *VD) { 538 // <member-data-pointer> ::= <integer-literal> 539 // ::= $F <number> <number> 540 // ::= $G <number> <number> <number> 541 542 int64_t FieldOffset; 543 int64_t VBTableOffset; 544 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel(); 545 if (VD) { 546 FieldOffset = getASTContext().getFieldOffset(VD); 547 assert(FieldOffset % getASTContext().getCharWidth() == 0 && 548 "cannot take address of bitfield"); 549 FieldOffset /= getASTContext().getCharWidth(); 550 551 VBTableOffset = 0; 552 553 if (IM == MSInheritanceAttr::Keyword_virtual_inheritance) 554 FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity(); 555 } else { 556 FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1; 557 558 VBTableOffset = -1; 559 } 560 561 char Code = '\0'; 562 switch (IM) { 563 case MSInheritanceAttr::Keyword_single_inheritance: Code = '0'; break; 564 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = '0'; break; 565 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'F'; break; 566 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break; 567 } 568 569 Out << '$' << Code; 570 571 mangleNumber(FieldOffset); 572 573 // The C++ standard doesn't allow base-to-derived member pointer conversions 574 // in template parameter contexts, so the vbptr offset of data member pointers 575 // is always zero. 576 if (MSInheritanceAttr::hasVBPtrOffsetField(IM)) 577 mangleNumber(0); 578 if (MSInheritanceAttr::hasVBTableOffsetField(IM)) 579 mangleNumber(VBTableOffset); 580 } 581 582 void 583 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD, 584 const CXXMethodDecl *MD) { 585 // <member-function-pointer> ::= $1? <name> 586 // ::= $H? <name> <number> 587 // ::= $I? <name> <number> <number> 588 // ::= $J? <name> <number> <number> <number> 589 590 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel(); 591 592 char Code = '\0'; 593 switch (IM) { 594 case MSInheritanceAttr::Keyword_single_inheritance: Code = '1'; break; 595 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = 'H'; break; 596 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'I'; break; 597 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break; 598 } 599 600 // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr 601 // thunk. 602 uint64_t NVOffset = 0; 603 uint64_t VBTableOffset = 0; 604 uint64_t VBPtrOffset = 0; 605 if (MD) { 606 Out << '$' << Code << '?'; 607 if (MD->isVirtual()) { 608 MicrosoftVTableContext *VTContext = 609 cast<MicrosoftVTableContext>(getASTContext().getVTableContext()); 610 const MicrosoftVTableContext::MethodVFTableLocation &ML = 611 VTContext->getMethodVFTableLocation(GlobalDecl(MD)); 612 mangleVirtualMemPtrThunk(MD, ML); 613 NVOffset = ML.VFPtrOffset.getQuantity(); 614 VBTableOffset = ML.VBTableIndex * 4; 615 if (ML.VBase) { 616 const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD); 617 VBPtrOffset = Layout.getVBPtrOffset().getQuantity(); 618 } 619 } else { 620 mangleName(MD); 621 mangleFunctionEncoding(MD, /*ShouldMangle=*/true); 622 } 623 624 if (VBTableOffset == 0 && 625 IM == MSInheritanceAttr::Keyword_virtual_inheritance) 626 NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity(); 627 } else { 628 // Null single inheritance member functions are encoded as a simple nullptr. 629 if (IM == MSInheritanceAttr::Keyword_single_inheritance) { 630 Out << "$0A@"; 631 return; 632 } 633 if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance) 634 VBTableOffset = -1; 635 Out << '$' << Code; 636 } 637 638 if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM)) 639 mangleNumber(static_cast<uint32_t>(NVOffset)); 640 if (MSInheritanceAttr::hasVBPtrOffsetField(IM)) 641 mangleNumber(VBPtrOffset); 642 if (MSInheritanceAttr::hasVBTableOffsetField(IM)) 643 mangleNumber(VBTableOffset); 644 } 645 646 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk( 647 const CXXMethodDecl *MD, 648 const MicrosoftVTableContext::MethodVFTableLocation &ML) { 649 // Get the vftable offset. 650 CharUnits PointerWidth = getASTContext().toCharUnitsFromBits( 651 getASTContext().getTargetInfo().getPointerWidth(0)); 652 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity(); 653 654 Out << "?_9"; 655 mangleName(MD->getParent()); 656 Out << "$B"; 657 mangleNumber(OffsetInVFTable); 658 Out << 'A'; 659 mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>()); 660 } 661 662 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) { 663 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @ 664 665 // Always start with the unqualified name. 666 mangleUnqualifiedName(ND); 667 668 mangleNestedName(ND); 669 670 // Terminate the whole name with an '@'. 671 Out << '@'; 672 } 673 674 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) { 675 // <non-negative integer> ::= A@ # when Number == 0 676 // ::= <decimal digit> # when 1 <= Number <= 10 677 // ::= <hex digit>+ @ # when Number >= 10 678 // 679 // <number> ::= [?] <non-negative integer> 680 681 uint64_t Value = static_cast<uint64_t>(Number); 682 if (Number < 0) { 683 Value = -Value; 684 Out << '?'; 685 } 686 687 if (Value == 0) 688 Out << "A@"; 689 else if (Value >= 1 && Value <= 10) 690 Out << (Value - 1); 691 else { 692 // Numbers that are not encoded as decimal digits are represented as nibbles 693 // in the range of ASCII characters 'A' to 'P'. 694 // The number 0x123450 would be encoded as 'BCDEFA' 695 char EncodedNumberBuffer[sizeof(uint64_t) * 2]; 696 MutableArrayRef<char> BufferRef(EncodedNumberBuffer); 697 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin(); 698 for (; Value != 0; Value >>= 4) 699 *I++ = 'A' + (Value & 0xf); 700 Out.write(I.base(), I - BufferRef.rbegin()); 701 Out << '@'; 702 } 703 } 704 705 static const TemplateDecl * 706 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) { 707 // Check if we have a function template. 708 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 709 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) { 710 TemplateArgs = FD->getTemplateSpecializationArgs(); 711 return TD; 712 } 713 } 714 715 // Check if we have a class template. 716 if (const ClassTemplateSpecializationDecl *Spec = 717 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 718 TemplateArgs = &Spec->getTemplateArgs(); 719 return Spec->getSpecializedTemplate(); 720 } 721 722 // Check if we have a variable template. 723 if (const VarTemplateSpecializationDecl *Spec = 724 dyn_cast<VarTemplateSpecializationDecl>(ND)) { 725 TemplateArgs = &Spec->getTemplateArgs(); 726 return Spec->getSpecializedTemplate(); 727 } 728 729 return nullptr; 730 } 731 732 void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND, 733 DeclarationName Name) { 734 // <unqualified-name> ::= <operator-name> 735 // ::= <ctor-dtor-name> 736 // ::= <source-name> 737 // ::= <template-name> 738 739 // Check if we have a template. 740 const TemplateArgumentList *TemplateArgs = nullptr; 741 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { 742 // Function templates aren't considered for name back referencing. This 743 // makes sense since function templates aren't likely to occur multiple 744 // times in a symbol. 745 if (isa<FunctionTemplateDecl>(TD)) { 746 mangleTemplateInstantiationName(TD, *TemplateArgs); 747 Out << '@'; 748 return; 749 } 750 751 // Here comes the tricky thing: if we need to mangle something like 752 // void foo(A::X<Y>, B::X<Y>), 753 // the X<Y> part is aliased. However, if you need to mangle 754 // void foo(A::X<A::Y>, A::X<B::Y>), 755 // the A::X<> part is not aliased. 756 // That said, from the mangler's perspective we have a structure like this: 757 // namespace[s] -> type[ -> template-parameters] 758 // but from the Clang perspective we have 759 // type [ -> template-parameters] 760 // \-> namespace[s] 761 // What we do is we create a new mangler, mangle the same type (without 762 // a namespace suffix) to a string using the extra mangler and then use 763 // the mangled type name as a key to check the mangling of different types 764 // for aliasing. 765 766 llvm::SmallString<64> TemplateMangling; 767 llvm::raw_svector_ostream Stream(TemplateMangling); 768 MicrosoftCXXNameMangler Extra(Context, Stream); 769 Extra.mangleTemplateInstantiationName(TD, *TemplateArgs); 770 771 mangleSourceName(TemplateMangling); 772 return; 773 } 774 775 switch (Name.getNameKind()) { 776 case DeclarationName::Identifier: { 777 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) { 778 mangleSourceName(II->getName()); 779 break; 780 } 781 782 // Otherwise, an anonymous entity. We must have a declaration. 783 assert(ND && "mangling empty name without declaration"); 784 785 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 786 if (NS->isAnonymousNamespace()) { 787 Out << "?A@"; 788 break; 789 } 790 } 791 792 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(ND)) { 793 // FIXME: Invented mangling for decomposition declarations: 794 // [X,Y,Z] 795 // where X,Y,Z are the names of the bindings. 796 llvm::SmallString<128> Name("["); 797 for (auto *BD : DD->bindings()) { 798 if (Name.size() > 1) 799 Name += ','; 800 Name += BD->getDeclName().getAsIdentifierInfo()->getName(); 801 } 802 Name += ']'; 803 mangleSourceName(Name); 804 break; 805 } 806 807 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { 808 // We must have an anonymous union or struct declaration. 809 const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl(); 810 assert(RD && "expected variable decl to have a record type"); 811 // Anonymous types with no tag or typedef get the name of their 812 // declarator mangled in. If they have no declarator, number them with 813 // a $S prefix. 814 llvm::SmallString<64> Name("$S"); 815 // Get a unique id for the anonymous struct. 816 Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1); 817 mangleSourceName(Name.str()); 818 break; 819 } 820 821 // We must have an anonymous struct. 822 const TagDecl *TD = cast<TagDecl>(ND); 823 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) { 824 assert(TD->getDeclContext() == D->getDeclContext() && 825 "Typedef should not be in another decl context!"); 826 assert(D->getDeclName().getAsIdentifierInfo() && 827 "Typedef was not named!"); 828 mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName()); 829 break; 830 } 831 832 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) { 833 if (Record->isLambda()) { 834 llvm::SmallString<10> Name("<lambda_"); 835 836 Decl *LambdaContextDecl = Record->getLambdaContextDecl(); 837 unsigned LambdaManglingNumber = Record->getLambdaManglingNumber(); 838 unsigned LambdaId; 839 const ParmVarDecl *Parm = 840 dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl); 841 const FunctionDecl *Func = 842 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr; 843 844 if (Func) { 845 unsigned DefaultArgNo = 846 Func->getNumParams() - Parm->getFunctionScopeIndex(); 847 Name += llvm::utostr(DefaultArgNo); 848 Name += "_"; 849 } 850 851 if (LambdaManglingNumber) 852 LambdaId = LambdaManglingNumber; 853 else 854 LambdaId = Context.getLambdaId(Record); 855 856 Name += llvm::utostr(LambdaId); 857 Name += ">"; 858 859 mangleSourceName(Name); 860 861 // If the context of a closure type is an initializer for a class 862 // member (static or nonstatic), it is encoded in a qualified name. 863 if (LambdaManglingNumber && LambdaContextDecl) { 864 if ((isa<VarDecl>(LambdaContextDecl) || 865 isa<FieldDecl>(LambdaContextDecl)) && 866 LambdaContextDecl->getDeclContext()->isRecord()) { 867 mangleUnqualifiedName(cast<NamedDecl>(LambdaContextDecl)); 868 } 869 } 870 break; 871 } 872 } 873 874 llvm::SmallString<64> Name; 875 if (DeclaratorDecl *DD = 876 Context.getASTContext().getDeclaratorForUnnamedTagDecl(TD)) { 877 // Anonymous types without a name for linkage purposes have their 878 // declarator mangled in if they have one. 879 Name += "<unnamed-type-"; 880 Name += DD->getName(); 881 } else if (TypedefNameDecl *TND = 882 Context.getASTContext().getTypedefNameForUnnamedTagDecl( 883 TD)) { 884 // Anonymous types without a name for linkage purposes have their 885 // associate typedef mangled in if they have one. 886 Name += "<unnamed-type-"; 887 Name += TND->getName(); 888 } else if (auto *ED = dyn_cast<EnumDecl>(TD)) { 889 auto EnumeratorI = ED->enumerator_begin(); 890 assert(EnumeratorI != ED->enumerator_end()); 891 Name += "<unnamed-enum-"; 892 Name += EnumeratorI->getName(); 893 } else { 894 // Otherwise, number the types using a $S prefix. 895 Name += "<unnamed-type-$S"; 896 Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1); 897 } 898 Name += ">"; 899 mangleSourceName(Name.str()); 900 break; 901 } 902 903 case DeclarationName::ObjCZeroArgSelector: 904 case DeclarationName::ObjCOneArgSelector: 905 case DeclarationName::ObjCMultiArgSelector: 906 llvm_unreachable("Can't mangle Objective-C selector names here!"); 907 908 case DeclarationName::CXXConstructorName: 909 if (isStructorDecl(ND)) { 910 if (StructorType == Ctor_CopyingClosure) { 911 Out << "?_O"; 912 return; 913 } 914 if (StructorType == Ctor_DefaultClosure) { 915 Out << "?_F"; 916 return; 917 } 918 } 919 Out << "?0"; 920 return; 921 922 case DeclarationName::CXXDestructorName: 923 if (isStructorDecl(ND)) 924 // If the named decl is the C++ destructor we're mangling, 925 // use the type we were given. 926 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType)); 927 else 928 // Otherwise, use the base destructor name. This is relevant if a 929 // class with a destructor is declared within a destructor. 930 mangleCXXDtorType(Dtor_Base); 931 break; 932 933 case DeclarationName::CXXConversionFunctionName: 934 // <operator-name> ::= ?B # (cast) 935 // The target type is encoded as the return type. 936 Out << "?B"; 937 break; 938 939 case DeclarationName::CXXOperatorName: 940 mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation()); 941 break; 942 943 case DeclarationName::CXXLiteralOperatorName: { 944 Out << "?__K"; 945 mangleSourceName(Name.getCXXLiteralIdentifier()->getName()); 946 break; 947 } 948 949 case DeclarationName::CXXDeductionGuideName: 950 llvm_unreachable("Can't mangle a deduction guide name!"); 951 952 case DeclarationName::CXXUsingDirective: 953 llvm_unreachable("Can't mangle a using directive name!"); 954 } 955 } 956 957 // <postfix> ::= <unqualified-name> [<postfix>] 958 // ::= <substitution> [<postfix>] 959 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) { 960 const DeclContext *DC = getEffectiveDeclContext(ND); 961 while (!DC->isTranslationUnit()) { 962 if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) { 963 unsigned Disc; 964 if (Context.getNextDiscriminator(ND, Disc)) { 965 Out << '?'; 966 mangleNumber(Disc); 967 Out << '?'; 968 } 969 } 970 971 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) { 972 auto Discriminate = 973 [](StringRef Name, const unsigned Discriminator, 974 const unsigned ParameterDiscriminator) -> std::string { 975 std::string Buffer; 976 llvm::raw_string_ostream Stream(Buffer); 977 Stream << Name; 978 if (Discriminator) 979 Stream << '_' << Discriminator; 980 if (ParameterDiscriminator) 981 Stream << '_' << ParameterDiscriminator; 982 return Stream.str(); 983 }; 984 985 unsigned Discriminator = BD->getBlockManglingNumber(); 986 if (!Discriminator) 987 Discriminator = Context.getBlockId(BD, /*Local=*/false); 988 989 // Mangle the parameter position as a discriminator to deal with unnamed 990 // parameters. Rather than mangling the unqualified parameter name, 991 // always use the position to give a uniform mangling. 992 unsigned ParameterDiscriminator = 0; 993 if (const auto *MC = BD->getBlockManglingContextDecl()) 994 if (const auto *P = dyn_cast<ParmVarDecl>(MC)) 995 if (const auto *F = dyn_cast<FunctionDecl>(P->getDeclContext())) 996 ParameterDiscriminator = 997 F->getNumParams() - P->getFunctionScopeIndex(); 998 999 DC = getEffectiveDeclContext(BD); 1000 1001 Out << '?'; 1002 mangleSourceName(Discriminate("_block_invoke", Discriminator, 1003 ParameterDiscriminator)); 1004 // If we have a block mangling context, encode that now. This allows us 1005 // to discriminate between named static data initializers in the same 1006 // scope. This is handled differently from parameters, which use 1007 // positions to discriminate between multiple instances. 1008 if (const auto *MC = BD->getBlockManglingContextDecl()) 1009 if (!isa<ParmVarDecl>(MC)) 1010 if (const auto *ND = dyn_cast<NamedDecl>(MC)) 1011 mangleUnqualifiedName(ND); 1012 // MS ABI and Itanium manglings are in inverted scopes. In the case of a 1013 // RecordDecl, mangle the entire scope hierachy at this point rather than 1014 // just the unqualified name to get the ordering correct. 1015 if (const auto *RD = dyn_cast<RecordDecl>(DC)) 1016 mangleName(RD); 1017 else 1018 Out << '@'; 1019 // void __cdecl 1020 Out << "YAX"; 1021 // struct __block_literal * 1022 Out << 'P'; 1023 // __ptr64 1024 if (PointersAre64Bit) 1025 Out << 'E'; 1026 Out << 'A'; 1027 mangleArtificalTagType(TTK_Struct, 1028 Discriminate("__block_literal", Discriminator, 1029 ParameterDiscriminator)); 1030 Out << "@Z"; 1031 1032 // If the effective context was a Record, we have fully mangled the 1033 // qualified name and do not need to continue. 1034 if (isa<RecordDecl>(DC)) 1035 break; 1036 continue; 1037 } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) { 1038 mangleObjCMethodName(Method); 1039 } else if (isa<NamedDecl>(DC)) { 1040 ND = cast<NamedDecl>(DC); 1041 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 1042 mangle(FD, "?"); 1043 break; 1044 } else { 1045 mangleUnqualifiedName(ND); 1046 // Lambdas in default arguments conceptually belong to the function the 1047 // parameter corresponds to. 1048 if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(ND)) { 1049 DC = LDADC; 1050 continue; 1051 } 1052 } 1053 } 1054 DC = DC->getParent(); 1055 } 1056 } 1057 1058 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) { 1059 // Microsoft uses the names on the case labels for these dtor variants. Clang 1060 // uses the Itanium terminology internally. Everything in this ABI delegates 1061 // towards the base dtor. 1062 switch (T) { 1063 // <operator-name> ::= ?1 # destructor 1064 case Dtor_Base: Out << "?1"; return; 1065 // <operator-name> ::= ?_D # vbase destructor 1066 case Dtor_Complete: Out << "?_D"; return; 1067 // <operator-name> ::= ?_G # scalar deleting destructor 1068 case Dtor_Deleting: Out << "?_G"; return; 1069 // <operator-name> ::= ?_E # vector deleting destructor 1070 // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need 1071 // it. 1072 case Dtor_Comdat: 1073 llvm_unreachable("not expecting a COMDAT"); 1074 } 1075 llvm_unreachable("Unsupported dtor type?"); 1076 } 1077 1078 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, 1079 SourceLocation Loc) { 1080 switch (OO) { 1081 // ?0 # constructor 1082 // ?1 # destructor 1083 // <operator-name> ::= ?2 # new 1084 case OO_New: Out << "?2"; break; 1085 // <operator-name> ::= ?3 # delete 1086 case OO_Delete: Out << "?3"; break; 1087 // <operator-name> ::= ?4 # = 1088 case OO_Equal: Out << "?4"; break; 1089 // <operator-name> ::= ?5 # >> 1090 case OO_GreaterGreater: Out << "?5"; break; 1091 // <operator-name> ::= ?6 # << 1092 case OO_LessLess: Out << "?6"; break; 1093 // <operator-name> ::= ?7 # ! 1094 case OO_Exclaim: Out << "?7"; break; 1095 // <operator-name> ::= ?8 # == 1096 case OO_EqualEqual: Out << "?8"; break; 1097 // <operator-name> ::= ?9 # != 1098 case OO_ExclaimEqual: Out << "?9"; break; 1099 // <operator-name> ::= ?A # [] 1100 case OO_Subscript: Out << "?A"; break; 1101 // ?B # conversion 1102 // <operator-name> ::= ?C # -> 1103 case OO_Arrow: Out << "?C"; break; 1104 // <operator-name> ::= ?D # * 1105 case OO_Star: Out << "?D"; break; 1106 // <operator-name> ::= ?E # ++ 1107 case OO_PlusPlus: Out << "?E"; break; 1108 // <operator-name> ::= ?F # -- 1109 case OO_MinusMinus: Out << "?F"; break; 1110 // <operator-name> ::= ?G # - 1111 case OO_Minus: Out << "?G"; break; 1112 // <operator-name> ::= ?H # + 1113 case OO_Plus: Out << "?H"; break; 1114 // <operator-name> ::= ?I # & 1115 case OO_Amp: Out << "?I"; break; 1116 // <operator-name> ::= ?J # ->* 1117 case OO_ArrowStar: Out << "?J"; break; 1118 // <operator-name> ::= ?K # / 1119 case OO_Slash: Out << "?K"; break; 1120 // <operator-name> ::= ?L # % 1121 case OO_Percent: Out << "?L"; break; 1122 // <operator-name> ::= ?M # < 1123 case OO_Less: Out << "?M"; break; 1124 // <operator-name> ::= ?N # <= 1125 case OO_LessEqual: Out << "?N"; break; 1126 // <operator-name> ::= ?O # > 1127 case OO_Greater: Out << "?O"; break; 1128 // <operator-name> ::= ?P # >= 1129 case OO_GreaterEqual: Out << "?P"; break; 1130 // <operator-name> ::= ?Q # , 1131 case OO_Comma: Out << "?Q"; break; 1132 // <operator-name> ::= ?R # () 1133 case OO_Call: Out << "?R"; break; 1134 // <operator-name> ::= ?S # ~ 1135 case OO_Tilde: Out << "?S"; break; 1136 // <operator-name> ::= ?T # ^ 1137 case OO_Caret: Out << "?T"; break; 1138 // <operator-name> ::= ?U # | 1139 case OO_Pipe: Out << "?U"; break; 1140 // <operator-name> ::= ?V # && 1141 case OO_AmpAmp: Out << "?V"; break; 1142 // <operator-name> ::= ?W # || 1143 case OO_PipePipe: Out << "?W"; break; 1144 // <operator-name> ::= ?X # *= 1145 case OO_StarEqual: Out << "?X"; break; 1146 // <operator-name> ::= ?Y # += 1147 case OO_PlusEqual: Out << "?Y"; break; 1148 // <operator-name> ::= ?Z # -= 1149 case OO_MinusEqual: Out << "?Z"; break; 1150 // <operator-name> ::= ?_0 # /= 1151 case OO_SlashEqual: Out << "?_0"; break; 1152 // <operator-name> ::= ?_1 # %= 1153 case OO_PercentEqual: Out << "?_1"; break; 1154 // <operator-name> ::= ?_2 # >>= 1155 case OO_GreaterGreaterEqual: Out << "?_2"; break; 1156 // <operator-name> ::= ?_3 # <<= 1157 case OO_LessLessEqual: Out << "?_3"; break; 1158 // <operator-name> ::= ?_4 # &= 1159 case OO_AmpEqual: Out << "?_4"; break; 1160 // <operator-name> ::= ?_5 # |= 1161 case OO_PipeEqual: Out << "?_5"; break; 1162 // <operator-name> ::= ?_6 # ^= 1163 case OO_CaretEqual: Out << "?_6"; break; 1164 // ?_7 # vftable 1165 // ?_8 # vbtable 1166 // ?_9 # vcall 1167 // ?_A # typeof 1168 // ?_B # local static guard 1169 // ?_C # string 1170 // ?_D # vbase destructor 1171 // ?_E # vector deleting destructor 1172 // ?_F # default constructor closure 1173 // ?_G # scalar deleting destructor 1174 // ?_H # vector constructor iterator 1175 // ?_I # vector destructor iterator 1176 // ?_J # vector vbase constructor iterator 1177 // ?_K # virtual displacement map 1178 // ?_L # eh vector constructor iterator 1179 // ?_M # eh vector destructor iterator 1180 // ?_N # eh vector vbase constructor iterator 1181 // ?_O # copy constructor closure 1182 // ?_P<name> # udt returning <name> 1183 // ?_Q # <unknown> 1184 // ?_R0 # RTTI Type Descriptor 1185 // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d) 1186 // ?_R2 # RTTI Base Class Array 1187 // ?_R3 # RTTI Class Hierarchy Descriptor 1188 // ?_R4 # RTTI Complete Object Locator 1189 // ?_S # local vftable 1190 // ?_T # local vftable constructor closure 1191 // <operator-name> ::= ?_U # new[] 1192 case OO_Array_New: Out << "?_U"; break; 1193 // <operator-name> ::= ?_V # delete[] 1194 case OO_Array_Delete: Out << "?_V"; break; 1195 // <operator-name> ::= ?__L # co_await 1196 case OO_Coawait: Out << "?__L"; break; 1197 1198 case OO_Spaceship: { 1199 // FIXME: Once MS picks a mangling, use it. 1200 DiagnosticsEngine &Diags = Context.getDiags(); 1201 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1202 "cannot mangle this three-way comparison operator yet"); 1203 Diags.Report(Loc, DiagID); 1204 break; 1205 } 1206 1207 case OO_Conditional: { 1208 DiagnosticsEngine &Diags = Context.getDiags(); 1209 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1210 "cannot mangle this conditional operator yet"); 1211 Diags.Report(Loc, DiagID); 1212 break; 1213 } 1214 1215 case OO_None: 1216 case NUM_OVERLOADED_OPERATORS: 1217 llvm_unreachable("Not an overloaded operator"); 1218 } 1219 } 1220 1221 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) { 1222 // <source name> ::= <identifier> @ 1223 BackRefVec::iterator Found = 1224 std::find(NameBackReferences.begin(), NameBackReferences.end(), Name); 1225 if (Found == NameBackReferences.end()) { 1226 if (NameBackReferences.size() < 10) 1227 NameBackReferences.push_back(Name); 1228 Out << Name << '@'; 1229 } else { 1230 Out << (Found - NameBackReferences.begin()); 1231 } 1232 } 1233 1234 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) { 1235 Context.mangleObjCMethodName(MD, Out); 1236 } 1237 1238 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName( 1239 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) { 1240 // <template-name> ::= <unscoped-template-name> <template-args> 1241 // ::= <substitution> 1242 // Always start with the unqualified name. 1243 1244 // Templates have their own context for back references. 1245 ArgBackRefMap OuterArgsContext; 1246 BackRefVec OuterTemplateContext; 1247 PassObjectSizeArgsSet OuterPassObjectSizeArgs; 1248 NameBackReferences.swap(OuterTemplateContext); 1249 TypeBackReferences.swap(OuterArgsContext); 1250 PassObjectSizeArgs.swap(OuterPassObjectSizeArgs); 1251 1252 mangleUnscopedTemplateName(TD); 1253 mangleTemplateArgs(TD, TemplateArgs); 1254 1255 // Restore the previous back reference contexts. 1256 NameBackReferences.swap(OuterTemplateContext); 1257 TypeBackReferences.swap(OuterArgsContext); 1258 PassObjectSizeArgs.swap(OuterPassObjectSizeArgs); 1259 } 1260 1261 void 1262 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) { 1263 // <unscoped-template-name> ::= ?$ <unqualified-name> 1264 Out << "?$"; 1265 mangleUnqualifiedName(TD); 1266 } 1267 1268 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value, 1269 bool IsBoolean) { 1270 // <integer-literal> ::= $0 <number> 1271 Out << "$0"; 1272 // Make sure booleans are encoded as 0/1. 1273 if (IsBoolean && Value.getBoolValue()) 1274 mangleNumber(1); 1275 else if (Value.isSigned()) 1276 mangleNumber(Value.getSExtValue()); 1277 else 1278 mangleNumber(Value.getZExtValue()); 1279 } 1280 1281 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) { 1282 // See if this is a constant expression. 1283 llvm::APSInt Value; 1284 if (E->isIntegerConstantExpr(Value, Context.getASTContext())) { 1285 mangleIntegerLiteral(Value, E->getType()->isBooleanType()); 1286 return; 1287 } 1288 1289 // Look through no-op casts like template parameter substitutions. 1290 E = E->IgnoreParenNoopCasts(Context.getASTContext()); 1291 1292 const CXXUuidofExpr *UE = nullptr; 1293 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 1294 if (UO->getOpcode() == UO_AddrOf) 1295 UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr()); 1296 } else 1297 UE = dyn_cast<CXXUuidofExpr>(E); 1298 1299 if (UE) { 1300 // If we had to peek through an address-of operator, treat this like we are 1301 // dealing with a pointer type. Otherwise, treat it like a const reference. 1302 // 1303 // N.B. This matches up with the handling of TemplateArgument::Declaration 1304 // in mangleTemplateArg 1305 if (UE == E) 1306 Out << "$E?"; 1307 else 1308 Out << "$1?"; 1309 1310 // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from 1311 // const __s_GUID _GUID_{lower case UUID with underscores} 1312 StringRef Uuid = UE->getUuidStr(); 1313 std::string Name = "_GUID_" + Uuid.lower(); 1314 std::replace(Name.begin(), Name.end(), '-', '_'); 1315 1316 mangleSourceName(Name); 1317 // Terminate the whole name with an '@'. 1318 Out << '@'; 1319 // It's a global variable. 1320 Out << '3'; 1321 // It's a struct called __s_GUID. 1322 mangleArtificalTagType(TTK_Struct, "__s_GUID"); 1323 // It's const. 1324 Out << 'B'; 1325 return; 1326 } 1327 1328 // As bad as this diagnostic is, it's better than crashing. 1329 DiagnosticsEngine &Diags = Context.getDiags(); 1330 unsigned DiagID = Diags.getCustomDiagID( 1331 DiagnosticsEngine::Error, "cannot yet mangle expression type %0"); 1332 Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName() 1333 << E->getSourceRange(); 1334 } 1335 1336 void MicrosoftCXXNameMangler::mangleTemplateArgs( 1337 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) { 1338 // <template-args> ::= <template-arg>+ 1339 const TemplateParameterList *TPL = TD->getTemplateParameters(); 1340 assert(TPL->size() == TemplateArgs.size() && 1341 "size mismatch between args and parms!"); 1342 1343 unsigned Idx = 0; 1344 for (const TemplateArgument &TA : TemplateArgs.asArray()) 1345 mangleTemplateArg(TD, TA, TPL->getParam(Idx++)); 1346 } 1347 1348 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD, 1349 const TemplateArgument &TA, 1350 const NamedDecl *Parm) { 1351 // <template-arg> ::= <type> 1352 // ::= <integer-literal> 1353 // ::= <member-data-pointer> 1354 // ::= <member-function-pointer> 1355 // ::= $E? <name> <type-encoding> 1356 // ::= $1? <name> <type-encoding> 1357 // ::= $0A@ 1358 // ::= <template-args> 1359 1360 switch (TA.getKind()) { 1361 case TemplateArgument::Null: 1362 llvm_unreachable("Can't mangle null template arguments!"); 1363 case TemplateArgument::TemplateExpansion: 1364 llvm_unreachable("Can't mangle template expansion arguments!"); 1365 case TemplateArgument::Type: { 1366 QualType T = TA.getAsType(); 1367 mangleType(T, SourceRange(), QMM_Escape); 1368 break; 1369 } 1370 case TemplateArgument::Declaration: { 1371 const NamedDecl *ND = TA.getAsDecl(); 1372 if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) { 1373 mangleMemberDataPointer( 1374 cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(), 1375 cast<ValueDecl>(ND)); 1376 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 1377 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 1378 if (MD && MD->isInstance()) { 1379 mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD); 1380 } else { 1381 Out << "$1?"; 1382 mangleName(FD); 1383 mangleFunctionEncoding(FD, /*ShouldMangle=*/true); 1384 } 1385 } else { 1386 mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?"); 1387 } 1388 break; 1389 } 1390 case TemplateArgument::Integral: 1391 mangleIntegerLiteral(TA.getAsIntegral(), 1392 TA.getIntegralType()->isBooleanType()); 1393 break; 1394 case TemplateArgument::NullPtr: { 1395 QualType T = TA.getNullPtrType(); 1396 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) { 1397 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1398 if (MPT->isMemberFunctionPointerType() && 1399 !isa<FunctionTemplateDecl>(TD)) { 1400 mangleMemberFunctionPointer(RD, nullptr); 1401 return; 1402 } 1403 if (MPT->isMemberDataPointer()) { 1404 if (!isa<FunctionTemplateDecl>(TD)) { 1405 mangleMemberDataPointer(RD, nullptr); 1406 return; 1407 } 1408 // nullptr data pointers are always represented with a single field 1409 // which is initialized with either 0 or -1. Why -1? Well, we need to 1410 // distinguish the case where the data member is at offset zero in the 1411 // record. 1412 // However, we are free to use 0 *if* we would use multiple fields for 1413 // non-nullptr member pointers. 1414 if (!RD->nullFieldOffsetIsZero()) { 1415 mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false); 1416 return; 1417 } 1418 } 1419 } 1420 mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false); 1421 break; 1422 } 1423 case TemplateArgument::Expression: 1424 mangleExpression(TA.getAsExpr()); 1425 break; 1426 case TemplateArgument::Pack: { 1427 ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray(); 1428 if (TemplateArgs.empty()) { 1429 if (isa<TemplateTypeParmDecl>(Parm) || 1430 isa<TemplateTemplateParmDecl>(Parm)) 1431 // MSVC 2015 changed the mangling for empty expanded template packs, 1432 // use the old mangling for link compatibility for old versions. 1433 Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC( 1434 LangOptions::MSVC2015) 1435 ? "$$V" 1436 : "$$$V"); 1437 else if (isa<NonTypeTemplateParmDecl>(Parm)) 1438 Out << "$S"; 1439 else 1440 llvm_unreachable("unexpected template parameter decl!"); 1441 } else { 1442 for (const TemplateArgument &PA : TemplateArgs) 1443 mangleTemplateArg(TD, PA, Parm); 1444 } 1445 break; 1446 } 1447 case TemplateArgument::Template: { 1448 const NamedDecl *ND = 1449 TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl(); 1450 if (const auto *TD = dyn_cast<TagDecl>(ND)) { 1451 mangleType(TD); 1452 } else if (isa<TypeAliasDecl>(ND)) { 1453 Out << "$$Y"; 1454 mangleName(ND); 1455 } else { 1456 llvm_unreachable("unexpected template template NamedDecl!"); 1457 } 1458 break; 1459 } 1460 } 1461 } 1462 1463 void MicrosoftCXXNameMangler::mangleObjCProtocol(const ObjCProtocolDecl *PD) { 1464 llvm::SmallString<64> TemplateMangling; 1465 llvm::raw_svector_ostream Stream(TemplateMangling); 1466 MicrosoftCXXNameMangler Extra(Context, Stream); 1467 1468 Stream << "?$"; 1469 Extra.mangleSourceName("Protocol"); 1470 Extra.mangleArtificalTagType(TTK_Struct, PD->getName()); 1471 1472 mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__ObjC"}); 1473 } 1474 1475 void MicrosoftCXXNameMangler::mangleObjCLifetime(const QualType Type, 1476 Qualifiers Quals, 1477 SourceRange Range) { 1478 llvm::SmallString<64> TemplateMangling; 1479 llvm::raw_svector_ostream Stream(TemplateMangling); 1480 MicrosoftCXXNameMangler Extra(Context, Stream); 1481 1482 Stream << "?$"; 1483 switch (Quals.getObjCLifetime()) { 1484 case Qualifiers::OCL_None: 1485 case Qualifiers::OCL_ExplicitNone: 1486 break; 1487 case Qualifiers::OCL_Autoreleasing: 1488 Extra.mangleSourceName("Autoreleasing"); 1489 break; 1490 case Qualifiers::OCL_Strong: 1491 Extra.mangleSourceName("Strong"); 1492 break; 1493 case Qualifiers::OCL_Weak: 1494 Extra.mangleSourceName("Weak"); 1495 break; 1496 } 1497 Extra.manglePointerCVQualifiers(Quals); 1498 Extra.manglePointerExtQualifiers(Quals, Type); 1499 Extra.mangleType(Type, Range); 1500 1501 mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__ObjC"}); 1502 } 1503 1504 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals, 1505 bool IsMember) { 1506 // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers> 1507 // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only); 1508 // 'I' means __restrict (32/64-bit). 1509 // Note that the MSVC __restrict keyword isn't the same as the C99 restrict 1510 // keyword! 1511 // <base-cvr-qualifiers> ::= A # near 1512 // ::= B # near const 1513 // ::= C # near volatile 1514 // ::= D # near const volatile 1515 // ::= E # far (16-bit) 1516 // ::= F # far const (16-bit) 1517 // ::= G # far volatile (16-bit) 1518 // ::= H # far const volatile (16-bit) 1519 // ::= I # huge (16-bit) 1520 // ::= J # huge const (16-bit) 1521 // ::= K # huge volatile (16-bit) 1522 // ::= L # huge const volatile (16-bit) 1523 // ::= M <basis> # based 1524 // ::= N <basis> # based const 1525 // ::= O <basis> # based volatile 1526 // ::= P <basis> # based const volatile 1527 // ::= Q # near member 1528 // ::= R # near const member 1529 // ::= S # near volatile member 1530 // ::= T # near const volatile member 1531 // ::= U # far member (16-bit) 1532 // ::= V # far const member (16-bit) 1533 // ::= W # far volatile member (16-bit) 1534 // ::= X # far const volatile member (16-bit) 1535 // ::= Y # huge member (16-bit) 1536 // ::= Z # huge const member (16-bit) 1537 // ::= 0 # huge volatile member (16-bit) 1538 // ::= 1 # huge const volatile member (16-bit) 1539 // ::= 2 <basis> # based member 1540 // ::= 3 <basis> # based const member 1541 // ::= 4 <basis> # based volatile member 1542 // ::= 5 <basis> # based const volatile member 1543 // ::= 6 # near function (pointers only) 1544 // ::= 7 # far function (pointers only) 1545 // ::= 8 # near method (pointers only) 1546 // ::= 9 # far method (pointers only) 1547 // ::= _A <basis> # based function (pointers only) 1548 // ::= _B <basis> # based function (far?) (pointers only) 1549 // ::= _C <basis> # based method (pointers only) 1550 // ::= _D <basis> # based method (far?) (pointers only) 1551 // ::= _E # block (Clang) 1552 // <basis> ::= 0 # __based(void) 1553 // ::= 1 # __based(segment)? 1554 // ::= 2 <name> # __based(name) 1555 // ::= 3 # ? 1556 // ::= 4 # ? 1557 // ::= 5 # not really based 1558 bool HasConst = Quals.hasConst(), 1559 HasVolatile = Quals.hasVolatile(); 1560 1561 if (!IsMember) { 1562 if (HasConst && HasVolatile) { 1563 Out << 'D'; 1564 } else if (HasVolatile) { 1565 Out << 'C'; 1566 } else if (HasConst) { 1567 Out << 'B'; 1568 } else { 1569 Out << 'A'; 1570 } 1571 } else { 1572 if (HasConst && HasVolatile) { 1573 Out << 'T'; 1574 } else if (HasVolatile) { 1575 Out << 'S'; 1576 } else if (HasConst) { 1577 Out << 'R'; 1578 } else { 1579 Out << 'Q'; 1580 } 1581 } 1582 1583 // FIXME: For now, just drop all extension qualifiers on the floor. 1584 } 1585 1586 void 1587 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) { 1588 // <ref-qualifier> ::= G # lvalue reference 1589 // ::= H # rvalue-reference 1590 switch (RefQualifier) { 1591 case RQ_None: 1592 break; 1593 1594 case RQ_LValue: 1595 Out << 'G'; 1596 break; 1597 1598 case RQ_RValue: 1599 Out << 'H'; 1600 break; 1601 } 1602 } 1603 1604 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals, 1605 QualType PointeeType) { 1606 if (PointersAre64Bit && 1607 (PointeeType.isNull() || !PointeeType->isFunctionType())) 1608 Out << 'E'; 1609 1610 if (Quals.hasRestrict()) 1611 Out << 'I'; 1612 1613 if (Quals.hasUnaligned() || 1614 (!PointeeType.isNull() && PointeeType.getLocalQualifiers().hasUnaligned())) 1615 Out << 'F'; 1616 } 1617 1618 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) { 1619 // <pointer-cv-qualifiers> ::= P # no qualifiers 1620 // ::= Q # const 1621 // ::= R # volatile 1622 // ::= S # const volatile 1623 bool HasConst = Quals.hasConst(), 1624 HasVolatile = Quals.hasVolatile(); 1625 1626 if (HasConst && HasVolatile) { 1627 Out << 'S'; 1628 } else if (HasVolatile) { 1629 Out << 'R'; 1630 } else if (HasConst) { 1631 Out << 'Q'; 1632 } else { 1633 Out << 'P'; 1634 } 1635 } 1636 1637 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T, 1638 SourceRange Range) { 1639 // MSVC will backreference two canonically equivalent types that have slightly 1640 // different manglings when mangled alone. 1641 1642 // Decayed types do not match up with non-decayed versions of the same type. 1643 // 1644 // e.g. 1645 // void (*x)(void) will not form a backreference with void x(void) 1646 void *TypePtr; 1647 if (const auto *DT = T->getAs<DecayedType>()) { 1648 QualType OriginalType = DT->getOriginalType(); 1649 // All decayed ArrayTypes should be treated identically; as-if they were 1650 // a decayed IncompleteArrayType. 1651 if (const auto *AT = getASTContext().getAsArrayType(OriginalType)) 1652 OriginalType = getASTContext().getIncompleteArrayType( 1653 AT->getElementType(), AT->getSizeModifier(), 1654 AT->getIndexTypeCVRQualifiers()); 1655 1656 TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr(); 1657 // If the original parameter was textually written as an array, 1658 // instead treat the decayed parameter like it's const. 1659 // 1660 // e.g. 1661 // int [] -> int * const 1662 if (OriginalType->isArrayType()) 1663 T = T.withConst(); 1664 } else { 1665 TypePtr = T.getCanonicalType().getAsOpaquePtr(); 1666 } 1667 1668 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr); 1669 1670 if (Found == TypeBackReferences.end()) { 1671 size_t OutSizeBefore = Out.tell(); 1672 1673 mangleType(T, Range, QMM_Drop); 1674 1675 // See if it's worth creating a back reference. 1676 // Only types longer than 1 character are considered 1677 // and only 10 back references slots are available: 1678 bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1); 1679 if (LongerThanOneChar && TypeBackReferences.size() < 10) { 1680 size_t Size = TypeBackReferences.size(); 1681 TypeBackReferences[TypePtr] = Size; 1682 } 1683 } else { 1684 Out << Found->second; 1685 } 1686 } 1687 1688 void MicrosoftCXXNameMangler::manglePassObjectSizeArg( 1689 const PassObjectSizeAttr *POSA) { 1690 int Type = POSA->getType(); 1691 1692 auto Iter = PassObjectSizeArgs.insert(Type).first; 1693 auto *TypePtr = (const void *)&*Iter; 1694 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr); 1695 1696 if (Found == TypeBackReferences.end()) { 1697 mangleArtificalTagType(TTK_Enum, "__pass_object_size" + llvm::utostr(Type), 1698 {"__clang"}); 1699 1700 if (TypeBackReferences.size() < 10) { 1701 size_t Size = TypeBackReferences.size(); 1702 TypeBackReferences[TypePtr] = Size; 1703 } 1704 } else { 1705 Out << Found->second; 1706 } 1707 } 1708 1709 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range, 1710 QualifierMangleMode QMM) { 1711 // Don't use the canonical types. MSVC includes things like 'const' on 1712 // pointer arguments to function pointers that canonicalization strips away. 1713 T = T.getDesugaredType(getASTContext()); 1714 Qualifiers Quals = T.getLocalQualifiers(); 1715 if (const ArrayType *AT = getASTContext().getAsArrayType(T)) { 1716 // If there were any Quals, getAsArrayType() pushed them onto the array 1717 // element type. 1718 if (QMM == QMM_Mangle) 1719 Out << 'A'; 1720 else if (QMM == QMM_Escape || QMM == QMM_Result) 1721 Out << "$$B"; 1722 mangleArrayType(AT); 1723 return; 1724 } 1725 1726 bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() || 1727 T->isReferenceType() || T->isBlockPointerType(); 1728 1729 switch (QMM) { 1730 case QMM_Drop: 1731 if (Quals.hasObjCLifetime()) 1732 Quals = Quals.withoutObjCLifetime(); 1733 break; 1734 case QMM_Mangle: 1735 if (const FunctionType *FT = dyn_cast<FunctionType>(T)) { 1736 Out << '6'; 1737 mangleFunctionType(FT); 1738 return; 1739 } 1740 mangleQualifiers(Quals, false); 1741 break; 1742 case QMM_Escape: 1743 if (!IsPointer && Quals) { 1744 Out << "$$C"; 1745 mangleQualifiers(Quals, false); 1746 } 1747 break; 1748 case QMM_Result: 1749 // Presence of __unaligned qualifier shouldn't affect mangling here. 1750 Quals.removeUnaligned(); 1751 if (Quals.hasObjCLifetime()) 1752 Quals = Quals.withoutObjCLifetime(); 1753 if ((!IsPointer && Quals) || isa<TagType>(T)) { 1754 Out << '?'; 1755 mangleQualifiers(Quals, false); 1756 } 1757 break; 1758 } 1759 1760 const Type *ty = T.getTypePtr(); 1761 1762 switch (ty->getTypeClass()) { 1763 #define ABSTRACT_TYPE(CLASS, PARENT) 1764 #define NON_CANONICAL_TYPE(CLASS, PARENT) \ 1765 case Type::CLASS: \ 1766 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \ 1767 return; 1768 #define TYPE(CLASS, PARENT) \ 1769 case Type::CLASS: \ 1770 mangleType(cast<CLASS##Type>(ty), Quals, Range); \ 1771 break; 1772 #include "clang/AST/TypeNodes.def" 1773 #undef ABSTRACT_TYPE 1774 #undef NON_CANONICAL_TYPE 1775 #undef TYPE 1776 } 1777 } 1778 1779 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers, 1780 SourceRange Range) { 1781 // <type> ::= <builtin-type> 1782 // <builtin-type> ::= X # void 1783 // ::= C # signed char 1784 // ::= D # char 1785 // ::= E # unsigned char 1786 // ::= F # short 1787 // ::= G # unsigned short (or wchar_t if it's not a builtin) 1788 // ::= H # int 1789 // ::= I # unsigned int 1790 // ::= J # long 1791 // ::= K # unsigned long 1792 // L # <none> 1793 // ::= M # float 1794 // ::= N # double 1795 // ::= O # long double (__float80 is mangled differently) 1796 // ::= _J # long long, __int64 1797 // ::= _K # unsigned long long, __int64 1798 // ::= _L # __int128 1799 // ::= _M # unsigned __int128 1800 // ::= _N # bool 1801 // _O # <array in parameter> 1802 // ::= _T # __float80 (Intel) 1803 // ::= _S # char16_t 1804 // ::= _U # char32_t 1805 // ::= _W # wchar_t 1806 // ::= _Z # __float80 (Digital Mars) 1807 switch (T->getKind()) { 1808 case BuiltinType::Void: 1809 Out << 'X'; 1810 break; 1811 case BuiltinType::SChar: 1812 Out << 'C'; 1813 break; 1814 case BuiltinType::Char_U: 1815 case BuiltinType::Char_S: 1816 Out << 'D'; 1817 break; 1818 case BuiltinType::UChar: 1819 Out << 'E'; 1820 break; 1821 case BuiltinType::Short: 1822 Out << 'F'; 1823 break; 1824 case BuiltinType::UShort: 1825 Out << 'G'; 1826 break; 1827 case BuiltinType::Int: 1828 Out << 'H'; 1829 break; 1830 case BuiltinType::UInt: 1831 Out << 'I'; 1832 break; 1833 case BuiltinType::Long: 1834 Out << 'J'; 1835 break; 1836 case BuiltinType::ULong: 1837 Out << 'K'; 1838 break; 1839 case BuiltinType::Float: 1840 Out << 'M'; 1841 break; 1842 case BuiltinType::Double: 1843 Out << 'N'; 1844 break; 1845 // TODO: Determine size and mangle accordingly 1846 case BuiltinType::LongDouble: 1847 Out << 'O'; 1848 break; 1849 case BuiltinType::LongLong: 1850 Out << "_J"; 1851 break; 1852 case BuiltinType::ULongLong: 1853 Out << "_K"; 1854 break; 1855 case BuiltinType::Int128: 1856 Out << "_L"; 1857 break; 1858 case BuiltinType::UInt128: 1859 Out << "_M"; 1860 break; 1861 case BuiltinType::Bool: 1862 Out << "_N"; 1863 break; 1864 case BuiltinType::Char16: 1865 Out << "_S"; 1866 break; 1867 case BuiltinType::Char32: 1868 Out << "_U"; 1869 break; 1870 case BuiltinType::WChar_S: 1871 case BuiltinType::WChar_U: 1872 Out << "_W"; 1873 break; 1874 1875 #define BUILTIN_TYPE(Id, SingletonId) 1876 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 1877 case BuiltinType::Id: 1878 #include "clang/AST/BuiltinTypes.def" 1879 case BuiltinType::Dependent: 1880 llvm_unreachable("placeholder types shouldn't get to name mangling"); 1881 1882 case BuiltinType::ObjCId: 1883 mangleArtificalTagType(TTK_Struct, "objc_object"); 1884 break; 1885 case BuiltinType::ObjCClass: 1886 mangleArtificalTagType(TTK_Struct, "objc_class"); 1887 break; 1888 case BuiltinType::ObjCSel: 1889 mangleArtificalTagType(TTK_Struct, "objc_selector"); 1890 break; 1891 1892 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1893 case BuiltinType::Id: \ 1894 Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \ 1895 break; 1896 #include "clang/Basic/OpenCLImageTypes.def" 1897 case BuiltinType::OCLSampler: 1898 Out << "PA"; 1899 mangleArtificalTagType(TTK_Struct, "ocl_sampler"); 1900 break; 1901 case BuiltinType::OCLEvent: 1902 Out << "PA"; 1903 mangleArtificalTagType(TTK_Struct, "ocl_event"); 1904 break; 1905 case BuiltinType::OCLClkEvent: 1906 Out << "PA"; 1907 mangleArtificalTagType(TTK_Struct, "ocl_clkevent"); 1908 break; 1909 case BuiltinType::OCLQueue: 1910 Out << "PA"; 1911 mangleArtificalTagType(TTK_Struct, "ocl_queue"); 1912 break; 1913 case BuiltinType::OCLReserveID: 1914 Out << "PA"; 1915 mangleArtificalTagType(TTK_Struct, "ocl_reserveid"); 1916 break; 1917 1918 case BuiltinType::NullPtr: 1919 Out << "$$T"; 1920 break; 1921 1922 case BuiltinType::Float16: 1923 case BuiltinType::Float128: 1924 case BuiltinType::Half: { 1925 DiagnosticsEngine &Diags = Context.getDiags(); 1926 unsigned DiagID = Diags.getCustomDiagID( 1927 DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet"); 1928 Diags.Report(Range.getBegin(), DiagID) 1929 << T->getName(Context.getASTContext().getPrintingPolicy()) << Range; 1930 break; 1931 } 1932 } 1933 } 1934 1935 // <type> ::= <function-type> 1936 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers, 1937 SourceRange) { 1938 // Structors only appear in decls, so at this point we know it's not a 1939 // structor type. 1940 // FIXME: This may not be lambda-friendly. 1941 if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) { 1942 Out << "$$A8@@"; 1943 mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true); 1944 } else { 1945 Out << "$$A6"; 1946 mangleFunctionType(T); 1947 } 1948 } 1949 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T, 1950 Qualifiers, SourceRange) { 1951 Out << "$$A6"; 1952 mangleFunctionType(T); 1953 } 1954 1955 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T, 1956 const FunctionDecl *D, 1957 bool ForceThisQuals) { 1958 // <function-type> ::= <this-cvr-qualifiers> <calling-convention> 1959 // <return-type> <argument-list> <throw-spec> 1960 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T); 1961 1962 SourceRange Range; 1963 if (D) Range = D->getSourceRange(); 1964 1965 bool IsInLambda = false; 1966 bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false; 1967 CallingConv CC = T->getCallConv(); 1968 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) { 1969 if (MD->getParent()->isLambda()) 1970 IsInLambda = true; 1971 if (MD->isInstance()) 1972 HasThisQuals = true; 1973 if (isa<CXXDestructorDecl>(MD)) { 1974 IsStructor = true; 1975 } else if (isa<CXXConstructorDecl>(MD)) { 1976 IsStructor = true; 1977 IsCtorClosure = (StructorType == Ctor_CopyingClosure || 1978 StructorType == Ctor_DefaultClosure) && 1979 isStructorDecl(MD); 1980 if (IsCtorClosure) 1981 CC = getASTContext().getDefaultCallingConvention( 1982 /*IsVariadic=*/false, /*IsCXXMethod=*/true); 1983 } 1984 } 1985 1986 // If this is a C++ instance method, mangle the CVR qualifiers for the 1987 // this pointer. 1988 if (HasThisQuals) { 1989 Qualifiers Quals = Qualifiers::fromCVRUMask(Proto->getTypeQuals()); 1990 manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType()); 1991 mangleRefQualifier(Proto->getRefQualifier()); 1992 mangleQualifiers(Quals, /*IsMember=*/false); 1993 } 1994 1995 mangleCallingConvention(CC); 1996 1997 // <return-type> ::= <type> 1998 // ::= @ # structors (they have no declared return type) 1999 if (IsStructor) { 2000 if (isa<CXXDestructorDecl>(D) && isStructorDecl(D)) { 2001 // The scalar deleting destructor takes an extra int argument which is not 2002 // reflected in the AST. 2003 if (StructorType == Dtor_Deleting) { 2004 Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z"); 2005 return; 2006 } 2007 // The vbase destructor returns void which is not reflected in the AST. 2008 if (StructorType == Dtor_Complete) { 2009 Out << "XXZ"; 2010 return; 2011 } 2012 } 2013 if (IsCtorClosure) { 2014 // Default constructor closure and copy constructor closure both return 2015 // void. 2016 Out << 'X'; 2017 2018 if (StructorType == Ctor_DefaultClosure) { 2019 // Default constructor closure always has no arguments. 2020 Out << 'X'; 2021 } else if (StructorType == Ctor_CopyingClosure) { 2022 // Copy constructor closure always takes an unqualified reference. 2023 mangleArgumentType(getASTContext().getLValueReferenceType( 2024 Proto->getParamType(0) 2025 ->getAs<LValueReferenceType>() 2026 ->getPointeeType(), 2027 /*SpelledAsLValue=*/true), 2028 Range); 2029 Out << '@'; 2030 } else { 2031 llvm_unreachable("unexpected constructor closure!"); 2032 } 2033 Out << 'Z'; 2034 return; 2035 } 2036 Out << '@'; 2037 } else { 2038 QualType ResultType = T->getReturnType(); 2039 if (const auto *AT = 2040 dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) { 2041 Out << '?'; 2042 mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false); 2043 Out << '?'; 2044 assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType && 2045 "shouldn't need to mangle __auto_type!"); 2046 mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>"); 2047 Out << '@'; 2048 } else if (IsInLambda) { 2049 Out << '@'; 2050 } else { 2051 if (ResultType->isVoidType()) 2052 ResultType = ResultType.getUnqualifiedType(); 2053 mangleType(ResultType, Range, QMM_Result); 2054 } 2055 } 2056 2057 // <argument-list> ::= X # void 2058 // ::= <type>+ @ 2059 // ::= <type>* Z # varargs 2060 if (!Proto) { 2061 // Function types without prototypes can arise when mangling a function type 2062 // within an overloadable function in C. We mangle these as the absence of 2063 // any parameter types (not even an empty parameter list). 2064 Out << '@'; 2065 } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) { 2066 Out << 'X'; 2067 } else { 2068 // Happens for function pointer type arguments for example. 2069 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) { 2070 mangleArgumentType(Proto->getParamType(I), Range); 2071 // Mangle each pass_object_size parameter as if it's a parameter of enum 2072 // type passed directly after the parameter with the pass_object_size 2073 // attribute. The aforementioned enum's name is __pass_object_size, and we 2074 // pretend it resides in a top-level namespace called __clang. 2075 // 2076 // FIXME: Is there a defined extension notation for the MS ABI, or is it 2077 // necessary to just cross our fingers and hope this type+namespace 2078 // combination doesn't conflict with anything? 2079 if (D) 2080 if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) 2081 manglePassObjectSizeArg(P); 2082 } 2083 // <builtin-type> ::= Z # ellipsis 2084 if (Proto->isVariadic()) 2085 Out << 'Z'; 2086 else 2087 Out << '@'; 2088 } 2089 2090 mangleThrowSpecification(Proto); 2091 } 2092 2093 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) { 2094 // <function-class> ::= <member-function> E? # E designates a 64-bit 'this' 2095 // # pointer. in 64-bit mode *all* 2096 // # 'this' pointers are 64-bit. 2097 // ::= <global-function> 2098 // <member-function> ::= A # private: near 2099 // ::= B # private: far 2100 // ::= C # private: static near 2101 // ::= D # private: static far 2102 // ::= E # private: virtual near 2103 // ::= F # private: virtual far 2104 // ::= I # protected: near 2105 // ::= J # protected: far 2106 // ::= K # protected: static near 2107 // ::= L # protected: static far 2108 // ::= M # protected: virtual near 2109 // ::= N # protected: virtual far 2110 // ::= Q # public: near 2111 // ::= R # public: far 2112 // ::= S # public: static near 2113 // ::= T # public: static far 2114 // ::= U # public: virtual near 2115 // ::= V # public: virtual far 2116 // <global-function> ::= Y # global near 2117 // ::= Z # global far 2118 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 2119 bool IsVirtual = MD->isVirtual(); 2120 // When mangling vbase destructor variants, ignore whether or not the 2121 // underlying destructor was defined to be virtual. 2122 if (isa<CXXDestructorDecl>(MD) && isStructorDecl(MD) && 2123 StructorType == Dtor_Complete) { 2124 IsVirtual = false; 2125 } 2126 switch (MD->getAccess()) { 2127 case AS_none: 2128 llvm_unreachable("Unsupported access specifier"); 2129 case AS_private: 2130 if (MD->isStatic()) 2131 Out << 'C'; 2132 else if (IsVirtual) 2133 Out << 'E'; 2134 else 2135 Out << 'A'; 2136 break; 2137 case AS_protected: 2138 if (MD->isStatic()) 2139 Out << 'K'; 2140 else if (IsVirtual) 2141 Out << 'M'; 2142 else 2143 Out << 'I'; 2144 break; 2145 case AS_public: 2146 if (MD->isStatic()) 2147 Out << 'S'; 2148 else if (IsVirtual) 2149 Out << 'U'; 2150 else 2151 Out << 'Q'; 2152 } 2153 } else { 2154 Out << 'Y'; 2155 } 2156 } 2157 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) { 2158 // <calling-convention> ::= A # __cdecl 2159 // ::= B # __export __cdecl 2160 // ::= C # __pascal 2161 // ::= D # __export __pascal 2162 // ::= E # __thiscall 2163 // ::= F # __export __thiscall 2164 // ::= G # __stdcall 2165 // ::= H # __export __stdcall 2166 // ::= I # __fastcall 2167 // ::= J # __export __fastcall 2168 // ::= Q # __vectorcall 2169 // ::= w # __regcall 2170 // The 'export' calling conventions are from a bygone era 2171 // (*cough*Win16*cough*) when functions were declared for export with 2172 // that keyword. (It didn't actually export them, it just made them so 2173 // that they could be in a DLL and somebody from another module could call 2174 // them.) 2175 2176 switch (CC) { 2177 default: 2178 llvm_unreachable("Unsupported CC for mangling"); 2179 case CC_Win64: 2180 case CC_X86_64SysV: 2181 case CC_C: Out << 'A'; break; 2182 case CC_X86Pascal: Out << 'C'; break; 2183 case CC_X86ThisCall: Out << 'E'; break; 2184 case CC_X86StdCall: Out << 'G'; break; 2185 case CC_X86FastCall: Out << 'I'; break; 2186 case CC_X86VectorCall: Out << 'Q'; break; 2187 case CC_Swift: Out << 'S'; break; 2188 case CC_X86RegCall: Out << 'w'; break; 2189 } 2190 } 2191 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) { 2192 mangleCallingConvention(T->getCallConv()); 2193 } 2194 void MicrosoftCXXNameMangler::mangleThrowSpecification( 2195 const FunctionProtoType *FT) { 2196 // <throw-spec> ::= Z # throw(...) (default) 2197 // ::= @ # throw() or __declspec/__attribute__((nothrow)) 2198 // ::= <type>+ 2199 // NOTE: Since the Microsoft compiler ignores throw specifications, they are 2200 // all actually mangled as 'Z'. (They're ignored because their associated 2201 // functionality isn't implemented, and probably never will be.) 2202 Out << 'Z'; 2203 } 2204 2205 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T, 2206 Qualifiers, SourceRange Range) { 2207 // Probably should be mangled as a template instantiation; need to see what 2208 // VC does first. 2209 DiagnosticsEngine &Diags = Context.getDiags(); 2210 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2211 "cannot mangle this unresolved dependent type yet"); 2212 Diags.Report(Range.getBegin(), DiagID) 2213 << Range; 2214 } 2215 2216 // <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type> 2217 // <union-type> ::= T <name> 2218 // <struct-type> ::= U <name> 2219 // <class-type> ::= V <name> 2220 // <enum-type> ::= W4 <name> 2221 void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) { 2222 switch (TTK) { 2223 case TTK_Union: 2224 Out << 'T'; 2225 break; 2226 case TTK_Struct: 2227 case TTK_Interface: 2228 Out << 'U'; 2229 break; 2230 case TTK_Class: 2231 Out << 'V'; 2232 break; 2233 case TTK_Enum: 2234 Out << "W4"; 2235 break; 2236 } 2237 } 2238 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers, 2239 SourceRange) { 2240 mangleType(cast<TagType>(T)->getDecl()); 2241 } 2242 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers, 2243 SourceRange) { 2244 mangleType(cast<TagType>(T)->getDecl()); 2245 } 2246 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) { 2247 mangleTagTypeKind(TD->getTagKind()); 2248 mangleName(TD); 2249 } 2250 void MicrosoftCXXNameMangler::mangleArtificalTagType( 2251 TagTypeKind TK, StringRef UnqualifiedName, ArrayRef<StringRef> NestedNames) { 2252 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @ 2253 mangleTagTypeKind(TK); 2254 2255 // Always start with the unqualified name. 2256 mangleSourceName(UnqualifiedName); 2257 2258 for (auto I = NestedNames.rbegin(), E = NestedNames.rend(); I != E; ++I) 2259 mangleSourceName(*I); 2260 2261 // Terminate the whole name with an '@'. 2262 Out << '@'; 2263 } 2264 2265 // <type> ::= <array-type> 2266 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers> 2267 // [Y <dimension-count> <dimension>+] 2268 // <element-type> # as global, E is never required 2269 // It's supposed to be the other way around, but for some strange reason, it 2270 // isn't. Today this behavior is retained for the sole purpose of backwards 2271 // compatibility. 2272 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) { 2273 // This isn't a recursive mangling, so now we have to do it all in this 2274 // one call. 2275 manglePointerCVQualifiers(T->getElementType().getQualifiers()); 2276 mangleType(T->getElementType(), SourceRange()); 2277 } 2278 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers, 2279 SourceRange) { 2280 llvm_unreachable("Should have been special cased"); 2281 } 2282 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers, 2283 SourceRange) { 2284 llvm_unreachable("Should have been special cased"); 2285 } 2286 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T, 2287 Qualifiers, SourceRange) { 2288 llvm_unreachable("Should have been special cased"); 2289 } 2290 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T, 2291 Qualifiers, SourceRange) { 2292 llvm_unreachable("Should have been special cased"); 2293 } 2294 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) { 2295 QualType ElementTy(T, 0); 2296 SmallVector<llvm::APInt, 3> Dimensions; 2297 for (;;) { 2298 if (ElementTy->isConstantArrayType()) { 2299 const ConstantArrayType *CAT = 2300 getASTContext().getAsConstantArrayType(ElementTy); 2301 Dimensions.push_back(CAT->getSize()); 2302 ElementTy = CAT->getElementType(); 2303 } else if (ElementTy->isIncompleteArrayType()) { 2304 const IncompleteArrayType *IAT = 2305 getASTContext().getAsIncompleteArrayType(ElementTy); 2306 Dimensions.push_back(llvm::APInt(32, 0)); 2307 ElementTy = IAT->getElementType(); 2308 } else if (ElementTy->isVariableArrayType()) { 2309 const VariableArrayType *VAT = 2310 getASTContext().getAsVariableArrayType(ElementTy); 2311 Dimensions.push_back(llvm::APInt(32, 0)); 2312 ElementTy = VAT->getElementType(); 2313 } else if (ElementTy->isDependentSizedArrayType()) { 2314 // The dependent expression has to be folded into a constant (TODO). 2315 const DependentSizedArrayType *DSAT = 2316 getASTContext().getAsDependentSizedArrayType(ElementTy); 2317 DiagnosticsEngine &Diags = Context.getDiags(); 2318 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2319 "cannot mangle this dependent-length array yet"); 2320 Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID) 2321 << DSAT->getBracketsRange(); 2322 return; 2323 } else { 2324 break; 2325 } 2326 } 2327 Out << 'Y'; 2328 // <dimension-count> ::= <number> # number of extra dimensions 2329 mangleNumber(Dimensions.size()); 2330 for (const llvm::APInt &Dimension : Dimensions) 2331 mangleNumber(Dimension.getLimitedValue()); 2332 mangleType(ElementTy, SourceRange(), QMM_Escape); 2333 } 2334 2335 // <type> ::= <pointer-to-member-type> 2336 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers> 2337 // <class name> <type> 2338 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, Qualifiers Quals, 2339 SourceRange Range) { 2340 QualType PointeeType = T->getPointeeType(); 2341 manglePointerCVQualifiers(Quals); 2342 manglePointerExtQualifiers(Quals, PointeeType); 2343 if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) { 2344 Out << '8'; 2345 mangleName(T->getClass()->castAs<RecordType>()->getDecl()); 2346 mangleFunctionType(FPT, nullptr, true); 2347 } else { 2348 mangleQualifiers(PointeeType.getQualifiers(), true); 2349 mangleName(T->getClass()->castAs<RecordType>()->getDecl()); 2350 mangleType(PointeeType, Range, QMM_Drop); 2351 } 2352 } 2353 2354 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T, 2355 Qualifiers, SourceRange Range) { 2356 DiagnosticsEngine &Diags = Context.getDiags(); 2357 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2358 "cannot mangle this template type parameter type yet"); 2359 Diags.Report(Range.getBegin(), DiagID) 2360 << Range; 2361 } 2362 2363 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T, 2364 Qualifiers, SourceRange Range) { 2365 DiagnosticsEngine &Diags = Context.getDiags(); 2366 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2367 "cannot mangle this substituted parameter pack yet"); 2368 Diags.Report(Range.getBegin(), DiagID) 2369 << Range; 2370 } 2371 2372 // <type> ::= <pointer-type> 2373 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type> 2374 // # the E is required for 64-bit non-static pointers 2375 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals, 2376 SourceRange Range) { 2377 QualType PointeeType = T->getPointeeType(); 2378 manglePointerCVQualifiers(Quals); 2379 manglePointerExtQualifiers(Quals, PointeeType); 2380 mangleType(PointeeType, Range); 2381 } 2382 2383 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T, 2384 Qualifiers Quals, SourceRange Range) { 2385 QualType PointeeType = T->getPointeeType(); 2386 switch (Quals.getObjCLifetime()) { 2387 case Qualifiers::OCL_None: 2388 case Qualifiers::OCL_ExplicitNone: 2389 break; 2390 case Qualifiers::OCL_Autoreleasing: 2391 case Qualifiers::OCL_Strong: 2392 case Qualifiers::OCL_Weak: 2393 return mangleObjCLifetime(PointeeType, Quals, Range); 2394 } 2395 manglePointerCVQualifiers(Quals); 2396 manglePointerExtQualifiers(Quals, PointeeType); 2397 mangleType(PointeeType, Range); 2398 } 2399 2400 // <type> ::= <reference-type> 2401 // <reference-type> ::= A E? <cvr-qualifiers> <type> 2402 // # the E is required for 64-bit non-static lvalue references 2403 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T, 2404 Qualifiers Quals, SourceRange Range) { 2405 QualType PointeeType = T->getPointeeType(); 2406 assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!"); 2407 Out << 'A'; 2408 manglePointerExtQualifiers(Quals, PointeeType); 2409 mangleType(PointeeType, Range); 2410 } 2411 2412 // <type> ::= <r-value-reference-type> 2413 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type> 2414 // # the E is required for 64-bit non-static rvalue references 2415 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T, 2416 Qualifiers Quals, SourceRange Range) { 2417 QualType PointeeType = T->getPointeeType(); 2418 assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!"); 2419 Out << "$$Q"; 2420 manglePointerExtQualifiers(Quals, PointeeType); 2421 mangleType(PointeeType, Range); 2422 } 2423 2424 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers, 2425 SourceRange Range) { 2426 QualType ElementType = T->getElementType(); 2427 2428 llvm::SmallString<64> TemplateMangling; 2429 llvm::raw_svector_ostream Stream(TemplateMangling); 2430 MicrosoftCXXNameMangler Extra(Context, Stream); 2431 Stream << "?$"; 2432 Extra.mangleSourceName("_Complex"); 2433 Extra.mangleType(ElementType, Range, QMM_Escape); 2434 2435 mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__clang"}); 2436 } 2437 2438 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals, 2439 SourceRange Range) { 2440 const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>(); 2441 assert(ET && "vectors with non-builtin elements are unsupported"); 2442 uint64_t Width = getASTContext().getTypeSize(T); 2443 // Pattern match exactly the typedefs in our intrinsic headers. Anything that 2444 // doesn't match the Intel types uses a custom mangling below. 2445 size_t OutSizeBefore = Out.tell(); 2446 llvm::Triple::ArchType AT = 2447 getASTContext().getTargetInfo().getTriple().getArch(); 2448 if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) { 2449 if (Width == 64 && ET->getKind() == BuiltinType::LongLong) { 2450 mangleArtificalTagType(TTK_Union, "__m64"); 2451 } else if (Width >= 128) { 2452 if (ET->getKind() == BuiltinType::Float) 2453 mangleArtificalTagType(TTK_Union, "__m" + llvm::utostr(Width)); 2454 else if (ET->getKind() == BuiltinType::LongLong) 2455 mangleArtificalTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i'); 2456 else if (ET->getKind() == BuiltinType::Double) 2457 mangleArtificalTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd'); 2458 } 2459 } 2460 2461 bool IsBuiltin = Out.tell() != OutSizeBefore; 2462 if (!IsBuiltin) { 2463 // The MS ABI doesn't have a special mangling for vector types, so we define 2464 // our own mangling to handle uses of __vector_size__ on user-specified 2465 // types, and for extensions like __v4sf. 2466 2467 llvm::SmallString<64> TemplateMangling; 2468 llvm::raw_svector_ostream Stream(TemplateMangling); 2469 MicrosoftCXXNameMangler Extra(Context, Stream); 2470 Stream << "?$"; 2471 Extra.mangleSourceName("__vector"); 2472 Extra.mangleType(QualType(ET, 0), Range, QMM_Escape); 2473 Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()), 2474 /*IsBoolean=*/false); 2475 2476 mangleArtificalTagType(TTK_Union, TemplateMangling, {"__clang"}); 2477 } 2478 } 2479 2480 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T, 2481 Qualifiers Quals, SourceRange Range) { 2482 mangleType(static_cast<const VectorType *>(T), Quals, Range); 2483 } 2484 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T, 2485 Qualifiers, SourceRange Range) { 2486 DiagnosticsEngine &Diags = Context.getDiags(); 2487 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2488 "cannot mangle this dependent-sized extended vector type yet"); 2489 Diags.Report(Range.getBegin(), DiagID) 2490 << Range; 2491 } 2492 2493 void MicrosoftCXXNameMangler::mangleType(const DependentAddressSpaceType *T, 2494 Qualifiers, SourceRange Range) { 2495 DiagnosticsEngine &Diags = Context.getDiags(); 2496 unsigned DiagID = Diags.getCustomDiagID( 2497 DiagnosticsEngine::Error, 2498 "cannot mangle this dependent address space type yet"); 2499 Diags.Report(Range.getBegin(), DiagID) << Range; 2500 } 2501 2502 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers, 2503 SourceRange) { 2504 // ObjC interfaces have structs underlying them. 2505 mangleTagTypeKind(TTK_Struct); 2506 mangleName(T->getDecl()); 2507 } 2508 2509 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, Qualifiers, 2510 SourceRange Range) { 2511 if (T->qual_empty()) 2512 return mangleType(T->getBaseType(), Range, QMM_Drop); 2513 2514 ArgBackRefMap OuterArgsContext; 2515 BackRefVec OuterTemplateContext; 2516 2517 TypeBackReferences.swap(OuterArgsContext); 2518 NameBackReferences.swap(OuterTemplateContext); 2519 2520 mangleTagTypeKind(TTK_Struct); 2521 2522 Out << "?$"; 2523 if (T->isObjCId()) 2524 mangleSourceName("objc_object"); 2525 else if (T->isObjCClass()) 2526 mangleSourceName("objc_class"); 2527 else 2528 mangleSourceName(T->getInterface()->getName()); 2529 2530 for (const auto &Q : T->quals()) 2531 mangleObjCProtocol(Q); 2532 Out << '@'; 2533 2534 Out << '@'; 2535 2536 TypeBackReferences.swap(OuterArgsContext); 2537 NameBackReferences.swap(OuterTemplateContext); 2538 } 2539 2540 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T, 2541 Qualifiers Quals, SourceRange Range) { 2542 QualType PointeeType = T->getPointeeType(); 2543 manglePointerCVQualifiers(Quals); 2544 manglePointerExtQualifiers(Quals, PointeeType); 2545 2546 Out << "_E"; 2547 2548 mangleFunctionType(PointeeType->castAs<FunctionProtoType>()); 2549 } 2550 2551 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *, 2552 Qualifiers, SourceRange) { 2553 llvm_unreachable("Cannot mangle injected class name type."); 2554 } 2555 2556 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T, 2557 Qualifiers, SourceRange Range) { 2558 DiagnosticsEngine &Diags = Context.getDiags(); 2559 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2560 "cannot mangle this template specialization type yet"); 2561 Diags.Report(Range.getBegin(), DiagID) 2562 << Range; 2563 } 2564 2565 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers, 2566 SourceRange Range) { 2567 DiagnosticsEngine &Diags = Context.getDiags(); 2568 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2569 "cannot mangle this dependent name type yet"); 2570 Diags.Report(Range.getBegin(), DiagID) 2571 << Range; 2572 } 2573 2574 void MicrosoftCXXNameMangler::mangleType( 2575 const DependentTemplateSpecializationType *T, Qualifiers, 2576 SourceRange Range) { 2577 DiagnosticsEngine &Diags = Context.getDiags(); 2578 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2579 "cannot mangle this dependent template specialization type yet"); 2580 Diags.Report(Range.getBegin(), DiagID) 2581 << Range; 2582 } 2583 2584 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers, 2585 SourceRange Range) { 2586 DiagnosticsEngine &Diags = Context.getDiags(); 2587 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2588 "cannot mangle this pack expansion yet"); 2589 Diags.Report(Range.getBegin(), DiagID) 2590 << Range; 2591 } 2592 2593 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers, 2594 SourceRange Range) { 2595 DiagnosticsEngine &Diags = Context.getDiags(); 2596 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2597 "cannot mangle this typeof(type) yet"); 2598 Diags.Report(Range.getBegin(), DiagID) 2599 << Range; 2600 } 2601 2602 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers, 2603 SourceRange Range) { 2604 DiagnosticsEngine &Diags = Context.getDiags(); 2605 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2606 "cannot mangle this typeof(expression) yet"); 2607 Diags.Report(Range.getBegin(), DiagID) 2608 << Range; 2609 } 2610 2611 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers, 2612 SourceRange Range) { 2613 DiagnosticsEngine &Diags = Context.getDiags(); 2614 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2615 "cannot mangle this decltype() yet"); 2616 Diags.Report(Range.getBegin(), DiagID) 2617 << Range; 2618 } 2619 2620 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T, 2621 Qualifiers, SourceRange Range) { 2622 DiagnosticsEngine &Diags = Context.getDiags(); 2623 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2624 "cannot mangle this unary transform type yet"); 2625 Diags.Report(Range.getBegin(), DiagID) 2626 << Range; 2627 } 2628 2629 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers, 2630 SourceRange Range) { 2631 assert(T->getDeducedType().isNull() && "expecting a dependent type!"); 2632 2633 DiagnosticsEngine &Diags = Context.getDiags(); 2634 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2635 "cannot mangle this 'auto' type yet"); 2636 Diags.Report(Range.getBegin(), DiagID) 2637 << Range; 2638 } 2639 2640 void MicrosoftCXXNameMangler::mangleType( 2641 const DeducedTemplateSpecializationType *T, Qualifiers, SourceRange Range) { 2642 assert(T->getDeducedType().isNull() && "expecting a dependent type!"); 2643 2644 DiagnosticsEngine &Diags = Context.getDiags(); 2645 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2646 "cannot mangle this deduced class template specialization type yet"); 2647 Diags.Report(Range.getBegin(), DiagID) 2648 << Range; 2649 } 2650 2651 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers, 2652 SourceRange Range) { 2653 QualType ValueType = T->getValueType(); 2654 2655 llvm::SmallString<64> TemplateMangling; 2656 llvm::raw_svector_ostream Stream(TemplateMangling); 2657 MicrosoftCXXNameMangler Extra(Context, Stream); 2658 Stream << "?$"; 2659 Extra.mangleSourceName("_Atomic"); 2660 Extra.mangleType(ValueType, Range, QMM_Escape); 2661 2662 mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__clang"}); 2663 } 2664 2665 void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers, 2666 SourceRange Range) { 2667 DiagnosticsEngine &Diags = Context.getDiags(); 2668 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2669 "cannot mangle this OpenCL pipe type yet"); 2670 Diags.Report(Range.getBegin(), DiagID) 2671 << Range; 2672 } 2673 2674 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D, 2675 raw_ostream &Out) { 2676 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) && 2677 "Invalid mangleName() call, argument is not a variable or function!"); 2678 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) && 2679 "Invalid mangleName() call on 'structor decl!"); 2680 2681 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 2682 getASTContext().getSourceManager(), 2683 "Mangling declaration"); 2684 2685 msvc_hashing_ostream MHO(Out); 2686 MicrosoftCXXNameMangler Mangler(*this, MHO); 2687 return Mangler.mangle(D); 2688 } 2689 2690 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> | 2691 // <virtual-adjustment> 2692 // <no-adjustment> ::= A # private near 2693 // ::= B # private far 2694 // ::= I # protected near 2695 // ::= J # protected far 2696 // ::= Q # public near 2697 // ::= R # public far 2698 // <static-adjustment> ::= G <static-offset> # private near 2699 // ::= H <static-offset> # private far 2700 // ::= O <static-offset> # protected near 2701 // ::= P <static-offset> # protected far 2702 // ::= W <static-offset> # public near 2703 // ::= X <static-offset> # public far 2704 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near 2705 // ::= $1 <virtual-shift> <static-offset> # private far 2706 // ::= $2 <virtual-shift> <static-offset> # protected near 2707 // ::= $3 <virtual-shift> <static-offset> # protected far 2708 // ::= $4 <virtual-shift> <static-offset> # public near 2709 // ::= $5 <virtual-shift> <static-offset> # public far 2710 // <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift> 2711 // <vtordisp-shift> ::= <offset-to-vtordisp> 2712 // <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset> 2713 // <offset-to-vtordisp> 2714 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD, 2715 const ThisAdjustment &Adjustment, 2716 MicrosoftCXXNameMangler &Mangler, 2717 raw_ostream &Out) { 2718 if (!Adjustment.Virtual.isEmpty()) { 2719 Out << '$'; 2720 char AccessSpec; 2721 switch (MD->getAccess()) { 2722 case AS_none: 2723 llvm_unreachable("Unsupported access specifier"); 2724 case AS_private: 2725 AccessSpec = '0'; 2726 break; 2727 case AS_protected: 2728 AccessSpec = '2'; 2729 break; 2730 case AS_public: 2731 AccessSpec = '4'; 2732 } 2733 if (Adjustment.Virtual.Microsoft.VBPtrOffset) { 2734 Out << 'R' << AccessSpec; 2735 Mangler.mangleNumber( 2736 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset)); 2737 Mangler.mangleNumber( 2738 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset)); 2739 Mangler.mangleNumber( 2740 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset)); 2741 Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual)); 2742 } else { 2743 Out << AccessSpec; 2744 Mangler.mangleNumber( 2745 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset)); 2746 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual)); 2747 } 2748 } else if (Adjustment.NonVirtual != 0) { 2749 switch (MD->getAccess()) { 2750 case AS_none: 2751 llvm_unreachable("Unsupported access specifier"); 2752 case AS_private: 2753 Out << 'G'; 2754 break; 2755 case AS_protected: 2756 Out << 'O'; 2757 break; 2758 case AS_public: 2759 Out << 'W'; 2760 } 2761 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual)); 2762 } else { 2763 switch (MD->getAccess()) { 2764 case AS_none: 2765 llvm_unreachable("Unsupported access specifier"); 2766 case AS_private: 2767 Out << 'A'; 2768 break; 2769 case AS_protected: 2770 Out << 'I'; 2771 break; 2772 case AS_public: 2773 Out << 'Q'; 2774 } 2775 } 2776 } 2777 2778 void 2779 MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD, 2780 raw_ostream &Out) { 2781 MicrosoftVTableContext *VTContext = 2782 cast<MicrosoftVTableContext>(getASTContext().getVTableContext()); 2783 const MicrosoftVTableContext::MethodVFTableLocation &ML = 2784 VTContext->getMethodVFTableLocation(GlobalDecl(MD)); 2785 2786 msvc_hashing_ostream MHO(Out); 2787 MicrosoftCXXNameMangler Mangler(*this, MHO); 2788 Mangler.getStream() << "\01?"; 2789 Mangler.mangleVirtualMemPtrThunk(MD, ML); 2790 } 2791 2792 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, 2793 const ThunkInfo &Thunk, 2794 raw_ostream &Out) { 2795 msvc_hashing_ostream MHO(Out); 2796 MicrosoftCXXNameMangler Mangler(*this, MHO); 2797 Mangler.getStream() << "\01?"; 2798 Mangler.mangleName(MD); 2799 mangleThunkThisAdjustment(MD, Thunk.This, Mangler, MHO); 2800 if (!Thunk.Return.isEmpty()) 2801 assert(Thunk.Method != nullptr && 2802 "Thunk info should hold the overridee decl"); 2803 2804 const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD; 2805 Mangler.mangleFunctionType( 2806 DeclForFPT->getType()->castAs<FunctionProtoType>(), MD); 2807 } 2808 2809 void MicrosoftMangleContextImpl::mangleCXXDtorThunk( 2810 const CXXDestructorDecl *DD, CXXDtorType Type, 2811 const ThisAdjustment &Adjustment, raw_ostream &Out) { 2812 // FIXME: Actually, the dtor thunk should be emitted for vector deleting 2813 // dtors rather than scalar deleting dtors. Just use the vector deleting dtor 2814 // mangling manually until we support both deleting dtor types. 2815 assert(Type == Dtor_Deleting); 2816 msvc_hashing_ostream MHO(Out); 2817 MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type); 2818 Mangler.getStream() << "\01??_E"; 2819 Mangler.mangleName(DD->getParent()); 2820 mangleThunkThisAdjustment(DD, Adjustment, Mangler, MHO); 2821 Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD); 2822 } 2823 2824 void MicrosoftMangleContextImpl::mangleCXXVFTable( 2825 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath, 2826 raw_ostream &Out) { 2827 // <mangled-name> ::= ?_7 <class-name> <storage-class> 2828 // <cvr-qualifiers> [<name>] @ 2829 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class> 2830 // is always '6' for vftables. 2831 msvc_hashing_ostream MHO(Out); 2832 MicrosoftCXXNameMangler Mangler(*this, MHO); 2833 if (Derived->hasAttr<DLLImportAttr>()) 2834 Mangler.getStream() << "\01??_S"; 2835 else 2836 Mangler.getStream() << "\01??_7"; 2837 Mangler.mangleName(Derived); 2838 Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const. 2839 for (const CXXRecordDecl *RD : BasePath) 2840 Mangler.mangleName(RD); 2841 Mangler.getStream() << '@'; 2842 } 2843 2844 void MicrosoftMangleContextImpl::mangleCXXVBTable( 2845 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath, 2846 raw_ostream &Out) { 2847 // <mangled-name> ::= ?_8 <class-name> <storage-class> 2848 // <cvr-qualifiers> [<name>] @ 2849 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class> 2850 // is always '7' for vbtables. 2851 msvc_hashing_ostream MHO(Out); 2852 MicrosoftCXXNameMangler Mangler(*this, MHO); 2853 Mangler.getStream() << "\01??_8"; 2854 Mangler.mangleName(Derived); 2855 Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const. 2856 for (const CXXRecordDecl *RD : BasePath) 2857 Mangler.mangleName(RD); 2858 Mangler.getStream() << '@'; 2859 } 2860 2861 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) { 2862 msvc_hashing_ostream MHO(Out); 2863 MicrosoftCXXNameMangler Mangler(*this, MHO); 2864 Mangler.getStream() << "\01??_R0"; 2865 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result); 2866 Mangler.getStream() << "@8"; 2867 } 2868 2869 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T, 2870 raw_ostream &Out) { 2871 MicrosoftCXXNameMangler Mangler(*this, Out); 2872 Mangler.getStream() << '.'; 2873 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result); 2874 } 2875 2876 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap( 2877 const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) { 2878 msvc_hashing_ostream MHO(Out); 2879 MicrosoftCXXNameMangler Mangler(*this, MHO); 2880 Mangler.getStream() << "\01??_K"; 2881 Mangler.mangleName(SrcRD); 2882 Mangler.getStream() << "$C"; 2883 Mangler.mangleName(DstRD); 2884 } 2885 2886 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst, 2887 bool IsVolatile, 2888 bool IsUnaligned, 2889 uint32_t NumEntries, 2890 raw_ostream &Out) { 2891 msvc_hashing_ostream MHO(Out); 2892 MicrosoftCXXNameMangler Mangler(*this, MHO); 2893 Mangler.getStream() << "_TI"; 2894 if (IsConst) 2895 Mangler.getStream() << 'C'; 2896 if (IsVolatile) 2897 Mangler.getStream() << 'V'; 2898 if (IsUnaligned) 2899 Mangler.getStream() << 'U'; 2900 Mangler.getStream() << NumEntries; 2901 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result); 2902 } 2903 2904 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray( 2905 QualType T, uint32_t NumEntries, raw_ostream &Out) { 2906 msvc_hashing_ostream MHO(Out); 2907 MicrosoftCXXNameMangler Mangler(*this, MHO); 2908 Mangler.getStream() << "_CTA"; 2909 Mangler.getStream() << NumEntries; 2910 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result); 2911 } 2912 2913 void MicrosoftMangleContextImpl::mangleCXXCatchableType( 2914 QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size, 2915 uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex, 2916 raw_ostream &Out) { 2917 MicrosoftCXXNameMangler Mangler(*this, Out); 2918 Mangler.getStream() << "_CT"; 2919 2920 llvm::SmallString<64> RTTIMangling; 2921 { 2922 llvm::raw_svector_ostream Stream(RTTIMangling); 2923 msvc_hashing_ostream MHO(Stream); 2924 mangleCXXRTTI(T, MHO); 2925 } 2926 Mangler.getStream() << RTTIMangling.substr(1); 2927 2928 // VS2015 CTP6 omits the copy-constructor in the mangled name. This name is, 2929 // in fact, superfluous but I'm not sure the change was made consciously. 2930 llvm::SmallString<64> CopyCtorMangling; 2931 if (!getASTContext().getLangOpts().isCompatibleWithMSVC( 2932 LangOptions::MSVC2015) && 2933 CD) { 2934 llvm::raw_svector_ostream Stream(CopyCtorMangling); 2935 msvc_hashing_ostream MHO(Stream); 2936 mangleCXXCtor(CD, CT, MHO); 2937 } 2938 Mangler.getStream() << CopyCtorMangling.substr(1); 2939 2940 Mangler.getStream() << Size; 2941 if (VBPtrOffset == -1) { 2942 if (NVOffset) { 2943 Mangler.getStream() << NVOffset; 2944 } 2945 } else { 2946 Mangler.getStream() << NVOffset; 2947 Mangler.getStream() << VBPtrOffset; 2948 Mangler.getStream() << VBIndex; 2949 } 2950 } 2951 2952 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor( 2953 const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset, 2954 uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) { 2955 msvc_hashing_ostream MHO(Out); 2956 MicrosoftCXXNameMangler Mangler(*this, MHO); 2957 Mangler.getStream() << "\01??_R1"; 2958 Mangler.mangleNumber(NVOffset); 2959 Mangler.mangleNumber(VBPtrOffset); 2960 Mangler.mangleNumber(VBTableOffset); 2961 Mangler.mangleNumber(Flags); 2962 Mangler.mangleName(Derived); 2963 Mangler.getStream() << "8"; 2964 } 2965 2966 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray( 2967 const CXXRecordDecl *Derived, raw_ostream &Out) { 2968 msvc_hashing_ostream MHO(Out); 2969 MicrosoftCXXNameMangler Mangler(*this, MHO); 2970 Mangler.getStream() << "\01??_R2"; 2971 Mangler.mangleName(Derived); 2972 Mangler.getStream() << "8"; 2973 } 2974 2975 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor( 2976 const CXXRecordDecl *Derived, raw_ostream &Out) { 2977 msvc_hashing_ostream MHO(Out); 2978 MicrosoftCXXNameMangler Mangler(*this, MHO); 2979 Mangler.getStream() << "\01??_R3"; 2980 Mangler.mangleName(Derived); 2981 Mangler.getStream() << "8"; 2982 } 2983 2984 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator( 2985 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath, 2986 raw_ostream &Out) { 2987 // <mangled-name> ::= ?_R4 <class-name> <storage-class> 2988 // <cvr-qualifiers> [<name>] @ 2989 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class> 2990 // is always '6' for vftables. 2991 llvm::SmallString<64> VFTableMangling; 2992 llvm::raw_svector_ostream Stream(VFTableMangling); 2993 mangleCXXVFTable(Derived, BasePath, Stream); 2994 2995 if (VFTableMangling.startswith("\01??@")) { 2996 assert(VFTableMangling.endswith("@")); 2997 Out << VFTableMangling << "??_R4@"; 2998 return; 2999 } 3000 3001 assert(VFTableMangling.startswith("\01??_7") || 3002 VFTableMangling.startswith("\01??_S")); 3003 3004 Out << "\01??_R4" << StringRef(VFTableMangling).drop_front(5); 3005 } 3006 3007 void MicrosoftMangleContextImpl::mangleSEHFilterExpression( 3008 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 3009 msvc_hashing_ostream MHO(Out); 3010 MicrosoftCXXNameMangler Mangler(*this, MHO); 3011 // The function body is in the same comdat as the function with the handler, 3012 // so the numbering here doesn't have to be the same across TUs. 3013 // 3014 // <mangled-name> ::= ?filt$ <filter-number> @0 3015 Mangler.getStream() << "\01?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@"; 3016 Mangler.mangleName(EnclosingDecl); 3017 } 3018 3019 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock( 3020 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 3021 msvc_hashing_ostream MHO(Out); 3022 MicrosoftCXXNameMangler Mangler(*this, MHO); 3023 // The function body is in the same comdat as the function with the handler, 3024 // so the numbering here doesn't have to be the same across TUs. 3025 // 3026 // <mangled-name> ::= ?fin$ <filter-number> @0 3027 Mangler.getStream() << "\01?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@"; 3028 Mangler.mangleName(EnclosingDecl); 3029 } 3030 3031 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) { 3032 // This is just a made up unique string for the purposes of tbaa. undname 3033 // does *not* know how to demangle it. 3034 MicrosoftCXXNameMangler Mangler(*this, Out); 3035 Mangler.getStream() << '?'; 3036 Mangler.mangleType(T, SourceRange()); 3037 } 3038 3039 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D, 3040 CXXCtorType Type, 3041 raw_ostream &Out) { 3042 msvc_hashing_ostream MHO(Out); 3043 MicrosoftCXXNameMangler mangler(*this, MHO, D, Type); 3044 mangler.mangle(D); 3045 } 3046 3047 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D, 3048 CXXDtorType Type, 3049 raw_ostream &Out) { 3050 msvc_hashing_ostream MHO(Out); 3051 MicrosoftCXXNameMangler mangler(*this, MHO, D, Type); 3052 mangler.mangle(D); 3053 } 3054 3055 void MicrosoftMangleContextImpl::mangleReferenceTemporary( 3056 const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) { 3057 msvc_hashing_ostream MHO(Out); 3058 MicrosoftCXXNameMangler Mangler(*this, MHO); 3059 3060 Mangler.getStream() << "\01?$RT" << ManglingNumber << '@'; 3061 Mangler.mangle(VD, ""); 3062 } 3063 3064 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable( 3065 const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) { 3066 msvc_hashing_ostream MHO(Out); 3067 MicrosoftCXXNameMangler Mangler(*this, MHO); 3068 3069 Mangler.getStream() << "\01?$TSS" << GuardNum << '@'; 3070 Mangler.mangleNestedName(VD); 3071 Mangler.getStream() << "@4HA"; 3072 } 3073 3074 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD, 3075 raw_ostream &Out) { 3076 // <guard-name> ::= ?_B <postfix> @5 <scope-depth> 3077 // ::= ?__J <postfix> @5 <scope-depth> 3078 // ::= ?$S <guard-num> @ <postfix> @4IA 3079 3080 // The first mangling is what MSVC uses to guard static locals in inline 3081 // functions. It uses a different mangling in external functions to support 3082 // guarding more than 32 variables. MSVC rejects inline functions with more 3083 // than 32 static locals. We don't fully implement the second mangling 3084 // because those guards are not externally visible, and instead use LLVM's 3085 // default renaming when creating a new guard variable. 3086 msvc_hashing_ostream MHO(Out); 3087 MicrosoftCXXNameMangler Mangler(*this, MHO); 3088 3089 bool Visible = VD->isExternallyVisible(); 3090 if (Visible) { 3091 Mangler.getStream() << (VD->getTLSKind() ? "\01??__J" : "\01??_B"); 3092 } else { 3093 Mangler.getStream() << "\01?$S1@"; 3094 } 3095 unsigned ScopeDepth = 0; 3096 if (Visible && !getNextDiscriminator(VD, ScopeDepth)) 3097 // If we do not have a discriminator and are emitting a guard variable for 3098 // use at global scope, then mangling the nested name will not be enough to 3099 // remove ambiguities. 3100 Mangler.mangle(VD, ""); 3101 else 3102 Mangler.mangleNestedName(VD); 3103 Mangler.getStream() << (Visible ? "@5" : "@4IA"); 3104 if (ScopeDepth) 3105 Mangler.mangleNumber(ScopeDepth); 3106 } 3107 3108 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D, 3109 char CharCode, 3110 raw_ostream &Out) { 3111 msvc_hashing_ostream MHO(Out); 3112 MicrosoftCXXNameMangler Mangler(*this, MHO); 3113 Mangler.getStream() << "\01??__" << CharCode; 3114 Mangler.mangleName(D); 3115 if (D->isStaticDataMember()) { 3116 Mangler.mangleVariableEncoding(D); 3117 Mangler.getStream() << '@'; 3118 } 3119 // This is the function class mangling. These stubs are global, non-variadic, 3120 // cdecl functions that return void and take no args. 3121 Mangler.getStream() << "YAXXZ"; 3122 } 3123 3124 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D, 3125 raw_ostream &Out) { 3126 // <initializer-name> ::= ?__E <name> YAXXZ 3127 mangleInitFiniStub(D, 'E', Out); 3128 } 3129 3130 void 3131 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D, 3132 raw_ostream &Out) { 3133 // <destructor-name> ::= ?__F <name> YAXXZ 3134 mangleInitFiniStub(D, 'F', Out); 3135 } 3136 3137 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL, 3138 raw_ostream &Out) { 3139 // <char-type> ::= 0 # char 3140 // ::= 1 # wchar_t 3141 // ::= ??? # char16_t/char32_t will need a mangling too... 3142 // 3143 // <literal-length> ::= <non-negative integer> # the length of the literal 3144 // 3145 // <encoded-crc> ::= <hex digit>+ @ # crc of the literal including 3146 // # null-terminator 3147 // 3148 // <encoded-string> ::= <simple character> # uninteresting character 3149 // ::= '?$' <hex digit> <hex digit> # these two nibbles 3150 // # encode the byte for the 3151 // # character 3152 // ::= '?' [a-z] # \xe1 - \xfa 3153 // ::= '?' [A-Z] # \xc1 - \xda 3154 // ::= '?' [0-9] # [,/\:. \n\t'-] 3155 // 3156 // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc> 3157 // <encoded-string> '@' 3158 MicrosoftCXXNameMangler Mangler(*this, Out); 3159 Mangler.getStream() << "\01??_C@_"; 3160 3161 // <char-type>: The "kind" of string literal is encoded into the mangled name. 3162 if (SL->isWide()) 3163 Mangler.getStream() << '1'; 3164 else 3165 Mangler.getStream() << '0'; 3166 3167 // <literal-length>: The next part of the mangled name consists of the length 3168 // of the string. 3169 // The StringLiteral does not consider the NUL terminator byte(s) but the 3170 // mangling does. 3171 // N.B. The length is in terms of bytes, not characters. 3172 Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth()); 3173 3174 auto GetLittleEndianByte = [&SL](unsigned Index) { 3175 unsigned CharByteWidth = SL->getCharByteWidth(); 3176 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth); 3177 unsigned OffsetInCodeUnit = Index % CharByteWidth; 3178 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff); 3179 }; 3180 3181 auto GetBigEndianByte = [&SL](unsigned Index) { 3182 unsigned CharByteWidth = SL->getCharByteWidth(); 3183 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth); 3184 unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth); 3185 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff); 3186 }; 3187 3188 // CRC all the bytes of the StringLiteral. 3189 llvm::JamCRC JC; 3190 for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I) 3191 JC.update(GetLittleEndianByte(I)); 3192 3193 // The NUL terminator byte(s) were not present earlier, 3194 // we need to manually process those bytes into the CRC. 3195 for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth(); 3196 ++NullTerminator) 3197 JC.update('\x00'); 3198 3199 // <encoded-crc>: The CRC is encoded utilizing the standard number mangling 3200 // scheme. 3201 Mangler.mangleNumber(JC.getCRC()); 3202 3203 // <encoded-string>: The mangled name also contains the first 32 _characters_ 3204 // (including null-terminator bytes) of the StringLiteral. 3205 // Each character is encoded by splitting them into bytes and then encoding 3206 // the constituent bytes. 3207 auto MangleByte = [&Mangler](char Byte) { 3208 // There are five different manglings for characters: 3209 // - [a-zA-Z0-9_$]: A one-to-one mapping. 3210 // - ?[a-z]: The range from \xe1 to \xfa. 3211 // - ?[A-Z]: The range from \xc1 to \xda. 3212 // - ?[0-9]: The set of [,/\:. \n\t'-]. 3213 // - ?$XX: A fallback which maps nibbles. 3214 if (isIdentifierBody(Byte, /*AllowDollar=*/true)) { 3215 Mangler.getStream() << Byte; 3216 } else if (isLetter(Byte & 0x7f)) { 3217 Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f); 3218 } else { 3219 const char SpecialChars[] = {',', '/', '\\', ':', '.', 3220 ' ', '\n', '\t', '\'', '-'}; 3221 const char *Pos = 3222 std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte); 3223 if (Pos != std::end(SpecialChars)) { 3224 Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars)); 3225 } else { 3226 Mangler.getStream() << "?$"; 3227 Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf)); 3228 Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf)); 3229 } 3230 } 3231 }; 3232 3233 // Enforce our 32 character max. 3234 unsigned NumCharsToMangle = std::min(32U, SL->getLength()); 3235 for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E; 3236 ++I) 3237 if (SL->isWide()) 3238 MangleByte(GetBigEndianByte(I)); 3239 else 3240 MangleByte(GetLittleEndianByte(I)); 3241 3242 // Encode the NUL terminator if there is room. 3243 if (NumCharsToMangle < 32) 3244 for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth(); 3245 ++NullTerminator) 3246 MangleByte(0); 3247 3248 Mangler.getStream() << '@'; 3249 } 3250 3251 MicrosoftMangleContext * 3252 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) { 3253 return new MicrosoftMangleContextImpl(Context, Diags); 3254 } 3255