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