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