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