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