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/Line.h" 17 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 18 #include "llvm/DebugInfo/CodeView/TypeIndex.h" 19 #include "llvm/DebugInfo/CodeView/TypeRecord.h" 20 #include "llvm/MC/MCExpr.h" 21 #include "llvm/MC/MCSymbol.h" 22 #include "llvm/Support/COFF.h" 23 #include "llvm/Target/TargetSubtargetInfo.h" 24 #include "llvm/Target/TargetRegisterInfo.h" 25 #include "llvm/Target/TargetFrameLowering.h" 26 27 using namespace llvm; 28 using namespace llvm::codeview; 29 30 CodeViewDebug::CodeViewDebug(AsmPrinter *AP) 31 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) { 32 // If module doesn't have named metadata anchors or COFF debug section 33 // is not available, skip any debug info related stuff. 34 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") || 35 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) { 36 Asm = nullptr; 37 return; 38 } 39 40 // Tell MMI that we have debug info. 41 MMI->setDebugInfoAvailability(true); 42 } 43 44 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) { 45 std::string &Filepath = FileToFilepathMap[File]; 46 if (!Filepath.empty()) 47 return Filepath; 48 49 StringRef Dir = File->getDirectory(), Filename = File->getFilename(); 50 51 // Clang emits directory and relative filename info into the IR, but CodeView 52 // operates on full paths. We could change Clang to emit full paths too, but 53 // that would increase the IR size and probably not needed for other users. 54 // For now, just concatenate and canonicalize the path here. 55 if (Filename.find(':') == 1) 56 Filepath = Filename; 57 else 58 Filepath = (Dir + "\\" + Filename).str(); 59 60 // Canonicalize the path. We have to do it textually because we may no longer 61 // have access the file in the filesystem. 62 // First, replace all slashes with backslashes. 63 std::replace(Filepath.begin(), Filepath.end(), '/', '\\'); 64 65 // Remove all "\.\" with "\". 66 size_t Cursor = 0; 67 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos) 68 Filepath.erase(Cursor, 2); 69 70 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original 71 // path should be well-formatted, e.g. start with a drive letter, etc. 72 Cursor = 0; 73 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) { 74 // Something's wrong if the path starts with "\..\", abort. 75 if (Cursor == 0) 76 break; 77 78 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1); 79 if (PrevSlash == std::string::npos) 80 // Something's wrong, abort. 81 break; 82 83 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash); 84 // The next ".." might be following the one we've just erased. 85 Cursor = PrevSlash; 86 } 87 88 // Remove all duplicate backslashes. 89 Cursor = 0; 90 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos) 91 Filepath.erase(Cursor, 1); 92 93 return Filepath; 94 } 95 96 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) { 97 unsigned NextId = FileIdMap.size() + 1; 98 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId)); 99 if (Insertion.second) { 100 // We have to compute the full filepath and emit a .cv_file directive. 101 StringRef FullPath = getFullFilepath(F); 102 NextId = OS.EmitCVFileDirective(NextId, FullPath); 103 assert(NextId == FileIdMap.size() && ".cv_file directive failed"); 104 } 105 return Insertion.first->second; 106 } 107 108 CodeViewDebug::InlineSite & 109 CodeViewDebug::getInlineSite(const DILocation *InlinedAt, 110 const DISubprogram *Inlinee) { 111 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()}); 112 InlineSite *Site = &SiteInsertion.first->second; 113 if (SiteInsertion.second) { 114 Site->SiteFuncId = NextFuncId++; 115 Site->Inlinee = Inlinee; 116 auto InlineeInsertion = 117 SubprogramIndices.insert({Inlinee, InlinedSubprograms.size()}); 118 if (InlineeInsertion.second) 119 InlinedSubprograms.push_back(Inlinee); 120 } 121 return *Site; 122 } 123 124 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var, 125 const DILocation *InlinedAt) { 126 if (InlinedAt) { 127 // This variable was inlined. Associate it with the InlineSite. 128 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram(); 129 InlineSite &Site = getInlineSite(InlinedAt, Inlinee); 130 Site.InlinedLocals.emplace_back(Var); 131 } else { 132 // This variable goes in the main ProcSym. 133 CurFn->Locals.emplace_back(Var); 134 } 135 } 136 137 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs, 138 const DILocation *Loc) { 139 auto B = Locs.begin(), E = Locs.end(); 140 if (std::find(B, E, Loc) == E) 141 Locs.push_back(Loc); 142 } 143 144 void CodeViewDebug::maybeRecordLocation(DebugLoc DL, 145 const MachineFunction *MF) { 146 // Skip this instruction if it has the same location as the previous one. 147 if (DL == CurFn->LastLoc) 148 return; 149 150 const DIScope *Scope = DL.get()->getScope(); 151 if (!Scope) 152 return; 153 154 // Skip this line if it is longer than the maximum we can record. 155 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true); 156 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() || 157 LI.isNeverStepInto()) 158 return; 159 160 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0); 161 if (CI.getStartColumn() != DL.getCol()) 162 return; 163 164 if (!CurFn->HaveLineInfo) 165 CurFn->HaveLineInfo = true; 166 unsigned FileId = 0; 167 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile()) 168 FileId = CurFn->LastFileId; 169 else 170 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile()); 171 CurFn->LastLoc = DL; 172 173 unsigned FuncId = CurFn->FuncId; 174 if (const DILocation *SiteLoc = DL->getInlinedAt()) { 175 const DILocation *Loc = DL.get(); 176 177 // If this location was actually inlined from somewhere else, give it the ID 178 // of the inline call site. 179 FuncId = 180 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId; 181 182 // Ensure we have links in the tree of inline call sites. 183 bool FirstLoc = true; 184 while ((SiteLoc = Loc->getInlinedAt())) { 185 InlineSite &Site = 186 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()); 187 if (!FirstLoc) 188 addLocIfNotPresent(Site.ChildSites, Loc); 189 FirstLoc = false; 190 Loc = SiteLoc; 191 } 192 addLocIfNotPresent(CurFn->ChildSites, Loc); 193 } 194 195 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(), 196 /*PrologueEnd=*/false, 197 /*IsStmt=*/false, DL->getFilename()); 198 } 199 200 void CodeViewDebug::endModule() { 201 if (FnDebugInfo.empty()) 202 return; 203 204 emitTypeInformation(); 205 206 // FIXME: For functions that are comdat, we should emit separate .debug$S 207 // sections that are comdat associative with the main function instead of 208 // having one big .debug$S section. 209 assert(Asm != nullptr); 210 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugSymbolsSection()); 211 OS.AddComment("Debug section magic"); 212 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4); 213 214 // The COFF .debug$S section consists of several subsections, each starting 215 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length 216 // of the payload followed by the payload itself. The subsections are 4-byte 217 // aligned. 218 219 // Make a subsection for all the inlined subprograms. 220 emitInlineeFuncIdsAndLines(); 221 222 // Emit per-function debug information. 223 for (auto &P : FnDebugInfo) 224 emitDebugInfoForFunction(P.first, P.second); 225 226 // This subsection holds a file index to offset in string table table. 227 OS.AddComment("File index to string table offset subsection"); 228 OS.EmitCVFileChecksumsDirective(); 229 230 // This subsection holds the string table. 231 OS.AddComment("String table"); 232 OS.EmitCVStringTableDirective(); 233 234 clear(); 235 } 236 237 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) { 238 // Microsoft's linker seems to have trouble with symbol names longer than 239 // 0xffd8 bytes. 240 S = S.substr(0, 0xffd8); 241 SmallString<32> NullTerminatedString(S); 242 NullTerminatedString.push_back('\0'); 243 OS.EmitBytes(NullTerminatedString); 244 } 245 246 void CodeViewDebug::emitTypeInformation() { 247 // Do nothing if we have no debug info or no inlined subprograms. The types 248 // we currently emit exist only to support inlined call site info. 249 NamedMDNode *CU_Nodes = 250 MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); 251 if (!CU_Nodes) 252 return; 253 if (InlinedSubprograms.empty()) 254 return; 255 256 // Start the .debug$T section with 0x4. 257 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection()); 258 OS.AddComment("Debug section magic"); 259 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4); 260 261 // This type info currently only holds function ids for use with inline call 262 // frame info. All functions are assigned a simple 'void ()' type. Emit that 263 // type here. 264 unsigned ArgListIndex = getNextTypeIndex(); 265 OS.AddComment("Type record length"); 266 OS.EmitIntValue(2 + sizeof(ArgList), 2); 267 OS.AddComment("Leaf type: LF_ARGLIST"); 268 OS.EmitIntValue(LF_ARGLIST, 2); 269 OS.AddComment("Number of arguments"); 270 OS.EmitIntValue(0, 4); 271 272 unsigned VoidFnTyIdx = getNextTypeIndex(); 273 OS.AddComment("Type record length"); 274 OS.EmitIntValue(2 + sizeof(ProcedureType), 2); 275 OS.AddComment("Leaf type: LF_PROCEDURE"); 276 OS.EmitIntValue(LF_PROCEDURE, 2); 277 OS.AddComment("Return type index"); 278 OS.EmitIntValue(TypeIndex::Void().getIndex(), 4); 279 OS.AddComment("Calling convention"); 280 OS.EmitIntValue(char(CallingConvention::NearC), 1); 281 OS.AddComment("Function options"); 282 OS.EmitIntValue(char(FunctionOptions::None), 1); 283 OS.AddComment("# of parameters"); 284 OS.EmitIntValue(0, 2); 285 OS.AddComment("Argument list type index"); 286 OS.EmitIntValue(ArgListIndex, 4); 287 288 // Emit LF_FUNC_ID records for all inlined subprograms to the type stream. 289 // Allocate one type index for each func id. 290 unsigned NextIdx = getNextTypeIndex(InlinedSubprograms.size()); 291 assert(NextIdx == FuncIdTypeIndexStart && "func id type indices broken"); 292 for (auto *SP : InlinedSubprograms) { 293 StringRef DisplayName = SP->getDisplayName(); 294 OS.AddComment("Type record length"); 295 MCSymbol *FuncBegin = MMI->getContext().createTempSymbol(), 296 *FuncEnd = MMI->getContext().createTempSymbol(); 297 OS.emitAbsoluteSymbolDiff(FuncEnd, FuncBegin, 2); 298 OS.EmitLabel(FuncBegin); 299 OS.AddComment("Leaf type: LF_FUNC_ID"); 300 OS.EmitIntValue(LF_FUNC_ID, 2); 301 302 OS.AddComment("Scope type index"); 303 OS.EmitIntValue(0, 4); 304 OS.AddComment("Function type"); 305 OS.EmitIntValue(VoidFnTyIdx, 4); 306 { 307 OS.AddComment("Function name"); 308 emitNullTerminatedSymbolName(OS, DisplayName); 309 } 310 OS.EmitLabel(FuncEnd); 311 } 312 } 313 314 void CodeViewDebug::emitInlineeFuncIdsAndLines() { 315 if (InlinedSubprograms.empty()) 316 return; 317 318 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(), 319 *InlineEnd = MMI->getContext().createTempSymbol(); 320 321 OS.AddComment("Inlinee lines subsection"); 322 OS.EmitIntValue(unsigned(ModuleSubstreamKind::InlineeLines), 4); 323 OS.AddComment("Subsection size"); 324 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 4); 325 OS.EmitLabel(InlineBegin); 326 327 // We don't provide any extra file info. 328 // FIXME: Find out if debuggers use this info. 329 OS.AddComment("Inlinee lines signature"); 330 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4); 331 332 unsigned InlineeIndex = FuncIdTypeIndexStart; 333 for (const DISubprogram *SP : InlinedSubprograms) { 334 OS.AddBlankLine(); 335 unsigned FileId = maybeRecordFile(SP->getFile()); 336 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " + 337 SP->getFilename() + Twine(':') + Twine(SP->getLine())); 338 OS.AddBlankLine(); 339 // The filechecksum table uses 8 byte entries for now, and file ids start at 340 // 1. 341 unsigned FileOffset = (FileId - 1) * 8; 342 OS.AddComment("Type index of inlined function"); 343 OS.EmitIntValue(InlineeIndex, 4); 344 OS.AddComment("Offset into filechecksum table"); 345 OS.EmitIntValue(FileOffset, 4); 346 OS.AddComment("Starting line number"); 347 OS.EmitIntValue(SP->getLine(), 4); 348 349 // The next inlined subprogram has the next function id. 350 InlineeIndex++; 351 } 352 353 OS.EmitLabel(InlineEnd); 354 } 355 356 void CodeViewDebug::collectInlineSiteChildren( 357 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI, 358 const InlineSite &Site) { 359 for (const DILocation *ChildSiteLoc : Site.ChildSites) { 360 auto I = FI.InlineSites.find(ChildSiteLoc); 361 const InlineSite &ChildSite = I->second; 362 Children.push_back(ChildSite.SiteFuncId); 363 collectInlineSiteChildren(Children, FI, ChildSite); 364 } 365 } 366 367 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI, 368 const DILocation *InlinedAt, 369 const InlineSite &Site) { 370 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(), 371 *InlineEnd = MMI->getContext().createTempSymbol(); 372 373 assert(SubprogramIndices.count(Site.Inlinee)); 374 unsigned InlineeIdx = FuncIdTypeIndexStart + SubprogramIndices[Site.Inlinee]; 375 376 // SymbolRecord 377 OS.AddComment("Record length"); 378 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength 379 OS.EmitLabel(InlineBegin); 380 OS.AddComment("Record kind: S_INLINESITE"); 381 OS.EmitIntValue(SymbolRecordKind::S_INLINESITE, 2); // RecordKind 382 383 OS.AddComment("PtrParent"); 384 OS.EmitIntValue(0, 4); 385 OS.AddComment("PtrEnd"); 386 OS.EmitIntValue(0, 4); 387 OS.AddComment("Inlinee type index"); 388 OS.EmitIntValue(InlineeIdx, 4); 389 390 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile()); 391 unsigned StartLineNum = Site.Inlinee->getLine(); 392 SmallVector<unsigned, 3> SecondaryFuncIds; 393 collectInlineSiteChildren(SecondaryFuncIds, FI, Site); 394 395 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum, 396 FI.Begin, FI.End, SecondaryFuncIds); 397 398 OS.EmitLabel(InlineEnd); 399 400 for (const LocalVariable &Var : Site.InlinedLocals) 401 emitLocalVariable(Var); 402 403 // Recurse on child inlined call sites before closing the scope. 404 for (const DILocation *ChildSite : Site.ChildSites) { 405 auto I = FI.InlineSites.find(ChildSite); 406 assert(I != FI.InlineSites.end() && 407 "child site not in function inline site map"); 408 emitInlinedCallSite(FI, ChildSite, I->second); 409 } 410 411 // Close the scope. 412 OS.AddComment("Record length"); 413 OS.EmitIntValue(2, 2); // RecordLength 414 OS.AddComment("Record kind: S_INLINESITE_END"); 415 OS.EmitIntValue(SymbolRecordKind::S_INLINESITE_END, 2); // RecordKind 416 } 417 418 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV, 419 FunctionInfo &FI) { 420 // For each function there is a separate subsection 421 // which holds the PC to file:line table. 422 const MCSymbol *Fn = Asm->getSymbol(GV); 423 assert(Fn); 424 425 StringRef FuncName; 426 if (auto *SP = GV->getSubprogram()) 427 FuncName = SP->getDisplayName(); 428 429 // If our DISubprogram name is empty, use the mangled name. 430 if (FuncName.empty()) 431 FuncName = GlobalValue::getRealLinkageName(GV->getName()); 432 433 // Emit a symbol subsection, required by VS2012+ to find function boundaries. 434 MCSymbol *SymbolsBegin = MMI->getContext().createTempSymbol(), 435 *SymbolsEnd = MMI->getContext().createTempSymbol(); 436 OS.AddComment("Symbol subsection for " + Twine(FuncName)); 437 OS.EmitIntValue(unsigned(ModuleSubstreamKind::Symbols), 4); 438 OS.AddComment("Subsection size"); 439 OS.emitAbsoluteSymbolDiff(SymbolsEnd, SymbolsBegin, 4); 440 OS.EmitLabel(SymbolsBegin); 441 { 442 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(), 443 *ProcRecordEnd = MMI->getContext().createTempSymbol(); 444 OS.AddComment("Record length"); 445 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2); 446 OS.EmitLabel(ProcRecordBegin); 447 448 OS.AddComment("Record kind: S_GPROC32_ID"); 449 OS.EmitIntValue(unsigned(SymbolRecordKind::S_GPROC32_ID), 2); 450 451 // These fields are filled in by tools like CVPACK which run after the fact. 452 OS.AddComment("PtrParent"); 453 OS.EmitIntValue(0, 4); 454 OS.AddComment("PtrEnd"); 455 OS.EmitIntValue(0, 4); 456 OS.AddComment("PtrNext"); 457 OS.EmitIntValue(0, 4); 458 // This is the important bit that tells the debugger where the function 459 // code is located and what's its size: 460 OS.AddComment("Code size"); 461 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4); 462 OS.AddComment("Offset after prologue"); 463 OS.EmitIntValue(0, 4); 464 OS.AddComment("Offset before epilogue"); 465 OS.EmitIntValue(0, 4); 466 OS.AddComment("Function type index"); 467 OS.EmitIntValue(0, 4); 468 OS.AddComment("Function section relative address"); 469 OS.EmitCOFFSecRel32(Fn); 470 OS.AddComment("Function section index"); 471 OS.EmitCOFFSectionIndex(Fn); 472 OS.AddComment("Flags"); 473 OS.EmitIntValue(0, 1); 474 // Emit the function display name as a null-terminated string. 475 OS.AddComment("Function name"); 476 // Truncate the name so we won't overflow the record length field. 477 emitNullTerminatedSymbolName(OS, FuncName); 478 OS.EmitLabel(ProcRecordEnd); 479 480 for (const LocalVariable &Var : FI.Locals) 481 emitLocalVariable(Var); 482 483 // Emit inlined call site information. Only emit functions inlined directly 484 // into the parent function. We'll emit the other sites recursively as part 485 // of their parent inline site. 486 for (const DILocation *InlinedAt : FI.ChildSites) { 487 auto I = FI.InlineSites.find(InlinedAt); 488 assert(I != FI.InlineSites.end() && 489 "child site not in function inline site map"); 490 emitInlinedCallSite(FI, InlinedAt, I->second); 491 } 492 493 // We're done with this function. 494 OS.AddComment("Record length"); 495 OS.EmitIntValue(0x0002, 2); 496 OS.AddComment("Record kind: S_PROC_ID_END"); 497 OS.EmitIntValue(unsigned(SymbolRecordKind::S_PROC_ID_END), 2); 498 } 499 OS.EmitLabel(SymbolsEnd); 500 // Every subsection must be aligned to a 4-byte boundary. 501 OS.EmitValueToAlignment(4); 502 503 // We have an assembler directive that takes care of the whole line table. 504 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End); 505 } 506 507 CodeViewDebug::LocalVarDefRange 508 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) { 509 LocalVarDefRange DR; 510 DR.InMemory = -1; 511 DR.DataOffset = Offset; 512 assert(DR.DataOffset == Offset && "truncation"); 513 DR.StructOffset = 0; 514 DR.CVRegister = CVRegister; 515 return DR; 516 } 517 518 CodeViewDebug::LocalVarDefRange 519 CodeViewDebug::createDefRangeReg(uint16_t CVRegister) { 520 LocalVarDefRange DR; 521 DR.InMemory = 0; 522 DR.DataOffset = 0; 523 DR.StructOffset = 0; 524 DR.CVRegister = CVRegister; 525 return DR; 526 } 527 528 void CodeViewDebug::collectVariableInfoFromMMITable( 529 DenseSet<InlinedVariable> &Processed) { 530 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget(); 531 const TargetFrameLowering *TFI = TSI.getFrameLowering(); 532 const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); 533 534 for (const MachineModuleInfo::VariableDbgInfo &VI : 535 MMI->getVariableDbgInfo()) { 536 if (!VI.Var) 537 continue; 538 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 539 "Expected inlined-at fields to agree"); 540 541 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt())); 542 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 543 544 // If variable scope is not found then skip this variable. 545 if (!Scope) 546 continue; 547 548 // Get the frame register used and the offset. 549 unsigned FrameReg = 0; 550 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg); 551 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg); 552 553 // Calculate the label ranges. 554 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset); 555 for (const InsnRange &Range : Scope->getRanges()) { 556 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 557 const MCSymbol *End = getLabelAfterInsn(Range.second); 558 End = End ? End : Asm->getFunctionEnd(); 559 DefRange.Ranges.emplace_back(Begin, End); 560 } 561 562 LocalVariable Var; 563 Var.DIVar = VI.Var; 564 Var.DefRanges.emplace_back(std::move(DefRange)); 565 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt()); 566 } 567 } 568 569 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) { 570 DenseSet<InlinedVariable> Processed; 571 // Grab the variable info that was squirreled away in the MMI side-table. 572 collectVariableInfoFromMMITable(Processed); 573 574 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo(); 575 576 for (const auto &I : DbgValues) { 577 InlinedVariable IV = I.first; 578 if (Processed.count(IV)) 579 continue; 580 const DILocalVariable *DIVar = IV.first; 581 const DILocation *InlinedAt = IV.second; 582 583 // Instruction ranges, specifying where IV is accessible. 584 const auto &Ranges = I.second; 585 586 LexicalScope *Scope = nullptr; 587 if (InlinedAt) 588 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt); 589 else 590 Scope = LScopes.findLexicalScope(DIVar->getScope()); 591 // If variable scope is not found then skip this variable. 592 if (!Scope) 593 continue; 594 595 LocalVariable Var; 596 Var.DIVar = DIVar; 597 598 // Calculate the definition ranges. 599 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 600 const InsnRange &Range = *I; 601 const MachineInstr *DVInst = Range.first; 602 assert(DVInst->isDebugValue() && "Invalid History entry"); 603 const DIExpression *DIExpr = DVInst->getDebugExpression(); 604 605 // Bail if there is a complex DWARF expression for now. 606 if (DIExpr && DIExpr->getNumElements() > 0) 607 continue; 608 609 // Bail if operand 0 is not a valid register. This means the variable is a 610 // simple constant, or is described by a complex expression. 611 // FIXME: Find a way to represent constant variables, since they are 612 // relatively common. 613 unsigned Reg = 614 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0; 615 if (Reg == 0) 616 continue; 617 618 // Handle the two cases we can handle: indirect in memory and in register. 619 bool IsIndirect = DVInst->getOperand(1).isImm(); 620 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg()); 621 { 622 LocalVarDefRange DefRange; 623 if (IsIndirect) { 624 int64_t Offset = DVInst->getOperand(1).getImm(); 625 DefRange = createDefRangeMem(CVReg, Offset); 626 } else { 627 DefRange = createDefRangeReg(CVReg); 628 } 629 if (Var.DefRanges.empty() || 630 Var.DefRanges.back().isDifferentLocation(DefRange)) { 631 Var.DefRanges.emplace_back(std::move(DefRange)); 632 } 633 } 634 635 // Compute the label range. 636 const MCSymbol *Begin = getLabelBeforeInsn(Range.first); 637 const MCSymbol *End = getLabelAfterInsn(Range.second); 638 if (!End) { 639 if (std::next(I) != E) 640 End = getLabelBeforeInsn(std::next(I)->first); 641 else 642 End = Asm->getFunctionEnd(); 643 } 644 645 // If the last range end is our begin, just extend the last range. 646 // Otherwise make a new range. 647 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges = 648 Var.DefRanges.back().Ranges; 649 if (!Ranges.empty() && Ranges.back().second == Begin) 650 Ranges.back().second = End; 651 else 652 Ranges.emplace_back(Begin, End); 653 654 // FIXME: Do more range combining. 655 } 656 657 recordLocalVariable(std::move(Var), InlinedAt); 658 } 659 } 660 661 void CodeViewDebug::beginFunction(const MachineFunction *MF) { 662 assert(!CurFn && "Can't process two functions at once!"); 663 664 if (!Asm || !MMI->hasDebugInfo()) 665 return; 666 667 DebugHandlerBase::beginFunction(MF); 668 669 const Function *GV = MF->getFunction(); 670 assert(FnDebugInfo.count(GV) == false); 671 CurFn = &FnDebugInfo[GV]; 672 CurFn->FuncId = NextFuncId++; 673 CurFn->Begin = Asm->getFunctionBegin(); 674 675 // Find the end of the function prolog. First known non-DBG_VALUE and 676 // non-frame setup location marks the beginning of the function body. 677 // FIXME: is there a simpler a way to do this? Can we just search 678 // for the first instruction of the function, not the last of the prolog? 679 DebugLoc PrologEndLoc; 680 bool EmptyPrologue = true; 681 for (const auto &MBB : *MF) { 682 for (const auto &MI : MBB) { 683 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) && 684 MI.getDebugLoc()) { 685 PrologEndLoc = MI.getDebugLoc(); 686 break; 687 } else if (!MI.isDebugValue()) { 688 EmptyPrologue = false; 689 } 690 } 691 } 692 693 // Record beginning of function if we have a non-empty prologue. 694 if (PrologEndLoc && !EmptyPrologue) { 695 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc(); 696 maybeRecordLocation(FnStartDL, MF); 697 } 698 } 699 700 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) { 701 // LocalSym record, see SymbolRecord.h for more info. 702 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(), 703 *LocalEnd = MMI->getContext().createTempSymbol(); 704 OS.AddComment("Record length"); 705 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2); 706 OS.EmitLabel(LocalBegin); 707 708 OS.AddComment("Record kind: S_LOCAL"); 709 OS.EmitIntValue(unsigned(SymbolRecordKind::S_LOCAL), 2); 710 711 uint16_t Flags = 0; 712 if (Var.DIVar->isParameter()) 713 Flags |= LocalSym::IsParameter; 714 if (Var.DefRanges.empty()) 715 Flags |= LocalSym::IsOptimizedOut; 716 717 OS.AddComment("TypeIndex"); 718 OS.EmitIntValue(TypeIndex::Int32().getIndex(), 4); 719 OS.AddComment("Flags"); 720 OS.EmitIntValue(Flags, 2); 721 // Truncate the name so we won't overflow the record length field. 722 emitNullTerminatedSymbolName(OS, Var.DIVar->getName()); 723 OS.EmitLabel(LocalEnd); 724 725 // Calculate the on disk prefix of the appropriate def range record. The 726 // records and on disk formats are described in SymbolRecords.h. BytePrefix 727 // should be big enough to hold all forms without memory allocation. 728 SmallString<20> BytePrefix; 729 for (const LocalVarDefRange &DefRange : Var.DefRanges) { 730 BytePrefix.clear(); 731 // FIXME: Handle bitpieces. 732 if (DefRange.StructOffset != 0) 733 continue; 734 735 if (DefRange.InMemory) { 736 DefRangeRegisterRelSym Sym{}; 737 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL); 738 Sym.BaseRegister = DefRange.CVRegister; 739 Sym.Flags = 0; // Unclear what matters here. 740 Sym.BasePointerOffset = DefRange.DataOffset; 741 BytePrefix += 742 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 743 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym), 744 sizeof(Sym) - sizeof(LocalVariableAddrRange)); 745 } else { 746 assert(DefRange.DataOffset == 0 && "unexpected offset into register"); 747 DefRangeRegisterSym Sym{}; 748 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER); 749 Sym.Register = DefRange.CVRegister; 750 Sym.MayHaveNoName = 0; // Unclear what matters here. 751 BytePrefix += 752 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind)); 753 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym), 754 sizeof(Sym) - sizeof(LocalVariableAddrRange)); 755 } 756 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix); 757 } 758 } 759 760 void CodeViewDebug::endFunction(const MachineFunction *MF) { 761 if (!Asm || !CurFn) // We haven't created any debug info for this function. 762 return; 763 764 const Function *GV = MF->getFunction(); 765 assert(FnDebugInfo.count(GV)); 766 assert(CurFn == &FnDebugInfo[GV]); 767 768 collectVariableInfo(GV->getSubprogram()); 769 770 DebugHandlerBase::endFunction(MF); 771 772 // Don't emit anything if we don't have any line tables. 773 if (!CurFn->HaveLineInfo) { 774 FnDebugInfo.erase(GV); 775 CurFn = nullptr; 776 return; 777 } 778 779 CurFn->End = Asm->getFunctionEnd(); 780 781 CurFn = nullptr; 782 } 783 784 void CodeViewDebug::beginInstruction(const MachineInstr *MI) { 785 DebugHandlerBase::beginInstruction(MI); 786 787 // Ignore DBG_VALUE locations and function prologue. 788 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup)) 789 return; 790 DebugLoc DL = MI->getDebugLoc(); 791 if (DL == PrevInstLoc || !DL) 792 return; 793 maybeRecordLocation(DL, Asm->MF); 794 } 795