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/DebugInfo/CodeView/CodeView.h" 16 #include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h" 17 #include "llvm/DebugInfo/CodeView/Line.h" 18 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 19 #include "llvm/DebugInfo/CodeView/TypeDumper.h" 20 #include "llvm/DebugInfo/CodeView/TypeIndex.h" 21 #include "llvm/DebugInfo/CodeView/TypeRecord.h" 22 #include "llvm/MC/MCExpr.h" 23 #include "llvm/MC/MCSectionCOFF.h" 24 #include "llvm/MC/MCSymbol.h" 25 #include "llvm/Support/COFF.h" 26 #include "llvm/Support/ScopedPrinter.h" 27 #include "llvm/Target/TargetFrameLowering.h" 28 #include "llvm/Target/TargetRegisterInfo.h" 29 #include "llvm/Target/TargetSubtargetInfo.h" 30 31 using namespace llvm; 32 using namespace llvm::codeview; 33 34 CodeViewDebug::CodeViewDebug(AsmPrinter *AP) 35 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) { 36 // If module doesn't have named metadata anchors or COFF debug section 37 // is not available, skip any debug info related stuff. 38 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") || 39 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) { 40 Asm = nullptr; 41 return; 42 } 43 44 // Tell MMI that we have debug info. 45 MMI->setDebugInfoAvailability(true); 46 } 47 48 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) { 49 std::string &Filepath = FileToFilepathMap[File]; 50 if (!Filepath.empty()) 51 return Filepath; 52 53 StringRef Dir = File->getDirectory(), Filename = File->getFilename(); 54 55 // Clang emits directory and relative filename info into the IR, but CodeView 56 // operates on full paths. We could change Clang to emit full paths too, but 57 // that would increase the IR size and probably not needed for other users. 58 // For now, just concatenate and canonicalize the path here. 59 if (Filename.find(':') == 1) 60 Filepath = Filename; 61 else 62 Filepath = (Dir + "\\" + Filename).str(); 63 64 // Canonicalize the path. We have to do it textually because we may no longer 65 // have access the file in the filesystem. 66 // First, replace all slashes with backslashes. 67 std::replace(Filepath.begin(), Filepath.end(), '/', '\\'); 68 69 // Remove all "\.\" with "\". 70 size_t Cursor = 0; 71 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos) 72 Filepath.erase(Cursor, 2); 73 74 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original 75 // path should be well-formatted, e.g. start with a drive letter, etc. 76 Cursor = 0; 77 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) { 78 // Something's wrong if the path starts with "\..\", abort. 79 if (Cursor == 0) 80 break; 81 82 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1); 83 if (PrevSlash == std::string::npos) 84 // Something's wrong, abort. 85 break; 86 87 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash); 88 // The next ".." might be following the one we've just erased. 89 Cursor = PrevSlash; 90 } 91 92 // Remove all duplicate backslashes. 93 Cursor = 0; 94 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos) 95 Filepath.erase(Cursor, 1); 96 97 return Filepath; 98 } 99 100 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) { 101 unsigned NextId = FileIdMap.size() + 1; 102 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId)); 103 if (Insertion.second) { 104 // We have to compute the full filepath and emit a .cv_file directive. 105 StringRef FullPath = getFullFilepath(F); 106 NextId = OS.EmitCVFileDirective(NextId, FullPath); 107 assert(NextId == FileIdMap.size() && ".cv_file directive failed"); 108 } 109 return Insertion.first->second; 110 } 111 112 CodeViewDebug::InlineSite & 113 CodeViewDebug::getInlineSite(const DILocation *InlinedAt, 114 const DISubprogram *Inlinee) { 115 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()}); 116 InlineSite *Site = &SiteInsertion.first->second; 117 if (SiteInsertion.second) { 118 Site->SiteFuncId = NextFuncId++; 119 Site->Inlinee = Inlinee; 120 InlinedSubprograms.insert(Inlinee); 121 getFuncIdForSubprogram(Inlinee); 122 } 123 return *Site; 124 } 125 126 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) { 127 // It's possible to ask for the FuncId of a function which doesn't have a 128 // subprogram: inlining a function with debug info into a function with none. 129 if (!SP) 130 return TypeIndex::None(); 131 132 // Check if we've already translated this subprogram. 133 auto I = TypeIndices.find({SP, nullptr}); 134 if (I != TypeIndices.end()) 135 return I->second; 136 137 TypeIndex ParentScope = TypeIndex(0); 138 // The display name includes function template arguments. Drop them to match 139 // MSVC. 140 StringRef DisplayName = SP->getDisplayName().split('<').first; 141 FuncIdRecord FuncId(ParentScope, lowerSubprogramType(SP), DisplayName); 142 TypeIndex TI = TypeTable.writeFuncId(FuncId); 143 144 recordTypeIndexForDINode(SP, TI); 145 return TI; 146 } 147 148 void CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI, 149 const DIType *ClassTy) { 150 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI}); 151 (void)InsertResult; 152 assert(InsertResult.second && "DINode was already assigned a type index"); 153 } 154 155 unsigned CodeViewDebug::getPointerSizeInBytes() { 156 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8; 157 } 158 159 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var, 160 const DILocation *InlinedAt) { 161 if (InlinedAt) { 162 // This variable was inlined. Associate it with the InlineSite. 163 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram(); 164 InlineSite &Site = getInlineSite(InlinedAt, Inlinee); 165 Site.InlinedLocals.emplace_back(Var); 166 } else { 167 // This variable goes in the main ProcSym. 168 CurFn->Locals.emplace_back(Var); 169 } 170 } 171 172 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs, 173 const DILocation *Loc) { 174 auto B = Locs.begin(), E = Locs.end(); 175 if (std::find(B, E, Loc) == E) 176 Locs.push_back(Loc); 177 } 178 179 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL, 180 const MachineFunction *MF) { 181 // Skip this instruction if it has the same location as the previous one. 182 if (DL == CurFn->LastLoc) 183 return; 184 185 const DIScope *Scope = DL.get()->getScope(); 186 if (!Scope) 187 return; 188 189 // Skip this line if it is longer than the maximum we can record. 190 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true); 191 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() || 192 LI.isNeverStepInto()) 193 return; 194 195 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0); 196 if (CI.getStartColumn() != DL.getCol()) 197 return; 198 199 if (!CurFn->HaveLineInfo) 200 CurFn->HaveLineInfo = true; 201 unsigned FileId = 0; 202 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile()) 203 FileId = CurFn->LastFileId; 204 else 205 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile()); 206 CurFn->LastLoc = DL; 207 208 unsigned FuncId = CurFn->FuncId; 209 if (const DILocation *SiteLoc = DL->getInlinedAt()) { 210 const DILocation *Loc = DL.get(); 211 212 // If this location was actually inlined from somewhere else, give it the ID 213 // of the inline call site. 214 FuncId = 215 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId; 216 217 // Ensure we have links in the tree of inline call sites. 218 bool FirstLoc = true; 219 while ((SiteLoc = Loc->getInlinedAt())) { 220 InlineSite &Site = 221 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()); 222 if (!FirstLoc) 223 addLocIfNotPresent(Site.ChildSites, Loc); 224 FirstLoc = false; 225 Loc = SiteLoc; 226 } 227 addLocIfNotPresent(CurFn->ChildSites, Loc); 228 } 229 230 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(), 231 /*PrologueEnd=*/false, 232 /*IsStmt=*/false, DL->getFilename()); 233 } 234 235 void CodeViewDebug::emitCodeViewMagicVersion() { 236 OS.EmitValueToAlignment(4); 237 OS.AddComment("Debug section magic"); 238 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4); 239 } 240 241 void CodeViewDebug::endModule() { 242 if (!Asm || !MMI->hasDebugInfo()) 243 return; 244 245 assert(Asm != nullptr); 246 247 // The COFF .debug$S section consists of several subsections, each starting 248 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length 249 // of the payload followed by the payload itself. The subsections are 4-byte 250 // aligned. 251 252 // Use the generic .debug$S section, and make a subsection for all the inlined 253 // subprograms. 254 switchToDebugSectionForSymbol(nullptr); 255 emitInlineeLinesSubsection(); 256 257 // Emit per-function debug information. 258 for (auto &P : FnDebugInfo) 259 if (!P.first->isDeclarationForLinker()) 260 emitDebugInfoForFunction(P.first, P.second); 261 262 // Emit global variable debug information. 263 setCurrentSubprogram(nullptr); 264 emitDebugInfoForGlobals(); 265 266 // Switch back to the generic .debug$S section after potentially processing 267 // comdat symbol sections. 268 switchToDebugSectionForSymbol(nullptr); 269 270 // Emit UDT records for any types used by global variables. 271 if (!GlobalUDTs.empty()) { 272 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols); 273 emitDebugInfoForUDTs(GlobalUDTs); 274 endCVSubsection(SymbolsEnd); 275 } 276 277 // This subsection holds a file index to offset in string table table. 278 OS.AddComment("File index to string table offset subsection"); 279 OS.EmitCVFileChecksumsDirective(); 280 281 // This subsection holds the string table. 282 OS.AddComment("String table"); 283 OS.EmitCVStringTableDirective(); 284 285 // Emit type information last, so that any types we translate while emitting 286 // function info are included. 287 emitTypeInformation(); 288 289 clear(); 290 } 291 292 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) { 293 // Microsoft's linker seems to have trouble with symbol names longer than 294 // 0xffd8 bytes. 295 S = S.substr(0, 0xffd8); 296 SmallString<32> NullTerminatedString(S); 297 NullTerminatedString.push_back('\0'); 298 OS.EmitBytes(NullTerminatedString); 299 } 300 301 void CodeViewDebug::emitTypeInformation() { 302 // Do nothing if we have no debug info or if no non-trivial types were emitted 303 // to TypeTable during codegen. 304 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 305 if (!CU_Nodes) 306 return; 307 if (TypeTable.empty()) 308 return; 309 310 // Start the .debug$T section with 0x4. 311 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection()); 312 emitCodeViewMagicVersion(); 313 314 SmallString<8> CommentPrefix; 315 if (OS.isVerboseAsm()) { 316 CommentPrefix += '\t'; 317 CommentPrefix += Asm->MAI->getCommentString(); 318 CommentPrefix += ' '; 319 } 320 321 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false); 322 TypeTable.ForEachRecord( 323 [&](TypeIndex Index, StringRef Record) { 324 if (OS.isVerboseAsm()) { 325 // Emit a block comment describing the type record for readability. 326 SmallString<512> CommentBlock; 327 raw_svector_ostream CommentOS(CommentBlock); 328 ScopedPrinter SP(CommentOS); 329 SP.setPrefix(CommentPrefix); 330 CVTD.setPrinter(&SP); 331 Error EC = CVTD.dump({Record.bytes_begin(), Record.bytes_end()}); 332 assert(!EC && "produced malformed type record"); 333 consumeError(std::move(EC)); 334 // emitRawComment will insert its own tab and comment string before 335 // the first line, so strip off our first one. It also prints its own 336 // newline. 337 OS.emitRawComment( 338 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim()); 339 } 340 OS.EmitBinaryData(Record); 341 }); 342 } 343 344 void CodeViewDebug::emitInlineeLinesSubsection() { 345 if (InlinedSubprograms.empty()) 346 return; 347 348 OS.AddComment("Inlinee lines subsection"); 349 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines); 350 351 // We don't provide any extra file info. 352 // FIXME: Find out if debuggers use this info. 353 OS.AddComment("Inlinee lines signature"); 354 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4); 355 356 for (const DISubprogram *SP : InlinedSubprograms) { 357 assert(TypeIndices.count({SP, nullptr})); 358 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}]; 359 360 OS.AddBlankLine(); 361 unsigned FileId = maybeRecordFile(SP->getFile()); 362 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " + 363 SP->getFilename() + Twine(':') + Twine(SP->getLine())); 364 OS.AddBlankLine(); 365 // The filechecksum table uses 8 byte entries for now, and file ids start at 366 // 1. 367 unsigned FileOffset = (FileId - 1) * 8; 368 OS.AddComment("Type index of inlined function"); 369 OS.EmitIntValue(InlineeIdx.getIndex(), 4); 370 OS.AddComment("Offset into filechecksum table"); 371 OS.EmitIntValue(FileOffset, 4); 372 OS.AddComment("Starting line number"); 373 OS.EmitIntValue(SP->getLine(), 4); 374 } 375 376 endCVSubsection(InlineEnd); 377 } 378 379 void CodeViewDebug::collectInlineSiteChildren( 380 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI, 381 const InlineSite &Site) { 382 for (const DILocation *ChildSiteLoc : Site.ChildSites) { 383 auto I = FI.InlineSites.find(ChildSiteLoc); 384 const InlineSite &ChildSite = I->second; 385 Children.push_back(ChildSite.SiteFuncId); 386 collectInlineSiteChildren(Children, FI, ChildSite); 387 } 388 } 389 390 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI, 391 const DILocation *InlinedAt, 392 const InlineSite &Site) { 393 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(), 394 *InlineEnd = MMI->getContext().createTempSymbol(); 395 396 assert(TypeIndices.count({Site.Inlinee, nullptr})); 397 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}]; 398 399 // SymbolRecord 400 OS.AddComment("Record length"); 401 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength 402 OS.EmitLabel(InlineBegin); 403 OS.AddComment("Record kind: S_INLINESITE"); 404 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind 405 406 OS.AddComment("PtrParent"); 407 OS.EmitIntValue(0, 4); 408 OS.AddComment("PtrEnd"); 409 OS.EmitIntValue(0, 4); 410 OS.AddComment("Inlinee type index"); 411 OS.EmitIntValue(InlineeIdx.getIndex(), 4); 412 413 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile()); 414 unsigned StartLineNum = Site.Inlinee->getLine(); 415 SmallVector<unsigned, 3> SecondaryFuncIds; 416 collectInlineSiteChildren(SecondaryFuncIds, FI, Site); 417 418 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum, 419 FI.Begin, FI.End, SecondaryFuncIds); 420 421 OS.EmitLabel(InlineEnd); 422 423 for (const LocalVariable &Var : Site.InlinedLocals) 424 emitLocalVariable(Var); 425 426 // Recurse on child inlined call sites before closing the scope. 427 for (const DILocation *ChildSite : Site.ChildSites) { 428 auto I = FI.InlineSites.find(ChildSite); 429 assert(I != FI.InlineSites.end() && 430 "child site not in function inline site map"); 431 emitInlinedCallSite(FI, ChildSite, I->second); 432 } 433 434 // Close the scope. 435 OS.AddComment("Record length"); 436 OS.EmitIntValue(2, 2); // RecordLength 437 OS.AddComment("Record kind: S_INLINESITE_END"); 438 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind 439 } 440 441 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) { 442 // If we have a symbol, it may be in a section that is COMDAT. If so, find the 443 // comdat key. A section may be comdat because of -ffunction-sections or 444 // because it is comdat in the IR. 445 MCSectionCOFF *GVSec = 446 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr; 447 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr; 448 449 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>( 450 Asm->getObjFileLowering().getCOFFDebugSymbolsSection()); 451 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym); 452 453 OS.SwitchSection(DebugSec); 454 455 // Emit the magic version number if this is the first time we've switched to 456 // this section. 457 if (ComdatDebugSections.insert(DebugSec).second) 458 emitCodeViewMagicVersion(); 459 } 460 461 static const DISubprogram *getQualifiedNameComponents( 462 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) { 463 const DISubprogram *ClosestSubprogram = nullptr; 464 while (Scope != nullptr) { 465 if (ClosestSubprogram == nullptr) 466 ClosestSubprogram = dyn_cast<DISubprogram>(Scope); 467 StringRef ScopeName = Scope->getName(); 468 if (!ScopeName.empty()) 469 QualifiedNameComponents.push_back(ScopeName); 470 Scope = Scope->getScope().resolve(); 471 } 472 return ClosestSubprogram; 473 } 474 475 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents, 476 StringRef TypeName) { 477 std::string FullyQualifiedName; 478 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) { 479 FullyQualifiedName.append(QualifiedNameComponent); 480 FullyQualifiedName.append("::"); 481 } 482 FullyQualifiedName.append(TypeName); 483 return FullyQualifiedName; 484 } 485 486 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV, 487 FunctionInfo &FI) { 488 // For each function there is a separate subsection 489 // which holds the PC to file:line table. 490 const MCSymbol *Fn = Asm->getSymbol(GV); 491 assert(Fn); 492 493 // Switch to the to a comdat section, if appropriate. 494 switchToDebugSectionForSymbol(Fn); 495 496 std::string FuncName; 497 auto *SP = GV->getSubprogram(); 498 setCurrentSubprogram(SP); 499 500 // If we have a display name, build the fully qualified name by walking the 501 // chain of scopes. 502 if (SP != nullptr && !SP->getDisplayName().empty()) { 503 SmallVector<StringRef, 5> QualifiedNameComponents; 504 getQualifiedNameComponents(SP->getScope().resolve(), 505 QualifiedNameComponents); 506 FuncName = getQualifiedName(QualifiedNameComponents, SP->getDisplayName()); 507 } 508 509 // If our DISubprogram name is empty, use the mangled name. 510 if (FuncName.empty()) 511 FuncName = GlobalValue::getRealLinkageName(GV->getName()); 512 513 // Emit a symbol subsection, required by VS2012+ to find function boundaries. 514 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 515 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols); 516 { 517 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(), 518 *ProcRecordEnd = MMI->getContext().createTempSymbol(); 519 OS.AddComment("Record length"); 520 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2); 521 OS.EmitLabel(ProcRecordBegin); 522 523 OS.AddComment("Record kind: S_GPROC32_ID"); 524 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2); 525 526 // These fields are filled in by tools like CVPACK which run after the fact. 527 OS.AddComment("PtrParent"); 528 OS.EmitIntValue(0, 4); 529 OS.AddComment("PtrEnd"); 530 OS.EmitIntValue(0, 4); 531 OS.AddComment("PtrNext"); 532 OS.EmitIntValue(0, 4); 533 // This is the important bit that tells the debugger where the function 534 // code is located and what's its size: 535 OS.AddComment("Code size"); 536 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4); 537 OS.AddComment("Offset after prologue"); 538 OS.EmitIntValue(0, 4); 539 OS.AddComment("Offset before epilogue"); 540 OS.EmitIntValue(0, 4); 541 OS.AddComment("Function type index"); 542 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4); 543 OS.AddComment("Function section relative address"); 544 OS.EmitCOFFSecRel32(Fn); 545 OS.AddComment("Function section index"); 546 OS.EmitCOFFSectionIndex(Fn); 547 OS.AddComment("Flags"); 548 OS.EmitIntValue(0, 1); 549 // Emit the function display name as a null-terminated string. 550 OS.AddComment("Function name"); 551 // Truncate the name so we won't overflow the record length field. 552 emitNullTerminatedSymbolName(OS, FuncName); 553 OS.EmitLabel(ProcRecordEnd); 554 555 for (const LocalVariable &Var : FI.Locals) 556 emitLocalVariable(Var); 557 558 // Emit inlined call site information. Only emit functions inlined directly 559 // into the parent function. We'll emit the other sites recursively as part 560 // of their parent inline site. 561 for (const DILocation *InlinedAt : FI.ChildSites) { 562 auto I = FI.InlineSites.find(InlinedAt); 563 assert(I != FI.InlineSites.end() && 564 "child site not in function inline site map"); 565 emitInlinedCallSite(FI, InlinedAt, I->second); 566 } 567 568 if (SP != nullptr) 569 emitDebugInfoForUDTs(LocalUDTs); 570 571 // We're done with this function. 572 OS.AddComment("Record length"); 573 OS.EmitIntValue(0x0002, 2); 574 OS.AddComment("Record kind: S_PROC_ID_END"); 575 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2); 576 } 577 endCVSubsection(SymbolsEnd); 578 579 // We have an assembler directive that takes care of the whole line table. 580 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End); 581 } 582 583 CodeViewDebug::LocalVarDefRange 584 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) { 585 LocalVarDefRange DR; 586 DR.InMemory = -1; 587 DR.DataOffset = Offset; 588 assert(DR.DataOffset == Offset && "truncation"); 589 DR.StructOffset = 0; 590 DR.CVRegister = CVRegister; 591 return DR; 592 } 593 594 CodeViewDebug::LocalVarDefRange 595 CodeViewDebug::createDefRangeReg(uint16_t CVRegister) { 596 LocalVarDefRange DR; 597 DR.InMemory = 0; 598 DR.DataOffset = 0; 599 DR.StructOffset = 0; 600 DR.CVRegister = CVRegister; 601 return DR; 602 } 603 604 void CodeViewDebug::collectVariableInfoFromMMITable( 605 DenseSet<InlinedVariable> &Processed) { 606 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget(); 607 const TargetFrameLowering *TFI = TSI.getFrameLowering(); 608 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 609 610 for (const MachineModuleInfo::VariableDbgInfo &VI : 611 MMI->getVariableDbgInfo()) { 612 if (!VI.Var) 613 continue; 614 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 615 "Expected inlined-at fields to agree"); 616 617 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt())); 618 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 619 620 // If variable scope is not found then skip this variable. 621 if (!Scope) 622 continue; 623 624 // Get the frame register used and the offset. 625 unsigned FrameReg = 0; 626 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg); 627 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg); 628 629 // Calculate the label ranges. 630 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset); 631 for (const InsnRange &Range : Scope->getRanges()) { 632 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 633 const MCSymbol *End = getLabelAfterInsn(Range.second); 634 End = End ? End : Asm->getFunctionEnd(); 635 DefRange.Ranges.emplace_back(Begin, End); 636 } 637 638 LocalVariable Var; 639 Var.DIVar = VI.Var; 640 Var.DefRanges.emplace_back(std::move(DefRange)); 641 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt()); 642 } 643 } 644 645 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) { 646 DenseSet<InlinedVariable> Processed; 647 // Grab the variable info that was squirreled away in the MMI side-table. 648 collectVariableInfoFromMMITable(Processed); 649 650 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo(); 651 652 for (const auto &I : DbgValues) { 653 InlinedVariable IV = I.first; 654 if (Processed.count(IV)) 655 continue; 656 const DILocalVariable *DIVar = IV.first; 657 const DILocation *InlinedAt = IV.second; 658 659 // Instruction ranges, specifying where IV is accessible. 660 const auto &Ranges = I.second; 661 662 LexicalScope *Scope = nullptr; 663 if (InlinedAt) 664 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt); 665 else 666 Scope = LScopes.findLexicalScope(DIVar->getScope()); 667 // If variable scope is not found then skip this variable. 668 if (!Scope) 669 continue; 670 671 LocalVariable Var; 672 Var.DIVar = DIVar; 673 674 // Calculate the definition ranges. 675 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 676 const InsnRange &Range = *I; 677 const MachineInstr *DVInst = Range.first; 678 assert(DVInst->isDebugValue() && "Invalid History entry"); 679 const DIExpression *DIExpr = DVInst->getDebugExpression(); 680 681 // Bail if there is a complex DWARF expression for now. 682 if (DIExpr && DIExpr->getNumElements() > 0) 683 continue; 684 685 // Bail if operand 0 is not a valid register. This means the variable is a 686 // simple constant, or is described by a complex expression. 687 // FIXME: Find a way to represent constant variables, since they are 688 // relatively common. 689 unsigned Reg = 690 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0; 691 if (Reg == 0) 692 continue; 693 694 // Handle the two cases we can handle: indirect in memory and in register. 695 bool IsIndirect = DVInst->getOperand(1).isImm(); 696 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg()); 697 { 698 LocalVarDefRange DefRange; 699 if (IsIndirect) { 700 int64_t Offset = DVInst->getOperand(1).getImm(); 701 DefRange = createDefRangeMem(CVReg, Offset); 702 } else { 703 DefRange = createDefRangeReg(CVReg); 704 } 705 if (Var.DefRanges.empty() || 706 Var.DefRanges.back().isDifferentLocation(DefRange)) { 707 Var.DefRanges.emplace_back(std::move(DefRange)); 708 } 709 } 710 711 // Compute the label range. 712 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 713 const MCSymbol *End = getLabelAfterInsn(Range.second); 714 if (!End) { 715 if (std::next(I) != E) 716 End = getLabelBeforeInsn(std::next(I)->first); 717 else 718 End = Asm->getFunctionEnd(); 719 } 720 721 // If the last range end is our begin, just extend the last range. 722 // Otherwise make a new range. 723 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges = 724 Var.DefRanges.back().Ranges; 725 if (!Ranges.empty() && Ranges.back().second == Begin) 726 Ranges.back().second = End; 727 else 728 Ranges.emplace_back(Begin, End); 729 730 // FIXME: Do more range combining. 731 } 732 733 recordLocalVariable(std::move(Var), InlinedAt); 734 } 735 } 736 737 void CodeViewDebug::beginFunction(const MachineFunction *MF) { 738 assert(!CurFn && "Can't process two functions at once!"); 739 740 if (!Asm || !MMI->hasDebugInfo()) 741 return; 742 743 DebugHandlerBase::beginFunction(MF); 744 745 const Function *GV = MF->getFunction(); 746 assert(FnDebugInfo.count(GV) == false); 747 CurFn = &FnDebugInfo[GV]; 748 CurFn->FuncId = NextFuncId++; 749 CurFn->Begin = Asm->getFunctionBegin(); 750 751 // Find the end of the function prolog. First known non-DBG_VALUE and 752 // non-frame setup location marks the beginning of the function body. 753 // FIXME: is there a simpler a way to do this? Can we just search 754 // for the first instruction of the function, not the last of the prolog? 755 DebugLoc PrologEndLoc; 756 bool EmptyPrologue = true; 757 for (const auto &MBB : *MF) { 758 for (const auto &MI : MBB) { 759 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) && 760 MI.getDebugLoc()) { 761 PrologEndLoc = MI.getDebugLoc(); 762 break; 763 } else if (!MI.isDebugValue()) { 764 EmptyPrologue = false; 765 } 766 } 767 } 768 769 // Record beginning of function if we have a non-empty prologue. 770 if (PrologEndLoc && !EmptyPrologue) { 771 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc(); 772 maybeRecordLocation(FnStartDL, MF); 773 } 774 } 775 776 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) { 777 // Generic dispatch for lowering an unknown type. 778 switch (Ty->getTag()) { 779 case dwarf::DW_TAG_array_type: 780 return lowerTypeArray(cast<DICompositeType>(Ty)); 781 case dwarf::DW_TAG_typedef: 782 return lowerTypeAlias(cast<DIDerivedType>(Ty)); 783 case dwarf::DW_TAG_base_type: 784 return lowerTypeBasic(cast<DIBasicType>(Ty)); 785 case dwarf::DW_TAG_pointer_type: 786 case dwarf::DW_TAG_reference_type: 787 case dwarf::DW_TAG_rvalue_reference_type: 788 return lowerTypePointer(cast<DIDerivedType>(Ty)); 789 case dwarf::DW_TAG_ptr_to_member_type: 790 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty)); 791 case dwarf::DW_TAG_const_type: 792 case dwarf::DW_TAG_volatile_type: 793 return lowerTypeModifier(cast<DIDerivedType>(Ty)); 794 case dwarf::DW_TAG_subroutine_type: 795 if (ClassTy) 796 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy); 797 return lowerTypeFunction(cast<DISubroutineType>(Ty)); 798 case dwarf::DW_TAG_enumeration_type: 799 return lowerTypeEnum(cast<DICompositeType>(Ty)); 800 case dwarf::DW_TAG_class_type: 801 case dwarf::DW_TAG_structure_type: 802 return lowerTypeClass(cast<DICompositeType>(Ty)); 803 case dwarf::DW_TAG_union_type: 804 return lowerTypeUnion(cast<DICompositeType>(Ty)); 805 default: 806 // Use the null type index. 807 return TypeIndex(); 808 } 809 } 810 811 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) { 812 DITypeRef UnderlyingTypeRef = Ty->getBaseType(); 813 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef); 814 StringRef TypeName = Ty->getName(); 815 816 SmallVector<StringRef, 5> QualifiedNameComponents; 817 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents( 818 Ty->getScope().resolve(), QualifiedNameComponents); 819 820 if (ClosestSubprogram == nullptr) { 821 std::string FullyQualifiedName = 822 getQualifiedName(QualifiedNameComponents, TypeName); 823 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), UnderlyingTypeIndex); 824 } else if (ClosestSubprogram == CurrentSubprogram) { 825 std::string FullyQualifiedName = 826 getQualifiedName(QualifiedNameComponents, TypeName); 827 LocalUDTs.emplace_back(std::move(FullyQualifiedName), UnderlyingTypeIndex); 828 } 829 // TODO: What if the ClosestSubprogram is neither null or the current 830 // subprogram? Currently, the UDT just gets dropped on the floor. 831 // 832 // The current behavior is not desirable. To get maximal fidelity, we would 833 // need to perform all type translation before beginning emission of .debug$S 834 // and then make LocalUDTs a member of FunctionInfo 835 836 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) && 837 TypeName == "HRESULT") 838 return TypeIndex(SimpleTypeKind::HResult); 839 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) && 840 TypeName == "wchar_t") 841 return TypeIndex(SimpleTypeKind::WideCharacter); 842 return UnderlyingTypeIndex; 843 } 844 845 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) { 846 DITypeRef ElementTypeRef = Ty->getBaseType(); 847 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef); 848 // IndexType is size_t, which depends on the bitness of the target. 849 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8 850 ? TypeIndex(SimpleTypeKind::UInt64Quad) 851 : TypeIndex(SimpleTypeKind::UInt32Long); 852 uint64_t Size = Ty->getSizeInBits() / 8; 853 ArrayRecord Record(ElementTypeIndex, IndexType, Size, Ty->getName()); 854 return TypeTable.writeArray(Record); 855 } 856 857 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) { 858 TypeIndex Index; 859 dwarf::TypeKind Kind; 860 uint32_t ByteSize; 861 862 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding()); 863 ByteSize = Ty->getSizeInBits() / 8; 864 865 SimpleTypeKind STK = SimpleTypeKind::None; 866 switch (Kind) { 867 case dwarf::DW_ATE_address: 868 // FIXME: Translate 869 break; 870 case dwarf::DW_ATE_boolean: 871 switch (ByteSize) { 872 case 1: STK = SimpleTypeKind::Boolean8; break; 873 case 2: STK = SimpleTypeKind::Boolean16; break; 874 case 4: STK = SimpleTypeKind::Boolean32; break; 875 case 8: STK = SimpleTypeKind::Boolean64; break; 876 case 16: STK = SimpleTypeKind::Boolean128; break; 877 } 878 break; 879 case dwarf::DW_ATE_complex_float: 880 switch (ByteSize) { 881 case 2: STK = SimpleTypeKind::Complex16; break; 882 case 4: STK = SimpleTypeKind::Complex32; break; 883 case 8: STK = SimpleTypeKind::Complex64; break; 884 case 10: STK = SimpleTypeKind::Complex80; break; 885 case 16: STK = SimpleTypeKind::Complex128; break; 886 } 887 break; 888 case dwarf::DW_ATE_float: 889 switch (ByteSize) { 890 case 2: STK = SimpleTypeKind::Float16; break; 891 case 4: STK = SimpleTypeKind::Float32; break; 892 case 6: STK = SimpleTypeKind::Float48; break; 893 case 8: STK = SimpleTypeKind::Float64; break; 894 case 10: STK = SimpleTypeKind::Float80; break; 895 case 16: STK = SimpleTypeKind::Float128; break; 896 } 897 break; 898 case dwarf::DW_ATE_signed: 899 switch (ByteSize) { 900 case 1: STK = SimpleTypeKind::SByte; break; 901 case 2: STK = SimpleTypeKind::Int16Short; break; 902 case 4: STK = SimpleTypeKind::Int32; break; 903 case 8: STK = SimpleTypeKind::Int64Quad; break; 904 case 16: STK = SimpleTypeKind::Int128Oct; break; 905 } 906 break; 907 case dwarf::DW_ATE_unsigned: 908 switch (ByteSize) { 909 case 1: STK = SimpleTypeKind::Byte; break; 910 case 2: STK = SimpleTypeKind::UInt16Short; break; 911 case 4: STK = SimpleTypeKind::UInt32; break; 912 case 8: STK = SimpleTypeKind::UInt64Quad; break; 913 case 16: STK = SimpleTypeKind::UInt128Oct; break; 914 } 915 break; 916 case dwarf::DW_ATE_UTF: 917 switch (ByteSize) { 918 case 2: STK = SimpleTypeKind::Character16; break; 919 case 4: STK = SimpleTypeKind::Character32; break; 920 } 921 break; 922 case dwarf::DW_ATE_signed_char: 923 if (ByteSize == 1) 924 STK = SimpleTypeKind::SignedCharacter; 925 break; 926 case dwarf::DW_ATE_unsigned_char: 927 if (ByteSize == 1) 928 STK = SimpleTypeKind::UnsignedCharacter; 929 break; 930 default: 931 break; 932 } 933 934 // Apply some fixups based on the source-level type name. 935 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int") 936 STK = SimpleTypeKind::Int32Long; 937 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int") 938 STK = SimpleTypeKind::UInt32Long; 939 if (STK == SimpleTypeKind::UInt16Short && 940 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t")) 941 STK = SimpleTypeKind::WideCharacter; 942 if ((STK == SimpleTypeKind::SignedCharacter || 943 STK == SimpleTypeKind::UnsignedCharacter) && 944 Ty->getName() == "char") 945 STK = SimpleTypeKind::NarrowCharacter; 946 947 return TypeIndex(STK); 948 } 949 950 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) { 951 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType()); 952 953 // While processing the type being pointed to it is possible we already 954 // created this pointer type. If so, we check here and return the existing 955 // pointer type. 956 auto I = TypeIndices.find({Ty, nullptr}); 957 if (I != TypeIndices.end()) 958 return I->second; 959 960 // Pointers to simple types can use SimpleTypeMode, rather than having a 961 // dedicated pointer type record. 962 if (PointeeTI.isSimple() && 963 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct && 964 Ty->getTag() == dwarf::DW_TAG_pointer_type) { 965 SimpleTypeMode Mode = Ty->getSizeInBits() == 64 966 ? SimpleTypeMode::NearPointer64 967 : SimpleTypeMode::NearPointer32; 968 return TypeIndex(PointeeTI.getSimpleKind(), Mode); 969 } 970 971 PointerKind PK = 972 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32; 973 PointerMode PM = PointerMode::Pointer; 974 switch (Ty->getTag()) { 975 default: llvm_unreachable("not a pointer tag type"); 976 case dwarf::DW_TAG_pointer_type: 977 PM = PointerMode::Pointer; 978 break; 979 case dwarf::DW_TAG_reference_type: 980 PM = PointerMode::LValueReference; 981 break; 982 case dwarf::DW_TAG_rvalue_reference_type: 983 PM = PointerMode::RValueReference; 984 break; 985 } 986 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method 987 // 'this' pointer, but not normal contexts. Figure out what we're supposed to 988 // do. 989 PointerOptions PO = PointerOptions::None; 990 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8); 991 return TypeTable.writePointer(PR); 992 } 993 994 static PointerToMemberRepresentation 995 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) { 996 // SizeInBytes being zero generally implies that the member pointer type was 997 // incomplete, which can happen if it is part of a function prototype. In this 998 // case, use the unknown model instead of the general model. 999 if (IsPMF) { 1000 switch (Flags & DINode::FlagPtrToMemberRep) { 1001 case 0: 1002 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1003 : PointerToMemberRepresentation::GeneralFunction; 1004 case DINode::FlagSingleInheritance: 1005 return PointerToMemberRepresentation::SingleInheritanceFunction; 1006 case DINode::FlagMultipleInheritance: 1007 return PointerToMemberRepresentation::MultipleInheritanceFunction; 1008 case DINode::FlagVirtualInheritance: 1009 return PointerToMemberRepresentation::VirtualInheritanceFunction; 1010 } 1011 } else { 1012 switch (Flags & DINode::FlagPtrToMemberRep) { 1013 case 0: 1014 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown 1015 : PointerToMemberRepresentation::GeneralData; 1016 case DINode::FlagSingleInheritance: 1017 return PointerToMemberRepresentation::SingleInheritanceData; 1018 case DINode::FlagMultipleInheritance: 1019 return PointerToMemberRepresentation::MultipleInheritanceData; 1020 case DINode::FlagVirtualInheritance: 1021 return PointerToMemberRepresentation::VirtualInheritanceData; 1022 } 1023 } 1024 llvm_unreachable("invalid ptr to member representation"); 1025 } 1026 1027 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) { 1028 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type); 1029 TypeIndex ClassTI = getTypeIndex(Ty->getClassType()); 1030 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType()); 1031 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64 1032 : PointerKind::Near32; 1033 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType()); 1034 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction 1035 : PointerMode::PointerToDataMember; 1036 PointerOptions PO = PointerOptions::None; // FIXME 1037 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big"); 1038 uint8_t SizeInBytes = Ty->getSizeInBits() / 8; 1039 MemberPointerInfo MPI( 1040 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags())); 1041 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI); 1042 return TypeTable.writePointer(PR); 1043 } 1044 1045 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't 1046 /// have a translation, use the NearC convention. 1047 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) { 1048 switch (DwarfCC) { 1049 case dwarf::DW_CC_normal: return CallingConvention::NearC; 1050 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast; 1051 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall; 1052 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall; 1053 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal; 1054 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector; 1055 } 1056 return CallingConvention::NearC; 1057 } 1058 1059 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) { 1060 ModifierOptions Mods = ModifierOptions::None; 1061 bool IsModifier = true; 1062 const DIType *BaseTy = Ty; 1063 while (IsModifier && BaseTy) { 1064 // FIXME: Need to add DWARF tag for __unaligned. 1065 switch (BaseTy->getTag()) { 1066 case dwarf::DW_TAG_const_type: 1067 Mods |= ModifierOptions::Const; 1068 break; 1069 case dwarf::DW_TAG_volatile_type: 1070 Mods |= ModifierOptions::Volatile; 1071 break; 1072 default: 1073 IsModifier = false; 1074 break; 1075 } 1076 if (IsModifier) 1077 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve(); 1078 } 1079 TypeIndex ModifiedTI = getTypeIndex(BaseTy); 1080 1081 // While processing the type being pointed to, it is possible we already 1082 // created this modifier type. If so, we check here and return the existing 1083 // modifier type. 1084 auto I = TypeIndices.find({Ty, nullptr}); 1085 if (I != TypeIndices.end()) 1086 return I->second; 1087 1088 ModifierRecord MR(ModifiedTI, Mods); 1089 return TypeTable.writeModifier(MR); 1090 } 1091 1092 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) { 1093 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices; 1094 for (DITypeRef ArgTypeRef : Ty->getTypeArray()) 1095 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef)); 1096 1097 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 1098 ArrayRef<TypeIndex> ArgTypeIndices = None; 1099 if (!ReturnAndArgTypeIndices.empty()) { 1100 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices); 1101 ReturnTypeIndex = ReturnAndArgTypesRef.front(); 1102 ArgTypeIndices = ReturnAndArgTypesRef.drop_front(); 1103 } 1104 1105 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 1106 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec); 1107 1108 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 1109 1110 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None, 1111 ArgTypeIndices.size(), ArgListIndex); 1112 return TypeTable.writeProcedure(Procedure); 1113 } 1114 1115 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty, 1116 const DIType *ClassTy) { 1117 // Lower the containing class type. 1118 TypeIndex ClassType = getTypeIndex(ClassTy); 1119 1120 // While processing the class type it is possible we already created this 1121 // member function. If so, we check here and return the existing one. 1122 auto I = TypeIndices.find({Ty, ClassTy}); 1123 if (I != TypeIndices.end()) 1124 return I->second; 1125 1126 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices; 1127 for (DITypeRef ArgTypeRef : Ty->getTypeArray()) 1128 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef)); 1129 1130 TypeIndex ReturnTypeIndex = TypeIndex::Void(); 1131 ArrayRef<TypeIndex> ArgTypeIndices = None; 1132 if (!ReturnAndArgTypeIndices.empty()) { 1133 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices); 1134 ReturnTypeIndex = ReturnAndArgTypesRef.front(); 1135 ArgTypeIndices = ReturnAndArgTypesRef.drop_front(); 1136 } 1137 TypeIndex ThisTypeIndex = TypeIndex::Void(); 1138 if (!ArgTypeIndices.empty()) { 1139 ThisTypeIndex = ArgTypeIndices.front(); 1140 ArgTypeIndices = ArgTypeIndices.drop_front(); 1141 } 1142 1143 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); 1144 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec); 1145 1146 CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); 1147 1148 // TODO: Need to use the correct values for: 1149 // FunctionOptions 1150 // ThisPointerAdjustment. 1151 TypeIndex TI = TypeTable.writeMemberFunction(MemberFunctionRecord( 1152 ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None, 1153 ArgTypeIndices.size(), ArgListIndex, 0)); 1154 1155 return TI; 1156 } 1157 1158 TypeIndex CodeViewDebug::lowerSubprogramType(const DISubprogram *SP) { 1159 auto ClassType = dyn_cast_or_null<DIType>(SP->getScope().resolve()); 1160 TypeIndex TI = getTypeIndex(SP->getType(), ClassType); 1161 1162 return TI; 1163 } 1164 1165 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) { 1166 switch (Flags & DINode::FlagAccessibility) { 1167 case DINode::FlagPrivate: return MemberAccess::Private; 1168 case DINode::FlagPublic: return MemberAccess::Public; 1169 case DINode::FlagProtected: return MemberAccess::Protected; 1170 case 0: 1171 // If there was no explicit access control, provide the default for the tag. 1172 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private 1173 : MemberAccess::Public; 1174 } 1175 llvm_unreachable("access flags are exclusive"); 1176 } 1177 1178 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) { 1179 if (SP->isArtificial()) 1180 return MethodOptions::CompilerGenerated; 1181 1182 // FIXME: Handle other MethodOptions. 1183 1184 return MethodOptions::None; 1185 } 1186 1187 static MethodKind translateMethodKindFlags(const DISubprogram *SP, 1188 bool Introduced) { 1189 switch (SP->getVirtuality()) { 1190 case dwarf::DW_VIRTUALITY_none: 1191 break; 1192 case dwarf::DW_VIRTUALITY_virtual: 1193 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual; 1194 case dwarf::DW_VIRTUALITY_pure_virtual: 1195 return Introduced ? MethodKind::PureIntroducingVirtual 1196 : MethodKind::PureVirtual; 1197 default: 1198 llvm_unreachable("unhandled virtuality case"); 1199 } 1200 1201 // FIXME: Get Clang to mark DISubprogram as static and do something with it. 1202 1203 return MethodKind::Vanilla; 1204 } 1205 1206 static TypeRecordKind getRecordKind(const DICompositeType *Ty) { 1207 switch (Ty->getTag()) { 1208 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class; 1209 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct; 1210 } 1211 llvm_unreachable("unexpected tag"); 1212 } 1213 1214 /// Return the HasUniqueName option if it should be present in ClassOptions, or 1215 /// None otherwise. 1216 static ClassOptions getRecordUniqueNameOption(const DICompositeType *Ty) { 1217 // MSVC always sets this flag now, even for local types. Clang doesn't always 1218 // appear to give every type a linkage name, which may be problematic for us. 1219 // FIXME: Investigate the consequences of not following them here. 1220 return !Ty->getIdentifier().empty() ? ClassOptions::HasUniqueName 1221 : ClassOptions::None; 1222 } 1223 1224 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) { 1225 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty); 1226 TypeIndex FTI; 1227 unsigned EnumeratorCount = 0; 1228 1229 if (Ty->isForwardDecl()) { 1230 CO |= ClassOptions::ForwardReference; 1231 } else { 1232 FieldListRecordBuilder Fields; 1233 for (const DINode *Element : Ty->getElements()) { 1234 // We assume that the frontend provides all members in source declaration 1235 // order, which is what MSVC does. 1236 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) { 1237 Fields.writeEnumerator(EnumeratorRecord( 1238 MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()), 1239 Enumerator->getName())); 1240 EnumeratorCount++; 1241 } 1242 } 1243 FTI = TypeTable.writeFieldList(Fields); 1244 } 1245 1246 return TypeTable.writeEnum(EnumRecord(EnumeratorCount, CO, FTI, Ty->getName(), 1247 Ty->getIdentifier(), 1248 getTypeIndex(Ty->getBaseType()))); 1249 } 1250 1251 //===----------------------------------------------------------------------===// 1252 // ClassInfo 1253 //===----------------------------------------------------------------------===// 1254 1255 struct llvm::ClassInfo { 1256 struct MemberInfo { 1257 const DIDerivedType *MemberTypeNode; 1258 unsigned BaseOffset; 1259 }; 1260 // [MemberInfo] 1261 typedef std::vector<MemberInfo> MemberList; 1262 1263 struct MethodInfo { 1264 const DISubprogram *Method; 1265 bool Introduced; 1266 }; 1267 // [MethodInfo] 1268 typedef std::vector<MethodInfo> MethodsList; 1269 // MethodName -> MethodsList 1270 typedef MapVector<MDString *, MethodsList> MethodsMap; 1271 1272 /// Direct members. 1273 MemberList Members; 1274 // Direct overloaded methods gathered by name. 1275 MethodsMap Methods; 1276 }; 1277 1278 void CodeViewDebug::clear() { 1279 assert(CurFn == nullptr); 1280 FileIdMap.clear(); 1281 FnDebugInfo.clear(); 1282 FileToFilepathMap.clear(); 1283 LocalUDTs.clear(); 1284 GlobalUDTs.clear(); 1285 TypeIndices.clear(); 1286 CompleteTypeIndices.clear(); 1287 ClassInfoMap.clear(); 1288 } 1289 1290 void CodeViewDebug::collectMemberInfo(ClassInfo &Info, 1291 const DIDerivedType *DDTy) { 1292 if (!DDTy->getName().empty()) { 1293 Info.Members.push_back({DDTy, 0}); 1294 return; 1295 } 1296 // Member with no name, must be nested structure/union, collects its memebers 1297 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!"); 1298 unsigned offset = DDTy->getOffsetInBits() / 8; 1299 const DIType *Ty = DDTy->getBaseType().resolve(); 1300 assert(dyn_cast<DICompositeType>(Ty) && "Expects structure or union type"); 1301 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty); 1302 ClassInfo &NestedInfo = collectClassInfo(DCTy); 1303 ClassInfo::MemberList &Members = NestedInfo.Members; 1304 for (unsigned i = 0, e = Members.size(); i != e; ++i) 1305 Info.Members.push_back( 1306 {Members[i].MemberTypeNode, Members[i].BaseOffset + offset}); 1307 } 1308 1309 ClassInfo &CodeViewDebug::collectClassInfo(const DICompositeType *Ty) { 1310 auto Insertion = ClassInfoMap.insert({Ty, std::unique_ptr<ClassInfo>()}); 1311 std::unique_ptr<ClassInfo> &Info = Insertion.first->second; 1312 if (!Insertion.second) 1313 return *Info; 1314 Info.reset(new ClassInfo()); 1315 1316 // Add elements to structure type. 1317 DINodeArray Elements = Ty->getElements(); 1318 for (auto *Element : Elements) { 1319 // We assume that the frontend provides all members in source declaration 1320 // order, which is what MSVC does. 1321 if (!Element) 1322 continue; 1323 if (auto *SP = dyn_cast<DISubprogram>(Element)) { 1324 // Non-virtual methods does not need the introduced marker. 1325 // Set it to false. 1326 bool Introduced = false; 1327 Info->Methods[SP->getRawName()].push_back({SP, Introduced}); 1328 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) { 1329 if (DDTy->getTag() == dwarf::DW_TAG_member) 1330 collectMemberInfo(*Info, DDTy); 1331 else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) { 1332 // FIXME: collect class info from inheritance. 1333 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) { 1334 // Ignore friend members. It appears that MSVC emitted info about 1335 // friends in the past, but modern versions do not. 1336 } 1337 // FIXME: Get Clang to emit function virtual table here and handle it. 1338 // FIXME: Get clang to emit nested types here and do something with 1339 // them. 1340 } 1341 // Skip other unrecognized kinds of elements. 1342 } 1343 1344 return *Info; 1345 } 1346 1347 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) { 1348 // First, construct the forward decl. Don't look into Ty to compute the 1349 // forward decl options, since it might not be available in all TUs. 1350 TypeRecordKind Kind = getRecordKind(Ty); 1351 ClassOptions CO = 1352 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty); 1353 TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord( 1354 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(), 1355 TypeIndex(), TypeIndex(), 0, Ty->getName(), Ty->getIdentifier())); 1356 return FwdDeclTI; 1357 } 1358 1359 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) { 1360 // Construct the field list and complete type record. 1361 TypeRecordKind Kind = getRecordKind(Ty); 1362 // FIXME: Other ClassOptions, like ContainsNestedClass and NestedClass. 1363 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty); 1364 TypeIndex FieldTI; 1365 TypeIndex VShapeTI; 1366 unsigned FieldCount; 1367 std::tie(FieldTI, VShapeTI, FieldCount) = lowerRecordFieldList(Ty); 1368 1369 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 1370 return TypeTable.writeClass(ClassRecord( 1371 Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI, 1372 TypeIndex(), VShapeTI, SizeInBytes, Ty->getName(), Ty->getIdentifier())); 1373 // FIXME: Make an LF_UDT_SRC_LINE record. 1374 } 1375 1376 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) { 1377 ClassOptions CO = 1378 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty); 1379 TypeIndex FwdDeclTI = 1380 TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0, 1381 Ty->getName(), Ty->getIdentifier())); 1382 return FwdDeclTI; 1383 } 1384 1385 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) { 1386 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty); 1387 TypeIndex FieldTI; 1388 unsigned FieldCount; 1389 std::tie(FieldTI, std::ignore, FieldCount) = lowerRecordFieldList(Ty); 1390 uint64_t SizeInBytes = Ty->getSizeInBits() / 8; 1391 return TypeTable.writeUnion(UnionRecord(FieldCount, CO, HfaKind::None, 1392 FieldTI, SizeInBytes, Ty->getName(), 1393 Ty->getIdentifier())); 1394 // FIXME: Make an LF_UDT_SRC_LINE record. 1395 } 1396 1397 std::tuple<TypeIndex, TypeIndex, unsigned> 1398 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) { 1399 // Manually count members. MSVC appears to count everything that generates a 1400 // field list record. Each individual overload in a method overload group 1401 // contributes to this count, even though the overload group is a single field 1402 // list record. 1403 unsigned MemberCount = 0; 1404 ClassInfo &Info = collectClassInfo(Ty); 1405 FieldListRecordBuilder Fields; 1406 1407 // Create members. 1408 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) { 1409 const DIDerivedType *Member = MemberInfo.MemberTypeNode; 1410 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType()); 1411 1412 if (Member->isStaticMember()) { 1413 Fields.writeStaticDataMember(StaticDataMemberRecord( 1414 translateAccessFlags(Ty->getTag(), Member->getFlags()), 1415 MemberBaseType, Member->getName())); 1416 MemberCount++; 1417 continue; 1418 } 1419 1420 uint64_t OffsetInBytes = MemberInfo.BaseOffset; 1421 1422 // FIXME: Handle bitfield type memeber. 1423 OffsetInBytes += Member->getOffsetInBits() / 8; 1424 1425 Fields.writeDataMember( 1426 DataMemberRecord(translateAccessFlags(Ty->getTag(), Member->getFlags()), 1427 MemberBaseType, OffsetInBytes, Member->getName())); 1428 MemberCount++; 1429 } 1430 1431 // Create methods 1432 for (auto &MethodItr : Info.Methods) { 1433 StringRef Name = MethodItr.first->getString(); 1434 1435 std::vector<OneMethodRecord> Methods; 1436 for (ClassInfo::MethodInfo &MethodInfo : MethodItr.second) { 1437 const DISubprogram *SP = MethodInfo.Method; 1438 bool Introduced = MethodInfo.Introduced; 1439 1440 TypeIndex MethodType = getTypeIndex(SP->getType(), Ty); 1441 1442 unsigned VFTableOffset = -1; 1443 if (Introduced) 1444 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes(); 1445 1446 Methods.push_back( 1447 OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced), 1448 translateMethodOptionFlags(SP), 1449 translateAccessFlags(Ty->getTag(), SP->getFlags()), 1450 VFTableOffset, Name)); 1451 MemberCount++; 1452 } 1453 assert(Methods.size() > 0 && "Empty methods map entry"); 1454 if (Methods.size() == 1) 1455 Fields.writeOneMethod(Methods[0]); 1456 else { 1457 TypeIndex MethodList = 1458 TypeTable.writeMethodOverloadList(MethodOverloadListRecord(Methods)); 1459 Fields.writeOverloadedMethod( 1460 OverloadedMethodRecord(Methods.size(), MethodList, Name)); 1461 } 1462 } 1463 TypeIndex FieldTI = TypeTable.writeFieldList(Fields); 1464 return std::make_tuple(FieldTI, TypeIndex(), MemberCount); 1465 } 1466 1467 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) { 1468 const DIType *Ty = TypeRef.resolve(); 1469 const DIType *ClassTy = ClassTyRef.resolve(); 1470 1471 // The null DIType is the void type. Don't try to hash it. 1472 if (!Ty) 1473 return TypeIndex::Void(); 1474 1475 // Check if we've already translated this type. Don't try to do a 1476 // get-or-create style insertion that caches the hash lookup across the 1477 // lowerType call. It will update the TypeIndices map. 1478 auto I = TypeIndices.find({Ty, ClassTy}); 1479 if (I != TypeIndices.end()) 1480 return I->second; 1481 1482 TypeIndex TI = lowerType(Ty, ClassTy); 1483 1484 recordTypeIndexForDINode(Ty, TI, ClassTy); 1485 return TI; 1486 } 1487 1488 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) { 1489 const DIType *Ty = TypeRef.resolve(); 1490 1491 // The null DIType is the void type. Don't try to hash it. 1492 if (!Ty) 1493 return TypeIndex::Void(); 1494 1495 // If this is a non-record type, the complete type index is the same as the 1496 // normal type index. Just call getTypeIndex. 1497 switch (Ty->getTag()) { 1498 case dwarf::DW_TAG_class_type: 1499 case dwarf::DW_TAG_structure_type: 1500 case dwarf::DW_TAG_union_type: 1501 break; 1502 default: 1503 return getTypeIndex(Ty); 1504 } 1505 1506 // Check if we've already translated the complete record type. Lowering a 1507 // complete type should never trigger lowering another complete type, so we 1508 // can reuse the hash table lookup result. 1509 const auto *CTy = cast<DICompositeType>(Ty); 1510 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()}); 1511 if (!InsertResult.second) 1512 return InsertResult.first->second; 1513 1514 // Make sure the forward declaration is emitted first. It's unclear if this 1515 // is necessary, but MSVC does it, and we should follow suit until we can show 1516 // otherwise. 1517 TypeIndex FwdDeclTI = getTypeIndex(CTy); 1518 1519 // Just use the forward decl if we don't have complete type info. This might 1520 // happen if the frontend is using modules and expects the complete definition 1521 // to be emitted elsewhere. 1522 if (CTy->isForwardDecl()) 1523 return FwdDeclTI; 1524 1525 TypeIndex TI; 1526 switch (CTy->getTag()) { 1527 case dwarf::DW_TAG_class_type: 1528 case dwarf::DW_TAG_structure_type: 1529 TI = lowerCompleteTypeClass(CTy); 1530 break; 1531 case dwarf::DW_TAG_union_type: 1532 TI = lowerCompleteTypeUnion(CTy); 1533 break; 1534 default: 1535 llvm_unreachable("not a record"); 1536 } 1537 1538 InsertResult.first->second = TI; 1539 return TI; 1540 } 1541 1542 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) { 1543 // LocalSym record, see SymbolRecord.h for more info. 1544 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(), 1545 *LocalEnd = MMI->getContext().createTempSymbol(); 1546 OS.AddComment("Record length"); 1547 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2); 1548 OS.EmitLabel(LocalBegin); 1549 1550 OS.AddComment("Record kind: S_LOCAL"); 1551 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2); 1552 1553 LocalSymFlags Flags = LocalSymFlags::None; 1554 if (Var.DIVar->isParameter()) 1555 Flags |= LocalSymFlags::IsParameter; 1556 if (Var.DefRanges.empty()) 1557 Flags |= LocalSymFlags::IsOptimizedOut; 1558 1559 OS.AddComment("TypeIndex"); 1560 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType()); 1561 OS.EmitIntValue(TI.getIndex(), 4); 1562 OS.AddComment("Flags"); 1563 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2); 1564 // Truncate the name so we won't overflow the record length field. 1565 emitNullTerminatedSymbolName(OS, Var.DIVar->getName()); 1566 OS.EmitLabel(LocalEnd); 1567 1568 // Calculate the on disk prefix of the appropriate def range record. The 1569 // records and on disk formats are described in SymbolRecords.h. BytePrefix 1570 // should be big enough to hold all forms without memory allocation. 1571 SmallString<20> BytePrefix; 1572 for (const LocalVarDefRange &DefRange : Var.DefRanges) { 1573 BytePrefix.clear(); 1574 // FIXME: Handle bitpieces. 1575 if (DefRange.StructOffset != 0) 1576 continue; 1577 1578 if (DefRange.InMemory) { 1579 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0, 1580 0, 0, ArrayRef<LocalVariableAddrGap>()); 1581 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL); 1582 BytePrefix += 1583 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 1584 BytePrefix += 1585 StringRef(reinterpret_cast<const char *>(&Sym.Header), 1586 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange)); 1587 } else { 1588 assert(DefRange.DataOffset == 0 && "unexpected offset into register"); 1589 // Unclear what matters here. 1590 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0, 1591 ArrayRef<LocalVariableAddrGap>()); 1592 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER); 1593 BytePrefix += 1594 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 1595 BytePrefix += 1596 StringRef(reinterpret_cast<const char *>(&Sym.Header), 1597 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange)); 1598 } 1599 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix); 1600 } 1601 } 1602 1603 void CodeViewDebug::endFunction(const MachineFunction *MF) { 1604 if (!Asm || !CurFn) // We haven't created any debug info for this function. 1605 return; 1606 1607 const Function *GV = MF->getFunction(); 1608 assert(FnDebugInfo.count(GV)); 1609 assert(CurFn == &FnDebugInfo[GV]); 1610 1611 collectVariableInfo(GV->getSubprogram()); 1612 1613 DebugHandlerBase::endFunction(MF); 1614 1615 // Don't emit anything if we don't have any line tables. 1616 if (!CurFn->HaveLineInfo) { 1617 FnDebugInfo.erase(GV); 1618 CurFn = nullptr; 1619 return; 1620 } 1621 1622 CurFn->End = Asm->getFunctionEnd(); 1623 1624 CurFn = nullptr; 1625 } 1626 1627 void CodeViewDebug::beginInstruction(const MachineInstr *MI) { 1628 DebugHandlerBase::beginInstruction(MI); 1629 1630 // Ignore DBG_VALUE locations and function prologue. 1631 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup)) 1632 return; 1633 DebugLoc DL = MI->getDebugLoc(); 1634 if (DL == PrevInstLoc || !DL) 1635 return; 1636 maybeRecordLocation(DL, Asm->MF); 1637 } 1638 1639 MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) { 1640 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(), 1641 *EndLabel = MMI->getContext().createTempSymbol(); 1642 OS.EmitIntValue(unsigned(Kind), 4); 1643 OS.AddComment("Subsection size"); 1644 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4); 1645 OS.EmitLabel(BeginLabel); 1646 return EndLabel; 1647 } 1648 1649 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) { 1650 OS.EmitLabel(EndLabel); 1651 // Every subsection must be aligned to a 4-byte boundary. 1652 OS.EmitValueToAlignment(4); 1653 } 1654 1655 void CodeViewDebug::emitDebugInfoForUDTs( 1656 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) { 1657 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) { 1658 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(), 1659 *UDTRecordEnd = MMI->getContext().createTempSymbol(); 1660 OS.AddComment("Record length"); 1661 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2); 1662 OS.EmitLabel(UDTRecordBegin); 1663 1664 OS.AddComment("Record kind: S_UDT"); 1665 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2); 1666 1667 OS.AddComment("Type"); 1668 OS.EmitIntValue(UDT.second.getIndex(), 4); 1669 1670 emitNullTerminatedSymbolName(OS, UDT.first); 1671 OS.EmitLabel(UDTRecordEnd); 1672 } 1673 } 1674 1675 void CodeViewDebug::emitDebugInfoForGlobals() { 1676 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 1677 for (const MDNode *Node : CUs->operands()) { 1678 const auto *CU = cast<DICompileUnit>(Node); 1679 1680 // First, emit all globals that are not in a comdat in a single symbol 1681 // substream. MSVC doesn't like it if the substream is empty, so only open 1682 // it if we have at least one global to emit. 1683 switchToDebugSectionForSymbol(nullptr); 1684 MCSymbol *EndLabel = nullptr; 1685 for (const DIGlobalVariable *G : CU->getGlobalVariables()) { 1686 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) { 1687 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) { 1688 if (!EndLabel) { 1689 OS.AddComment("Symbol subsection for globals"); 1690 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols); 1691 } 1692 emitDebugInfoForGlobal(G, Asm->getSymbol(GV)); 1693 } 1694 } 1695 } 1696 if (EndLabel) 1697 endCVSubsection(EndLabel); 1698 1699 // Second, emit each global that is in a comdat into its own .debug$S 1700 // section along with its own symbol substream. 1701 for (const DIGlobalVariable *G : CU->getGlobalVariables()) { 1702 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) { 1703 if (GV->hasComdat()) { 1704 MCSymbol *GVSym = Asm->getSymbol(GV); 1705 OS.AddComment("Symbol subsection for " + 1706 Twine(GlobalValue::getRealLinkageName(GV->getName()))); 1707 switchToDebugSectionForSymbol(GVSym); 1708 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols); 1709 emitDebugInfoForGlobal(G, GVSym); 1710 endCVSubsection(EndLabel); 1711 } 1712 } 1713 } 1714 } 1715 } 1716 1717 void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV, 1718 MCSymbol *GVSym) { 1719 // DataSym record, see SymbolRecord.h for more info. 1720 // FIXME: Thread local data, etc 1721 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(), 1722 *DataEnd = MMI->getContext().createTempSymbol(); 1723 OS.AddComment("Record length"); 1724 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2); 1725 OS.EmitLabel(DataBegin); 1726 OS.AddComment("Record kind: S_GDATA32"); 1727 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2); 1728 OS.AddComment("Type"); 1729 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4); 1730 OS.AddComment("DataOffset"); 1731 OS.EmitCOFFSecRel32(GVSym); 1732 OS.AddComment("Segment"); 1733 OS.EmitCOFFSectionIndex(GVSym); 1734 OS.AddComment("Name"); 1735 emitNullTerminatedSymbolName(OS, DIGV->getName()); 1736 OS.EmitLabel(DataEnd); 1737 } 1738