1 //===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===// 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 file contains support for writing Microsoft CodeView debug info. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeViewDebug.h" 15 #include "llvm/ADT/TinyPtrVector.h" 16 #include "llvm/DebugInfo/CodeView/CVTypeDumper.h" 17 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" 18 #include "llvm/DebugInfo/CodeView/CodeView.h" 19 #include "llvm/DebugInfo/CodeView/Line.h" 20 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 21 #include "llvm/DebugInfo/CodeView/TypeDatabase.h" 22 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h" 23 #include "llvm/DebugInfo/CodeView/TypeIndex.h" 24 #include "llvm/DebugInfo/CodeView/TypeRecord.h" 25 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/MC/MCAsmInfo.h" 28 #include "llvm/MC/MCExpr.h" 29 #include "llvm/MC/MCSectionCOFF.h" 30 #include "llvm/MC/MCSymbol.h" 31 #include "llvm/Support/BinaryByteStream.h" 32 #include "llvm/Support/BinaryStreamReader.h" 33 #include "llvm/Support/COFF.h" 34 #include "llvm/Support/ScopedPrinter.h" 35 #include "llvm/Target/TargetFrameLowering.h" 36 #include "llvm/Target/TargetRegisterInfo.h" 37 #include "llvm/Target/TargetSubtargetInfo.h" 38 39 using namespace llvm; 40 using namespace llvm::codeview; 41 42 CodeViewDebug::CodeViewDebug(AsmPrinter *AP) 43 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), Allocator(), 44 TypeTable(Allocator), CurFn(nullptr) { 45 // If module doesn't have named metadata anchors or COFF debug section 46 // is not available, skip any debug info related stuff. 47 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") || 48 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) { 49 Asm = nullptr; 50 return; 51 } 52 53 // Tell MMI that we have debug info. 54 MMI->setDebugInfoAvailability(true); 55 } 56 57 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) { 58 std::string &Filepath = FileToFilepathMap[File]; 59 if (!Filepath.empty()) 60 return Filepath; 61 62 StringRef Dir = File->getDirectory(), Filename = File->getFilename(); 63 64 // Clang emits directory and relative filename info into the IR, but CodeView 65 // operates on full paths. We could change Clang to emit full paths too, but 66 // that would increase the IR size and probably not needed for other users. 67 // For now, just concatenate and canonicalize the path here. 68 if (Filename.find(':') == 1) 69 Filepath = Filename; 70 else 71 Filepath = (Dir + "\\" + Filename).str(); 72 73 // Canonicalize the path. We have to do it textually because we may no longer 74 // have access the file in the filesystem. 75 // First, replace all slashes with backslashes. 76 std::replace(Filepath.begin(), Filepath.end(), '/', '\\'); 77 78 // Remove all "\.\" with "\". 79 size_t Cursor = 0; 80 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos) 81 Filepath.erase(Cursor, 2); 82 83 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original 84 // path should be well-formatted, e.g. start with a drive letter, etc. 85 Cursor = 0; 86 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) { 87 // Something's wrong if the path starts with "\..\", abort. 88 if (Cursor == 0) 89 break; 90 91 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1); 92 if (PrevSlash == std::string::npos) 93 // Something's wrong, abort. 94 break; 95 96 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash); 97 // The next ".." might be following the one we've just erased. 98 Cursor = PrevSlash; 99 } 100 101 // Remove all duplicate backslashes. 102 Cursor = 0; 103 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos) 104 Filepath.erase(Cursor, 1); 105 106 return Filepath; 107 } 108 109 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) { 110 unsigned NextId = FileIdMap.size() + 1; 111 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId)); 112 if (Insertion.second) { 113 // We have to compute the full filepath and emit a .cv_file directive. 114 StringRef FullPath = getFullFilepath(F); 115 bool Success = OS.EmitCVFileDirective(NextId, FullPath); 116 (void)Success; 117 assert(Success && ".cv_file directive failed"); 118 } 119 return Insertion.first->second; 120 } 121 122 CodeViewDebug::InlineSite & 123 CodeViewDebug::getInlineSite(const DILocation *InlinedAt, 124 const DISubprogram *Inlinee) { 125 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()}); 126 InlineSite *Site = &SiteInsertion.first->second; 127 if (SiteInsertion.second) { 128 unsigned ParentFuncId = CurFn->FuncId; 129 if (const DILocation *OuterIA = InlinedAt->getInlinedAt()) 130 ParentFuncId = 131 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram()) 132 .SiteFuncId; 133 134 Site->SiteFuncId = NextFuncId++; 135 OS.EmitCVInlineSiteIdDirective( 136 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()), 137 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc()); 138 Site->Inlinee = Inlinee; 139 InlinedSubprograms.insert(Inlinee); 140 getFuncIdForSubprogram(Inlinee); 141 } 142 return *Site; 143 } 144 145 static StringRef getPrettyScopeName(const DIScope *Scope) { 146 StringRef ScopeName = Scope->getName(); 147 if (!ScopeName.empty()) 148 return ScopeName; 149 150 switch (Scope->getTag()) { 151 case dwarf::DW_TAG_enumeration_type: 152 case dwarf::DW_TAG_class_type: 153 case dwarf::DW_TAG_structure_type: 154 case dwarf::DW_TAG_union_type: 155 return "<unnamed-tag>"; 156 case dwarf::DW_TAG_namespace: 157 return "`anonymous namespace'"; 158 } 159 160 return StringRef(); 161 } 162 163 static const DISubprogram *getQualifiedNameComponents( 164 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) { 165 const DISubprogram *ClosestSubprogram = nullptr; 166 while (Scope != nullptr) { 167 if (ClosestSubprogram == nullptr) 168 ClosestSubprogram = dyn_cast<DISubprogram>(Scope); 169 StringRef ScopeName = getPrettyScopeName(Scope); 170 if (!ScopeName.empty()) 171 QualifiedNameComponents.push_back(ScopeName); 172 Scope = Scope->getScope().resolve(); 173 } 174 return ClosestSubprogram; 175 } 176 177 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents, 178 StringRef TypeName) { 179 std::string FullyQualifiedName; 180 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) { 181 FullyQualifiedName.append(QualifiedNameComponent); 182 FullyQualifiedName.append("::"); 183 } 184 FullyQualifiedName.append(TypeName); 185 return FullyQualifiedName; 186 } 187 188 static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) { 189 SmallVector<StringRef, 5> QualifiedNameComponents; 190 getQualifiedNameComponents(Scope, QualifiedNameComponents); 191 return getQualifiedName(QualifiedNameComponents, Name); 192 } 193 194 struct CodeViewDebug::TypeLoweringScope { 195 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; } 196 ~TypeLoweringScope() { 197 // Don't decrement TypeEmissionLevel until after emitting deferred types, so 198 // inner TypeLoweringScopes don't attempt to emit deferred types. 199 if (CVD.TypeEmissionLevel == 1) 200 CVD.emitDeferredCompleteTypes(); 201 --CVD.TypeEmissionLevel; 202 } 203 CodeViewDebug &CVD; 204 }; 205 206 static std::string getFullyQualifiedName(const DIScope *Ty) { 207 const DIScope *Scope = Ty->getScope().resolve(); 208 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty)); 209 } 210 211 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) { 212 // No scope means global scope and that uses the zero index. 213 if (!Scope || isa<DIFile>(Scope)) 214 return TypeIndex(); 215 216 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type"); 217 218 // Check if we've already translated this scope. 219 auto I = TypeIndices.find({Scope, nullptr}); 220 if (I != TypeIndices.end()) 221 return I->second; 222 223 // Build the fully qualified name of the scope. 224 std::string ScopeName = getFullyQualifiedName(Scope); 225 StringIdRecord SID(TypeIndex(), ScopeName); 226 auto TI = TypeTable.writeKnownType(SID); 227 return recordTypeIndexForDINode(Scope, TI); 228 } 229 230 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) { 231 assert(SP); 232 233 // Check if we've already translated this subprogram. 234 auto I = TypeIndices.find({SP, nullptr}); 235 if (I != TypeIndices.end()) 236 return I->second; 237 238 // The display name includes function template arguments. Drop them to match 239 // MSVC. 240 StringRef DisplayName = SP->getName().split('<').first; 241 242 const DIScope *Scope = SP->getScope().resolve(); 243 TypeIndex TI; 244 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) { 245 // If the scope is a DICompositeType, then this must be a method. Member 246 // function types take some special handling, and require access to the 247 // subprogram. 248 TypeIndex ClassType = getTypeIndex(Class); 249 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class), 250 DisplayName); 251 TI = TypeTable.writeKnownType(MFuncId); 252 } else { 253 // Otherwise, this must be a free function. 254 TypeIndex ParentScope = getScopeIndex(Scope); 255 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName); 256 TI = TypeTable.writeKnownType(FuncId); 257 } 258 259 return recordTypeIndexForDINode(SP, TI); 260 } 261 262 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP, 263 const DICompositeType *Class) { 264 // Always use the method declaration as the key for the function type. The 265 // method declaration contains the this adjustment. 266 if (SP->getDeclaration()) 267 SP = SP->getDeclaration(); 268 assert(!SP->getDeclaration() && "should use declaration as key"); 269 270 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide 271 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}. 272 auto I = TypeIndices.find({SP, Class}); 273 if (I != TypeIndices.end()) 274 return I->second; 275 276 // Make sure complete type info for the class is emitted *after* the member 277 // function type, as the complete class type is likely to reference this 278 // member function type. 279 TypeLoweringScope S(*this); 280 TypeIndex TI = 281 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment()); 282 return recordTypeIndexForDINode(SP, TI, Class); 283 } 284 285 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, 286 TypeIndex TI, 287 const DIType *ClassTy) { 288 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI}); 289 (void)InsertResult; 290 assert(InsertResult.second && "DINode was already assigned a type index"); 291 return TI; 292 } 293 294 unsigned CodeViewDebug::getPointerSizeInBytes() { 295 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8; 296 } 297 298 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var, 299 const DILocation *InlinedAt) { 300 if (InlinedAt) { 301 // This variable was inlined. Associate it with the InlineSite. 302 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram(); 303 InlineSite &Site = getInlineSite(InlinedAt, Inlinee); 304 Site.InlinedLocals.emplace_back(Var); 305 } else { 306 // This variable goes in the main ProcSym. 307 CurFn->Locals.emplace_back(Var); 308 } 309 } 310 311 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs, 312 const DILocation *Loc) { 313 auto B = Locs.begin(), E = Locs.end(); 314 if (std::find(B, E, Loc) == E) 315 Locs.push_back(Loc); 316 } 317 318 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL, 319 const MachineFunction *MF) { 320 // Skip this instruction if it has the same location as the previous one. 321 if (DL == CurFn->LastLoc) 322 return; 323 324 const DIScope *Scope = DL.get()->getScope(); 325 if (!Scope) 326 return; 327 328 // Skip this line if it is longer than the maximum we can record. 329 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true); 330 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() || 331 LI.isNeverStepInto()) 332 return; 333 334 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0); 335 if (CI.getStartColumn() != DL.getCol()) 336 return; 337 338 if (!CurFn->HaveLineInfo) 339 CurFn->HaveLineInfo = true; 340 unsigned FileId = 0; 341 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile()) 342 FileId = CurFn->LastFileId; 343 else 344 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile()); 345 CurFn->LastLoc = DL; 346 347 unsigned FuncId = CurFn->FuncId; 348 if (const DILocation *SiteLoc = DL->getInlinedAt()) { 349 const DILocation *Loc = DL.get(); 350 351 // If this location was actually inlined from somewhere else, give it the ID 352 // of the inline call site. 353 FuncId = 354 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId; 355 356 // Ensure we have links in the tree of inline call sites. 357 bool FirstLoc = true; 358 while ((SiteLoc = Loc->getInlinedAt())) { 359 InlineSite &Site = 360 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()); 361 if (!FirstLoc) 362 addLocIfNotPresent(Site.ChildSites, Loc); 363 FirstLoc = false; 364 Loc = SiteLoc; 365 } 366 addLocIfNotPresent(CurFn->ChildSites, Loc); 367 } 368 369 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(), 370 /*PrologueEnd=*/false, /*IsStmt=*/false, 371 DL->getFilename(), SMLoc()); 372 } 373 374 void CodeViewDebug::emitCodeViewMagicVersion() { 375 OS.EmitValueToAlignment(4); 376 OS.AddComment("Debug section magic"); 377 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4); 378 } 379 380 void CodeViewDebug::endModule() { 381 if (!Asm || !MMI->hasDebugInfo()) 382 return; 383 384 assert(Asm != nullptr); 385 386 // The COFF .debug$S section consists of several subsections, each starting 387 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length 388 // of the payload followed by the payload itself. The subsections are 4-byte 389 // aligned. 390 391 // Use the generic .debug$S section, and make a subsection for all the inlined 392 // subprograms. 393 switchToDebugSectionForSymbol(nullptr); 394 395 MCSymbol *CompilerInfo = beginCVSubsection(ModuleDebugFragmentKind::Symbols); 396 emitCompilerInformation(); 397 endCVSubsection(CompilerInfo); 398 399 emitInlineeLinesSubsection(); 400 401 // Emit per-function debug information. 402 for (auto &P : FnDebugInfo) 403 if (!P.first->isDeclarationForLinker()) 404 emitDebugInfoForFunction(P.first, P.second); 405 406 // Emit global variable debug information. 407 setCurrentSubprogram(nullptr); 408 emitDebugInfoForGlobals(); 409 410 // Emit retained types. 411 emitDebugInfoForRetainedTypes(); 412 413 // Switch back to the generic .debug$S section after potentially processing 414 // comdat symbol sections. 415 switchToDebugSectionForSymbol(nullptr); 416 417 // Emit UDT records for any types used by global variables. 418 if (!GlobalUDTs.empty()) { 419 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleDebugFragmentKind::Symbols); 420 emitDebugInfoForUDTs(GlobalUDTs); 421 endCVSubsection(SymbolsEnd); 422 } 423 424 // This subsection holds a file index to offset in string table table. 425 OS.AddComment("File index to string table offset subsection"); 426 OS.EmitCVFileChecksumsDirective(); 427 428 // This subsection holds the string table. 429 OS.AddComment("String table"); 430 OS.EmitCVStringTableDirective(); 431 432 // Emit type information last, so that any types we translate while emitting 433 // function info are included. 434 emitTypeInformation(); 435 436 clear(); 437 } 438 439 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) { 440 // The maximum CV record length is 0xFF00. Most of the strings we emit appear 441 // after a fixed length portion of the record. The fixed length portion should 442 // always be less than 0xF00 (3840) bytes, so truncate the string so that the 443 // overall record size is less than the maximum allowed. 444 unsigned MaxFixedRecordLength = 0xF00; 445 SmallString<32> NullTerminatedString( 446 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1)); 447 NullTerminatedString.push_back('\0'); 448 OS.EmitBytes(NullTerminatedString); 449 } 450 451 void CodeViewDebug::emitTypeInformation() { 452 // Do nothing if we have no debug info or if no non-trivial types were emitted 453 // to TypeTable during codegen. 454 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 455 if (!CU_Nodes) 456 return; 457 if (TypeTable.empty()) 458 return; 459 460 // Start the .debug$T section with 0x4. 461 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection()); 462 emitCodeViewMagicVersion(); 463 464 SmallString<8> CommentPrefix; 465 if (OS.isVerboseAsm()) { 466 CommentPrefix += '\t'; 467 CommentPrefix += Asm->MAI->getCommentString(); 468 CommentPrefix += ' '; 469 } 470 471 TypeDatabase TypeDB; 472 CVTypeDumper CVTD(TypeDB); 473 TypeTable.ForEachRecord([&](TypeIndex Index, ArrayRef<uint8_t> Record) { 474 if (OS.isVerboseAsm()) { 475 // Emit a block comment describing the type record for readability. 476 SmallString<512> CommentBlock; 477 raw_svector_ostream CommentOS(CommentBlock); 478 ScopedPrinter SP(CommentOS); 479 SP.setPrefix(CommentPrefix); 480 TypeDumpVisitor TDV(TypeDB, &SP, false); 481 Error E = CVTD.dump(Record, TDV); 482 if (E) { 483 logAllUnhandledErrors(std::move(E), errs(), "error: "); 484 llvm_unreachable("produced malformed type record"); 485 } 486 // emitRawComment will insert its own tab and comment string before 487 // the first line, so strip off our first one. It also prints its own 488 // newline. 489 OS.emitRawComment( 490 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim()); 491 } else { 492 #ifndef NDEBUG 493 // Assert that the type data is valid even if we aren't dumping 494 // comments. The MSVC linker doesn't do much type record validation, 495 // so the first link of an invalid type record can succeed while 496 // subsequent links will fail with LNK1285. 497 BinaryByteStream Stream(Record, llvm::support::little); 498 CVTypeArray Types; 499 BinaryStreamReader Reader(Stream); 500 Error E = Reader.readArray(Types, Reader.getLength()); 501 if (!E) { 502 TypeVisitorCallbacks C; 503 E = CVTypeVisitor(C).visitTypeStream(Types); 504 } 505 if (E) { 506 logAllUnhandledErrors(std::move(E), errs(), "error: "); 507 llvm_unreachable("produced malformed type record"); 508 } 509 #endif 510 } 511 StringRef S(reinterpret_cast<const char *>(Record.data()), Record.size()); 512 OS.EmitBinaryData(S); 513 }); 514 } 515 516 namespace { 517 518 static SourceLanguage MapDWLangToCVLang(unsigned DWLang) { 519 switch (DWLang) { 520 case dwarf::DW_LANG_C: 521 case dwarf::DW_LANG_C89: 522 case dwarf::DW_LANG_C99: 523 case dwarf::DW_LANG_C11: 524 case dwarf::DW_LANG_ObjC: 525 return SourceLanguage::C; 526 case dwarf::DW_LANG_C_plus_plus: 527 case dwarf::DW_LANG_C_plus_plus_03: 528 case dwarf::DW_LANG_C_plus_plus_11: 529 case dwarf::DW_LANG_C_plus_plus_14: 530 return SourceLanguage::Cpp; 531 case dwarf::DW_LANG_Fortran77: 532 case dwarf::DW_LANG_Fortran90: 533 case dwarf::DW_LANG_Fortran03: 534 case dwarf::DW_LANG_Fortran08: 535 return SourceLanguage::Fortran; 536 case dwarf::DW_LANG_Pascal83: 537 return SourceLanguage::Pascal; 538 case dwarf::DW_LANG_Cobol74: 539 case dwarf::DW_LANG_Cobol85: 540 return SourceLanguage::Cobol; 541 case dwarf::DW_LANG_Java: 542 return SourceLanguage::Java; 543 default: 544 // There's no CodeView representation for this language, and CV doesn't 545 // have an "unknown" option for the language field, so we'll use MASM, 546 // as it's very low level. 547 return SourceLanguage::Masm; 548 } 549 } 550 551 struct Version { 552 int Part[4]; 553 }; 554 555 // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out 556 // the version number. 557 static Version parseVersion(StringRef Name) { 558 Version V = {{0}}; 559 int N = 0; 560 for (const char C : Name) { 561 if (isdigit(C)) { 562 V.Part[N] *= 10; 563 V.Part[N] += C - '0'; 564 } else if (C == '.') { 565 ++N; 566 if (N >= 4) 567 return V; 568 } else if (N > 0) 569 return V; 570 } 571 return V; 572 } 573 574 static CPUType mapArchToCVCPUType(Triple::ArchType Type) { 575 switch (Type) { 576 case Triple::ArchType::x86: 577 return CPUType::Pentium3; 578 case Triple::ArchType::x86_64: 579 return CPUType::X64; 580 case Triple::ArchType::thumb: 581 return CPUType::Thumb; 582 default: 583 report_fatal_error("target architecture doesn't map to a CodeView " 584 "CPUType"); 585 } 586 } 587 588 } // anonymous namespace 589 590 void CodeViewDebug::emitCompilerInformation() { 591 MCContext &Context = MMI->getContext(); 592 MCSymbol *CompilerBegin = Context.createTempSymbol(), 593 *CompilerEnd = Context.createTempSymbol(); 594 OS.AddComment("Record length"); 595 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2); 596 OS.EmitLabel(CompilerBegin); 597 OS.AddComment("Record kind: S_COMPILE3"); 598 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2); 599 uint32_t Flags = 0; 600 601 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 602 const MDNode *Node = *CUs->operands().begin(); 603 const auto *CU = cast<DICompileUnit>(Node); 604 605 // The low byte of the flags indicates the source language. 606 Flags = MapDWLangToCVLang(CU->getSourceLanguage()); 607 // TODO: Figure out which other flags need to be set. 608 609 OS.AddComment("Flags and language"); 610 OS.EmitIntValue(Flags, 4); 611 612 OS.AddComment("CPUType"); 613 CPUType CPU = 614 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch()); 615 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2); 616 617 StringRef CompilerVersion = CU->getProducer(); 618 Version FrontVer = parseVersion(CompilerVersion); 619 OS.AddComment("Frontend version"); 620 for (int N = 0; N < 4; ++N) 621 OS.EmitIntValue(FrontVer.Part[N], 2); 622 623 // Some Microsoft tools, like Binscope, expect a backend version number of at 624 // least 8.something, so we'll coerce the LLVM version into a form that 625 // guarantees it'll be big enough without really lying about the version. 626 int Major = 1000 * LLVM_VERSION_MAJOR + 627 10 * LLVM_VERSION_MINOR + 628 LLVM_VERSION_PATCH; 629 // Clamp it for builds that use unusually large version numbers. 630 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max()); 631 Version BackVer = {{ Major, 0, 0, 0 }}; 632 OS.AddComment("Backend version"); 633 for (int N = 0; N < 4; ++N) 634 OS.EmitIntValue(BackVer.Part[N], 2); 635 636 OS.AddComment("Null-terminated compiler version string"); 637 emitNullTerminatedSymbolName(OS, CompilerVersion); 638 639 OS.EmitLabel(CompilerEnd); 640 } 641 642 void CodeViewDebug::emitInlineeLinesSubsection() { 643 if (InlinedSubprograms.empty()) 644 return; 645 646 OS.AddComment("Inlinee lines subsection"); 647 MCSymbol *InlineEnd = 648 beginCVSubsection(ModuleDebugFragmentKind::InlineeLines); 649 650 // We don't provide any extra file info. 651 // FIXME: Find out if debuggers use this info. 652 OS.AddComment("Inlinee lines signature"); 653 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4); 654 655 for (const DISubprogram *SP : InlinedSubprograms) { 656 assert(TypeIndices.count({SP, nullptr})); 657 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}]; 658 659 OS.AddBlankLine(); 660 unsigned FileId = maybeRecordFile(SP->getFile()); 661 OS.AddComment("Inlined function " + SP->getName() + " starts at " + 662 SP->getFilename() + Twine(':') + Twine(SP->getLine())); 663 OS.AddBlankLine(); 664 // The filechecksum table uses 8 byte entries for now, and file ids start at 665 // 1. 666 unsigned FileOffset = (FileId - 1) * 8; 667 OS.AddComment("Type index of inlined function"); 668 OS.EmitIntValue(InlineeIdx.getIndex(), 4); 669 OS.AddComment("Offset into filechecksum table"); 670 OS.EmitIntValue(FileOffset, 4); 671 OS.AddComment("Starting line number"); 672 OS.EmitIntValue(SP->getLine(), 4); 673 } 674 675 endCVSubsection(InlineEnd); 676 } 677 678 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI, 679 const DILocation *InlinedAt, 680 const InlineSite &Site) { 681 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(), 682 *InlineEnd = MMI->getContext().createTempSymbol(); 683 684 assert(TypeIndices.count({Site.Inlinee, nullptr})); 685 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}]; 686 687 // SymbolRecord 688 OS.AddComment("Record length"); 689 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength 690 OS.EmitLabel(InlineBegin); 691 OS.AddComment("Record kind: S_INLINESITE"); 692 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind 693 694 OS.AddComment("PtrParent"); 695 OS.EmitIntValue(0, 4); 696 OS.AddComment("PtrEnd"); 697 OS.EmitIntValue(0, 4); 698 OS.AddComment("Inlinee type index"); 699 OS.EmitIntValue(InlineeIdx.getIndex(), 4); 700 701 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile()); 702 unsigned StartLineNum = Site.Inlinee->getLine(); 703 704 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum, 705 FI.Begin, FI.End); 706 707 OS.EmitLabel(InlineEnd); 708 709 emitLocalVariableList(Site.InlinedLocals); 710 711 // Recurse on child inlined call sites before closing the scope. 712 for (const DILocation *ChildSite : Site.ChildSites) { 713 auto I = FI.InlineSites.find(ChildSite); 714 assert(I != FI.InlineSites.end() && 715 "child site not in function inline site map"); 716 emitInlinedCallSite(FI, ChildSite, I->second); 717 } 718 719 // Close the scope. 720 OS.AddComment("Record length"); 721 OS.EmitIntValue(2, 2); // RecordLength 722 OS.AddComment("Record kind: S_INLINESITE_END"); 723 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind 724 } 725 726 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) { 727 // If we have a symbol, it may be in a section that is COMDAT. If so, find the 728 // comdat key. A section may be comdat because of -ffunction-sections or 729 // because it is comdat in the IR. 730 MCSectionCOFF *GVSec = 731 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr; 732 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr; 733 734 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>( 735 Asm->getObjFileLowering().getCOFFDebugSymbolsSection()); 736 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym); 737 738 OS.SwitchSection(DebugSec); 739 740 // Emit the magic version number if this is the first time we've switched to 741 // this section. 742 if (ComdatDebugSections.insert(DebugSec).second) 743 emitCodeViewMagicVersion(); 744 } 745 746 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV, 747 FunctionInfo &FI) { 748 // For each function there is a separate subsection 749 // which holds the PC to file:line table. 750 const MCSymbol *Fn = Asm->getSymbol(GV); 751 assert(Fn); 752 753 // Switch to the to a comdat section, if appropriate. 754 switchToDebugSectionForSymbol(Fn); 755 756 std::string FuncName; 757 auto *SP = GV->getSubprogram(); 758 assert(SP); 759 setCurrentSubprogram(SP); 760 761 // If we have a display name, build the fully qualified name by walking the 762 // chain of scopes. 763 if (!SP->getName().empty()) 764 FuncName = 765 getFullyQualifiedName(SP->getScope().resolve(), SP->getName()); 766 767 // If our DISubprogram name is empty, use the mangled name. 768 if (FuncName.empty()) 769 FuncName = GlobalValue::getRealLinkageName(GV->getName()); 770 771 // Emit a symbol subsection, required by VS2012+ to find function boundaries. 772 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 773 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleDebugFragmentKind::Symbols); 774 { 775 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(), 776 *ProcRecordEnd = MMI->getContext().createTempSymbol(); 777 OS.AddComment("Record length"); 778 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2); 779 OS.EmitLabel(ProcRecordBegin); 780 781 if (GV->hasLocalLinkage()) { 782 OS.AddComment("Record kind: S_LPROC32_ID"); 783 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2); 784 } else { 785 OS.AddComment("Record kind: S_GPROC32_ID"); 786 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2); 787 } 788 789 // These fields are filled in by tools like CVPACK which run after the fact. 790 OS.AddComment("PtrParent"); 791 OS.EmitIntValue(0, 4); 792 OS.AddComment("PtrEnd"); 793 OS.EmitIntValue(0, 4); 794 OS.AddComment("PtrNext"); 795 OS.EmitIntValue(0, 4); 796 // This is the important bit that tells the debugger where the function 797 // code is located and what's its size: 798 OS.AddComment("Code size"); 799 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4); 800 OS.AddComment("Offset after prologue"); 801 OS.EmitIntValue(0, 4); 802 OS.AddComment("Offset before epilogue"); 803 OS.EmitIntValue(0, 4); 804 OS.AddComment("Function type index"); 805 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4); 806 OS.AddComment("Function section relative address"); 807 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0); 808 OS.AddComment("Function section index"); 809 OS.EmitCOFFSectionIndex(Fn); 810 OS.AddComment("Flags"); 811 OS.EmitIntValue(0, 1); 812 // Emit the function display name as a null-terminated string. 813 OS.AddComment("Function name"); 814 // Truncate the name so we won't overflow the record length field. 815 emitNullTerminatedSymbolName(OS, FuncName); 816 OS.EmitLabel(ProcRecordEnd); 817 818 emitLocalVariableList(FI.Locals); 819 820 // Emit inlined call site information. Only emit functions inlined directly 821 // into the parent function. We'll emit the other sites recursively as part 822 // of their parent inline site. 823 for (const DILocation *InlinedAt : FI.ChildSites) { 824 auto I = FI.InlineSites.find(InlinedAt); 825 assert(I != FI.InlineSites.end() && 826 "child site not in function inline site map"); 827 emitInlinedCallSite(FI, InlinedAt, I->second); 828 } 829 830 if (SP != nullptr) 831 emitDebugInfoForUDTs(LocalUDTs); 832 833 // We're done with this function. 834 OS.AddComment("Record length"); 835 OS.EmitIntValue(0x0002, 2); 836 OS.AddComment("Record kind: S_PROC_ID_END"); 837 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2); 838 } 839 endCVSubsection(SymbolsEnd); 840 841 // We have an assembler directive that takes care of the whole line table. 842 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End); 843 } 844 845 CodeViewDebug::LocalVarDefRange 846 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) { 847 LocalVarDefRange DR; 848 DR.InMemory = -1; 849 DR.DataOffset = Offset; 850 assert(DR.DataOffset == Offset && "truncation"); 851 DR.IsSubfield = 0; 852 DR.StructOffset = 0; 853 DR.CVRegister = CVRegister; 854 return DR; 855 } 856 857 CodeViewDebug::LocalVarDefRange 858 CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory, 859 int Offset, bool IsSubfield, 860 uint16_t StructOffset) { 861 LocalVarDefRange DR; 862 DR.InMemory = InMemory; 863 DR.DataOffset = Offset; 864 DR.IsSubfield = IsSubfield; 865 DR.StructOffset = StructOffset; 866 DR.CVRegister = CVRegister; 867 return DR; 868 } 869 870 void CodeViewDebug::collectVariableInfoFromMFTable( 871 DenseSet<InlinedVariable> &Processed) { 872 const MachineFunction &MF = *Asm->MF; 873 const TargetSubtargetInfo &TSI = MF.getSubtarget(); 874 const TargetFrameLowering *TFI = TSI.getFrameLowering(); 875 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 876 877 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) { 878 if (!VI.Var) 879 continue; 880 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 881 "Expected inlined-at fields to agree"); 882 883 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt())); 884 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 885 886 // If variable scope is not found then skip this variable. 887 if (!Scope) 888 continue; 889 890 // Get the frame register used and the offset. 891 unsigned FrameReg = 0; 892 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg); 893 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg); 894 895 // Calculate the label ranges. 896 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset); 897 for (const InsnRange &Range : Scope->getRanges()) { 898 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 899 const MCSymbol *End = getLabelAfterInsn(Range.second); 900 End = End ? End : Asm->getFunctionEnd(); 901 DefRange.Ranges.emplace_back(Begin, End); 902 } 903 904 LocalVariable Var; 905 Var.DIVar = VI.Var; 906 Var.DefRanges.emplace_back(std::move(DefRange)); 907 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt()); 908 } 909 } 910 911 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) { 912 DenseSet<InlinedVariable> Processed; 913 // Grab the variable info that was squirreled away in the MMI side-table. 914 collectVariableInfoFromMFTable(Processed); 915 916 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo(); 917 918 for (const auto &I : DbgValues) { 919 InlinedVariable IV = I.first; 920 if (Processed.count(IV)) 921 continue; 922 const DILocalVariable *DIVar = IV.first; 923 const DILocation *InlinedAt = IV.second; 924 925 // Instruction ranges, specifying where IV is accessible. 926 const auto &Ranges = I.second; 927 928 LexicalScope *Scope = nullptr; 929 if (InlinedAt) 930 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt); 931 else 932 Scope = LScopes.findLexicalScope(DIVar->getScope()); 933 // If variable scope is not found then skip this variable. 934 if (!Scope) 935 continue; 936 937 LocalVariable Var; 938 Var.DIVar = DIVar; 939 940 // Calculate the definition ranges. 941 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 942 const InsnRange &Range = *I; 943 const MachineInstr *DVInst = Range.first; 944 assert(DVInst->isDebugValue() && "Invalid History entry"); 945 const DIExpression *DIExpr = DVInst->getDebugExpression(); 946 bool IsSubfield = false; 947 unsigned StructOffset = 0; 948 949 // Handle fragments. 950 auto Fragment = DIExpr->getFragmentInfo(); 951 if (Fragment) { 952 IsSubfield = true; 953 StructOffset = Fragment->OffsetInBits / 8; 954 } else if (DIExpr->getNumElements() > 0) { 955 continue; // Ignore unrecognized exprs. 956 } 957 958 // Bail if operand 0 is not a valid register. This means the variable is a 959 // simple constant, or is described by a complex expression. 960 // FIXME: Find a way to represent constant variables, since they are 961 // relatively common. 962 unsigned Reg = 963 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0; 964 if (Reg == 0) 965 continue; 966 967 // Handle the two cases we can handle: indirect in memory and in register. 968 unsigned CVReg = TRI->getCodeViewRegNum(Reg); 969 bool InMemory = DVInst->getOperand(1).isImm(); 970 int Offset = InMemory ? DVInst->getOperand(1).getImm() : 0; 971 { 972 LocalVarDefRange DR; 973 DR.CVRegister = CVReg; 974 DR.InMemory = InMemory; 975 DR.DataOffset = Offset; 976 DR.IsSubfield = IsSubfield; 977 DR.StructOffset = StructOffset; 978 979 if (Var.DefRanges.empty() || 980 Var.DefRanges.back().isDifferentLocation(DR)) { 981 Var.DefRanges.emplace_back(std::move(DR)); 982 } 983 } 984 985 // Compute the label range. 986 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 987 const MCSymbol *End = getLabelAfterInsn(Range.second); 988 if (!End) { 989 // This range is valid until the next overlapping bitpiece. In the 990 // common case, ranges will not be bitpieces, so they will overlap. 991 auto J = std::next(I); 992 while (J != E && 993 !fragmentsOverlap(DIExpr, J->first->getDebugExpression())) 994 ++J; 995 if (J != E) 996 End = getLabelBeforeInsn(J->first); 997 else 998 End = Asm->getFunctionEnd(); 999 } 1000 1001 // If the last range end is our begin, just extend the last range. 1002 // Otherwise make a new range. 1003 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges = 1004 Var.DefRanges.back().Ranges; 1005 if (!Ranges.empty() && Ranges.back().second == Begin) 1006 Ranges.back().second = End; 1007 else 1008 Ranges.emplace_back(Begin, End); 1009 1010 // FIXME: Do more range combining. 1011 } 1012 1013 recordLocalVariable(std::move(Var), InlinedAt); 1014 } 1015 } 1016 1017 void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) { 1018 const Function *GV = MF->getFunction(); 1019 assert(FnDebugInfo.count(GV) == false); 1020 CurFn = &FnDebugInfo[GV]; 1021 CurFn->FuncId = NextFuncId++; 1022 CurFn->Begin = Asm->getFunctionBegin(); 1023 1024 OS.EmitCVFuncIdDirective(CurFn->FuncId); 1025 1026 // Find the end of the function prolog. First known non-DBG_VALUE and 1027 // non-frame setup location marks the beginning of the function body. 1028 // FIXME: is there a simpler a way to do this? Can we just search 1029 // for the first instruction of the function, not the last of the prolog? 1030 DebugLoc PrologEndLoc; 1031 bool EmptyPrologue = true; 1032 for (const auto &MBB : *MF) { 1033 for (const auto &MI : MBB) { 1034 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) && 1035 MI.getDebugLoc()) { 1036 PrologEndLoc = MI.getDebugLoc(); 1037 break; 1038 } else if (!MI.isDebugValue()) { 1039 EmptyPrologue = false; 1040 } 1041 } 1042 } 1043 1044 // Record beginning of function if we have a non-empty prologue. 1045 if (PrologEndLoc && !EmptyPrologue) { 1046 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc(); 1047 maybeRecordLocation(FnStartDL, MF); 1048 } 1049 } 1050 1051 void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) { 1052 // Don't record empty UDTs. 1053 if (Ty->getName().empty()) 1054 return; 1055 1056 SmallVector<StringRef, 5> QualifiedNameComponents; 1057 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents( 1058 Ty->getScope().resolve(), QualifiedNameComponents); 1059 1060 std::string FullyQualifiedName = 1061 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty)); 1062 1063 if (ClosestSubprogram == nullptr) 1064 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI); 1065 else if (ClosestSubprogram == CurrentSubprogram) 1066 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI); 1067 1068 // TODO: What if the ClosestSubprogram is neither null or the current 1069 // subprogram? Currently, the UDT just gets dropped on the floor. 1070 // 1071 // The current behavior is not desirable. To get maximal fidelity, we would 1072 // need to perform all type translation before beginning emission of .debug$S 1073 // and then make LocalUDTs a member of FunctionInfo 1074 } 1075 1076 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) { 1077 // Generic dispatch for lowering an unknown type. 1078 switch (Ty->getTag()) { 1079 case dwarf::DW_TAG_array_type: 1080 return lowerTypeArray(cast<DICompositeType>(Ty)); 1081 case dwarf::DW_TAG_typedef: 1082 return lowerTypeAlias(cast<DIDerivedType>(Ty)); 1083 case dwarf::DW_TAG_base_type: 1084 return lowerTypeBasic(cast<DIBasicType>(Ty)); 1085 case dwarf::DW_TAG_pointer_type: 1086 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type") 1087 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty)); 1088 LLVM_FALLTHROUGH; 1089 case dwarf::DW_TAG_reference_type: 1090 case dwarf::DW_TAG_rvalue_reference_type: 1091 return lowerTypePointer(cast<DIDerivedType>(Ty)); 1092 case dwarf::DW_TAG_ptr_to_member_type: 1093 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty)); 1094 case dwarf::DW_TAG_const_type: 1095 case dwarf::DW_TAG_volatile_type: 1096 // TODO: add support for DW_TAG_atomic_type here 1097 return lowerTypeModifier(cast<DIDerivedType>(Ty)); 1098 case dwarf::DW_TAG_subroutine_type: 1099 if (ClassTy) { 1100 // The member function type of a member function pointer has no 1101 // ThisAdjustment. 1102 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy, 1103 /*ThisAdjustment=*/0); 1104 } 1105 return lowerTypeFunction(cast<DISubroutineType>(Ty)); 1106 case dwarf::DW_TAG_enumeration_type: 1107 return lowerTypeEnum(cast<DICompositeType>(Ty)); 1108 case dwarf::DW_TAG_class_type: 1109 case dwarf::DW_TAG_structure_type: 1110 return lowerTypeClass(cast<DICompositeType>(Ty)); 1111 case dwarf::DW_TAG_union_type: 1112 return lowerTypeUnion(cast<DICompositeType>(Ty)); 1113 default: 1114 // Use the null type index. 1115 return TypeIndex(); 1116 } 1117 } 1118 1119 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) { 1120 DITypeRef UnderlyingTypeRef = Ty->getBaseType(); 1121 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef); 1122 StringRef TypeName = Ty->getName(); 1123 1124 addToUDTs(Ty, UnderlyingTypeIndex); 1125 1126 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) && 1127 TypeName == "HRESULT") 1128 return TypeIndex(SimpleTypeKind::HResult); 1129 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) && 1130 TypeName == "wchar_t") 1131 return TypeIndex(SimpleTypeKind::WideCharacter); 1132 1133 return UnderlyingTypeIndex; 1134 } 1135 1136 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) { 1137 DITypeRef ElementTypeRef = Ty->getBaseType(); 1138 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef); 1139 // IndexType is size_t, which depends on the bitness of the target. 1140 TypeIndex IndexType = Asm->TM.getPointerSize() == 8 1141 ? TypeIndex(SimpleTypeKind::UInt64Quad) 1142 : TypeIndex(SimpleTypeKind::UInt32Long); 1143 1144 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8; 1145 1146 // Add subranges to array type. 1147 DINodeArray Elements = Ty->getElements(); 1148 for (int i = Elements.size() - 1; i >= 0; --i) { 1149 const DINode *Element = Elements[i]; 1150 assert(Element->getTag() == dwarf::DW_TAG_subrange_type); 1151 1152 const DISubrange *Subrange = cast<DISubrange>(Element); 1153 assert(Subrange->getLowerBound() == 0 && 1154 "codeview doesn't support subranges with lower bounds"); 1155 int64_t Count = Subrange->getCount(); 1156 1157 // Variable Length Array (VLA) has Count equal to '-1'. 1158 // Replace with Count '1', assume it is the minimum VLA length. 1159 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU. 1160 if (Count == -1) 1161 Count = 1; 1162 1163 // Update the element size and element type index for subsequent subranges. 1164 ElementSize *= Count; 1165 1166 // If this is the outermost array, use the size from the array. It will be 1167 // more accurate if we had a VLA or an incomplete element type size. 1168 uint64_t ArraySize = 1169 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize; 1170 1171 StringRef Name = (i == 0) ? Ty->getName() : ""; 1172 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name); 1173 ElementTypeIndex = TypeTable.writeKnownType(AR); 1174 } 1175 1176 return ElementTypeIndex; 1177 } 1178 1179 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) { 1180 TypeIndex Index; 1181 dwarf::TypeKind Kind; 1182 uint32_t ByteSize; 1183 1184 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding()); 1185 ByteSize = Ty->getSizeInBits() / 8; 1186 1187 SimpleTypeKind STK = SimpleTypeKind::None; 1188 switch (Kind) { 1189 case dwarf::DW_ATE_address: 1190 // FIXME: Translate 1191 break; 1192 case dwarf::DW_ATE_boolean: 1193 switch (ByteSize) { 1194 case 1: STK = SimpleTypeKind::Boolean8; break; 1195 case 2: STK = SimpleTypeKind::Boolean16; break; 1196 case 4: STK = SimpleTypeKind::Boolean32; break; 1197 case 8: STK = SimpleTypeKind::Boolean64; break; 1198 case 16: STK = SimpleTypeKind::Boolean128; break; 1199 } 1200 break; 1201 case dwarf::DW_ATE_complex_float: 1202 switch (ByteSize) { 1203 case 2: STK = SimpleTypeKind::Complex16; break; 1204 case 4: STK = SimpleTypeKind::Complex32; break; 1205 case 8: STK = SimpleTypeKind::Complex64; break; 1206 case 10: STK = SimpleTypeKind::Complex80; break; 1207 case 16: STK = SimpleTypeKind::Complex128; break; 1208 } 1209 break; 1210 case dwarf::DW_ATE_float: 1211 switch (ByteSize) { 1212 case 2: STK = SimpleTypeKind::Float16; break; 1213 case 4: STK = SimpleTypeKind::Float32; break; 1214 case 6: STK = SimpleTypeKind::Float48; break; 1215 case 8: STK = SimpleTypeKind::Float64; break; 1216 case 10: STK = SimpleTypeKind::Float80; break; 1217 case 16: STK = SimpleTypeKind::Float128; break; 1218 } 1219 break; 1220 case dwarf::DW_ATE_signed: 1221 switch (ByteSize) { 1222 case 1: STK = SimpleTypeKind::SignedCharacter; break; 1223 case 2: STK = SimpleTypeKind::Int16Short; break; 1224 case 4: STK = SimpleTypeKind::Int32; break; 1225 case 8: STK = SimpleTypeKind::Int64Quad; break; 1226 case 16: STK = SimpleTypeKind::Int128Oct; break; 1227 } 1228 break; 1229 case dwarf::DW_ATE_unsigned: 1230 switch (ByteSize) { 1231 case 1: STK = SimpleTypeKind::UnsignedCharacter; break; 1232 case 2: STK = SimpleTypeKind::UInt16Short; break; 1233 case 4: STK = SimpleTypeKind::UInt32; break; 1234 case 8: STK = SimpleTypeKind::UInt64Quad; break; 1235 case 16: STK = SimpleTypeKind::UInt128Oct; break; 1236 } 1237 break; 1238 case dwarf::DW_ATE_UTF: 1239 switch (ByteSize) { 1240 case 2: STK = SimpleTypeKind::Character16; break; 1241 case 4: STK = SimpleTypeKind::Character32; break; 1242 } 1243 break; 1244 case dwarf::DW_ATE_signed_char: 1245 if (ByteSize == 1) 1246 STK = SimpleTypeKind::SignedCharacter; 1247 break; 1248 case dwarf::DW_ATE_unsigned_char: 1249 if (ByteSize == 1) 1250 STK = SimpleTypeKind::UnsignedCharacter; 1251 break; 1252 default: 1253 break; 1254 } 1255 1256 // Apply some fixups based on the source-level type name. 1257 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int") 1258 STK = SimpleTypeKind::Int32Long; 1259 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int") 1260 STK = SimpleTypeKind::UInt32Long; 1261 if (STK == SimpleTypeKind::UInt16Short && 1262 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t")) 1263 STK = SimpleTypeKind::WideCharacter; 1264 if ((STK == SimpleTypeKind::SignedCharacter || 1265 STK == SimpleTypeKind::UnsignedCharacter) && 1266 Ty->getName() == "char") 1267 STK = SimpleTypeKind::NarrowCharacter; 1268 1269 return TypeIndex(STK); 1270 } 1271 1272 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) { 1273 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType()); 1274 1275 // Pointers to simple types can use SimpleTypeMode, rather than having a 1276 // dedicated pointer type record. 1277 if (PointeeTI.isSimple() && 1278 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct && 1279 Ty->getTag() == dwarf::DW_TAG_pointer_type) { 1280 SimpleTypeMode Mode = Ty->getSizeInBits() == 64 1281 ? SimpleTypeMode::NearPointer64 1282 : SimpleTypeMode::NearPointer32; 1283 return TypeIndex(PointeeTI.getSimpleKind(), Mode); 1284 } 1285 1286 PointerKind PK = 1287 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32; 1288 PointerMode PM = PointerMode::Pointer; 1289 switch (Ty->getTag()) { 1290 default: llvm_unreachable("not a pointer tag type"); 1291 case dwarf::DW_TAG_pointer_type: 1292 PM = PointerMode::Pointer; 1293 break; 1294 case dwarf::DW_TAG_reference_type: 1295 PM = PointerMode::LValueReference; 1296 break; 1297 case dwarf::DW_TAG_rvalue_reference_type: 1298 PM = PointerMode::RValueReference; 1299 break; 1300 } 1301 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method 1302 // 'this' pointer, but not normal contexts. Figure out what we're supposed to 1303 // do. 1304 PointerOptions PO = PointerOptions::None; 1305 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8); 1306 return TypeTable.writeKnownType(PR); 1307 } 1308 1309 static PointerToMemberRepresentation 1310 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) { 1311 // SizeInBytes being zero generally implies that the member pointer type was 1312 // incomplete, which can happen if it is part of a function prototype. In this 1313 // case, use the unknown model instead of the general model. 1314 if (IsPMF) { 1315 switch (Flags & DINode::FlagPtrToMemberRep) { 1316 case 0: 1317 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1318 : PointerToMemberRepresentation::GeneralFunction; 1319 case DINode::FlagSingleInheritance: 1320 return PointerToMemberRepresentation::SingleInheritanceFunction; 1321 case DINode::FlagMultipleInheritance: 1322 return PointerToMemberRepresentation::MultipleInheritanceFunction; 1323 case DINode::FlagVirtualInheritance: 1324 return PointerToMemberRepresentation::VirtualInheritanceFunction; 1325 } 1326 } else { 1327 switch (Flags & DINode::FlagPtrToMemberRep) { 1328 case 0: 1329 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1330 : PointerToMemberRepresentation::GeneralData; 1331 case DINode::FlagSingleInheritance: 1332 return PointerToMemberRepresentation::SingleInheritanceData; 1333 case DINode::FlagMultipleInheritance: 1334 return PointerToMemberRepresentation::MultipleInheritanceData; 1335 case DINode::FlagVirtualInheritance: 1336 return PointerToMemberRepresentation::VirtualInheritanceData; 1337 } 1338 } 1339 llvm_unreachable("invalid ptr to member representation"); 1340 } 1341 1342 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) { 1343 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type); 1344 TypeIndex ClassTI = getTypeIndex(Ty->getClassType()); 1345 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType()); 1346 PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64 1347 : PointerKind::Near32; 1348 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType()); 1349 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction 1350 : PointerMode::PointerToDataMember; 1351 PointerOptions PO = PointerOptions::None; // FIXME 1352 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big"); 1353 uint8_t SizeInBytes = Ty->getSizeInBits() / 8; 1354 MemberPointerInfo MPI( 1355 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags())); 1356 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI); 1357 return TypeTable.writeKnownType(PR); 1358 } 1359 1360 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't 1361 /// have a translation, use the NearC convention. 1362 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) { 1363 switch (DwarfCC) { 1364 case dwarf::DW_CC_normal: return CallingConvention::NearC; 1365 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast; 1366 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall; 1367 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall; 1368 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal; 1369 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector; 1370 } 1371 return CallingConvention::NearC; 1372 } 1373 1374 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) { 1375 ModifierOptions Mods = ModifierOptions::None; 1376 bool IsModifier = true; 1377 const DIType *BaseTy = Ty; 1378 while (IsModifier && BaseTy) { 1379 // FIXME: Need to add DWARF tags for __unaligned and _Atomic 1380 switch (BaseTy->getTag()) { 1381 case dwarf::DW_TAG_const_type: 1382 Mods |= ModifierOptions::Const; 1383 break; 1384 case dwarf::DW_TAG_volatile_type: 1385 Mods |= ModifierOptions::Volatile; 1386 break; 1387 default: 1388 IsModifier = false; 1389 break; 1390 } 1391 if (IsModifier) 1392 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve(); 1393 } 1394 TypeIndex ModifiedTI = getTypeIndex(BaseTy); 1395 ModifierRecord MR(ModifiedTI, Mods); 1396 return TypeTable.writeKnownType(MR); 1397 } 1398 1399 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) { 1400 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices; 1401 for (DITypeRef ArgTypeRef : Ty->getTypeArray()) 1402 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef)); 1403 1404 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 1405 ArrayRef<TypeIndex> ArgTypeIndices = None; 1406 if (!ReturnAndArgTypeIndices.empty()) { 1407 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices); 1408 ReturnTypeIndex = ReturnAndArgTypesRef.front(); 1409 ArgTypeIndices = ReturnAndArgTypesRef.drop_front(); 1410 } 1411 1412 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 1413 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec); 1414 1415 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 1416 1417 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None, 1418 ArgTypeIndices.size(), ArgListIndex); 1419 return TypeTable.writeKnownType(Procedure); 1420 } 1421 1422 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty, 1423 const DIType *ClassTy, 1424 int ThisAdjustment) { 1425 // Lower the containing class type. 1426 TypeIndex ClassType = getTypeIndex(ClassTy); 1427 1428 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices; 1429 for (DITypeRef ArgTypeRef : Ty->getTypeArray()) 1430 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef)); 1431 1432 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 1433 ArrayRef<TypeIndex> ArgTypeIndices = None; 1434 if (!ReturnAndArgTypeIndices.empty()) { 1435 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices); 1436 ReturnTypeIndex = ReturnAndArgTypesRef.front(); 1437 ArgTypeIndices = ReturnAndArgTypesRef.drop_front(); 1438 } 1439 TypeIndex ThisTypeIndex = TypeIndex::Void(); 1440 if (!ArgTypeIndices.empty()) { 1441 ThisTypeIndex = ArgTypeIndices.front(); 1442 ArgTypeIndices = ArgTypeIndices.drop_front(); 1443 } 1444 1445 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 1446 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec); 1447 1448 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 1449 1450 // TODO: Need to use the correct values for: 1451 // FunctionOptions 1452 // ThisPointerAdjustment. 1453 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, 1454 FunctionOptions::None, ArgTypeIndices.size(), 1455 ArgListIndex, ThisAdjustment); 1456 TypeIndex TI = TypeTable.writeKnownType(MFR); 1457 1458 return TI; 1459 } 1460 1461 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) { 1462 unsigned VSlotCount = 1463 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize()); 1464 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near); 1465 1466 VFTableShapeRecord VFTSR(Slots); 1467 return TypeTable.writeKnownType(VFTSR); 1468 } 1469 1470 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) { 1471 switch (Flags & DINode::FlagAccessibility) { 1472 case DINode::FlagPrivate: return MemberAccess::Private; 1473 case DINode::FlagPublic: return MemberAccess::Public; 1474 case DINode::FlagProtected: return MemberAccess::Protected; 1475 case 0: 1476 // If there was no explicit access control, provide the default for the tag. 1477 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private 1478 : MemberAccess::Public; 1479 } 1480 llvm_unreachable("access flags are exclusive"); 1481 } 1482 1483 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) { 1484 if (SP->isArtificial()) 1485 return MethodOptions::CompilerGenerated; 1486 1487 // FIXME: Handle other MethodOptions. 1488 1489 return MethodOptions::None; 1490 } 1491 1492 static MethodKind translateMethodKindFlags(const DISubprogram *SP, 1493 bool Introduced) { 1494 switch (SP->getVirtuality()) { 1495 case dwarf::DW_VIRTUALITY_none: 1496 break; 1497 case dwarf::DW_VIRTUALITY_virtual: 1498 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual; 1499 case dwarf::DW_VIRTUALITY_pure_virtual: 1500 return Introduced ? MethodKind::PureIntroducingVirtual 1501 : MethodKind::PureVirtual; 1502 default: 1503 llvm_unreachable("unhandled virtuality case"); 1504 } 1505 1506 // FIXME: Get Clang to mark DISubprogram as static and do something with it. 1507 1508 return MethodKind::Vanilla; 1509 } 1510 1511 static TypeRecordKind getRecordKind(const DICompositeType *Ty) { 1512 switch (Ty->getTag()) { 1513 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class; 1514 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct; 1515 } 1516 llvm_unreachable("unexpected tag"); 1517 } 1518 1519 /// Return ClassOptions that should be present on both the forward declaration 1520 /// and the defintion of a tag type. 1521 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) { 1522 ClassOptions CO = ClassOptions::None; 1523 1524 // MSVC always sets this flag, even for local types. Clang doesn't always 1525 // appear to give every type a linkage name, which may be problematic for us. 1526 // FIXME: Investigate the consequences of not following them here. 1527 if (!Ty->getIdentifier().empty()) 1528 CO |= ClassOptions::HasUniqueName; 1529 1530 // Put the Nested flag on a type if it appears immediately inside a tag type. 1531 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass 1532 // here. That flag is only set on definitions, and not forward declarations. 1533 const DIScope *ImmediateScope = Ty->getScope().resolve(); 1534 if (ImmediateScope && isa<DICompositeType>(ImmediateScope)) 1535 CO |= ClassOptions::Nested; 1536 1537 // Put the Scoped flag on function-local types. 1538 for (const DIScope *Scope = ImmediateScope; Scope != nullptr; 1539 Scope = Scope->getScope().resolve()) { 1540 if (isa<DISubprogram>(Scope)) { 1541 CO |= ClassOptions::Scoped; 1542 break; 1543 } 1544 } 1545 1546 return CO; 1547 } 1548 1549 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) { 1550 ClassOptions CO = getCommonClassOptions(Ty); 1551 TypeIndex FTI; 1552 unsigned EnumeratorCount = 0; 1553 1554 if (Ty->isForwardDecl()) { 1555 CO |= ClassOptions::ForwardReference; 1556 } else { 1557 FieldListRecordBuilder FLRB(TypeTable); 1558 1559 FLRB.begin(); 1560 for (const DINode *Element : Ty->getElements()) { 1561 // We assume that the frontend provides all members in source declaration 1562 // order, which is what MSVC does. 1563 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) { 1564 EnumeratorRecord ER(MemberAccess::Public, 1565 APSInt::getUnsigned(Enumerator->getValue()), 1566 Enumerator->getName()); 1567 FLRB.writeMemberType(ER); 1568 EnumeratorCount++; 1569 } 1570 } 1571 FTI = FLRB.end(); 1572 } 1573 1574 std::string FullName = getFullyQualifiedName(Ty); 1575 1576 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(), 1577 getTypeIndex(Ty->getBaseType())); 1578 return TypeTable.writeKnownType(ER); 1579 } 1580 1581 //===----------------------------------------------------------------------===// 1582 // ClassInfo 1583 //===----------------------------------------------------------------------===// 1584 1585 struct llvm::ClassInfo { 1586 struct MemberInfo { 1587 const DIDerivedType *MemberTypeNode; 1588 uint64_t BaseOffset; 1589 }; 1590 // [MemberInfo] 1591 typedef std::vector<MemberInfo> MemberList; 1592 1593 typedef TinyPtrVector<const DISubprogram *> MethodsList; 1594 // MethodName -> MethodsList 1595 typedef MapVector<MDString *, MethodsList> MethodsMap; 1596 1597 /// Base classes. 1598 std::vector<const DIDerivedType *> Inheritance; 1599 1600 /// Direct members. 1601 MemberList Members; 1602 // Direct overloaded methods gathered by name. 1603 MethodsMap Methods; 1604 1605 TypeIndex VShapeTI; 1606 1607 std::vector<const DICompositeType *> NestedClasses; 1608 }; 1609 1610 void CodeViewDebug::clear() { 1611 assert(CurFn == nullptr); 1612 FileIdMap.clear(); 1613 FnDebugInfo.clear(); 1614 FileToFilepathMap.clear(); 1615 LocalUDTs.clear(); 1616 GlobalUDTs.clear(); 1617 TypeIndices.clear(); 1618 CompleteTypeIndices.clear(); 1619 } 1620 1621 void CodeViewDebug::collectMemberInfo(ClassInfo &Info, 1622 const DIDerivedType *DDTy) { 1623 if (!DDTy->getName().empty()) { 1624 Info.Members.push_back({DDTy, 0}); 1625 return; 1626 } 1627 // An unnamed member must represent a nested struct or union. Add all the 1628 // indirect fields to the current record. 1629 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!"); 1630 uint64_t Offset = DDTy->getOffsetInBits(); 1631 const DIType *Ty = DDTy->getBaseType().resolve(); 1632 const DICompositeType *DCTy = cast<DICompositeType>(Ty); 1633 ClassInfo NestedInfo = collectClassInfo(DCTy); 1634 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members) 1635 Info.Members.push_back( 1636 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset}); 1637 } 1638 1639 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) { 1640 ClassInfo Info; 1641 // Add elements to structure type. 1642 DINodeArray Elements = Ty->getElements(); 1643 for (auto *Element : Elements) { 1644 // We assume that the frontend provides all members in source declaration 1645 // order, which is what MSVC does. 1646 if (!Element) 1647 continue; 1648 if (auto *SP = dyn_cast<DISubprogram>(Element)) { 1649 Info.Methods[SP->getRawName()].push_back(SP); 1650 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) { 1651 if (DDTy->getTag() == dwarf::DW_TAG_member) { 1652 collectMemberInfo(Info, DDTy); 1653 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) { 1654 Info.Inheritance.push_back(DDTy); 1655 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type && 1656 DDTy->getName() == "__vtbl_ptr_type") { 1657 Info.VShapeTI = getTypeIndex(DDTy); 1658 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) { 1659 // Ignore friend members. It appears that MSVC emitted info about 1660 // friends in the past, but modern versions do not. 1661 } 1662 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) { 1663 Info.NestedClasses.push_back(Composite); 1664 } 1665 // Skip other unrecognized kinds of elements. 1666 } 1667 return Info; 1668 } 1669 1670 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) { 1671 // First, construct the forward decl. Don't look into Ty to compute the 1672 // forward decl options, since it might not be available in all TUs. 1673 TypeRecordKind Kind = getRecordKind(Ty); 1674 ClassOptions CO = 1675 ClassOptions::ForwardReference | getCommonClassOptions(Ty); 1676 std::string FullName = getFullyQualifiedName(Ty); 1677 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0, 1678 FullName, Ty->getIdentifier()); 1679 TypeIndex FwdDeclTI = TypeTable.writeKnownType(CR); 1680 if (!Ty->isForwardDecl()) 1681 DeferredCompleteTypes.push_back(Ty); 1682 return FwdDeclTI; 1683 } 1684 1685 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) { 1686 // Construct the field list and complete type record. 1687 TypeRecordKind Kind = getRecordKind(Ty); 1688 ClassOptions CO = getCommonClassOptions(Ty); 1689 TypeIndex FieldTI; 1690 TypeIndex VShapeTI; 1691 unsigned FieldCount; 1692 bool ContainsNestedClass; 1693 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) = 1694 lowerRecordFieldList(Ty); 1695 1696 if (ContainsNestedClass) 1697 CO |= ClassOptions::ContainsNestedClass; 1698 1699 std::string FullName = getFullyQualifiedName(Ty); 1700 1701 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 1702 1703 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI, 1704 SizeInBytes, FullName, Ty->getIdentifier()); 1705 TypeIndex ClassTI = TypeTable.writeKnownType(CR); 1706 1707 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(Ty->getFile())); 1708 TypeIndex SIDI = TypeTable.writeKnownType(SIDR); 1709 UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine()); 1710 TypeTable.writeKnownType(USLR); 1711 1712 addToUDTs(Ty, ClassTI); 1713 1714 return ClassTI; 1715 } 1716 1717 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) { 1718 ClassOptions CO = 1719 ClassOptions::ForwardReference | getCommonClassOptions(Ty); 1720 std::string FullName = getFullyQualifiedName(Ty); 1721 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier()); 1722 TypeIndex FwdDeclTI = TypeTable.writeKnownType(UR); 1723 if (!Ty->isForwardDecl()) 1724 DeferredCompleteTypes.push_back(Ty); 1725 return FwdDeclTI; 1726 } 1727 1728 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) { 1729 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty); 1730 TypeIndex FieldTI; 1731 unsigned FieldCount; 1732 bool ContainsNestedClass; 1733 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) = 1734 lowerRecordFieldList(Ty); 1735 1736 if (ContainsNestedClass) 1737 CO |= ClassOptions::ContainsNestedClass; 1738 1739 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 1740 std::string FullName = getFullyQualifiedName(Ty); 1741 1742 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName, 1743 Ty->getIdentifier()); 1744 TypeIndex UnionTI = TypeTable.writeKnownType(UR); 1745 1746 StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile())); 1747 TypeIndex SIRI = TypeTable.writeKnownType(SIR); 1748 UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine()); 1749 TypeTable.writeKnownType(USLR); 1750 1751 addToUDTs(Ty, UnionTI); 1752 1753 return UnionTI; 1754 } 1755 1756 std::tuple<TypeIndex, TypeIndex, unsigned, bool> 1757 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) { 1758 // Manually count members. MSVC appears to count everything that generates a 1759 // field list record. Each individual overload in a method overload group 1760 // contributes to this count, even though the overload group is a single field 1761 // list record. 1762 unsigned MemberCount = 0; 1763 ClassInfo Info = collectClassInfo(Ty); 1764 FieldListRecordBuilder FLBR(TypeTable); 1765 FLBR.begin(); 1766 1767 // Create base classes. 1768 for (const DIDerivedType *I : Info.Inheritance) { 1769 if (I->getFlags() & DINode::FlagVirtual) { 1770 // Virtual base. 1771 // FIXME: Emit VBPtrOffset when the frontend provides it. 1772 unsigned VBPtrOffset = 0; 1773 // FIXME: Despite the accessor name, the offset is really in bytes. 1774 unsigned VBTableIndex = I->getOffsetInBits() / 4; 1775 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase 1776 ? TypeRecordKind::IndirectVirtualBaseClass 1777 : TypeRecordKind::VirtualBaseClass; 1778 VirtualBaseClassRecord VBCR( 1779 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()), 1780 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset, 1781 VBTableIndex); 1782 1783 FLBR.writeMemberType(VBCR); 1784 } else { 1785 assert(I->getOffsetInBits() % 8 == 0 && 1786 "bases must be on byte boundaries"); 1787 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()), 1788 getTypeIndex(I->getBaseType()), 1789 I->getOffsetInBits() / 8); 1790 FLBR.writeMemberType(BCR); 1791 } 1792 } 1793 1794 // Create members. 1795 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) { 1796 const DIDerivedType *Member = MemberInfo.MemberTypeNode; 1797 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType()); 1798 StringRef MemberName = Member->getName(); 1799 MemberAccess Access = 1800 translateAccessFlags(Ty->getTag(), Member->getFlags()); 1801 1802 if (Member->isStaticMember()) { 1803 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName); 1804 FLBR.writeMemberType(SDMR); 1805 MemberCount++; 1806 continue; 1807 } 1808 1809 // Virtual function pointer member. 1810 if ((Member->getFlags() & DINode::FlagArtificial) && 1811 Member->getName().startswith("_vptr$")) { 1812 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType())); 1813 FLBR.writeMemberType(VFPR); 1814 MemberCount++; 1815 continue; 1816 } 1817 1818 // Data member. 1819 uint64_t MemberOffsetInBits = 1820 Member->getOffsetInBits() + MemberInfo.BaseOffset; 1821 if (Member->isBitField()) { 1822 uint64_t StartBitOffset = MemberOffsetInBits; 1823 if (const auto *CI = 1824 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) { 1825 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset; 1826 } 1827 StartBitOffset -= MemberOffsetInBits; 1828 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(), 1829 StartBitOffset); 1830 MemberBaseType = TypeTable.writeKnownType(BFR); 1831 } 1832 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8; 1833 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes, 1834 MemberName); 1835 FLBR.writeMemberType(DMR); 1836 MemberCount++; 1837 } 1838 1839 // Create methods 1840 for (auto &MethodItr : Info.Methods) { 1841 StringRef Name = MethodItr.first->getString(); 1842 1843 std::vector<OneMethodRecord> Methods; 1844 for (const DISubprogram *SP : MethodItr.second) { 1845 TypeIndex MethodType = getMemberFunctionType(SP, Ty); 1846 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual; 1847 1848 unsigned VFTableOffset = -1; 1849 if (Introduced) 1850 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes(); 1851 1852 Methods.push_back(OneMethodRecord( 1853 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()), 1854 translateMethodKindFlags(SP, Introduced), 1855 translateMethodOptionFlags(SP), VFTableOffset, Name)); 1856 MemberCount++; 1857 } 1858 assert(Methods.size() > 0 && "Empty methods map entry"); 1859 if (Methods.size() == 1) 1860 FLBR.writeMemberType(Methods[0]); 1861 else { 1862 MethodOverloadListRecord MOLR(Methods); 1863 TypeIndex MethodList = TypeTable.writeKnownType(MOLR); 1864 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name); 1865 FLBR.writeMemberType(OMR); 1866 } 1867 } 1868 1869 // Create nested classes. 1870 for (const DICompositeType *Nested : Info.NestedClasses) { 1871 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName()); 1872 FLBR.writeMemberType(R); 1873 MemberCount++; 1874 } 1875 1876 TypeIndex FieldTI = FLBR.end(); 1877 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount, 1878 !Info.NestedClasses.empty()); 1879 } 1880 1881 TypeIndex CodeViewDebug::getVBPTypeIndex() { 1882 if (!VBPType.getIndex()) { 1883 // Make a 'const int *' type. 1884 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const); 1885 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR); 1886 1887 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64 1888 : PointerKind::Near32; 1889 PointerMode PM = PointerMode::Pointer; 1890 PointerOptions PO = PointerOptions::None; 1891 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes()); 1892 1893 VBPType = TypeTable.writeKnownType(PR); 1894 } 1895 1896 return VBPType; 1897 } 1898 1899 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) { 1900 const DIType *Ty = TypeRef.resolve(); 1901 const DIType *ClassTy = ClassTyRef.resolve(); 1902 1903 // The null DIType is the void type. Don't try to hash it. 1904 if (!Ty) 1905 return TypeIndex::Void(); 1906 1907 // Check if we've already translated this type. Don't try to do a 1908 // get-or-create style insertion that caches the hash lookup across the 1909 // lowerType call. It will update the TypeIndices map. 1910 auto I = TypeIndices.find({Ty, ClassTy}); 1911 if (I != TypeIndices.end()) 1912 return I->second; 1913 1914 TypeLoweringScope S(*this); 1915 TypeIndex TI = lowerType(Ty, ClassTy); 1916 return recordTypeIndexForDINode(Ty, TI, ClassTy); 1917 } 1918 1919 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) { 1920 const DIType *Ty = TypeRef.resolve(); 1921 1922 // The null DIType is the void type. Don't try to hash it. 1923 if (!Ty) 1924 return TypeIndex::Void(); 1925 1926 // If this is a non-record type, the complete type index is the same as the 1927 // normal type index. Just call getTypeIndex. 1928 switch (Ty->getTag()) { 1929 case dwarf::DW_TAG_class_type: 1930 case dwarf::DW_TAG_structure_type: 1931 case dwarf::DW_TAG_union_type: 1932 break; 1933 default: 1934 return getTypeIndex(Ty); 1935 } 1936 1937 // Check if we've already translated the complete record type. Lowering a 1938 // complete type should never trigger lowering another complete type, so we 1939 // can reuse the hash table lookup result. 1940 const auto *CTy = cast<DICompositeType>(Ty); 1941 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()}); 1942 if (!InsertResult.second) 1943 return InsertResult.first->second; 1944 1945 TypeLoweringScope S(*this); 1946 1947 // Make sure the forward declaration is emitted first. It's unclear if this 1948 // is necessary, but MSVC does it, and we should follow suit until we can show 1949 // otherwise. 1950 TypeIndex FwdDeclTI = getTypeIndex(CTy); 1951 1952 // Just use the forward decl if we don't have complete type info. This might 1953 // happen if the frontend is using modules and expects the complete definition 1954 // to be emitted elsewhere. 1955 if (CTy->isForwardDecl()) 1956 return FwdDeclTI; 1957 1958 TypeIndex TI; 1959 switch (CTy->getTag()) { 1960 case dwarf::DW_TAG_class_type: 1961 case dwarf::DW_TAG_structure_type: 1962 TI = lowerCompleteTypeClass(CTy); 1963 break; 1964 case dwarf::DW_TAG_union_type: 1965 TI = lowerCompleteTypeUnion(CTy); 1966 break; 1967 default: 1968 llvm_unreachable("not a record"); 1969 } 1970 1971 InsertResult.first->second = TI; 1972 return TI; 1973 } 1974 1975 /// Emit all the deferred complete record types. Try to do this in FIFO order, 1976 /// and do this until fixpoint, as each complete record type typically 1977 /// references 1978 /// many other record types. 1979 void CodeViewDebug::emitDeferredCompleteTypes() { 1980 SmallVector<const DICompositeType *, 4> TypesToEmit; 1981 while (!DeferredCompleteTypes.empty()) { 1982 std::swap(DeferredCompleteTypes, TypesToEmit); 1983 for (const DICompositeType *RecordTy : TypesToEmit) 1984 getCompleteTypeIndex(RecordTy); 1985 TypesToEmit.clear(); 1986 } 1987 } 1988 1989 void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) { 1990 // Get the sorted list of parameters and emit them first. 1991 SmallVector<const LocalVariable *, 6> Params; 1992 for (const LocalVariable &L : Locals) 1993 if (L.DIVar->isParameter()) 1994 Params.push_back(&L); 1995 std::sort(Params.begin(), Params.end(), 1996 [](const LocalVariable *L, const LocalVariable *R) { 1997 return L->DIVar->getArg() < R->DIVar->getArg(); 1998 }); 1999 for (const LocalVariable *L : Params) 2000 emitLocalVariable(*L); 2001 2002 // Next emit all non-parameters in the order that we found them. 2003 for (const LocalVariable &L : Locals) 2004 if (!L.DIVar->isParameter()) 2005 emitLocalVariable(L); 2006 } 2007 2008 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) { 2009 // LocalSym record, see SymbolRecord.h for more info. 2010 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(), 2011 *LocalEnd = MMI->getContext().createTempSymbol(); 2012 OS.AddComment("Record length"); 2013 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2); 2014 OS.EmitLabel(LocalBegin); 2015 2016 OS.AddComment("Record kind: S_LOCAL"); 2017 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2); 2018 2019 LocalSymFlags Flags = LocalSymFlags::None; 2020 if (Var.DIVar->isParameter()) 2021 Flags |= LocalSymFlags::IsParameter; 2022 if (Var.DefRanges.empty()) 2023 Flags |= LocalSymFlags::IsOptimizedOut; 2024 2025 OS.AddComment("TypeIndex"); 2026 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType()); 2027 OS.EmitIntValue(TI.getIndex(), 4); 2028 OS.AddComment("Flags"); 2029 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2); 2030 // Truncate the name so we won't overflow the record length field. 2031 emitNullTerminatedSymbolName(OS, Var.DIVar->getName()); 2032 OS.EmitLabel(LocalEnd); 2033 2034 // Calculate the on disk prefix of the appropriate def range record. The 2035 // records and on disk formats are described in SymbolRecords.h. BytePrefix 2036 // should be big enough to hold all forms without memory allocation. 2037 SmallString<20> BytePrefix; 2038 for (const LocalVarDefRange &DefRange : Var.DefRanges) { 2039 BytePrefix.clear(); 2040 if (DefRange.InMemory) { 2041 uint16_t RegRelFlags = 0; 2042 if (DefRange.IsSubfield) { 2043 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag | 2044 (DefRange.StructOffset 2045 << DefRangeRegisterRelSym::OffsetInParentShift); 2046 } 2047 DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL); 2048 Sym.Hdr.Register = DefRange.CVRegister; 2049 Sym.Hdr.Flags = RegRelFlags; 2050 Sym.Hdr.BasePointerOffset = DefRange.DataOffset; 2051 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL); 2052 BytePrefix += 2053 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 2054 BytePrefix += 2055 StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr)); 2056 } else { 2057 assert(DefRange.DataOffset == 0 && "unexpected offset into register"); 2058 if (DefRange.IsSubfield) { 2059 // Unclear what matters here. 2060 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER); 2061 Sym.Hdr.Register = DefRange.CVRegister; 2062 Sym.Hdr.MayHaveNoName = 0; 2063 Sym.Hdr.OffsetInParent = DefRange.StructOffset; 2064 2065 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER); 2066 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind), 2067 sizeof(SymKind)); 2068 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr), 2069 sizeof(Sym.Hdr)); 2070 } else { 2071 // Unclear what matters here. 2072 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER); 2073 Sym.Hdr.Register = DefRange.CVRegister; 2074 Sym.Hdr.MayHaveNoName = 0; 2075 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER); 2076 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind), 2077 sizeof(SymKind)); 2078 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr), 2079 sizeof(Sym.Hdr)); 2080 } 2081 } 2082 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix); 2083 } 2084 } 2085 2086 void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) { 2087 const Function *GV = MF->getFunction(); 2088 assert(FnDebugInfo.count(GV)); 2089 assert(CurFn == &FnDebugInfo[GV]); 2090 2091 collectVariableInfo(GV->getSubprogram()); 2092 2093 // Don't emit anything if we don't have any line tables. 2094 if (!CurFn->HaveLineInfo) { 2095 FnDebugInfo.erase(GV); 2096 CurFn = nullptr; 2097 return; 2098 } 2099 2100 CurFn->End = Asm->getFunctionEnd(); 2101 2102 CurFn = nullptr; 2103 } 2104 2105 void CodeViewDebug::beginInstruction(const MachineInstr *MI) { 2106 DebugHandlerBase::beginInstruction(MI); 2107 2108 // Ignore DBG_VALUE locations and function prologue. 2109 if (!Asm || !CurFn || MI->isDebugValue() || 2110 MI->getFlag(MachineInstr::FrameSetup)) 2111 return; 2112 DebugLoc DL = MI->getDebugLoc(); 2113 if (DL == PrevInstLoc || !DL) 2114 return; 2115 maybeRecordLocation(DL, Asm->MF); 2116 } 2117 2118 MCSymbol *CodeViewDebug::beginCVSubsection(ModuleDebugFragmentKind Kind) { 2119 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(), 2120 *EndLabel = MMI->getContext().createTempSymbol(); 2121 OS.EmitIntValue(unsigned(Kind), 4); 2122 OS.AddComment("Subsection size"); 2123 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4); 2124 OS.EmitLabel(BeginLabel); 2125 return EndLabel; 2126 } 2127 2128 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) { 2129 OS.EmitLabel(EndLabel); 2130 // Every subsection must be aligned to a 4-byte boundary. 2131 OS.EmitValueToAlignment(4); 2132 } 2133 2134 void CodeViewDebug::emitDebugInfoForUDTs( 2135 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) { 2136 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) { 2137 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(), 2138 *UDTRecordEnd = MMI->getContext().createTempSymbol(); 2139 OS.AddComment("Record length"); 2140 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2); 2141 OS.EmitLabel(UDTRecordBegin); 2142 2143 OS.AddComment("Record kind: S_UDT"); 2144 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2); 2145 2146 OS.AddComment("Type"); 2147 OS.EmitIntValue(UDT.second.getIndex(), 4); 2148 2149 emitNullTerminatedSymbolName(OS, UDT.first); 2150 OS.EmitLabel(UDTRecordEnd); 2151 } 2152 } 2153 2154 void CodeViewDebug::emitDebugInfoForGlobals() { 2155 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *> 2156 GlobalMap; 2157 for (const GlobalVariable &GV : MMI->getModule()->globals()) { 2158 SmallVector<DIGlobalVariableExpression *, 1> GVEs; 2159 GV.getDebugInfo(GVEs); 2160 for (const auto *GVE : GVEs) 2161 GlobalMap[GVE] = &GV; 2162 } 2163 2164 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 2165 for (const MDNode *Node : CUs->operands()) { 2166 const auto *CU = cast<DICompileUnit>(Node); 2167 2168 // First, emit all globals that are not in a comdat in a single symbol 2169 // substream. MSVC doesn't like it if the substream is empty, so only open 2170 // it if we have at least one global to emit. 2171 switchToDebugSectionForSymbol(nullptr); 2172 MCSymbol *EndLabel = nullptr; 2173 for (const auto *GVE : CU->getGlobalVariables()) { 2174 if (const auto *GV = GlobalMap.lookup(GVE)) 2175 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) { 2176 if (!EndLabel) { 2177 OS.AddComment("Symbol subsection for globals"); 2178 EndLabel = beginCVSubsection(ModuleDebugFragmentKind::Symbols); 2179 } 2180 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions. 2181 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV)); 2182 } 2183 } 2184 if (EndLabel) 2185 endCVSubsection(EndLabel); 2186 2187 // Second, emit each global that is in a comdat into its own .debug$S 2188 // section along with its own symbol substream. 2189 for (const auto *GVE : CU->getGlobalVariables()) { 2190 if (const auto *GV = GlobalMap.lookup(GVE)) { 2191 if (GV->hasComdat()) { 2192 MCSymbol *GVSym = Asm->getSymbol(GV); 2193 OS.AddComment("Symbol subsection for " + 2194 Twine(GlobalValue::getRealLinkageName(GV->getName()))); 2195 switchToDebugSectionForSymbol(GVSym); 2196 EndLabel = beginCVSubsection(ModuleDebugFragmentKind::Symbols); 2197 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions. 2198 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym); 2199 endCVSubsection(EndLabel); 2200 } 2201 } 2202 } 2203 } 2204 } 2205 2206 void CodeViewDebug::emitDebugInfoForRetainedTypes() { 2207 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 2208 for (const MDNode *Node : CUs->operands()) { 2209 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) { 2210 if (DIType *RT = dyn_cast<DIType>(Ty)) { 2211 getTypeIndex(RT); 2212 // FIXME: Add to global/local DTU list. 2213 } 2214 } 2215 } 2216 } 2217 2218 void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV, 2219 const GlobalVariable *GV, 2220 MCSymbol *GVSym) { 2221 // DataSym record, see SymbolRecord.h for more info. 2222 // FIXME: Thread local data, etc 2223 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(), 2224 *DataEnd = MMI->getContext().createTempSymbol(); 2225 OS.AddComment("Record length"); 2226 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2); 2227 OS.EmitLabel(DataBegin); 2228 if (DIGV->isLocalToUnit()) { 2229 if (GV->isThreadLocal()) { 2230 OS.AddComment("Record kind: S_LTHREAD32"); 2231 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2); 2232 } else { 2233 OS.AddComment("Record kind: S_LDATA32"); 2234 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2); 2235 } 2236 } else { 2237 if (GV->isThreadLocal()) { 2238 OS.AddComment("Record kind: S_GTHREAD32"); 2239 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2); 2240 } else { 2241 OS.AddComment("Record kind: S_GDATA32"); 2242 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2); 2243 } 2244 } 2245 OS.AddComment("Type"); 2246 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4); 2247 OS.AddComment("DataOffset"); 2248 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0); 2249 OS.AddComment("Segment"); 2250 OS.EmitCOFFSectionIndex(GVSym); 2251 OS.AddComment("Name"); 2252 emitNullTerminatedSymbolName(OS, DIGV->getName()); 2253 OS.EmitLabel(DataEnd); 2254 } 2255