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