1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===// 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 dwarf debug info into asm files. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "DwarfDebug.h" 15 #include "ByteStreamer.h" 16 #include "DIEHash.h" 17 #include "DebugLocEntry.h" 18 #include "DwarfCompileUnit.h" 19 #include "DwarfExpression.h" 20 #include "DwarfUnit.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/ADT/StringExtras.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/CodeGen/DIE.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/CodeGen/MachineModuleInfo.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DIBuilder.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/DebugInfo.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/Module.h" 34 #include "llvm/IR/ValueHandle.h" 35 #include "llvm/MC/MCAsmInfo.h" 36 #include "llvm/MC/MCDwarf.h" 37 #include "llvm/MC/MCSection.h" 38 #include "llvm/MC/MCStreamer.h" 39 #include "llvm/MC/MCSymbol.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/Dwarf.h" 43 #include "llvm/Support/Endian.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include "llvm/Support/FormattedStream.h" 46 #include "llvm/Support/LEB128.h" 47 #include "llvm/Support/MD5.h" 48 #include "llvm/Support/Path.h" 49 #include "llvm/Support/Timer.h" 50 #include "llvm/Support/raw_ostream.h" 51 #include "llvm/Target/TargetFrameLowering.h" 52 #include "llvm/Target/TargetLoweringObjectFile.h" 53 #include "llvm/Target/TargetMachine.h" 54 #include "llvm/Target/TargetOptions.h" 55 #include "llvm/Target/TargetRegisterInfo.h" 56 #include "llvm/Target/TargetSubtargetInfo.h" 57 using namespace llvm; 58 59 #define DEBUG_TYPE "dwarfdebug" 60 61 static cl::opt<bool> 62 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden, 63 cl::desc("Disable debug info printing")); 64 65 static cl::opt<bool> UnknownLocations( 66 "use-unknown-locations", cl::Hidden, 67 cl::desc("Make an absence of debug location information explicit."), 68 cl::init(false)); 69 70 static cl::opt<bool> 71 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden, 72 cl::desc("Generate GNU-style pubnames and pubtypes"), 73 cl::init(false)); 74 75 static cl::opt<bool> GenerateARangeSection("generate-arange-section", 76 cl::Hidden, 77 cl::desc("Generate dwarf aranges"), 78 cl::init(false)); 79 80 static cl::opt<DebuggerKind> 81 DebuggerTuningOpt("debugger-tune", 82 cl::desc("Tune debug info for a particular debugger"), 83 cl::init(DebuggerKind::Default), 84 cl::values( 85 clEnumValN(DebuggerKind::GDB, "gdb", "gdb"), 86 clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"), 87 clEnumValN(DebuggerKind::SCE, "sce", 88 "SCE targets (e.g. PS4)"), 89 clEnumValEnd)); 90 91 namespace { 92 enum DefaultOnOff { Default, Enable, Disable }; 93 } 94 95 static cl::opt<DefaultOnOff> 96 DwarfAccelTables("dwarf-accel-tables", cl::Hidden, 97 cl::desc("Output prototype dwarf accelerator tables."), 98 cl::values(clEnumVal(Default, "Default for platform"), 99 clEnumVal(Enable, "Enabled"), 100 clEnumVal(Disable, "Disabled"), clEnumValEnd), 101 cl::init(Default)); 102 103 static cl::opt<DefaultOnOff> 104 SplitDwarf("split-dwarf", cl::Hidden, 105 cl::desc("Output DWARF5 split debug info."), 106 cl::values(clEnumVal(Default, "Default for platform"), 107 clEnumVal(Enable, "Enabled"), 108 clEnumVal(Disable, "Disabled"), clEnumValEnd), 109 cl::init(Default)); 110 111 static cl::opt<DefaultOnOff> 112 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden, 113 cl::desc("Generate DWARF pubnames and pubtypes sections"), 114 cl::values(clEnumVal(Default, "Default for platform"), 115 clEnumVal(Enable, "Enabled"), 116 clEnumVal(Disable, "Disabled"), clEnumValEnd), 117 cl::init(Default)); 118 119 static cl::opt<DefaultOnOff> 120 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden, 121 cl::desc("Emit DWARF linkage-name attributes."), 122 cl::values(clEnumVal(Default, "Default for platform"), 123 clEnumVal(Enable, "Enabled"), 124 clEnumVal(Disable, "Disabled"), clEnumValEnd), 125 cl::init(Default)); 126 127 static const char *const DWARFGroupName = "DWARF Emission"; 128 static const char *const DbgTimerName = "DWARF Debug Writer"; 129 130 void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) { 131 BS.EmitInt8( 132 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op) 133 : dwarf::OperationEncodingString(Op)); 134 } 135 136 void DebugLocDwarfExpression::EmitSigned(int64_t Value) { 137 BS.EmitSLEB128(Value, Twine(Value)); 138 } 139 140 void DebugLocDwarfExpression::EmitUnsigned(uint64_t Value) { 141 BS.EmitULEB128(Value, Twine(Value)); 142 } 143 144 bool DebugLocDwarfExpression::isFrameRegister(unsigned MachineReg) { 145 // This information is not available while emitting .debug_loc entries. 146 return false; 147 } 148 149 //===----------------------------------------------------------------------===// 150 151 /// resolve - Look in the DwarfDebug map for the MDNode that 152 /// corresponds to the reference. 153 template <typename T> T *DbgVariable::resolve(TypedDINodeRef<T> Ref) const { 154 return DD->resolve(Ref); 155 } 156 157 bool DbgVariable::isBlockByrefVariable() const { 158 assert(Var && "Invalid complex DbgVariable!"); 159 return Var->getType() 160 .resolve(DD->getTypeIdentifierMap()) 161 ->isBlockByrefStruct(); 162 } 163 164 const DIType *DbgVariable::getType() const { 165 DIType *Ty = Var->getType().resolve(DD->getTypeIdentifierMap()); 166 // FIXME: isBlockByrefVariable should be reformulated in terms of complex 167 // addresses instead. 168 if (Ty->isBlockByrefStruct()) { 169 /* Byref variables, in Blocks, are declared by the programmer as 170 "SomeType VarName;", but the compiler creates a 171 __Block_byref_x_VarName struct, and gives the variable VarName 172 either the struct, or a pointer to the struct, as its type. This 173 is necessary for various behind-the-scenes things the compiler 174 needs to do with by-reference variables in blocks. 175 176 However, as far as the original *programmer* is concerned, the 177 variable should still have type 'SomeType', as originally declared. 178 179 The following function dives into the __Block_byref_x_VarName 180 struct to find the original type of the variable. This will be 181 passed back to the code generating the type for the Debug 182 Information Entry for the variable 'VarName'. 'VarName' will then 183 have the original type 'SomeType' in its debug information. 184 185 The original type 'SomeType' will be the type of the field named 186 'VarName' inside the __Block_byref_x_VarName struct. 187 188 NOTE: In order for this to not completely fail on the debugger 189 side, the Debug Information Entry for the variable VarName needs to 190 have a DW_AT_location that tells the debugger how to unwind through 191 the pointers and __Block_byref_x_VarName struct to find the actual 192 value of the variable. The function addBlockByrefType does this. */ 193 DIType *subType = Ty; 194 uint16_t tag = Ty->getTag(); 195 196 if (tag == dwarf::DW_TAG_pointer_type) 197 subType = resolve(cast<DIDerivedType>(Ty)->getBaseType()); 198 199 auto Elements = cast<DICompositeType>(subType)->getElements(); 200 for (unsigned i = 0, N = Elements.size(); i < N; ++i) { 201 auto *DT = cast<DIDerivedType>(Elements[i]); 202 if (getName() == DT->getName()) 203 return resolve(DT->getBaseType()); 204 } 205 } 206 return Ty; 207 } 208 209 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = { 210 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4), 211 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2), 212 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)}; 213 214 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M) 215 : Asm(A), MMI(Asm->MMI), DebugLocs(A->OutStreamer->isVerboseAsm()), 216 PrevLabel(nullptr), InfoHolder(A, "info_string", DIEValueAllocator), 217 UsedNonDefaultText(false), 218 SkeletonHolder(A, "skel_string", DIEValueAllocator), 219 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()), 220 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, 221 dwarf::DW_FORM_data4)), 222 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, 223 dwarf::DW_FORM_data4)), 224 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, 225 dwarf::DW_FORM_data4)), 226 AccelTypes(TypeAtoms), DebuggerTuning(DebuggerKind::Default) { 227 228 CurFn = nullptr; 229 CurMI = nullptr; 230 Triple TT(Asm->getTargetTriple()); 231 232 // Make sure we know our "debugger tuning." The command-line option takes 233 // precedence; fall back to triple-based defaults. 234 if (DebuggerTuningOpt != DebuggerKind::Default) 235 DebuggerTuning = DebuggerTuningOpt; 236 else if (IsDarwin || TT.isOSFreeBSD()) 237 DebuggerTuning = DebuggerKind::LLDB; 238 else if (TT.isPS4CPU()) 239 DebuggerTuning = DebuggerKind::SCE; 240 else 241 DebuggerTuning = DebuggerKind::GDB; 242 243 // Turn on accelerator tables for LLDB by default. 244 if (DwarfAccelTables == Default) 245 HasDwarfAccelTables = tuneForLLDB(); 246 else 247 HasDwarfAccelTables = DwarfAccelTables == Enable; 248 249 // Handle split DWARF. Off by default for now. 250 if (SplitDwarf == Default) 251 HasSplitDwarf = false; 252 else 253 HasSplitDwarf = SplitDwarf == Enable; 254 255 // Pubnames/pubtypes on by default for GDB. 256 if (DwarfPubSections == Default) 257 HasDwarfPubSections = tuneForGDB(); 258 else 259 HasDwarfPubSections = DwarfPubSections == Enable; 260 261 // SCE does not use linkage names. 262 if (DwarfLinkageNames == Default) 263 UseLinkageNames = !tuneForSCE(); 264 else 265 UseLinkageNames = DwarfLinkageNames == Enable; 266 267 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion; 268 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber 269 : MMI->getModule()->getDwarfVersion(); 270 // Use dwarf 4 by default if nothing is requested. 271 DwarfVersion = DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION; 272 273 // Work around a GDB bug. GDB doesn't support the standard opcode; 274 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which 275 // is defined as of DWARF 3. 276 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented 277 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616 278 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3; 279 280 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion); 281 282 { 283 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled); 284 beginModule(); 285 } 286 } 287 288 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h. 289 DwarfDebug::~DwarfDebug() { } 290 291 static bool isObjCClass(StringRef Name) { 292 return Name.startswith("+") || Name.startswith("-"); 293 } 294 295 static bool hasObjCCategory(StringRef Name) { 296 if (!isObjCClass(Name)) 297 return false; 298 299 return Name.find(") ") != StringRef::npos; 300 } 301 302 static void getObjCClassCategory(StringRef In, StringRef &Class, 303 StringRef &Category) { 304 if (!hasObjCCategory(In)) { 305 Class = In.slice(In.find('[') + 1, In.find(' ')); 306 Category = ""; 307 return; 308 } 309 310 Class = In.slice(In.find('[') + 1, In.find('(')); 311 Category = In.slice(In.find('[') + 1, In.find(' ')); 312 return; 313 } 314 315 static StringRef getObjCMethodName(StringRef In) { 316 return In.slice(In.find(' ') + 1, In.find(']')); 317 } 318 319 // Add the various names to the Dwarf accelerator table names. 320 // TODO: Determine whether or not we should add names for programs 321 // that do not have a DW_AT_name or DW_AT_linkage_name field - this 322 // is only slightly different than the lookup of non-standard ObjC names. 323 void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) { 324 if (!SP->isDefinition()) 325 return; 326 addAccelName(SP->getName(), Die); 327 328 // If the linkage name is different than the name, go ahead and output 329 // that as well into the name table. 330 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName()) 331 addAccelName(SP->getLinkageName(), Die); 332 333 // If this is an Objective-C selector name add it to the ObjC accelerator 334 // too. 335 if (isObjCClass(SP->getName())) { 336 StringRef Class, Category; 337 getObjCClassCategory(SP->getName(), Class, Category); 338 addAccelObjC(Class, Die); 339 if (Category != "") 340 addAccelObjC(Category, Die); 341 // Also add the base method name to the name table. 342 addAccelName(getObjCMethodName(SP->getName()), Die); 343 } 344 } 345 346 /// isSubprogramContext - Return true if Context is either a subprogram 347 /// or another context nested inside a subprogram. 348 bool DwarfDebug::isSubprogramContext(const MDNode *Context) { 349 if (!Context) 350 return false; 351 if (isa<DISubprogram>(Context)) 352 return true; 353 if (auto *T = dyn_cast<DIType>(Context)) 354 return isSubprogramContext(resolve(T->getScope())); 355 return false; 356 } 357 358 /// Check whether we should create a DIE for the given Scope, return true 359 /// if we don't create a DIE (the corresponding DIE is null). 360 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) { 361 if (Scope->isAbstractScope()) 362 return false; 363 364 // We don't create a DIE if there is no Range. 365 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges(); 366 if (Ranges.empty()) 367 return true; 368 369 if (Ranges.size() > 1) 370 return false; 371 372 // We don't create a DIE if we have a single Range and the end label 373 // is null. 374 return !getLabelAfterInsn(Ranges.front().second); 375 } 376 377 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) { 378 F(CU); 379 if (auto *SkelCU = CU.getSkeleton()) 380 F(*SkelCU); 381 } 382 383 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) { 384 assert(Scope && Scope->getScopeNode()); 385 assert(Scope->isAbstractScope()); 386 assert(!Scope->getInlinedAt()); 387 388 const MDNode *SP = Scope->getScopeNode(); 389 390 ProcessedSPNodes.insert(SP); 391 392 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 393 // was inlined from another compile unit. 394 auto &CU = SPMap[SP]; 395 forBothCUs(*CU, [&](DwarfCompileUnit &CU) { 396 CU.constructAbstractSubprogramScopeDIE(Scope); 397 }); 398 } 399 400 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const { 401 if (!GenerateGnuPubSections) 402 return; 403 404 U.addFlag(D, dwarf::DW_AT_GNU_pubnames); 405 } 406 407 // Create new DwarfCompileUnit for the given metadata node with tag 408 // DW_TAG_compile_unit. 409 DwarfCompileUnit & 410 DwarfDebug::constructDwarfCompileUnit(const DICompileUnit *DIUnit) { 411 StringRef FN = DIUnit->getFilename(); 412 CompilationDir = DIUnit->getDirectory(); 413 414 auto OwnedUnit = make_unique<DwarfCompileUnit>( 415 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder); 416 DwarfCompileUnit &NewCU = *OwnedUnit; 417 DIE &Die = NewCU.getUnitDie(); 418 InfoHolder.addUnit(std::move(OwnedUnit)); 419 if (useSplitDwarf()) 420 NewCU.setSkeleton(constructSkeletonCU(NewCU)); 421 422 // LTO with assembly output shares a single line table amongst multiple CUs. 423 // To avoid the compilation directory being ambiguous, let the line table 424 // explicitly describe the directory of all files, never relying on the 425 // compilation directory. 426 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU) 427 Asm->OutStreamer->getContext().setMCLineTableCompilationDir( 428 NewCU.getUniqueID(), CompilationDir); 429 430 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit->getProducer()); 431 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 432 DIUnit->getSourceLanguage()); 433 NewCU.addString(Die, dwarf::DW_AT_name, FN); 434 435 if (!useSplitDwarf()) { 436 NewCU.initStmtList(); 437 438 // If we're using split dwarf the compilation dir is going to be in the 439 // skeleton CU and so we don't need to duplicate it here. 440 if (!CompilationDir.empty()) 441 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 442 443 addGnuPubAttributes(NewCU, Die); 444 } 445 446 if (DIUnit->isOptimized()) 447 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized); 448 449 StringRef Flags = DIUnit->getFlags(); 450 if (!Flags.empty()) 451 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags); 452 453 if (unsigned RVer = DIUnit->getRuntimeVersion()) 454 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 455 dwarf::DW_FORM_data1, RVer); 456 457 if (useSplitDwarf()) 458 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection()); 459 else 460 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection()); 461 462 CUMap.insert(std::make_pair(DIUnit, &NewCU)); 463 CUDieMap.insert(std::make_pair(&Die, &NewCU)); 464 return NewCU; 465 } 466 467 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU, 468 const DIImportedEntity *N) { 469 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope())) 470 D->addChild(TheCU.constructImportedEntityDIE(N)); 471 } 472 473 // Emit all Dwarf sections that should come prior to the content. Create 474 // global DIEs and emit initial debug info sections. This is invoked by 475 // the target AsmPrinter. 476 void DwarfDebug::beginModule() { 477 if (DisableDebugInfoPrinting) 478 return; 479 480 const Module *M = MMI->getModule(); 481 482 FunctionDIs = makeSubprogramMap(*M); 483 484 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu"); 485 if (!CU_Nodes) 486 return; 487 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes); 488 489 SingleCU = CU_Nodes->getNumOperands() == 1; 490 491 for (MDNode *N : CU_Nodes->operands()) { 492 auto *CUNode = cast<DICompileUnit>(N); 493 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode); 494 for (auto *IE : CUNode->getImportedEntities()) 495 ScopesWithImportedEntities.push_back(std::make_pair(IE->getScope(), IE)); 496 // Stable sort to preserve the order of appearance of imported entities. 497 // This is to avoid out-of-order processing of interdependent declarations 498 // within the same scope, e.g. { namespace A = base; namespace B = A; } 499 std::stable_sort(ScopesWithImportedEntities.begin(), 500 ScopesWithImportedEntities.end(), less_first()); 501 for (auto *GV : CUNode->getGlobalVariables()) 502 CU.getOrCreateGlobalVariableDIE(GV); 503 for (auto *SP : CUNode->getSubprograms()) 504 SPMap.insert(std::make_pair(SP, &CU)); 505 for (auto *Ty : CUNode->getEnumTypes()) { 506 // The enum types array by design contains pointers to 507 // MDNodes rather than DIRefs. Unique them here. 508 CU.getOrCreateTypeDIE(cast<DIType>(resolve(Ty->getRef()))); 509 } 510 for (auto *Ty : CUNode->getRetainedTypes()) { 511 // The retained types array by design contains pointers to 512 // MDNodes rather than DIRefs. Unique them here. 513 DIType *RT = cast<DIType>(resolve(Ty->getRef())); 514 if (!RT->isExternalTypeRef()) 515 // There is no point in force-emitting a forward declaration. 516 CU.getOrCreateTypeDIE(RT); 517 } 518 // Emit imported_modules last so that the relevant context is already 519 // available. 520 for (auto *IE : CUNode->getImportedEntities()) 521 constructAndAddImportedEntityDIE(CU, IE); 522 } 523 524 // Tell MMI that we have debug info. 525 MMI->setDebugInfoAvailability(true); 526 } 527 528 void DwarfDebug::finishVariableDefinitions() { 529 for (const auto &Var : ConcreteVariables) { 530 DIE *VariableDie = Var->getDIE(); 531 assert(VariableDie); 532 // FIXME: Consider the time-space tradeoff of just storing the unit pointer 533 // in the ConcreteVariables list, rather than looking it up again here. 534 // DIE::getUnit isn't simple - it walks parent pointers, etc. 535 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit()); 536 assert(Unit); 537 DbgVariable *AbsVar = getExistingAbstractVariable( 538 InlinedVariable(Var->getVariable(), Var->getInlinedAt())); 539 if (AbsVar && AbsVar->getDIE()) { 540 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin, 541 *AbsVar->getDIE()); 542 } else 543 Unit->applyVariableAttributes(*Var, *VariableDie); 544 } 545 } 546 547 void DwarfDebug::finishSubprogramDefinitions() { 548 for (const auto &P : SPMap) 549 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) { 550 CU.finishSubprogramDefinition(cast<DISubprogram>(P.first)); 551 }); 552 } 553 554 555 // Collect info for variables that were optimized out. 556 void DwarfDebug::collectDeadVariables() { 557 const Module *M = MMI->getModule(); 558 559 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) { 560 for (MDNode *N : CU_Nodes->operands()) { 561 auto *TheCU = cast<DICompileUnit>(N); 562 // Construct subprogram DIE and add variables DIEs. 563 DwarfCompileUnit *SPCU = 564 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU)); 565 assert(SPCU && "Unable to find Compile Unit!"); 566 for (auto *SP : TheCU->getSubprograms()) { 567 if (ProcessedSPNodes.count(SP) != 0) 568 continue; 569 SPCU->collectDeadVariables(SP); 570 } 571 } 572 } 573 } 574 575 void DwarfDebug::finalizeModuleInfo() { 576 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 577 578 finishSubprogramDefinitions(); 579 580 finishVariableDefinitions(); 581 582 // Collect info for variables that were optimized out. 583 collectDeadVariables(); 584 585 // Handle anything that needs to be done on a per-unit basis after 586 // all other generation. 587 for (const auto &P : CUMap) { 588 auto &TheCU = *P.second; 589 // Emit DW_AT_containing_type attribute to connect types with their 590 // vtable holding type. 591 TheCU.constructContainingTypeDIEs(); 592 593 // Add CU specific attributes if we need to add any. 594 // If we're splitting the dwarf out now that we've got the entire 595 // CU then add the dwo id to it. 596 auto *SkCU = TheCU.getSkeleton(); 597 if (useSplitDwarf()) { 598 // Emit a unique identifier for this CU. 599 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie()); 600 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 601 dwarf::DW_FORM_data8, ID); 602 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 603 dwarf::DW_FORM_data8, ID); 604 605 // We don't keep track of which addresses are used in which CU so this 606 // is a bit pessimistic under LTO. 607 if (!AddrPool.isEmpty()) { 608 const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol(); 609 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base, 610 Sym, Sym); 611 } 612 if (!SkCU->getRangeLists().empty()) { 613 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol(); 614 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base, 615 Sym, Sym); 616 } 617 } 618 619 // If we have code split among multiple sections or non-contiguous 620 // ranges of code then emit a DW_AT_ranges attribute on the unit that will 621 // remain in the .o file, otherwise add a DW_AT_low_pc. 622 // FIXME: We should use ranges allow reordering of code ala 623 // .subsections_via_symbols in mach-o. This would mean turning on 624 // ranges for all subprogram DIEs for mach-o. 625 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 626 if (unsigned NumRanges = TheCU.getRanges().size()) { 627 if (NumRanges > 1) 628 // A DW_AT_low_pc attribute may also be specified in combination with 629 // DW_AT_ranges to specify the default base address for use in 630 // location lists (see Section 2.6.2) and range lists (see Section 631 // 2.17.3). 632 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0); 633 else 634 U.setBaseAddress(TheCU.getRanges().front().getStart()); 635 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges()); 636 } 637 } 638 639 // Compute DIE offsets and sizes. 640 InfoHolder.computeSizeAndOffsets(); 641 if (useSplitDwarf()) 642 SkeletonHolder.computeSizeAndOffsets(); 643 } 644 645 // Emit all Dwarf sections that should come after the content. 646 void DwarfDebug::endModule() { 647 assert(CurFn == nullptr); 648 assert(CurMI == nullptr); 649 650 // If we aren't actually generating debug info (check beginModule - 651 // conditionalized on !DisableDebugInfoPrinting and the presence of the 652 // llvm.dbg.cu metadata node) 653 if (!MMI->hasDebugInfo()) 654 return; 655 656 // Finalize the debug info for the module. 657 finalizeModuleInfo(); 658 659 emitDebugStr(); 660 661 if (useSplitDwarf()) 662 emitDebugLocDWO(); 663 else 664 // Emit info into a debug loc section. 665 emitDebugLoc(); 666 667 // Corresponding abbreviations into a abbrev section. 668 emitAbbreviations(); 669 670 // Emit all the DIEs into a debug info section. 671 emitDebugInfo(); 672 673 // Emit info into a debug aranges section. 674 if (GenerateARangeSection) 675 emitDebugARanges(); 676 677 // Emit info into a debug ranges section. 678 emitDebugRanges(); 679 680 if (useSplitDwarf()) { 681 emitDebugStrDWO(); 682 emitDebugInfoDWO(); 683 emitDebugAbbrevDWO(); 684 emitDebugLineDWO(); 685 // Emit DWO addresses. 686 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection()); 687 } 688 689 // Emit info into the dwarf accelerator table sections. 690 if (useDwarfAccelTables()) { 691 emitAccelNames(); 692 emitAccelObjC(); 693 emitAccelNamespaces(); 694 emitAccelTypes(); 695 } 696 697 // Emit the pubnames and pubtypes sections if requested. 698 if (HasDwarfPubSections) { 699 emitDebugPubNames(GenerateGnuPubSections); 700 emitDebugPubTypes(GenerateGnuPubSections); 701 } 702 703 // clean up. 704 SPMap.clear(); 705 AbstractVariables.clear(); 706 } 707 708 // Find abstract variable, if any, associated with Var. 709 DbgVariable * 710 DwarfDebug::getExistingAbstractVariable(InlinedVariable IV, 711 const DILocalVariable *&Cleansed) { 712 // More then one inlined variable corresponds to one abstract variable. 713 Cleansed = IV.first; 714 auto I = AbstractVariables.find(Cleansed); 715 if (I != AbstractVariables.end()) 716 return I->second.get(); 717 return nullptr; 718 } 719 720 DbgVariable *DwarfDebug::getExistingAbstractVariable(InlinedVariable IV) { 721 const DILocalVariable *Cleansed; 722 return getExistingAbstractVariable(IV, Cleansed); 723 } 724 725 void DwarfDebug::createAbstractVariable(const DILocalVariable *Var, 726 LexicalScope *Scope) { 727 auto AbsDbgVariable = make_unique<DbgVariable>(Var, /* IA */ nullptr, this); 728 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get()); 729 AbstractVariables[Var] = std::move(AbsDbgVariable); 730 } 731 732 void DwarfDebug::ensureAbstractVariableIsCreated(InlinedVariable IV, 733 const MDNode *ScopeNode) { 734 const DILocalVariable *Cleansed = nullptr; 735 if (getExistingAbstractVariable(IV, Cleansed)) 736 return; 737 738 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope( 739 cast<DILocalScope>(ScopeNode))); 740 } 741 742 void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped( 743 InlinedVariable IV, const MDNode *ScopeNode) { 744 const DILocalVariable *Cleansed = nullptr; 745 if (getExistingAbstractVariable(IV, Cleansed)) 746 return; 747 748 if (LexicalScope *Scope = 749 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode))) 750 createAbstractVariable(Cleansed, Scope); 751 } 752 753 // Collect variable information from side table maintained by MMI. 754 void DwarfDebug::collectVariableInfoFromMMITable( 755 DenseSet<InlinedVariable> &Processed) { 756 for (const auto &VI : MMI->getVariableDbgInfo()) { 757 if (!VI.Var) 758 continue; 759 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 760 "Expected inlined-at fields to agree"); 761 762 InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt()); 763 Processed.insert(Var); 764 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 765 766 // If variable scope is not found then skip this variable. 767 if (!Scope) 768 continue; 769 770 ensureAbstractVariableIsCreatedIfScoped(Var, Scope->getScopeNode()); 771 auto RegVar = make_unique<DbgVariable>(Var.first, Var.second, this); 772 RegVar->initializeMMI(VI.Expr, VI.Slot); 773 if (InfoHolder.addScopeVariable(Scope, RegVar.get())) 774 ConcreteVariables.push_back(std::move(RegVar)); 775 } 776 } 777 778 // Get .debug_loc entry for the instruction range starting at MI. 779 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) { 780 const DIExpression *Expr = MI->getDebugExpression(); 781 782 assert(MI->getNumOperands() == 4); 783 if (MI->getOperand(0).isReg()) { 784 MachineLocation MLoc; 785 // If the second operand is an immediate, this is a 786 // register-indirect address. 787 if (!MI->getOperand(1).isImm()) 788 MLoc.set(MI->getOperand(0).getReg()); 789 else 790 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm()); 791 return DebugLocEntry::Value(Expr, MLoc); 792 } 793 if (MI->getOperand(0).isImm()) 794 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm()); 795 if (MI->getOperand(0).isFPImm()) 796 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm()); 797 if (MI->getOperand(0).isCImm()) 798 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm()); 799 800 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!"); 801 } 802 803 /// Determine whether two variable pieces overlap. 804 static bool piecesOverlap(const DIExpression *P1, const DIExpression *P2) { 805 if (!P1->isBitPiece() || !P2->isBitPiece()) 806 return true; 807 unsigned l1 = P1->getBitPieceOffset(); 808 unsigned l2 = P2->getBitPieceOffset(); 809 unsigned r1 = l1 + P1->getBitPieceSize(); 810 unsigned r2 = l2 + P2->getBitPieceSize(); 811 // True where [l1,r1[ and [r1,r2[ overlap. 812 return (l1 < r2) && (l2 < r1); 813 } 814 815 /// Build the location list for all DBG_VALUEs in the function that 816 /// describe the same variable. If the ranges of several independent 817 /// pieces of the same variable overlap partially, split them up and 818 /// combine the ranges. The resulting DebugLocEntries are will have 819 /// strict monotonically increasing begin addresses and will never 820 /// overlap. 821 // 822 // Input: 823 // 824 // Ranges History [var, loc, piece ofs size] 825 // 0 | [x, (reg0, piece 0, 32)] 826 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry 827 // 2 | | ... 828 // 3 | [clobber reg0] 829 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of 830 // x. 831 // 832 // Output: 833 // 834 // [0-1] [x, (reg0, piece 0, 32)] 835 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)] 836 // [3-4] [x, (reg1, piece 32, 32)] 837 // [4- ] [x, (mem, piece 0, 64)] 838 void 839 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc, 840 const DbgValueHistoryMap::InstrRanges &Ranges) { 841 SmallVector<DebugLocEntry::Value, 4> OpenRanges; 842 843 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 844 const MachineInstr *Begin = I->first; 845 const MachineInstr *End = I->second; 846 assert(Begin->isDebugValue() && "Invalid History entry"); 847 848 // Check if a variable is inaccessible in this range. 849 if (Begin->getNumOperands() > 1 && 850 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) { 851 OpenRanges.clear(); 852 continue; 853 } 854 855 // If this piece overlaps with any open ranges, truncate them. 856 const DIExpression *DIExpr = Begin->getDebugExpression(); 857 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(), 858 [&](DebugLocEntry::Value R) { 859 return piecesOverlap(DIExpr, R.getExpression()); 860 }); 861 OpenRanges.erase(Last, OpenRanges.end()); 862 863 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin); 864 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!"); 865 866 const MCSymbol *EndLabel; 867 if (End != nullptr) 868 EndLabel = getLabelAfterInsn(End); 869 else if (std::next(I) == Ranges.end()) 870 EndLabel = Asm->getFunctionEnd(); 871 else 872 EndLabel = getLabelBeforeInsn(std::next(I)->first); 873 assert(EndLabel && "Forgot label after instruction ending a range!"); 874 875 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n"); 876 877 auto Value = getDebugLocValue(Begin); 878 DebugLocEntry Loc(StartLabel, EndLabel, Value); 879 bool couldMerge = false; 880 881 // If this is a piece, it may belong to the current DebugLocEntry. 882 if (DIExpr->isBitPiece()) { 883 // Add this value to the list of open ranges. 884 OpenRanges.push_back(Value); 885 886 // Attempt to add the piece to the last entry. 887 if (!DebugLoc.empty()) 888 if (DebugLoc.back().MergeValues(Loc)) 889 couldMerge = true; 890 } 891 892 if (!couldMerge) { 893 // Need to add a new DebugLocEntry. Add all values from still 894 // valid non-overlapping pieces. 895 if (OpenRanges.size()) 896 Loc.addValues(OpenRanges); 897 898 DebugLoc.push_back(std::move(Loc)); 899 } 900 901 // Attempt to coalesce the ranges of two otherwise identical 902 // DebugLocEntries. 903 auto CurEntry = DebugLoc.rbegin(); 904 DEBUG({ 905 dbgs() << CurEntry->getValues().size() << " Values:\n"; 906 for (auto &Value : CurEntry->getValues()) 907 Value.getExpression()->dump(); 908 dbgs() << "-----\n"; 909 }); 910 911 auto PrevEntry = std::next(CurEntry); 912 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry)) 913 DebugLoc.pop_back(); 914 } 915 } 916 917 DbgVariable *DwarfDebug::createConcreteVariable(LexicalScope &Scope, 918 InlinedVariable IV) { 919 ensureAbstractVariableIsCreatedIfScoped(IV, Scope.getScopeNode()); 920 ConcreteVariables.push_back( 921 make_unique<DbgVariable>(IV.first, IV.second, this)); 922 InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get()); 923 return ConcreteVariables.back().get(); 924 } 925 926 // Find variables for each lexical scope. 927 void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, 928 const DISubprogram *SP, 929 DenseSet<InlinedVariable> &Processed) { 930 // Grab the variable info that was squirreled away in the MMI side-table. 931 collectVariableInfoFromMMITable(Processed); 932 933 for (const auto &I : DbgValues) { 934 InlinedVariable IV = I.first; 935 if (Processed.count(IV)) 936 continue; 937 938 // Instruction ranges, specifying where IV is accessible. 939 const auto &Ranges = I.second; 940 if (Ranges.empty()) 941 continue; 942 943 LexicalScope *Scope = nullptr; 944 if (const DILocation *IA = IV.second) 945 Scope = LScopes.findInlinedScope(IV.first->getScope(), IA); 946 else 947 Scope = LScopes.findLexicalScope(IV.first->getScope()); 948 // If variable scope is not found then skip this variable. 949 if (!Scope) 950 continue; 951 952 Processed.insert(IV); 953 DbgVariable *RegVar = createConcreteVariable(*Scope, IV); 954 955 const MachineInstr *MInsn = Ranges.front().first; 956 assert(MInsn->isDebugValue() && "History must begin with debug value"); 957 958 // Check if the first DBG_VALUE is valid for the rest of the function. 959 if (Ranges.size() == 1 && Ranges.front().second == nullptr) { 960 RegVar->initializeDbgValue(MInsn); 961 continue; 962 } 963 964 // Handle multiple DBG_VALUE instructions describing one variable. 965 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn); 966 967 // Build the location list for this variable. 968 SmallVector<DebugLocEntry, 8> Entries; 969 buildLocationList(Entries, Ranges); 970 971 // If the variable has an DIBasicType, extract it. Basic types cannot have 972 // unique identifiers, so don't bother resolving the type with the 973 // identifier map. 974 const DIBasicType *BT = dyn_cast<DIBasicType>( 975 static_cast<const Metadata *>(IV.first->getType())); 976 977 // Finalize the entry by lowering it into a DWARF bytestream. 978 for (auto &Entry : Entries) 979 Entry.finalize(*Asm, List, BT); 980 } 981 982 // Collect info for variables that were optimized out. 983 for (const DILocalVariable *DV : SP->getVariables()) { 984 if (Processed.insert(InlinedVariable(DV, nullptr)).second) 985 if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope())) 986 createConcreteVariable(*Scope, InlinedVariable(DV, nullptr)); 987 } 988 } 989 990 // Return Label preceding the instruction. 991 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) { 992 MCSymbol *Label = LabelsBeforeInsn.lookup(MI); 993 assert(Label && "Didn't insert label before instruction"); 994 return Label; 995 } 996 997 // Return Label immediately following the instruction. 998 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) { 999 return LabelsAfterInsn.lookup(MI); 1000 } 1001 1002 // Process beginning of an instruction. 1003 void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1004 assert(CurMI == nullptr); 1005 CurMI = MI; 1006 // Check if source location changes, but ignore DBG_VALUE locations. 1007 if (!MI->isDebugValue()) { 1008 DebugLoc DL = MI->getDebugLoc(); 1009 if (DL != PrevInstLoc) { 1010 if (DL) { 1011 unsigned Flags = 0; 1012 PrevInstLoc = DL; 1013 if (DL == PrologEndLoc) { 1014 Flags |= DWARF2_FLAG_PROLOGUE_END; 1015 PrologEndLoc = DebugLoc(); 1016 Flags |= DWARF2_FLAG_IS_STMT; 1017 } 1018 if (DL.getLine() != 1019 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine()) 1020 Flags |= DWARF2_FLAG_IS_STMT; 1021 1022 const MDNode *Scope = DL.getScope(); 1023 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1024 } else if (UnknownLocations) { 1025 PrevInstLoc = DL; 1026 recordSourceLine(0, 0, nullptr, 0); 1027 } 1028 } 1029 } 1030 1031 // Insert labels where requested. 1032 DenseMap<const MachineInstr *, MCSymbol *>::iterator I = 1033 LabelsBeforeInsn.find(MI); 1034 1035 // No label needed. 1036 if (I == LabelsBeforeInsn.end()) 1037 return; 1038 1039 // Label already assigned. 1040 if (I->second) 1041 return; 1042 1043 if (!PrevLabel) { 1044 PrevLabel = MMI->getContext().createTempSymbol(); 1045 Asm->OutStreamer->EmitLabel(PrevLabel); 1046 } 1047 I->second = PrevLabel; 1048 } 1049 1050 // Process end of an instruction. 1051 void DwarfDebug::endInstruction() { 1052 assert(CurMI != nullptr); 1053 // Don't create a new label after DBG_VALUE instructions. 1054 // They don't generate code. 1055 if (!CurMI->isDebugValue()) 1056 PrevLabel = nullptr; 1057 1058 DenseMap<const MachineInstr *, MCSymbol *>::iterator I = 1059 LabelsAfterInsn.find(CurMI); 1060 CurMI = nullptr; 1061 1062 // No label needed. 1063 if (I == LabelsAfterInsn.end()) 1064 return; 1065 1066 // Label already assigned. 1067 if (I->second) 1068 return; 1069 1070 // We need a label after this instruction. 1071 if (!PrevLabel) { 1072 PrevLabel = MMI->getContext().createTempSymbol(); 1073 Asm->OutStreamer->EmitLabel(PrevLabel); 1074 } 1075 I->second = PrevLabel; 1076 } 1077 1078 // Each LexicalScope has first instruction and last instruction to mark 1079 // beginning and end of a scope respectively. Create an inverse map that list 1080 // scopes starts (and ends) with an instruction. One instruction may start (or 1081 // end) multiple scopes. Ignore scopes that are not reachable. 1082 void DwarfDebug::identifyScopeMarkers() { 1083 SmallVector<LexicalScope *, 4> WorkList; 1084 WorkList.push_back(LScopes.getCurrentFunctionScope()); 1085 while (!WorkList.empty()) { 1086 LexicalScope *S = WorkList.pop_back_val(); 1087 1088 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren(); 1089 if (!Children.empty()) 1090 WorkList.append(Children.begin(), Children.end()); 1091 1092 if (S->isAbstractScope()) 1093 continue; 1094 1095 for (const InsnRange &R : S->getRanges()) { 1096 assert(R.first && "InsnRange does not have first instruction!"); 1097 assert(R.second && "InsnRange does not have second instruction!"); 1098 requestLabelBeforeInsn(R.first); 1099 requestLabelAfterInsn(R.second); 1100 } 1101 } 1102 } 1103 1104 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) { 1105 // First known non-DBG_VALUE and non-frame setup location marks 1106 // the beginning of the function body. 1107 for (const auto &MBB : *MF) 1108 for (const auto &MI : MBB) 1109 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) && 1110 MI.getDebugLoc()) { 1111 // Did the target forget to set the FrameSetup flag for CFI insns? 1112 assert(!MI.isCFIInstruction() && 1113 "First non-frame-setup instruction is a CFI instruction."); 1114 return MI.getDebugLoc(); 1115 } 1116 return DebugLoc(); 1117 } 1118 1119 // Gather pre-function debug information. Assumes being called immediately 1120 // after the function entry point has been emitted. 1121 void DwarfDebug::beginFunction(const MachineFunction *MF) { 1122 CurFn = MF; 1123 1124 // If there's no debug info for the function we're not going to do anything. 1125 if (!MMI->hasDebugInfo()) 1126 return; 1127 1128 auto DI = FunctionDIs.find(MF->getFunction()); 1129 if (DI == FunctionDIs.end()) 1130 return; 1131 1132 // Grab the lexical scopes for the function, if we don't have any of those 1133 // then we're not going to be able to do anything. 1134 LScopes.initialize(*MF); 1135 if (LScopes.empty()) 1136 return; 1137 1138 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!"); 1139 1140 // Make sure that each lexical scope will have a begin/end label. 1141 identifyScopeMarkers(); 1142 1143 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 1144 // belongs to so that we add to the correct per-cu line table in the 1145 // non-asm case. 1146 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1147 // FnScope->getScopeNode() and DI->second should represent the same function, 1148 // though they may not be the same MDNode due to inline functions merged in 1149 // LTO where the debug info metadata still differs (either due to distinct 1150 // written differences - two versions of a linkonce_odr function 1151 // written/copied into two separate files, or some sub-optimal metadata that 1152 // isn't structurally identical (see: file path/name info from clang, which 1153 // includes the directory of the cpp file being built, even when the file name 1154 // is absolute (such as an <> lookup header))) 1155 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode()); 1156 assert(TheCU && "Unable to find compile unit!"); 1157 if (Asm->OutStreamer->hasRawTextSupport()) 1158 // Use a single line table if we are generating assembly. 1159 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1160 else 1161 Asm->OutStreamer->getContext().setDwarfCompileUnitID(TheCU->getUniqueID()); 1162 1163 // Calculate history for local variables. 1164 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(), 1165 DbgValues); 1166 1167 // Request labels for the full history. 1168 for (const auto &I : DbgValues) { 1169 const auto &Ranges = I.second; 1170 if (Ranges.empty()) 1171 continue; 1172 1173 // The first mention of a function argument gets the CurrentFnBegin 1174 // label, so arguments are visible when breaking at function entry. 1175 const DILocalVariable *DIVar = Ranges.front().first->getDebugVariable(); 1176 if (DIVar->isParameter() && 1177 getDISubprogram(DIVar->getScope())->describes(MF->getFunction())) { 1178 LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin(); 1179 if (Ranges.front().first->getDebugExpression()->isBitPiece()) { 1180 // Mark all non-overlapping initial pieces. 1181 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) { 1182 const DIExpression *Piece = I->first->getDebugExpression(); 1183 if (std::all_of(Ranges.begin(), I, 1184 [&](DbgValueHistoryMap::InstrRange Pred) { 1185 return !piecesOverlap(Piece, Pred.first->getDebugExpression()); 1186 })) 1187 LabelsBeforeInsn[I->first] = Asm->getFunctionBegin(); 1188 else 1189 break; 1190 } 1191 } 1192 } 1193 1194 for (const auto &Range : Ranges) { 1195 requestLabelBeforeInsn(Range.first); 1196 if (Range.second) 1197 requestLabelAfterInsn(Range.second); 1198 } 1199 } 1200 1201 PrevInstLoc = DebugLoc(); 1202 PrevLabel = Asm->getFunctionBegin(); 1203 1204 // Record beginning of function. 1205 PrologEndLoc = findPrologueEndLoc(MF); 1206 if (DILocation *L = PrologEndLoc) { 1207 // We'd like to list the prologue as "not statements" but GDB behaves 1208 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 1209 auto *SP = L->getInlinedAtScope()->getSubprogram(); 1210 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT); 1211 } 1212 } 1213 1214 // Gather and emit post-function debug information. 1215 void DwarfDebug::endFunction(const MachineFunction *MF) { 1216 assert(CurFn == MF && 1217 "endFunction should be called with the same function as beginFunction"); 1218 1219 if (!MMI->hasDebugInfo() || LScopes.empty() || 1220 !FunctionDIs.count(MF->getFunction())) { 1221 // If we don't have a lexical scope for this function then there will 1222 // be a hole in the range information. Keep note of this by setting the 1223 // previously used section to nullptr. 1224 PrevCU = nullptr; 1225 CurFn = nullptr; 1226 return; 1227 } 1228 1229 // Set DwarfDwarfCompileUnitID in MCContext to default value. 1230 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1231 1232 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1233 auto *SP = cast<DISubprogram>(FnScope->getScopeNode()); 1234 DwarfCompileUnit &TheCU = *SPMap.lookup(SP); 1235 1236 DenseSet<InlinedVariable> ProcessedVars; 1237 collectVariableInfo(TheCU, SP, ProcessedVars); 1238 1239 // Add the range of this function to the list of ranges for the CU. 1240 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd())); 1241 1242 // Under -gmlt, skip building the subprogram if there are no inlined 1243 // subroutines inside it. 1244 if (TheCU.getCUNode()->getEmissionKind() == DIBuilder::LineTablesOnly && 1245 LScopes.getAbstractScopesList().empty() && !IsDarwin) { 1246 assert(InfoHolder.getScopeVariables().empty()); 1247 assert(DbgValues.empty()); 1248 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed 1249 // by a -gmlt CU. Add a test and remove this assertion. 1250 assert(AbstractVariables.empty()); 1251 LabelsBeforeInsn.clear(); 1252 LabelsAfterInsn.clear(); 1253 PrevLabel = nullptr; 1254 CurFn = nullptr; 1255 return; 1256 } 1257 1258 #ifndef NDEBUG 1259 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size(); 1260 #endif 1261 // Construct abstract scopes. 1262 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) { 1263 auto *SP = cast<DISubprogram>(AScope->getScopeNode()); 1264 // Collect info for variables that were optimized out. 1265 for (const DILocalVariable *DV : SP->getVariables()) { 1266 if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second) 1267 continue; 1268 ensureAbstractVariableIsCreated(InlinedVariable(DV, nullptr), 1269 DV->getScope()); 1270 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes 1271 && "ensureAbstractVariableIsCreated inserted abstract scopes"); 1272 } 1273 constructAbstractSubprogramScopeDIE(AScope); 1274 } 1275 1276 TheCU.constructSubprogramScopeDIE(FnScope); 1277 if (auto *SkelCU = TheCU.getSkeleton()) 1278 if (!LScopes.getAbstractScopesList().empty()) 1279 SkelCU->constructSubprogramScopeDIE(FnScope); 1280 1281 // Clear debug info 1282 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the 1283 // DbgVariables except those that are also in AbstractVariables (since they 1284 // can be used cross-function) 1285 InfoHolder.getScopeVariables().clear(); 1286 DbgValues.clear(); 1287 LabelsBeforeInsn.clear(); 1288 LabelsAfterInsn.clear(); 1289 PrevLabel = nullptr; 1290 CurFn = nullptr; 1291 } 1292 1293 // Register a source line with debug info. Returns the unique label that was 1294 // emitted and which provides correspondence to the source line list. 1295 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1296 unsigned Flags) { 1297 StringRef Fn; 1298 StringRef Dir; 1299 unsigned Src = 1; 1300 unsigned Discriminator = 0; 1301 if (auto *Scope = cast_or_null<DIScope>(S)) { 1302 Fn = Scope->getFilename(); 1303 Dir = Scope->getDirectory(); 1304 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope)) 1305 Discriminator = LBF->getDiscriminator(); 1306 1307 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID(); 1308 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID]) 1309 .getOrCreateSourceID(Fn, Dir); 1310 } 1311 Asm->OutStreamer->EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 1312 Discriminator, Fn); 1313 } 1314 1315 //===----------------------------------------------------------------------===// 1316 // Emit Methods 1317 //===----------------------------------------------------------------------===// 1318 1319 // Emit the debug info section. 1320 void DwarfDebug::emitDebugInfo() { 1321 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1322 Holder.emitUnits(/* UseOffsets */ false); 1323 } 1324 1325 // Emit the abbreviation section. 1326 void DwarfDebug::emitAbbreviations() { 1327 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1328 1329 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection()); 1330 } 1331 1332 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, MCSection *Section, 1333 StringRef TableName) { 1334 Accel.FinalizeTable(Asm, TableName); 1335 Asm->OutStreamer->SwitchSection(Section); 1336 1337 // Emit the full data. 1338 Accel.emit(Asm, Section->getBeginSymbol(), this); 1339 } 1340 1341 // Emit visible names into a hashed accelerator table section. 1342 void DwarfDebug::emitAccelNames() { 1343 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(), 1344 "Names"); 1345 } 1346 1347 // Emit objective C classes and categories into a hashed accelerator table 1348 // section. 1349 void DwarfDebug::emitAccelObjC() { 1350 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(), 1351 "ObjC"); 1352 } 1353 1354 // Emit namespace dies into a hashed accelerator table. 1355 void DwarfDebug::emitAccelNamespaces() { 1356 emitAccel(AccelNamespace, 1357 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(), 1358 "namespac"); 1359 } 1360 1361 // Emit type dies into a hashed accelerator table. 1362 void DwarfDebug::emitAccelTypes() { 1363 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(), 1364 "types"); 1365 } 1366 1367 // Public name handling. 1368 // The format for the various pubnames: 1369 // 1370 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU 1371 // for the DIE that is named. 1372 // 1373 // gnu pubnames - offset/index value/name tuples where the offset is the offset 1374 // into the CU and the index value is computed according to the type of value 1375 // for the DIE that is named. 1376 // 1377 // For type units the offset is the offset of the skeleton DIE. For split dwarf 1378 // it's the offset within the debug_info/debug_types dwo section, however, the 1379 // reference in the pubname header doesn't change. 1380 1381 /// computeIndexValue - Compute the gdb index value for the DIE and CU. 1382 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, 1383 const DIE *Die) { 1384 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC; 1385 1386 // We could have a specification DIE that has our most of our knowledge, 1387 // look for that now. 1388 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) { 1389 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry(); 1390 if (SpecDIE.findAttribute(dwarf::DW_AT_external)) 1391 Linkage = dwarf::GIEL_EXTERNAL; 1392 } else if (Die->findAttribute(dwarf::DW_AT_external)) 1393 Linkage = dwarf::GIEL_EXTERNAL; 1394 1395 switch (Die->getTag()) { 1396 case dwarf::DW_TAG_class_type: 1397 case dwarf::DW_TAG_structure_type: 1398 case dwarf::DW_TAG_union_type: 1399 case dwarf::DW_TAG_enumeration_type: 1400 return dwarf::PubIndexEntryDescriptor( 1401 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus 1402 ? dwarf::GIEL_STATIC 1403 : dwarf::GIEL_EXTERNAL); 1404 case dwarf::DW_TAG_typedef: 1405 case dwarf::DW_TAG_base_type: 1406 case dwarf::DW_TAG_subrange_type: 1407 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC); 1408 case dwarf::DW_TAG_namespace: 1409 return dwarf::GIEK_TYPE; 1410 case dwarf::DW_TAG_subprogram: 1411 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage); 1412 case dwarf::DW_TAG_variable: 1413 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage); 1414 case dwarf::DW_TAG_enumerator: 1415 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, 1416 dwarf::GIEL_STATIC); 1417 default: 1418 return dwarf::GIEK_NONE; 1419 } 1420 } 1421 1422 /// emitDebugPubNames - Emit visible names into a debug pubnames section. 1423 /// 1424 void DwarfDebug::emitDebugPubNames(bool GnuStyle) { 1425 MCSection *PSec = GnuStyle 1426 ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection() 1427 : Asm->getObjFileLowering().getDwarfPubNamesSection(); 1428 1429 emitDebugPubSection(GnuStyle, PSec, "Names", 1430 &DwarfCompileUnit::getGlobalNames); 1431 } 1432 1433 void DwarfDebug::emitDebugPubSection( 1434 bool GnuStyle, MCSection *PSec, StringRef Name, 1435 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) { 1436 for (const auto &NU : CUMap) { 1437 DwarfCompileUnit *TheU = NU.second; 1438 1439 const auto &Globals = (TheU->*Accessor)(); 1440 1441 if (Globals.empty()) 1442 continue; 1443 1444 if (auto *Skeleton = TheU->getSkeleton()) 1445 TheU = Skeleton; 1446 1447 // Start the dwarf pubnames section. 1448 Asm->OutStreamer->SwitchSection(PSec); 1449 1450 // Emit the header. 1451 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info"); 1452 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin"); 1453 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end"); 1454 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); 1455 1456 Asm->OutStreamer->EmitLabel(BeginLabel); 1457 1458 Asm->OutStreamer->AddComment("DWARF Version"); 1459 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); 1460 1461 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info"); 1462 Asm->emitDwarfSymbolReference(TheU->getLabelBegin()); 1463 1464 Asm->OutStreamer->AddComment("Compilation Unit Length"); 1465 Asm->EmitInt32(TheU->getLength()); 1466 1467 // Emit the pubnames for this compilation unit. 1468 for (const auto &GI : Globals) { 1469 const char *Name = GI.getKeyData(); 1470 const DIE *Entity = GI.second; 1471 1472 Asm->OutStreamer->AddComment("DIE offset"); 1473 Asm->EmitInt32(Entity->getOffset()); 1474 1475 if (GnuStyle) { 1476 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity); 1477 Asm->OutStreamer->AddComment( 1478 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " + 1479 dwarf::GDBIndexEntryLinkageString(Desc.Linkage)); 1480 Asm->EmitInt8(Desc.toBits()); 1481 } 1482 1483 Asm->OutStreamer->AddComment("External Name"); 1484 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1)); 1485 } 1486 1487 Asm->OutStreamer->AddComment("End Mark"); 1488 Asm->EmitInt32(0); 1489 Asm->OutStreamer->EmitLabel(EndLabel); 1490 } 1491 } 1492 1493 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) { 1494 MCSection *PSec = GnuStyle 1495 ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection() 1496 : Asm->getObjFileLowering().getDwarfPubTypesSection(); 1497 1498 emitDebugPubSection(GnuStyle, PSec, "Types", 1499 &DwarfCompileUnit::getGlobalTypes); 1500 } 1501 1502 // Emit visible names into a debug str section. 1503 void DwarfDebug::emitDebugStr() { 1504 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1505 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection()); 1506 } 1507 1508 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer, 1509 const DebugLocStream::Entry &Entry) { 1510 auto &&Comments = DebugLocs.getComments(Entry); 1511 auto Comment = Comments.begin(); 1512 auto End = Comments.end(); 1513 for (uint8_t Byte : DebugLocs.getBytes(Entry)) 1514 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : ""); 1515 } 1516 1517 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, 1518 ByteStreamer &Streamer, 1519 const DebugLocEntry::Value &Value, 1520 unsigned PieceOffsetInBits) { 1521 DebugLocDwarfExpression DwarfExpr(*AP.MF->getSubtarget().getRegisterInfo(), 1522 AP.getDwarfDebug()->getDwarfVersion(), 1523 Streamer); 1524 // Regular entry. 1525 if (Value.isInt()) { 1526 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed || 1527 BT->getEncoding() == dwarf::DW_ATE_signed_char)) 1528 DwarfExpr.AddSignedConstant(Value.getInt()); 1529 else 1530 DwarfExpr.AddUnsignedConstant(Value.getInt()); 1531 } else if (Value.isLocation()) { 1532 MachineLocation Loc = Value.getLoc(); 1533 const DIExpression *Expr = Value.getExpression(); 1534 if (!Expr || !Expr->getNumElements()) 1535 // Regular entry. 1536 AP.EmitDwarfRegOp(Streamer, Loc); 1537 else { 1538 // Complex address entry. 1539 if (Loc.getOffset()) { 1540 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset()); 1541 DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end(), 1542 PieceOffsetInBits); 1543 } else 1544 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(), 1545 PieceOffsetInBits); 1546 } 1547 } 1548 // else ... ignore constant fp. There is not any good way to 1549 // to represent them here in dwarf. 1550 // FIXME: ^ 1551 } 1552 1553 void DebugLocEntry::finalize(const AsmPrinter &AP, 1554 DebugLocStream::ListBuilder &List, 1555 const DIBasicType *BT) { 1556 DebugLocStream::EntryBuilder Entry(List, Begin, End); 1557 BufferByteStreamer Streamer = Entry.getStreamer(); 1558 const DebugLocEntry::Value &Value = Values[0]; 1559 if (Value.isBitPiece()) { 1560 // Emit all pieces that belong to the same variable and range. 1561 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) { 1562 return P.isBitPiece(); 1563 }) && "all values are expected to be pieces"); 1564 assert(std::is_sorted(Values.begin(), Values.end()) && 1565 "pieces are expected to be sorted"); 1566 1567 unsigned Offset = 0; 1568 for (auto Piece : Values) { 1569 const DIExpression *Expr = Piece.getExpression(); 1570 unsigned PieceOffset = Expr->getBitPieceOffset(); 1571 unsigned PieceSize = Expr->getBitPieceSize(); 1572 assert(Offset <= PieceOffset && "overlapping or duplicate pieces"); 1573 if (Offset < PieceOffset) { 1574 // The DWARF spec seriously mandates pieces with no locations for gaps. 1575 DebugLocDwarfExpression Expr(*AP.MF->getSubtarget().getRegisterInfo(), 1576 AP.getDwarfDebug()->getDwarfVersion(), 1577 Streamer); 1578 Expr.AddOpPiece(PieceOffset-Offset, 0); 1579 Offset += PieceOffset-Offset; 1580 } 1581 Offset += PieceSize; 1582 1583 emitDebugLocValue(AP, BT, Streamer, Piece, PieceOffset); 1584 } 1585 } else { 1586 assert(Values.size() == 1 && "only pieces may have >1 value"); 1587 emitDebugLocValue(AP, BT, Streamer, Value, 0); 1588 } 1589 } 1590 1591 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) { 1592 // Emit the size. 1593 Asm->OutStreamer->AddComment("Loc expr size"); 1594 Asm->EmitInt16(DebugLocs.getBytes(Entry).size()); 1595 1596 // Emit the entry. 1597 APByteStreamer Streamer(*Asm); 1598 emitDebugLocEntry(Streamer, Entry); 1599 } 1600 1601 // Emit locations into the debug loc section. 1602 void DwarfDebug::emitDebugLoc() { 1603 // Start the dwarf loc section. 1604 Asm->OutStreamer->SwitchSection( 1605 Asm->getObjFileLowering().getDwarfLocSection()); 1606 unsigned char Size = Asm->getDataLayout().getPointerSize(); 1607 for (const auto &List : DebugLocs.getLists()) { 1608 Asm->OutStreamer->EmitLabel(List.Label); 1609 const DwarfCompileUnit *CU = List.CU; 1610 for (const auto &Entry : DebugLocs.getEntries(List)) { 1611 // Set up the range. This range is relative to the entry point of the 1612 // compile unit. This is a hard coded 0 for low_pc when we're emitting 1613 // ranges, or the DW_AT_low_pc on the compile unit otherwise. 1614 if (auto *Base = CU->getBaseAddress()) { 1615 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size); 1616 Asm->EmitLabelDifference(Entry.EndSym, Base, Size); 1617 } else { 1618 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size); 1619 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size); 1620 } 1621 1622 emitDebugLocEntryLocation(Entry); 1623 } 1624 Asm->OutStreamer->EmitIntValue(0, Size); 1625 Asm->OutStreamer->EmitIntValue(0, Size); 1626 } 1627 } 1628 1629 void DwarfDebug::emitDebugLocDWO() { 1630 Asm->OutStreamer->SwitchSection( 1631 Asm->getObjFileLowering().getDwarfLocDWOSection()); 1632 for (const auto &List : DebugLocs.getLists()) { 1633 Asm->OutStreamer->EmitLabel(List.Label); 1634 for (const auto &Entry : DebugLocs.getEntries(List)) { 1635 // Just always use start_length for now - at least that's one address 1636 // rather than two. We could get fancier and try to, say, reuse an 1637 // address we know we've emitted elsewhere (the start of the function? 1638 // The start of the CU or CU subrange that encloses this range?) 1639 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry); 1640 unsigned idx = AddrPool.getIndex(Entry.BeginSym); 1641 Asm->EmitULEB128(idx); 1642 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4); 1643 1644 emitDebugLocEntryLocation(Entry); 1645 } 1646 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry); 1647 } 1648 } 1649 1650 struct ArangeSpan { 1651 const MCSymbol *Start, *End; 1652 }; 1653 1654 // Emit a debug aranges section, containing a CU lookup for any 1655 // address we can tie back to a CU. 1656 void DwarfDebug::emitDebugARanges() { 1657 // Provides a unique id per text section. 1658 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap; 1659 1660 // Filter labels by section. 1661 for (const SymbolCU &SCU : ArangeLabels) { 1662 if (SCU.Sym->isInSection()) { 1663 // Make a note of this symbol and it's section. 1664 MCSection *Section = &SCU.Sym->getSection(); 1665 if (!Section->getKind().isMetadata()) 1666 SectionMap[Section].push_back(SCU); 1667 } else { 1668 // Some symbols (e.g. common/bss on mach-o) can have no section but still 1669 // appear in the output. This sucks as we rely on sections to build 1670 // arange spans. We can do it without, but it's icky. 1671 SectionMap[nullptr].push_back(SCU); 1672 } 1673 } 1674 1675 // Add terminating symbols for each section. 1676 for (const auto &I : SectionMap) { 1677 MCSection *Section = I.first; 1678 MCSymbol *Sym = nullptr; 1679 1680 if (Section) 1681 Sym = Asm->OutStreamer->endSection(Section); 1682 1683 // Insert a final terminator. 1684 SectionMap[Section].push_back(SymbolCU(nullptr, Sym)); 1685 } 1686 1687 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans; 1688 1689 for (auto &I : SectionMap) { 1690 const MCSection *Section = I.first; 1691 SmallVector<SymbolCU, 8> &List = I.second; 1692 if (List.size() < 2) 1693 continue; 1694 1695 // If we have no section (e.g. common), just write out 1696 // individual spans for each symbol. 1697 if (!Section) { 1698 for (const SymbolCU &Cur : List) { 1699 ArangeSpan Span; 1700 Span.Start = Cur.Sym; 1701 Span.End = nullptr; 1702 if (Cur.CU) 1703 Spans[Cur.CU].push_back(Span); 1704 } 1705 continue; 1706 } 1707 1708 // Sort the symbols by offset within the section. 1709 std::sort(List.begin(), List.end(), 1710 [&](const SymbolCU &A, const SymbolCU &B) { 1711 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0; 1712 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0; 1713 1714 // Symbols with no order assigned should be placed at the end. 1715 // (e.g. section end labels) 1716 if (IA == 0) 1717 return false; 1718 if (IB == 0) 1719 return true; 1720 return IA < IB; 1721 }); 1722 1723 // Build spans between each label. 1724 const MCSymbol *StartSym = List[0].Sym; 1725 for (size_t n = 1, e = List.size(); n < e; n++) { 1726 const SymbolCU &Prev = List[n - 1]; 1727 const SymbolCU &Cur = List[n]; 1728 1729 // Try and build the longest span we can within the same CU. 1730 if (Cur.CU != Prev.CU) { 1731 ArangeSpan Span; 1732 Span.Start = StartSym; 1733 Span.End = Cur.Sym; 1734 Spans[Prev.CU].push_back(Span); 1735 StartSym = Cur.Sym; 1736 } 1737 } 1738 } 1739 1740 // Start the dwarf aranges section. 1741 Asm->OutStreamer->SwitchSection( 1742 Asm->getObjFileLowering().getDwarfARangesSection()); 1743 1744 unsigned PtrSize = Asm->getDataLayout().getPointerSize(); 1745 1746 // Build a list of CUs used. 1747 std::vector<DwarfCompileUnit *> CUs; 1748 for (const auto &it : Spans) { 1749 DwarfCompileUnit *CU = it.first; 1750 CUs.push_back(CU); 1751 } 1752 1753 // Sort the CU list (again, to ensure consistent output order). 1754 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) { 1755 return A->getUniqueID() < B->getUniqueID(); 1756 }); 1757 1758 // Emit an arange table for each CU we used. 1759 for (DwarfCompileUnit *CU : CUs) { 1760 std::vector<ArangeSpan> &List = Spans[CU]; 1761 1762 // Describe the skeleton CU's offset and length, not the dwo file's. 1763 if (auto *Skel = CU->getSkeleton()) 1764 CU = Skel; 1765 1766 // Emit size of content not including length itself. 1767 unsigned ContentSize = 1768 sizeof(int16_t) + // DWARF ARange version number 1769 sizeof(int32_t) + // Offset of CU in the .debug_info section 1770 sizeof(int8_t) + // Pointer Size (in bytes) 1771 sizeof(int8_t); // Segment Size (in bytes) 1772 1773 unsigned TupleSize = PtrSize * 2; 1774 1775 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 1776 unsigned Padding = 1777 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize); 1778 1779 ContentSize += Padding; 1780 ContentSize += (List.size() + 1) * TupleSize; 1781 1782 // For each compile unit, write the list of spans it covers. 1783 Asm->OutStreamer->AddComment("Length of ARange Set"); 1784 Asm->EmitInt32(ContentSize); 1785 Asm->OutStreamer->AddComment("DWARF Arange version number"); 1786 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); 1787 Asm->OutStreamer->AddComment("Offset Into Debug Info Section"); 1788 Asm->emitDwarfSymbolReference(CU->getLabelBegin()); 1789 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 1790 Asm->EmitInt8(PtrSize); 1791 Asm->OutStreamer->AddComment("Segment Size (in bytes)"); 1792 Asm->EmitInt8(0); 1793 1794 Asm->OutStreamer->EmitFill(Padding, 0xff); 1795 1796 for (const ArangeSpan &Span : List) { 1797 Asm->EmitLabelReference(Span.Start, PtrSize); 1798 1799 // Calculate the size as being from the span start to it's end. 1800 if (Span.End) { 1801 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize); 1802 } else { 1803 // For symbols without an end marker (e.g. common), we 1804 // write a single arange entry containing just that one symbol. 1805 uint64_t Size = SymSize[Span.Start]; 1806 if (Size == 0) 1807 Size = 1; 1808 1809 Asm->OutStreamer->EmitIntValue(Size, PtrSize); 1810 } 1811 } 1812 1813 Asm->OutStreamer->AddComment("ARange terminator"); 1814 Asm->OutStreamer->EmitIntValue(0, PtrSize); 1815 Asm->OutStreamer->EmitIntValue(0, PtrSize); 1816 } 1817 } 1818 1819 // Emit visible names into a debug ranges section. 1820 void DwarfDebug::emitDebugRanges() { 1821 // Start the dwarf ranges section. 1822 Asm->OutStreamer->SwitchSection( 1823 Asm->getObjFileLowering().getDwarfRangesSection()); 1824 1825 // Size for our labels. 1826 unsigned char Size = Asm->getDataLayout().getPointerSize(); 1827 1828 // Grab the specific ranges for the compile units in the module. 1829 for (const auto &I : CUMap) { 1830 DwarfCompileUnit *TheCU = I.second; 1831 1832 if (auto *Skel = TheCU->getSkeleton()) 1833 TheCU = Skel; 1834 1835 // Iterate over the misc ranges for the compile units in the module. 1836 for (const RangeSpanList &List : TheCU->getRangeLists()) { 1837 // Emit our symbol so we can find the beginning of the range. 1838 Asm->OutStreamer->EmitLabel(List.getSym()); 1839 1840 for (const RangeSpan &Range : List.getRanges()) { 1841 const MCSymbol *Begin = Range.getStart(); 1842 const MCSymbol *End = Range.getEnd(); 1843 assert(Begin && "Range without a begin symbol?"); 1844 assert(End && "Range without an end symbol?"); 1845 if (auto *Base = TheCU->getBaseAddress()) { 1846 Asm->EmitLabelDifference(Begin, Base, Size); 1847 Asm->EmitLabelDifference(End, Base, Size); 1848 } else { 1849 Asm->OutStreamer->EmitSymbolValue(Begin, Size); 1850 Asm->OutStreamer->EmitSymbolValue(End, Size); 1851 } 1852 } 1853 1854 // And terminate the list with two 0 values. 1855 Asm->OutStreamer->EmitIntValue(0, Size); 1856 Asm->OutStreamer->EmitIntValue(0, Size); 1857 } 1858 } 1859 } 1860 1861 // DWARF5 Experimental Separate Dwarf emitters. 1862 1863 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die, 1864 std::unique_ptr<DwarfUnit> NewU) { 1865 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name, 1866 U.getCUNode()->getSplitDebugFilename()); 1867 1868 if (!CompilationDir.empty()) 1869 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 1870 1871 addGnuPubAttributes(*NewU, Die); 1872 1873 SkeletonHolder.addUnit(std::move(NewU)); 1874 } 1875 1876 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list, 1877 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id, 1878 // DW_AT_addr_base, DW_AT_ranges_base. 1879 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) { 1880 1881 auto OwnedUnit = make_unique<DwarfCompileUnit>( 1882 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder); 1883 DwarfCompileUnit &NewCU = *OwnedUnit; 1884 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection()); 1885 1886 NewCU.initStmtList(); 1887 1888 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit)); 1889 1890 return NewCU; 1891 } 1892 1893 // Emit the .debug_info.dwo section for separated dwarf. This contains the 1894 // compile units that would normally be in debug_info. 1895 void DwarfDebug::emitDebugInfoDWO() { 1896 assert(useSplitDwarf() && "No split dwarf debug info?"); 1897 // Don't emit relocations into the dwo file. 1898 InfoHolder.emitUnits(/* UseOffsets */ true); 1899 } 1900 1901 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 1902 // abbreviations for the .debug_info.dwo section. 1903 void DwarfDebug::emitDebugAbbrevDWO() { 1904 assert(useSplitDwarf() && "No split dwarf?"); 1905 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 1906 } 1907 1908 void DwarfDebug::emitDebugLineDWO() { 1909 assert(useSplitDwarf() && "No split dwarf?"); 1910 Asm->OutStreamer->SwitchSection( 1911 Asm->getObjFileLowering().getDwarfLineDWOSection()); 1912 SplitTypeUnitFileTable.Emit(*Asm->OutStreamer, MCDwarfLineTableParams()); 1913 } 1914 1915 // Emit the .debug_str.dwo section for separated dwarf. This contains the 1916 // string section and is identical in format to traditional .debug_str 1917 // sections. 1918 void DwarfDebug::emitDebugStrDWO() { 1919 assert(useSplitDwarf() && "No split dwarf?"); 1920 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 1921 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 1922 OffSec); 1923 } 1924 1925 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 1926 if (!useSplitDwarf()) 1927 return nullptr; 1928 if (SingleCU) 1929 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory()); 1930 return &SplitTypeUnitFileTable; 1931 } 1932 1933 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) { 1934 MD5 Hash; 1935 Hash.update(Identifier); 1936 // ... take the least significant 8 bytes and return those. Our MD5 1937 // implementation always returns its results in little endian, swap bytes 1938 // appropriately. 1939 MD5::MD5Result Result; 1940 Hash.final(Result); 1941 return support::endian::read64le(Result + 8); 1942 } 1943 1944 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 1945 StringRef Identifier, DIE &RefDie, 1946 const DICompositeType *CTy) { 1947 // Fast path if we're building some type units and one has already used the 1948 // address pool we know we're going to throw away all this work anyway, so 1949 // don't bother building dependent types. 1950 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed()) 1951 return; 1952 1953 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy]; 1954 if (TU) { 1955 CU.addDIETypeSignature(RefDie, *TU); 1956 return; 1957 } 1958 1959 bool TopLevelType = TypeUnitsUnderConstruction.empty(); 1960 AddrPool.resetUsedFlag(); 1961 1962 auto OwnedUnit = make_unique<DwarfTypeUnit>( 1963 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm, 1964 this, &InfoHolder, getDwoLineTable(CU)); 1965 DwarfTypeUnit &NewTU = *OwnedUnit; 1966 DIE &UnitDie = NewTU.getUnitDie(); 1967 TU = &NewTU; 1968 TypeUnitsUnderConstruction.push_back( 1969 std::make_pair(std::move(OwnedUnit), CTy)); 1970 1971 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 1972 CU.getLanguage()); 1973 1974 uint64_t Signature = makeTypeSignature(Identifier); 1975 NewTU.setTypeSignature(Signature); 1976 1977 if (useSplitDwarf()) 1978 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection()); 1979 else { 1980 CU.applyStmtList(UnitDie); 1981 NewTU.initSection( 1982 Asm->getObjFileLowering().getDwarfTypesSection(Signature)); 1983 } 1984 1985 NewTU.setType(NewTU.createTypeDIE(CTy)); 1986 1987 if (TopLevelType) { 1988 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction); 1989 TypeUnitsUnderConstruction.clear(); 1990 1991 // Types referencing entries in the address table cannot be placed in type 1992 // units. 1993 if (AddrPool.hasBeenUsed()) { 1994 1995 // Remove all the types built while building this type. 1996 // This is pessimistic as some of these types might not be dependent on 1997 // the type that used an address. 1998 for (const auto &TU : TypeUnitsToAdd) 1999 DwarfTypeUnits.erase(TU.second); 2000 2001 // Construct this type in the CU directly. 2002 // This is inefficient because all the dependent types will be rebuilt 2003 // from scratch, including building them in type units, discovering that 2004 // they depend on addresses, throwing them out and rebuilding them. 2005 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy)); 2006 return; 2007 } 2008 2009 // If the type wasn't dependent on fission addresses, finish adding the type 2010 // and all its dependent types. 2011 for (auto &TU : TypeUnitsToAdd) 2012 InfoHolder.addUnit(std::move(TU.first)); 2013 } 2014 CU.addDIETypeSignature(RefDie, NewTU); 2015 } 2016 2017 // Accelerator table mutators - add each name along with its companion 2018 // DIE to the proper table while ensuring that the name that we're going 2019 // to reference is in the string table. We do this since the names we 2020 // add may not only be identical to the names in the DIE. 2021 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) { 2022 if (!useDwarfAccelTables()) 2023 return; 2024 AccelNames.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 2025 } 2026 2027 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) { 2028 if (!useDwarfAccelTables()) 2029 return; 2030 AccelObjC.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 2031 } 2032 2033 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) { 2034 if (!useDwarfAccelTables()) 2035 return; 2036 AccelNamespace.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 2037 } 2038 2039 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) { 2040 if (!useDwarfAccelTables()) 2041 return; 2042 AccelTypes.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 2043 } 2044