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