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