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