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