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