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