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