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