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