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