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