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