1 //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains support for writing dwarf debug info into asm files. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "DwarfDebug.h" 14 #include "ByteStreamer.h" 15 #include "DIEHash.h" 16 #include "DebugLocEntry.h" 17 #include "DebugLocStream.h" 18 #include "DwarfCompileUnit.h" 19 #include "DwarfExpression.h" 20 #include "DwarfFile.h" 21 #include "DwarfUnit.h" 22 #include "llvm/ADT/APInt.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/DenseSet.h" 25 #include "llvm/ADT/MapVector.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/StringRef.h" 29 #include "llvm/ADT/Triple.h" 30 #include "llvm/ADT/Twine.h" 31 #include "llvm/BinaryFormat/Dwarf.h" 32 #include "llvm/CodeGen/AccelTable.h" 33 #include "llvm/CodeGen/AsmPrinter.h" 34 #include "llvm/CodeGen/DIE.h" 35 #include "llvm/CodeGen/LexicalScopes.h" 36 #include "llvm/CodeGen/MachineBasicBlock.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineInstr.h" 39 #include "llvm/CodeGen/MachineModuleInfo.h" 40 #include "llvm/CodeGen/MachineOperand.h" 41 #include "llvm/CodeGen/TargetInstrInfo.h" 42 #include "llvm/CodeGen/TargetRegisterInfo.h" 43 #include "llvm/CodeGen/TargetSubtargetInfo.h" 44 #include "llvm/DebugInfo/DWARF/DWARFExpression.h" 45 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h" 46 #include "llvm/IR/Constants.h" 47 #include "llvm/IR/DebugInfoMetadata.h" 48 #include "llvm/IR/DebugLoc.h" 49 #include "llvm/IR/Function.h" 50 #include "llvm/IR/GlobalVariable.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/MC/MCAsmInfo.h" 53 #include "llvm/MC/MCContext.h" 54 #include "llvm/MC/MCDwarf.h" 55 #include "llvm/MC/MCSection.h" 56 #include "llvm/MC/MCStreamer.h" 57 #include "llvm/MC/MCSymbol.h" 58 #include "llvm/MC/MCTargetOptions.h" 59 #include "llvm/MC/MachineLocation.h" 60 #include "llvm/MC/SectionKind.h" 61 #include "llvm/Pass.h" 62 #include "llvm/Support/Casting.h" 63 #include "llvm/Support/CommandLine.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/MD5.h" 67 #include "llvm/Support/MathExtras.h" 68 #include "llvm/Support/Timer.h" 69 #include "llvm/Support/raw_ostream.h" 70 #include "llvm/Target/TargetLoweringObjectFile.h" 71 #include "llvm/Target/TargetMachine.h" 72 #include "llvm/Target/TargetOptions.h" 73 #include <algorithm> 74 #include <cassert> 75 #include <cstddef> 76 #include <cstdint> 77 #include <iterator> 78 #include <string> 79 #include <utility> 80 #include <vector> 81 82 using namespace llvm; 83 84 #define DEBUG_TYPE "dwarfdebug" 85 86 static cl::opt<bool> 87 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden, 88 cl::desc("Disable debug info printing")); 89 90 static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier( 91 "use-dwarf-ranges-base-address-specifier", cl::Hidden, 92 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false)); 93 94 static cl::opt<bool> GenerateARangeSection("generate-arange-section", 95 cl::Hidden, 96 cl::desc("Generate dwarf aranges"), 97 cl::init(false)); 98 99 static cl::opt<bool> 100 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden, 101 cl::desc("Generate DWARF4 type units."), 102 cl::init(false)); 103 104 static cl::opt<bool> SplitDwarfCrossCuReferences( 105 "split-dwarf-cross-cu-references", cl::Hidden, 106 cl::desc("Enable cross-cu references in DWO files"), cl::init(false)); 107 108 enum DefaultOnOff { Default, Enable, Disable }; 109 110 static cl::opt<DefaultOnOff> UnknownLocations( 111 "use-unknown-locations", cl::Hidden, 112 cl::desc("Make an absence of debug location information explicit."), 113 cl::values(clEnumVal(Default, "At top of block or after label"), 114 clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")), 115 cl::init(Default)); 116 117 static cl::opt<AccelTableKind> AccelTables( 118 "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."), 119 cl::values(clEnumValN(AccelTableKind::Default, "Default", 120 "Default for platform"), 121 clEnumValN(AccelTableKind::None, "Disable", "Disabled."), 122 clEnumValN(AccelTableKind::Apple, "Apple", "Apple"), 123 clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")), 124 cl::init(AccelTableKind::Default)); 125 126 static cl::opt<DefaultOnOff> 127 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden, 128 cl::desc("Use inlined strings rather than string section."), 129 cl::values(clEnumVal(Default, "Default for platform"), 130 clEnumVal(Enable, "Enabled"), 131 clEnumVal(Disable, "Disabled")), 132 cl::init(Default)); 133 134 static cl::opt<bool> 135 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden, 136 cl::desc("Disable emission .debug_ranges section."), 137 cl::init(false)); 138 139 static cl::opt<DefaultOnOff> DwarfSectionsAsReferences( 140 "dwarf-sections-as-references", cl::Hidden, 141 cl::desc("Use sections+offset as references rather than labels."), 142 cl::values(clEnumVal(Default, "Default for platform"), 143 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), 144 cl::init(Default)); 145 146 enum LinkageNameOption { 147 DefaultLinkageNames, 148 AllLinkageNames, 149 AbstractLinkageNames 150 }; 151 152 static cl::opt<LinkageNameOption> 153 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden, 154 cl::desc("Which DWARF linkage-name attributes to emit."), 155 cl::values(clEnumValN(DefaultLinkageNames, "Default", 156 "Default for platform"), 157 clEnumValN(AllLinkageNames, "All", "All"), 158 clEnumValN(AbstractLinkageNames, "Abstract", 159 "Abstract subprograms")), 160 cl::init(DefaultLinkageNames)); 161 162 static const char *const DWARFGroupName = "dwarf"; 163 static const char *const DWARFGroupDescription = "DWARF Emission"; 164 static const char *const DbgTimerName = "writer"; 165 static const char *const DbgTimerDescription = "DWARF Debug Writer"; 166 static constexpr unsigned ULEB128PadSize = 4; 167 168 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) { 169 BS.EmitInt8( 170 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op) 171 : dwarf::OperationEncodingString(Op)); 172 } 173 174 void DebugLocDwarfExpression::emitSigned(int64_t Value) { 175 BS.EmitSLEB128(Value, Twine(Value)); 176 } 177 178 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) { 179 BS.EmitULEB128(Value, Twine(Value)); 180 } 181 182 void DebugLocDwarfExpression::emitData1(uint8_t Value) { 183 BS.EmitInt8(Value, Twine(Value)); 184 } 185 186 void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) { 187 assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit"); 188 BS.EmitULEB128(Idx, Twine(Idx), ULEB128PadSize); 189 } 190 191 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI, 192 unsigned MachineReg) { 193 // This information is not available while emitting .debug_loc entries. 194 return false; 195 } 196 197 bool DbgVariable::isBlockByrefVariable() const { 198 assert(getVariable() && "Invalid complex DbgVariable!"); 199 return getVariable()->getType()->isBlockByrefStruct(); 200 } 201 202 const DIType *DbgVariable::getType() const { 203 DIType *Ty = getVariable()->getType(); 204 // FIXME: isBlockByrefVariable should be reformulated in terms of complex 205 // addresses instead. 206 if (Ty->isBlockByrefStruct()) { 207 /* Byref variables, in Blocks, are declared by the programmer as 208 "SomeType VarName;", but the compiler creates a 209 __Block_byref_x_VarName struct, and gives the variable VarName 210 either the struct, or a pointer to the struct, as its type. This 211 is necessary for various behind-the-scenes things the compiler 212 needs to do with by-reference variables in blocks. 213 214 However, as far as the original *programmer* is concerned, the 215 variable should still have type 'SomeType', as originally declared. 216 217 The following function dives into the __Block_byref_x_VarName 218 struct to find the original type of the variable. This will be 219 passed back to the code generating the type for the Debug 220 Information Entry for the variable 'VarName'. 'VarName' will then 221 have the original type 'SomeType' in its debug information. 222 223 The original type 'SomeType' will be the type of the field named 224 'VarName' inside the __Block_byref_x_VarName struct. 225 226 NOTE: In order for this to not completely fail on the debugger 227 side, the Debug Information Entry for the variable VarName needs to 228 have a DW_AT_location that tells the debugger how to unwind through 229 the pointers and __Block_byref_x_VarName struct to find the actual 230 value of the variable. The function addBlockByrefType does this. */ 231 DIType *subType = Ty; 232 uint16_t tag = Ty->getTag(); 233 234 if (tag == dwarf::DW_TAG_pointer_type) 235 subType = cast<DIDerivedType>(Ty)->getBaseType(); 236 237 auto Elements = cast<DICompositeType>(subType)->getElements(); 238 for (unsigned i = 0, N = Elements.size(); i < N; ++i) { 239 auto *DT = cast<DIDerivedType>(Elements[i]); 240 if (getName() == DT->getName()) 241 return DT->getBaseType(); 242 } 243 } 244 return Ty; 245 } 246 247 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const { 248 if (FrameIndexExprs.size() == 1) 249 return FrameIndexExprs; 250 251 assert(llvm::all_of(FrameIndexExprs, 252 [](const FrameIndexExpr &A) { 253 return A.Expr->isFragment(); 254 }) && 255 "multiple FI expressions without DW_OP_LLVM_fragment"); 256 llvm::sort(FrameIndexExprs, 257 [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool { 258 return A.Expr->getFragmentInfo()->OffsetInBits < 259 B.Expr->getFragmentInfo()->OffsetInBits; 260 }); 261 262 return FrameIndexExprs; 263 } 264 265 void DbgVariable::addMMIEntry(const DbgVariable &V) { 266 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry"); 267 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry"); 268 assert(V.getVariable() == getVariable() && "conflicting variable"); 269 assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location"); 270 271 assert(!FrameIndexExprs.empty() && "Expected an MMI entry"); 272 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry"); 273 274 // FIXME: This logic should not be necessary anymore, as we now have proper 275 // deduplication. However, without it, we currently run into the assertion 276 // below, which means that we are likely dealing with broken input, i.e. two 277 // non-fragment entries for the same variable at different frame indices. 278 if (FrameIndexExprs.size()) { 279 auto *Expr = FrameIndexExprs.back().Expr; 280 if (!Expr || !Expr->isFragment()) 281 return; 282 } 283 284 for (const auto &FIE : V.FrameIndexExprs) 285 // Ignore duplicate entries. 286 if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) { 287 return FIE.FI == Other.FI && FIE.Expr == Other.Expr; 288 })) 289 FrameIndexExprs.push_back(FIE); 290 291 assert((FrameIndexExprs.size() == 1 || 292 llvm::all_of(FrameIndexExprs, 293 [](FrameIndexExpr &FIE) { 294 return FIE.Expr && FIE.Expr->isFragment(); 295 })) && 296 "conflicting locations for variable"); 297 } 298 299 static AccelTableKind computeAccelTableKind(unsigned DwarfVersion, 300 bool GenerateTypeUnits, 301 DebuggerKind Tuning, 302 const Triple &TT) { 303 // Honor an explicit request. 304 if (AccelTables != AccelTableKind::Default) 305 return AccelTables; 306 307 // Accelerator tables with type units are currently not supported. 308 if (GenerateTypeUnits) 309 return AccelTableKind::None; 310 311 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5 312 // always implies debug_names. For lower standard versions we use apple 313 // accelerator tables on apple platforms and debug_names elsewhere. 314 if (DwarfVersion >= 5) 315 return AccelTableKind::Dwarf; 316 if (Tuning == DebuggerKind::LLDB) 317 return TT.isOSBinFormatMachO() ? AccelTableKind::Apple 318 : AccelTableKind::Dwarf; 319 return AccelTableKind::None; 320 } 321 322 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M) 323 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()), 324 InfoHolder(A, "info_string", DIEValueAllocator), 325 SkeletonHolder(A, "skel_string", DIEValueAllocator), 326 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) { 327 const Triple &TT = Asm->TM.getTargetTriple(); 328 329 // Make sure we know our "debugger tuning". The target option takes 330 // precedence; fall back to triple-based defaults. 331 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default) 332 DebuggerTuning = Asm->TM.Options.DebuggerTuning; 333 else if (IsDarwin) 334 DebuggerTuning = DebuggerKind::LLDB; 335 else if (TT.isPS4CPU()) 336 DebuggerTuning = DebuggerKind::SCE; 337 else 338 DebuggerTuning = DebuggerKind::GDB; 339 340 if (DwarfInlinedStrings == Default) 341 UseInlineStrings = TT.isNVPTX(); 342 else 343 UseInlineStrings = DwarfInlinedStrings == Enable; 344 345 UseLocSection = !TT.isNVPTX(); 346 347 HasAppleExtensionAttributes = tuneForLLDB(); 348 349 // Handle split DWARF. 350 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty(); 351 352 // SCE defaults to linkage names only for abstract subprograms. 353 if (DwarfLinkageNames == DefaultLinkageNames) 354 UseAllLinkageNames = !tuneForSCE(); 355 else 356 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames; 357 358 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion; 359 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber 360 : MMI->getModule()->getDwarfVersion(); 361 // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2. 362 DwarfVersion = 363 TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION); 364 365 UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX(); 366 367 // Use sections as references. Force for NVPTX. 368 if (DwarfSectionsAsReferences == Default) 369 UseSectionsAsReferences = TT.isNVPTX(); 370 else 371 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable; 372 373 // Don't generate type units for unsupported object file formats. 374 GenerateTypeUnits = 375 A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits; 376 377 TheAccelTableKind = computeAccelTableKind( 378 DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple()); 379 380 // Work around a GDB bug. GDB doesn't support the standard opcode; 381 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which 382 // is defined as of DWARF 3. 383 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented 384 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616 385 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3; 386 387 // GDB does not fully support the DWARF 4 representation for bitfields. 388 UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB(); 389 390 // The DWARF v5 string offsets table has - possibly shared - contributions 391 // from each compile and type unit each preceded by a header. The string 392 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses 393 // a monolithic string offsets table without any header. 394 UseSegmentedStringOffsetsTable = DwarfVersion >= 5; 395 396 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion); 397 } 398 399 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h. 400 DwarfDebug::~DwarfDebug() = default; 401 402 static bool isObjCClass(StringRef Name) { 403 return Name.startswith("+") || Name.startswith("-"); 404 } 405 406 static bool hasObjCCategory(StringRef Name) { 407 if (!isObjCClass(Name)) 408 return false; 409 410 return Name.find(") ") != StringRef::npos; 411 } 412 413 static void getObjCClassCategory(StringRef In, StringRef &Class, 414 StringRef &Category) { 415 if (!hasObjCCategory(In)) { 416 Class = In.slice(In.find('[') + 1, In.find(' ')); 417 Category = ""; 418 return; 419 } 420 421 Class = In.slice(In.find('[') + 1, In.find('(')); 422 Category = In.slice(In.find('[') + 1, In.find(' ')); 423 } 424 425 static StringRef getObjCMethodName(StringRef In) { 426 return In.slice(In.find(' ') + 1, In.find(']')); 427 } 428 429 // Add the various names to the Dwarf accelerator table names. 430 void DwarfDebug::addSubprogramNames(const DICompileUnit &CU, 431 const DISubprogram *SP, DIE &Die) { 432 if (getAccelTableKind() != AccelTableKind::Apple && 433 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None) 434 return; 435 436 if (!SP->isDefinition()) 437 return; 438 439 if (SP->getName() != "") 440 addAccelName(CU, SP->getName(), Die); 441 442 // If the linkage name is different than the name, go ahead and output that as 443 // well into the name table. Only do that if we are going to actually emit 444 // that name. 445 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() && 446 (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP))) 447 addAccelName(CU, SP->getLinkageName(), Die); 448 449 // If this is an Objective-C selector name add it to the ObjC accelerator 450 // too. 451 if (isObjCClass(SP->getName())) { 452 StringRef Class, Category; 453 getObjCClassCategory(SP->getName(), Class, Category); 454 addAccelObjC(CU, Class, Die); 455 if (Category != "") 456 addAccelObjC(CU, Category, Die); 457 // Also add the base method name to the name table. 458 addAccelName(CU, getObjCMethodName(SP->getName()), Die); 459 } 460 } 461 462 /// Check whether we should create a DIE for the given Scope, return true 463 /// if we don't create a DIE (the corresponding DIE is null). 464 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) { 465 if (Scope->isAbstractScope()) 466 return false; 467 468 // We don't create a DIE if there is no Range. 469 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges(); 470 if (Ranges.empty()) 471 return true; 472 473 if (Ranges.size() > 1) 474 return false; 475 476 // We don't create a DIE if we have a single Range and the end label 477 // is null. 478 return !getLabelAfterInsn(Ranges.front().second); 479 } 480 481 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) { 482 F(CU); 483 if (auto *SkelCU = CU.getSkeleton()) 484 if (CU.getCUNode()->getSplitDebugInlining()) 485 F(*SkelCU); 486 } 487 488 bool DwarfDebug::shareAcrossDWOCUs() const { 489 return SplitDwarfCrossCuReferences; 490 } 491 492 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, 493 LexicalScope *Scope) { 494 assert(Scope && Scope->getScopeNode()); 495 assert(Scope->isAbstractScope()); 496 assert(!Scope->getInlinedAt()); 497 498 auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 499 500 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 501 // was inlined from another compile unit. 502 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining()) 503 // Avoid building the original CU if it won't be used 504 SrcCU.constructAbstractSubprogramScopeDIE(Scope); 505 else { 506 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 507 if (auto *SkelCU = CU.getSkeleton()) { 508 (shareAcrossDWOCUs() ? CU : SrcCU) 509 .constructAbstractSubprogramScopeDIE(Scope); 510 if (CU.getCUNode()->getSplitDebugInlining()) 511 SkelCU->constructAbstractSubprogramScopeDIE(Scope); 512 } else 513 CU.constructAbstractSubprogramScopeDIE(Scope); 514 } 515 } 516 517 void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP, 518 DwarfCompileUnit &CU, DIE &ScopeDIE, 519 const MachineFunction &MF) { 520 // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if 521 // the subprogram is required to have one. 522 if (!SP.areAllCallsDescribed() || !SP.isDefinition()) 523 return; 524 525 // Use DW_AT_call_all_calls to express that call site entries are present 526 // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls 527 // because one of its requirements is not met: call site entries for 528 // optimized-out calls are elided. 529 CU.addFlag(ScopeDIE, dwarf::DW_AT_call_all_calls); 530 531 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 532 assert(TII && "TargetInstrInfo not found: cannot label tail calls"); 533 534 // Emit call site entries for each call or tail call in the function. 535 for (const MachineBasicBlock &MBB : MF) { 536 for (const MachineInstr &MI : MBB.instrs()) { 537 // Skip instructions which aren't calls. Both calls and tail-calling jump 538 // instructions (e.g TAILJMPd64) are classified correctly here. 539 if (!MI.isCall()) 540 continue; 541 542 // TODO: Add support for targets with delay slots (see: beginInstruction). 543 if (MI.hasDelaySlot()) 544 return; 545 546 // If this is a direct call, find the callee's subprogram. 547 const MachineOperand &CalleeOp = MI.getOperand(0); 548 if (!CalleeOp.isGlobal()) 549 continue; 550 const Function *CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal()); 551 if (!CalleeDecl || !CalleeDecl->getSubprogram()) 552 continue; 553 554 // TODO: Omit call site entries for runtime calls (objc_msgSend, etc). 555 // TODO: Add support for indirect calls. 556 557 bool IsTail = TII->isTailCall(MI); 558 559 // For tail calls, no return PC information is needed. For regular calls, 560 // the return PC is needed to disambiguate paths in the call graph which 561 // could lead to some target function. 562 const MCExpr *PCOffset = 563 IsTail ? nullptr : getFunctionLocalOffsetAfterInsn(&MI); 564 565 assert((IsTail || PCOffset) && "Call without return PC information"); 566 LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> " 567 << CalleeDecl->getName() << (IsTail ? " [tail]" : "") 568 << "\n"); 569 CU.constructCallSiteEntryDIE(ScopeDIE, *CalleeDecl->getSubprogram(), 570 IsTail, PCOffset); 571 } 572 } 573 } 574 575 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const { 576 if (!U.hasDwarfPubSections()) 577 return; 578 579 U.addFlag(D, dwarf::DW_AT_GNU_pubnames); 580 } 581 582 void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit, 583 DwarfCompileUnit &NewCU) { 584 DIE &Die = NewCU.getUnitDie(); 585 StringRef FN = DIUnit->getFilename(); 586 587 StringRef Producer = DIUnit->getProducer(); 588 StringRef Flags = DIUnit->getFlags(); 589 if (!Flags.empty() && !useAppleExtensionAttributes()) { 590 std::string ProducerWithFlags = Producer.str() + " " + Flags.str(); 591 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags); 592 } else 593 NewCU.addString(Die, dwarf::DW_AT_producer, Producer); 594 595 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 596 DIUnit->getSourceLanguage()); 597 NewCU.addString(Die, dwarf::DW_AT_name, FN); 598 599 // Add DW_str_offsets_base to the unit DIE, except for split units. 600 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 601 NewCU.addStringOffsetsStart(); 602 603 if (!useSplitDwarf()) { 604 NewCU.initStmtList(); 605 606 // If we're using split dwarf the compilation dir is going to be in the 607 // skeleton CU and so we don't need to duplicate it here. 608 if (!CompilationDir.empty()) 609 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 610 611 addGnuPubAttributes(NewCU, Die); 612 } 613 614 if (useAppleExtensionAttributes()) { 615 if (DIUnit->isOptimized()) 616 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized); 617 618 StringRef Flags = DIUnit->getFlags(); 619 if (!Flags.empty()) 620 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags); 621 622 if (unsigned RVer = DIUnit->getRuntimeVersion()) 623 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 624 dwarf::DW_FORM_data1, RVer); 625 } 626 627 if (DIUnit->getDWOId()) { 628 // This CU is either a clang module DWO or a skeleton CU. 629 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 630 DIUnit->getDWOId()); 631 if (!DIUnit->getSplitDebugFilename().empty()) 632 // This is a prefabricated skeleton CU. 633 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name, 634 DIUnit->getSplitDebugFilename()); 635 } 636 } 637 // Create new DwarfCompileUnit for the given metadata node with tag 638 // DW_TAG_compile_unit. 639 DwarfCompileUnit & 640 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) { 641 if (auto *CU = CUMap.lookup(DIUnit)) 642 return *CU; 643 644 CompilationDir = DIUnit->getDirectory(); 645 646 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 647 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder); 648 DwarfCompileUnit &NewCU = *OwnedUnit; 649 InfoHolder.addUnit(std::move(OwnedUnit)); 650 651 for (auto *IE : DIUnit->getImportedEntities()) 652 NewCU.addImportedEntity(IE); 653 654 // LTO with assembly output shares a single line table amongst multiple CUs. 655 // To avoid the compilation directory being ambiguous, let the line table 656 // explicitly describe the directory of all files, never relying on the 657 // compilation directory. 658 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU) 659 Asm->OutStreamer->emitDwarfFile0Directive( 660 CompilationDir, DIUnit->getFilename(), 661 NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(), 662 NewCU.getUniqueID()); 663 664 if (useSplitDwarf()) { 665 NewCU.setSkeleton(constructSkeletonCU(NewCU)); 666 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection()); 667 } else { 668 finishUnitAttributes(DIUnit, NewCU); 669 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 670 } 671 672 CUMap.insert({DIUnit, &NewCU}); 673 CUDieMap.insert({&NewCU.getUnitDie(), &NewCU}); 674 return NewCU; 675 } 676 677 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU, 678 const DIImportedEntity *N) { 679 if (isa<DILocalScope>(N->getScope())) 680 return; 681 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope())) 682 D->addChild(TheCU.constructImportedEntityDIE(N)); 683 } 684 685 /// Sort and unique GVEs by comparing their fragment offset. 686 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> & 687 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) { 688 llvm::sort( 689 GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) { 690 // Sort order: first null exprs, then exprs without fragment 691 // info, then sort by fragment offset in bits. 692 // FIXME: Come up with a more comprehensive comparator so 693 // the sorting isn't non-deterministic, and so the following 694 // std::unique call works correctly. 695 if (!A.Expr || !B.Expr) 696 return !!B.Expr; 697 auto FragmentA = A.Expr->getFragmentInfo(); 698 auto FragmentB = B.Expr->getFragmentInfo(); 699 if (!FragmentA || !FragmentB) 700 return !!FragmentB; 701 return FragmentA->OffsetInBits < FragmentB->OffsetInBits; 702 }); 703 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(), 704 [](DwarfCompileUnit::GlobalExpr A, 705 DwarfCompileUnit::GlobalExpr B) { 706 return A.Expr == B.Expr; 707 }), 708 GVEs.end()); 709 return GVEs; 710 } 711 712 // Emit all Dwarf sections that should come prior to the content. Create 713 // global DIEs and emit initial debug info sections. This is invoked by 714 // the target AsmPrinter. 715 void DwarfDebug::beginModule() { 716 NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName, 717 DWARFGroupDescription, TimePassesIsEnabled); 718 if (DisableDebugInfoPrinting) { 719 MMI->setDebugInfoAvailability(false); 720 return; 721 } 722 723 const Module *M = MMI->getModule(); 724 725 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(), 726 M->debug_compile_units_end()); 727 // Tell MMI whether we have debug info. 728 assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) && 729 "DebugInfoAvailabilty initialized unexpectedly"); 730 SingleCU = NumDebugCUs == 1; 731 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>> 732 GVMap; 733 for (const GlobalVariable &Global : M->globals()) { 734 SmallVector<DIGlobalVariableExpression *, 1> GVs; 735 Global.getDebugInfo(GVs); 736 for (auto *GVE : GVs) 737 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()}); 738 } 739 740 // Create the symbol that designates the start of the unit's contribution 741 // to the string offsets table. In a split DWARF scenario, only the skeleton 742 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol). 743 if (useSegmentedStringOffsetsTable()) 744 (useSplitDwarf() ? SkeletonHolder : InfoHolder) 745 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base")); 746 747 748 // Create the symbols that designates the start of the DWARF v5 range list 749 // and locations list tables. They are located past the table headers. 750 if (getDwarfVersion() >= 5) { 751 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 752 Holder.setRnglistsTableBaseSym( 753 Asm->createTempSymbol("rnglists_table_base")); 754 Holder.setLoclistsTableBaseSym( 755 Asm->createTempSymbol("loclists_table_base")); 756 757 if (useSplitDwarf()) 758 InfoHolder.setRnglistsTableBaseSym( 759 Asm->createTempSymbol("rnglists_dwo_table_base")); 760 } 761 762 // Create the symbol that points to the first entry following the debug 763 // address table (.debug_addr) header. 764 AddrPool.setLabel(Asm->createTempSymbol("addr_table_base")); 765 766 for (DICompileUnit *CUNode : M->debug_compile_units()) { 767 // FIXME: Move local imported entities into a list attached to the 768 // subprogram, then this search won't be needed and a 769 // getImportedEntities().empty() test should go below with the rest. 770 bool HasNonLocalImportedEntities = llvm::any_of( 771 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) { 772 return !isa<DILocalScope>(IE->getScope()); 773 }); 774 775 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() && 776 CUNode->getRetainedTypes().empty() && 777 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty()) 778 continue; 779 780 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode); 781 782 // Global Variables. 783 for (auto *GVE : CUNode->getGlobalVariables()) { 784 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we 785 // already know about the variable and it isn't adding a constant 786 // expression. 787 auto &GVMapEntry = GVMap[GVE->getVariable()]; 788 auto *Expr = GVE->getExpression(); 789 if (!GVMapEntry.size() || (Expr && Expr->isConstant())) 790 GVMapEntry.push_back({nullptr, Expr}); 791 } 792 DenseSet<DIGlobalVariable *> Processed; 793 for (auto *GVE : CUNode->getGlobalVariables()) { 794 DIGlobalVariable *GV = GVE->getVariable(); 795 if (Processed.insert(GV).second) 796 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV])); 797 } 798 799 for (auto *Ty : CUNode->getEnumTypes()) { 800 // The enum types array by design contains pointers to 801 // MDNodes rather than DIRefs. Unique them here. 802 CU.getOrCreateTypeDIE(cast<DIType>(Ty)); 803 } 804 for (auto *Ty : CUNode->getRetainedTypes()) { 805 // The retained types array by design contains pointers to 806 // MDNodes rather than DIRefs. Unique them here. 807 if (DIType *RT = dyn_cast<DIType>(Ty)) 808 // There is no point in force-emitting a forward declaration. 809 CU.getOrCreateTypeDIE(RT); 810 } 811 // Emit imported_modules last so that the relevant context is already 812 // available. 813 for (auto *IE : CUNode->getImportedEntities()) 814 constructAndAddImportedEntityDIE(CU, IE); 815 } 816 } 817 818 void DwarfDebug::finishEntityDefinitions() { 819 for (const auto &Entity : ConcreteEntities) { 820 DIE *Die = Entity->getDIE(); 821 assert(Die); 822 // FIXME: Consider the time-space tradeoff of just storing the unit pointer 823 // in the ConcreteEntities list, rather than looking it up again here. 824 // DIE::getUnit isn't simple - it walks parent pointers, etc. 825 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie()); 826 assert(Unit); 827 Unit->finishEntityDefinition(Entity.get()); 828 } 829 } 830 831 void DwarfDebug::finishSubprogramDefinitions() { 832 for (const DISubprogram *SP : ProcessedSPNodes) { 833 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug); 834 forBothCUs( 835 getOrCreateDwarfCompileUnit(SP->getUnit()), 836 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); }); 837 } 838 } 839 840 void DwarfDebug::finalizeModuleInfo() { 841 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 842 843 finishSubprogramDefinitions(); 844 845 finishEntityDefinitions(); 846 847 // Include the DWO file name in the hash if there's more than one CU. 848 // This handles ThinLTO's situation where imported CUs may very easily be 849 // duplicate with the same CU partially imported into another ThinLTO unit. 850 StringRef DWOName; 851 if (CUMap.size() > 1) 852 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile; 853 854 // Handle anything that needs to be done on a per-unit basis after 855 // all other generation. 856 for (const auto &P : CUMap) { 857 auto &TheCU = *P.second; 858 if (TheCU.getCUNode()->isDebugDirectivesOnly()) 859 continue; 860 // Emit DW_AT_containing_type attribute to connect types with their 861 // vtable holding type. 862 TheCU.constructContainingTypeDIEs(); 863 864 // Add CU specific attributes if we need to add any. 865 // If we're splitting the dwarf out now that we've got the entire 866 // CU then add the dwo id to it. 867 auto *SkCU = TheCU.getSkeleton(); 868 if (useSplitDwarf() && !empty(TheCU.getUnitDie().children())) { 869 finishUnitAttributes(TheCU.getCUNode(), TheCU); 870 TheCU.addString(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_name, 871 Asm->TM.Options.MCOptions.SplitDwarfFile); 872 SkCU->addString(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_name, 873 Asm->TM.Options.MCOptions.SplitDwarfFile); 874 // Emit a unique identifier for this CU. 875 uint64_t ID = 876 DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie()); 877 if (getDwarfVersion() >= 5) { 878 TheCU.setDWOId(ID); 879 SkCU->setDWOId(ID); 880 } else { 881 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 882 dwarf::DW_FORM_data8, ID); 883 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 884 dwarf::DW_FORM_data8, ID); 885 } 886 887 if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) { 888 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol(); 889 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base, 890 Sym, Sym); 891 } 892 } else if (SkCU) { 893 finishUnitAttributes(SkCU->getCUNode(), *SkCU); 894 } 895 896 // If we have code split among multiple sections or non-contiguous 897 // ranges of code then emit a DW_AT_ranges attribute on the unit that will 898 // remain in the .o file, otherwise add a DW_AT_low_pc. 899 // FIXME: We should use ranges allow reordering of code ala 900 // .subsections_via_symbols in mach-o. This would mean turning on 901 // ranges for all subprogram DIEs for mach-o. 902 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 903 904 if (unsigned NumRanges = TheCU.getRanges().size()) { 905 if (NumRanges > 1 && useRangesSection()) 906 // A DW_AT_low_pc attribute may also be specified in combination with 907 // DW_AT_ranges to specify the default base address for use in 908 // location lists (see Section 2.6.2) and range lists (see Section 909 // 2.17.3). 910 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0); 911 else 912 U.setBaseAddress(TheCU.getRanges().front().getStart()); 913 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges()); 914 } 915 916 // We don't keep track of which addresses are used in which CU so this 917 // is a bit pessimistic under LTO. 918 if (!AddrPool.isEmpty() && 919 (getDwarfVersion() >= 5 || 920 (SkCU && !empty(TheCU.getUnitDie().children())))) 921 U.addAddrTableBase(); 922 923 if (getDwarfVersion() >= 5) { 924 if (U.hasRangeLists()) 925 U.addRnglistsBase(); 926 927 if (!DebugLocs.getLists().empty() && !useSplitDwarf()) 928 U.addLoclistsBase(); 929 } 930 931 auto *CUNode = cast<DICompileUnit>(P.first); 932 // If compile Unit has macros, emit "DW_AT_macro_info" attribute. 933 if (CUNode->getMacros()) 934 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info, 935 U.getMacroLabelBegin(), 936 TLOF.getDwarfMacinfoSection()->getBeginSymbol()); 937 } 938 939 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules. 940 for (auto *CUNode : MMI->getModule()->debug_compile_units()) 941 if (CUNode->getDWOId()) 942 getOrCreateDwarfCompileUnit(CUNode); 943 944 // Compute DIE offsets and sizes. 945 InfoHolder.computeSizeAndOffsets(); 946 if (useSplitDwarf()) 947 SkeletonHolder.computeSizeAndOffsets(); 948 } 949 950 // Emit all Dwarf sections that should come after the content. 951 void DwarfDebug::endModule() { 952 assert(CurFn == nullptr); 953 assert(CurMI == nullptr); 954 955 for (const auto &P : CUMap) { 956 auto &CU = *P.second; 957 CU.createBaseTypeDIEs(); 958 } 959 960 // If we aren't actually generating debug info (check beginModule - 961 // conditionalized on !DisableDebugInfoPrinting and the presence of the 962 // llvm.dbg.cu metadata node) 963 if (!MMI->hasDebugInfo()) 964 return; 965 966 // Finalize the debug info for the module. 967 finalizeModuleInfo(); 968 969 emitDebugStr(); 970 971 if (useSplitDwarf()) 972 emitDebugLocDWO(); 973 else 974 // Emit info into a debug loc section. 975 emitDebugLoc(); 976 977 // Corresponding abbreviations into a abbrev section. 978 emitAbbreviations(); 979 980 // Emit all the DIEs into a debug info section. 981 emitDebugInfo(); 982 983 // Emit info into a debug aranges section. 984 if (GenerateARangeSection) 985 emitDebugARanges(); 986 987 // Emit info into a debug ranges section. 988 emitDebugRanges(); 989 990 // Emit info into a debug macinfo section. 991 emitDebugMacinfo(); 992 993 if (useSplitDwarf()) { 994 emitDebugStrDWO(); 995 emitDebugInfoDWO(); 996 emitDebugAbbrevDWO(); 997 emitDebugLineDWO(); 998 emitDebugRangesDWO(); 999 } 1000 1001 emitDebugAddr(); 1002 1003 // Emit info into the dwarf accelerator table sections. 1004 switch (getAccelTableKind()) { 1005 case AccelTableKind::Apple: 1006 emitAccelNames(); 1007 emitAccelObjC(); 1008 emitAccelNamespaces(); 1009 emitAccelTypes(); 1010 break; 1011 case AccelTableKind::Dwarf: 1012 emitAccelDebugNames(); 1013 break; 1014 case AccelTableKind::None: 1015 break; 1016 case AccelTableKind::Default: 1017 llvm_unreachable("Default should have already been resolved."); 1018 } 1019 1020 // Emit the pubnames and pubtypes sections if requested. 1021 emitDebugPubSections(); 1022 1023 // clean up. 1024 // FIXME: AbstractVariables.clear(); 1025 } 1026 1027 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU, 1028 const DINode *Node, 1029 const MDNode *ScopeNode) { 1030 if (CU.getExistingAbstractEntity(Node)) 1031 return; 1032 1033 CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope( 1034 cast<DILocalScope>(ScopeNode))); 1035 } 1036 1037 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU, 1038 const DINode *Node, const MDNode *ScopeNode) { 1039 if (CU.getExistingAbstractEntity(Node)) 1040 return; 1041 1042 if (LexicalScope *Scope = 1043 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode))) 1044 CU.createAbstractEntity(Node, Scope); 1045 } 1046 1047 // Collect variable information from side table maintained by MF. 1048 void DwarfDebug::collectVariableInfoFromMFTable( 1049 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) { 1050 SmallDenseMap<InlinedEntity, DbgVariable *> MFVars; 1051 for (const auto &VI : Asm->MF->getVariableDbgInfo()) { 1052 if (!VI.Var) 1053 continue; 1054 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 1055 "Expected inlined-at fields to agree"); 1056 1057 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt()); 1058 Processed.insert(Var); 1059 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 1060 1061 // If variable scope is not found then skip this variable. 1062 if (!Scope) 1063 continue; 1064 1065 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode()); 1066 auto RegVar = llvm::make_unique<DbgVariable>( 1067 cast<DILocalVariable>(Var.first), Var.second); 1068 RegVar->initializeMMI(VI.Expr, VI.Slot); 1069 if (DbgVariable *DbgVar = MFVars.lookup(Var)) 1070 DbgVar->addMMIEntry(*RegVar); 1071 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) { 1072 MFVars.insert({Var, RegVar.get()}); 1073 ConcreteEntities.push_back(std::move(RegVar)); 1074 } 1075 } 1076 } 1077 1078 // Get .debug_loc entry for the instruction range starting at MI. 1079 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) { 1080 const DIExpression *Expr = MI->getDebugExpression(); 1081 assert(MI->getNumOperands() == 4); 1082 if (MI->getOperand(0).isReg()) { 1083 auto RegOp = MI->getOperand(0); 1084 auto Op1 = MI->getOperand(1); 1085 // If the second operand is an immediate, this is a 1086 // register-indirect address. 1087 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset"); 1088 MachineLocation MLoc(RegOp.getReg(), Op1.isImm()); 1089 return DebugLocEntry::Value(Expr, MLoc); 1090 } 1091 if (MI->getOperand(0).isImm()) 1092 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm()); 1093 if (MI->getOperand(0).isFPImm()) 1094 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm()); 1095 if (MI->getOperand(0).isCImm()) 1096 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm()); 1097 1098 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!"); 1099 } 1100 1101 /// Build the location list for all DBG_VALUEs in the function that 1102 /// describe the same variable. The resulting DebugLocEntries will have 1103 /// strict monotonically increasing begin addresses and will never 1104 /// overlap. 1105 // 1106 // See the definition of DbgValueHistoryMap::Entry for an explanation of the 1107 // different kinds of history map entries. One thing to be aware of is that if 1108 // a debug value is ended by another entry (rather than being valid until the 1109 // end of the function), that entry's instruction may or may not be included in 1110 // the range, depending on if the entry is a clobbering entry (it has an 1111 // instruction that clobbers one or more preceding locations), or if it is an 1112 // (overlapping) debug value entry. This distinction can be seen in the example 1113 // below. The first debug value is ended by the clobbering entry 2, and the 1114 // second and third debug values are ended by the overlapping debug value entry 1115 // 4. 1116 // 1117 // Input: 1118 // 1119 // History map entries [type, end index, mi] 1120 // 1121 // 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)] 1122 // 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)] 1123 // 2 | | [Clobber, $reg0 = [...], -, -] 1124 // 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)] 1125 // 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)] 1126 // 1127 // Output [start, end) [Value...]: 1128 // 1129 // [0-1) [(reg0, fragment 0, 32)] 1130 // [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)] 1131 // [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)] 1132 // [4-) [(@g, fragment 0, 96)] 1133 void DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc, 1134 const DbgValueHistoryMap::Entries &Entries) { 1135 using OpenRange = 1136 std::pair<DbgValueHistoryMap::EntryIndex, DebugLocEntry::Value>; 1137 SmallVector<OpenRange, 4> OpenRanges; 1138 1139 for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) { 1140 const MachineInstr *Instr = EI->getInstr(); 1141 1142 // Remove all values that are no longer live. 1143 size_t Index = std::distance(EB, EI); 1144 auto Last = 1145 remove_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; }); 1146 OpenRanges.erase(Last, OpenRanges.end()); 1147 1148 // If we are dealing with a clobbering entry, this iteration will result in 1149 // a location list entry starting after the clobbering instruction. 1150 const MCSymbol *StartLabel = 1151 EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr); 1152 assert(StartLabel && 1153 "Forgot label before/after instruction starting a range!"); 1154 1155 const MCSymbol *EndLabel; 1156 if (std::next(EI) == Entries.end()) 1157 EndLabel = Asm->getFunctionEnd(); 1158 else if (std::next(EI)->isClobber()) 1159 EndLabel = getLabelAfterInsn(std::next(EI)->getInstr()); 1160 else 1161 EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr()); 1162 assert(EndLabel && "Forgot label after instruction ending a range!"); 1163 1164 if (EI->isDbgValue()) 1165 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n"); 1166 1167 // If this history map entry has a debug value, add that to the list of 1168 // open ranges. 1169 if (EI->isDbgValue()) { 1170 // Do not add undef debug values, as they are redundant information in 1171 // the location list entries. An undef debug results in an empty location 1172 // description. If there are any non-undef fragments then padding pieces 1173 // with empty location descriptions will automatically be inserted, and if 1174 // all fragments are undef then the whole location list entry is 1175 // redundant. 1176 if (!Instr->isUndefDebugValue()) { 1177 auto Value = getDebugLocValue(Instr); 1178 OpenRanges.emplace_back(EI->getEndIndex(), Value); 1179 } 1180 } 1181 1182 // Location list entries with empty location descriptions are redundant 1183 // information in DWARF, so do not emit those. 1184 if (OpenRanges.empty()) 1185 continue; 1186 1187 // Omit entries with empty ranges as they do not have any effect in DWARF. 1188 if (StartLabel == EndLabel) { 1189 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n"); 1190 continue; 1191 } 1192 1193 SmallVector<DebugLocEntry::Value, 4> Values; 1194 for (auto &R : OpenRanges) 1195 Values.push_back(R.second); 1196 DebugLoc.emplace_back(StartLabel, EndLabel, Values); 1197 1198 // Attempt to coalesce the ranges of two otherwise identical 1199 // DebugLocEntries. 1200 auto CurEntry = DebugLoc.rbegin(); 1201 LLVM_DEBUG({ 1202 dbgs() << CurEntry->getValues().size() << " Values:\n"; 1203 for (auto &Value : CurEntry->getValues()) 1204 Value.dump(); 1205 dbgs() << "-----\n"; 1206 }); 1207 1208 auto PrevEntry = std::next(CurEntry); 1209 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry)) 1210 DebugLoc.pop_back(); 1211 } 1212 } 1213 1214 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU, 1215 LexicalScope &Scope, 1216 const DINode *Node, 1217 const DILocation *Location, 1218 const MCSymbol *Sym) { 1219 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode()); 1220 if (isa<const DILocalVariable>(Node)) { 1221 ConcreteEntities.push_back( 1222 llvm::make_unique<DbgVariable>(cast<const DILocalVariable>(Node), 1223 Location)); 1224 InfoHolder.addScopeVariable(&Scope, 1225 cast<DbgVariable>(ConcreteEntities.back().get())); 1226 } else if (isa<const DILabel>(Node)) { 1227 ConcreteEntities.push_back( 1228 llvm::make_unique<DbgLabel>(cast<const DILabel>(Node), 1229 Location, Sym)); 1230 InfoHolder.addScopeLabel(&Scope, 1231 cast<DbgLabel>(ConcreteEntities.back().get())); 1232 } 1233 return ConcreteEntities.back().get(); 1234 } 1235 1236 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its 1237 /// enclosing lexical scope. The check ensures there are no other instructions 1238 /// in the same lexical scope preceding the DBG_VALUE and that its range is 1239 /// either open or otherwise rolls off the end of the scope. 1240 static bool validThroughout(LexicalScopes &LScopes, 1241 const MachineInstr *DbgValue, 1242 const MachineInstr *RangeEnd) { 1243 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location"); 1244 auto MBB = DbgValue->getParent(); 1245 auto DL = DbgValue->getDebugLoc(); 1246 auto *LScope = LScopes.findLexicalScope(DL); 1247 // Scope doesn't exist; this is a dead DBG_VALUE. 1248 if (!LScope) 1249 return false; 1250 auto &LSRange = LScope->getRanges(); 1251 if (LSRange.size() == 0) 1252 return false; 1253 1254 // Determine if the DBG_VALUE is valid at the beginning of its lexical block. 1255 const MachineInstr *LScopeBegin = LSRange.front().first; 1256 // Early exit if the lexical scope begins outside of the current block. 1257 if (LScopeBegin->getParent() != MBB) 1258 return false; 1259 MachineBasicBlock::const_reverse_iterator Pred(DbgValue); 1260 for (++Pred; Pred != MBB->rend(); ++Pred) { 1261 if (Pred->getFlag(MachineInstr::FrameSetup)) 1262 break; 1263 auto PredDL = Pred->getDebugLoc(); 1264 if (!PredDL || Pred->isMetaInstruction()) 1265 continue; 1266 // Check whether the instruction preceding the DBG_VALUE is in the same 1267 // (sub)scope as the DBG_VALUE. 1268 if (DL->getScope() == PredDL->getScope()) 1269 return false; 1270 auto *PredScope = LScopes.findLexicalScope(PredDL); 1271 if (!PredScope || LScope->dominates(PredScope)) 1272 return false; 1273 } 1274 1275 // If the range of the DBG_VALUE is open-ended, report success. 1276 if (!RangeEnd) 1277 return true; 1278 1279 // Fail if there are instructions belonging to our scope in another block. 1280 const MachineInstr *LScopeEnd = LSRange.back().second; 1281 if (LScopeEnd->getParent() != MBB) 1282 return false; 1283 1284 // Single, constant DBG_VALUEs in the prologue are promoted to be live 1285 // throughout the function. This is a hack, presumably for DWARF v2 and not 1286 // necessarily correct. It would be much better to use a dbg.declare instead 1287 // if we know the constant is live throughout the scope. 1288 if (DbgValue->getOperand(0).isImm() && MBB->pred_empty()) 1289 return true; 1290 1291 return false; 1292 } 1293 1294 // Find variables for each lexical scope. 1295 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU, 1296 const DISubprogram *SP, 1297 DenseSet<InlinedEntity> &Processed) { 1298 // Grab the variable info that was squirreled away in the MMI side-table. 1299 collectVariableInfoFromMFTable(TheCU, Processed); 1300 1301 for (const auto &I : DbgValues) { 1302 InlinedEntity IV = I.first; 1303 if (Processed.count(IV)) 1304 continue; 1305 1306 // Instruction ranges, specifying where IV is accessible. 1307 const auto &HistoryMapEntries = I.second; 1308 if (HistoryMapEntries.empty()) 1309 continue; 1310 1311 LexicalScope *Scope = nullptr; 1312 const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first); 1313 if (const DILocation *IA = IV.second) 1314 Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA); 1315 else 1316 Scope = LScopes.findLexicalScope(LocalVar->getScope()); 1317 // If variable scope is not found then skip this variable. 1318 if (!Scope) 1319 continue; 1320 1321 Processed.insert(IV); 1322 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU, 1323 *Scope, LocalVar, IV.second)); 1324 1325 const MachineInstr *MInsn = HistoryMapEntries.front().getInstr(); 1326 assert(MInsn->isDebugValue() && "History must begin with debug value"); 1327 1328 // Check if there is a single DBG_VALUE, valid throughout the var's scope. 1329 // If the history map contains a single debug value, there may be an 1330 // additional entry which clobbers the debug value. 1331 bool SingleValueWithClobber = 1332 HistoryMapEntries.size() == 2 && HistoryMapEntries[1].isClobber(); 1333 if (HistoryMapEntries.size() == 1 || SingleValueWithClobber) { 1334 const auto *End = 1335 SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr; 1336 if (validThroughout(LScopes, MInsn, End)) { 1337 RegVar->initializeDbgValue(MInsn); 1338 continue; 1339 } 1340 } 1341 1342 // Do not emit location lists if .debug_loc secton is disabled. 1343 if (!useLocSection()) 1344 continue; 1345 1346 // Handle multiple DBG_VALUE instructions describing one variable. 1347 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn); 1348 1349 // Build the location list for this variable. 1350 SmallVector<DebugLocEntry, 8> Entries; 1351 buildLocationList(Entries, HistoryMapEntries); 1352 1353 // If the variable has a DIBasicType, extract it. Basic types cannot have 1354 // unique identifiers, so don't bother resolving the type with the 1355 // identifier map. 1356 const DIBasicType *BT = dyn_cast<DIBasicType>( 1357 static_cast<const Metadata *>(LocalVar->getType())); 1358 1359 // Finalize the entry by lowering it into a DWARF bytestream. 1360 for (auto &Entry : Entries) 1361 Entry.finalize(*Asm, List, BT, TheCU); 1362 } 1363 1364 // For each InlinedEntity collected from DBG_LABEL instructions, convert to 1365 // DWARF-related DbgLabel. 1366 for (const auto &I : DbgLabels) { 1367 InlinedEntity IL = I.first; 1368 const MachineInstr *MI = I.second; 1369 if (MI == nullptr) 1370 continue; 1371 1372 LexicalScope *Scope = nullptr; 1373 const DILabel *Label = cast<DILabel>(IL.first); 1374 // Get inlined DILocation if it is inlined label. 1375 if (const DILocation *IA = IL.second) 1376 Scope = LScopes.findInlinedScope(Label->getScope(), IA); 1377 else 1378 Scope = LScopes.findLexicalScope(Label->getScope()); 1379 // If label scope is not found then skip this label. 1380 if (!Scope) 1381 continue; 1382 1383 Processed.insert(IL); 1384 /// At this point, the temporary label is created. 1385 /// Save the temporary label to DbgLabel entity to get the 1386 /// actually address when generating Dwarf DIE. 1387 MCSymbol *Sym = getLabelBeforeInsn(MI); 1388 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym); 1389 } 1390 1391 // Collect info for variables/labels that were optimized out. 1392 for (const DINode *DN : SP->getRetainedNodes()) { 1393 if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 1394 continue; 1395 LexicalScope *Scope = nullptr; 1396 if (auto *DV = dyn_cast<DILocalVariable>(DN)) { 1397 Scope = LScopes.findLexicalScope(DV->getScope()); 1398 } else if (auto *DL = dyn_cast<DILabel>(DN)) { 1399 Scope = LScopes.findLexicalScope(DL->getScope()); 1400 } 1401 1402 if (Scope) 1403 createConcreteEntity(TheCU, *Scope, DN, nullptr); 1404 } 1405 } 1406 1407 // Process beginning of an instruction. 1408 void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1409 DebugHandlerBase::beginInstruction(MI); 1410 assert(CurMI); 1411 1412 const auto *SP = MI->getMF()->getFunction().getSubprogram(); 1413 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1414 return; 1415 1416 // Check if source location changes, but ignore DBG_VALUE and CFI locations. 1417 // If the instruction is part of the function frame setup code, do not emit 1418 // any line record, as there is no correspondence with any user code. 1419 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup)) 1420 return; 1421 const DebugLoc &DL = MI->getDebugLoc(); 1422 // When we emit a line-0 record, we don't update PrevInstLoc; so look at 1423 // the last line number actually emitted, to see if it was line 0. 1424 unsigned LastAsmLine = 1425 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine(); 1426 1427 // Request a label after the call in order to emit AT_return_pc information 1428 // in call site entries. TODO: Add support for targets with delay slots. 1429 if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot()) 1430 requestLabelAfterInsn(MI); 1431 1432 if (DL == PrevInstLoc) { 1433 // If we have an ongoing unspecified location, nothing to do here. 1434 if (!DL) 1435 return; 1436 // We have an explicit location, same as the previous location. 1437 // But we might be coming back to it after a line 0 record. 1438 if (LastAsmLine == 0 && DL.getLine() != 0) { 1439 // Reinstate the source location but not marked as a statement. 1440 const MDNode *Scope = DL.getScope(); 1441 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0); 1442 } 1443 return; 1444 } 1445 1446 if (!DL) { 1447 // We have an unspecified location, which might want to be line 0. 1448 // If we have already emitted a line-0 record, don't repeat it. 1449 if (LastAsmLine == 0) 1450 return; 1451 // If user said Don't Do That, don't do that. 1452 if (UnknownLocations == Disable) 1453 return; 1454 // See if we have a reason to emit a line-0 record now. 1455 // Reasons to emit a line-0 record include: 1456 // - User asked for it (UnknownLocations). 1457 // - Instruction has a label, so it's referenced from somewhere else, 1458 // possibly debug information; we want it to have a source location. 1459 // - Instruction is at the top of a block; we don't want to inherit the 1460 // location from the physically previous (maybe unrelated) block. 1461 if (UnknownLocations == Enable || PrevLabel || 1462 (PrevInstBB && PrevInstBB != MI->getParent())) { 1463 // Preserve the file and column numbers, if we can, to save space in 1464 // the encoded line table. 1465 // Do not update PrevInstLoc, it remembers the last non-0 line. 1466 const MDNode *Scope = nullptr; 1467 unsigned Column = 0; 1468 if (PrevInstLoc) { 1469 Scope = PrevInstLoc.getScope(); 1470 Column = PrevInstLoc.getCol(); 1471 } 1472 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0); 1473 } 1474 return; 1475 } 1476 1477 // We have an explicit location, different from the previous location. 1478 // Don't repeat a line-0 record, but otherwise emit the new location. 1479 // (The new location might be an explicit line 0, which we do emit.) 1480 if (DL.getLine() == 0 && LastAsmLine == 0) 1481 return; 1482 unsigned Flags = 0; 1483 if (DL == PrologEndLoc) { 1484 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT; 1485 PrologEndLoc = DebugLoc(); 1486 } 1487 // If the line changed, we call that a new statement; unless we went to 1488 // line 0 and came back, in which case it is not a new statement. 1489 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine; 1490 if (DL.getLine() && DL.getLine() != OldLine) 1491 Flags |= DWARF2_FLAG_IS_STMT; 1492 1493 const MDNode *Scope = DL.getScope(); 1494 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1495 1496 // If we're not at line 0, remember this location. 1497 if (DL.getLine()) 1498 PrevInstLoc = DL; 1499 } 1500 1501 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) { 1502 // First known non-DBG_VALUE and non-frame setup location marks 1503 // the beginning of the function body. 1504 for (const auto &MBB : *MF) 1505 for (const auto &MI : MBB) 1506 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) && 1507 MI.getDebugLoc()) 1508 return MI.getDebugLoc(); 1509 return DebugLoc(); 1510 } 1511 1512 /// Register a source line with debug info. Returns the unique label that was 1513 /// emitted and which provides correspondence to the source line list. 1514 static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col, 1515 const MDNode *S, unsigned Flags, unsigned CUID, 1516 uint16_t DwarfVersion, 1517 ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) { 1518 StringRef Fn; 1519 unsigned FileNo = 1; 1520 unsigned Discriminator = 0; 1521 if (auto *Scope = cast_or_null<DIScope>(S)) { 1522 Fn = Scope->getFilename(); 1523 if (Line != 0 && DwarfVersion >= 4) 1524 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope)) 1525 Discriminator = LBF->getDiscriminator(); 1526 1527 FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID]) 1528 .getOrCreateSourceID(Scope->getFile()); 1529 } 1530 Asm.OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0, 1531 Discriminator, Fn); 1532 } 1533 1534 DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF, 1535 unsigned CUID) { 1536 // Get beginning of function. 1537 if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) { 1538 // Ensure the compile unit is created if the function is called before 1539 // beginFunction(). 1540 (void)getOrCreateDwarfCompileUnit( 1541 MF.getFunction().getSubprogram()->getUnit()); 1542 // We'd like to list the prologue as "not statements" but GDB behaves 1543 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 1544 const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram(); 1545 ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT, 1546 CUID, getDwarfVersion(), getUnits()); 1547 return PrologEndLoc; 1548 } 1549 return DebugLoc(); 1550 } 1551 1552 // Gather pre-function debug information. Assumes being called immediately 1553 // after the function entry point has been emitted. 1554 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) { 1555 CurFn = MF; 1556 1557 auto *SP = MF->getFunction().getSubprogram(); 1558 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode()); 1559 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1560 return; 1561 1562 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 1563 1564 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 1565 // belongs to so that we add to the correct per-cu line table in the 1566 // non-asm case. 1567 if (Asm->OutStreamer->hasRawTextSupport()) 1568 // Use a single line table if we are generating assembly. 1569 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1570 else 1571 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID()); 1572 1573 // Record beginning of function. 1574 PrologEndLoc = emitInitialLocDirective( 1575 *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID()); 1576 } 1577 1578 void DwarfDebug::skippedNonDebugFunction() { 1579 // If we don't have a subprogram for this function then there will be a hole 1580 // in the range information. Keep note of this by setting the previously used 1581 // section to nullptr. 1582 PrevCU = nullptr; 1583 CurFn = nullptr; 1584 } 1585 1586 // Gather and emit post-function debug information. 1587 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) { 1588 const DISubprogram *SP = MF->getFunction().getSubprogram(); 1589 1590 assert(CurFn == MF && 1591 "endFunction should be called with the same function as beginFunction"); 1592 1593 // Set DwarfDwarfCompileUnitID in MCContext to default value. 1594 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1595 1596 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1597 assert(!FnScope || SP == FnScope->getScopeNode()); 1598 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit()); 1599 if (TheCU.getCUNode()->isDebugDirectivesOnly()) { 1600 PrevLabel = nullptr; 1601 CurFn = nullptr; 1602 return; 1603 } 1604 1605 DenseSet<InlinedEntity> Processed; 1606 collectEntityInfo(TheCU, SP, Processed); 1607 1608 // Add the range of this function to the list of ranges for the CU. 1609 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd())); 1610 1611 // Under -gmlt, skip building the subprogram if there are no inlined 1612 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram 1613 // is still needed as we need its source location. 1614 if (!TheCU.getCUNode()->getDebugInfoForProfiling() && 1615 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly && 1616 LScopes.getAbstractScopesList().empty() && !IsDarwin) { 1617 assert(InfoHolder.getScopeVariables().empty()); 1618 PrevLabel = nullptr; 1619 CurFn = nullptr; 1620 return; 1621 } 1622 1623 #ifndef NDEBUG 1624 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size(); 1625 #endif 1626 // Construct abstract scopes. 1627 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) { 1628 auto *SP = cast<DISubprogram>(AScope->getScopeNode()); 1629 for (const DINode *DN : SP->getRetainedNodes()) { 1630 if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 1631 continue; 1632 1633 const MDNode *Scope = nullptr; 1634 if (auto *DV = dyn_cast<DILocalVariable>(DN)) 1635 Scope = DV->getScope(); 1636 else if (auto *DL = dyn_cast<DILabel>(DN)) 1637 Scope = DL->getScope(); 1638 else 1639 llvm_unreachable("Unexpected DI type!"); 1640 1641 // Collect info for variables/labels that were optimized out. 1642 ensureAbstractEntityIsCreated(TheCU, DN, Scope); 1643 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes 1644 && "ensureAbstractEntityIsCreated inserted abstract scopes"); 1645 } 1646 constructAbstractSubprogramScopeDIE(TheCU, AScope); 1647 } 1648 1649 ProcessedSPNodes.insert(SP); 1650 DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope); 1651 if (auto *SkelCU = TheCU.getSkeleton()) 1652 if (!LScopes.getAbstractScopesList().empty() && 1653 TheCU.getCUNode()->getSplitDebugInlining()) 1654 SkelCU->constructSubprogramScopeDIE(SP, FnScope); 1655 1656 // Construct call site entries. 1657 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF); 1658 1659 // Clear debug info 1660 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the 1661 // DbgVariables except those that are also in AbstractVariables (since they 1662 // can be used cross-function) 1663 InfoHolder.getScopeVariables().clear(); 1664 InfoHolder.getScopeLabels().clear(); 1665 PrevLabel = nullptr; 1666 CurFn = nullptr; 1667 } 1668 1669 // Register a source line with debug info. Returns the unique label that was 1670 // emitted and which provides correspondence to the source line list. 1671 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1672 unsigned Flags) { 1673 ::recordSourceLine(*Asm, Line, Col, S, Flags, 1674 Asm->OutStreamer->getContext().getDwarfCompileUnitID(), 1675 getDwarfVersion(), getUnits()); 1676 } 1677 1678 //===----------------------------------------------------------------------===// 1679 // Emit Methods 1680 //===----------------------------------------------------------------------===// 1681 1682 // Emit the debug info section. 1683 void DwarfDebug::emitDebugInfo() { 1684 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1685 Holder.emitUnits(/* UseOffsets */ false); 1686 } 1687 1688 // Emit the abbreviation section. 1689 void DwarfDebug::emitAbbreviations() { 1690 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1691 1692 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection()); 1693 } 1694 1695 void DwarfDebug::emitStringOffsetsTableHeader() { 1696 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1697 Holder.getStringPool().emitStringOffsetsTableHeader( 1698 *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(), 1699 Holder.getStringOffsetsStartSym()); 1700 } 1701 1702 template <typename AccelTableT> 1703 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section, 1704 StringRef TableName) { 1705 Asm->OutStreamer->SwitchSection(Section); 1706 1707 // Emit the full data. 1708 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol()); 1709 } 1710 1711 void DwarfDebug::emitAccelDebugNames() { 1712 // Don't emit anything if we have no compilation units to index. 1713 if (getUnits().empty()) 1714 return; 1715 1716 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits()); 1717 } 1718 1719 // Emit visible names into a hashed accelerator table section. 1720 void DwarfDebug::emitAccelNames() { 1721 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(), 1722 "Names"); 1723 } 1724 1725 // Emit objective C classes and categories into a hashed accelerator table 1726 // section. 1727 void DwarfDebug::emitAccelObjC() { 1728 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(), 1729 "ObjC"); 1730 } 1731 1732 // Emit namespace dies into a hashed accelerator table. 1733 void DwarfDebug::emitAccelNamespaces() { 1734 emitAccel(AccelNamespace, 1735 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(), 1736 "namespac"); 1737 } 1738 1739 // Emit type dies into a hashed accelerator table. 1740 void DwarfDebug::emitAccelTypes() { 1741 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(), 1742 "types"); 1743 } 1744 1745 // Public name handling. 1746 // The format for the various pubnames: 1747 // 1748 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU 1749 // for the DIE that is named. 1750 // 1751 // gnu pubnames - offset/index value/name tuples where the offset is the offset 1752 // into the CU and the index value is computed according to the type of value 1753 // for the DIE that is named. 1754 // 1755 // For type units the offset is the offset of the skeleton DIE. For split dwarf 1756 // it's the offset within the debug_info/debug_types dwo section, however, the 1757 // reference in the pubname header doesn't change. 1758 1759 /// computeIndexValue - Compute the gdb index value for the DIE and CU. 1760 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, 1761 const DIE *Die) { 1762 // Entities that ended up only in a Type Unit reference the CU instead (since 1763 // the pub entry has offsets within the CU there's no real offset that can be 1764 // provided anyway). As it happens all such entities (namespaces and types, 1765 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out 1766 // not to be true it would be necessary to persist this information from the 1767 // point at which the entry is added to the index data structure - since by 1768 // the time the index is built from that, the original type/namespace DIE in a 1769 // type unit has already been destroyed so it can't be queried for properties 1770 // like tag, etc. 1771 if (Die->getTag() == dwarf::DW_TAG_compile_unit) 1772 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, 1773 dwarf::GIEL_EXTERNAL); 1774 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC; 1775 1776 // We could have a specification DIE that has our most of our knowledge, 1777 // look for that now. 1778 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) { 1779 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry(); 1780 if (SpecDIE.findAttribute(dwarf::DW_AT_external)) 1781 Linkage = dwarf::GIEL_EXTERNAL; 1782 } else if (Die->findAttribute(dwarf::DW_AT_external)) 1783 Linkage = dwarf::GIEL_EXTERNAL; 1784 1785 switch (Die->getTag()) { 1786 case dwarf::DW_TAG_class_type: 1787 case dwarf::DW_TAG_structure_type: 1788 case dwarf::DW_TAG_union_type: 1789 case dwarf::DW_TAG_enumeration_type: 1790 return dwarf::PubIndexEntryDescriptor( 1791 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus 1792 ? dwarf::GIEL_STATIC 1793 : dwarf::GIEL_EXTERNAL); 1794 case dwarf::DW_TAG_typedef: 1795 case dwarf::DW_TAG_base_type: 1796 case dwarf::DW_TAG_subrange_type: 1797 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC); 1798 case dwarf::DW_TAG_namespace: 1799 return dwarf::GIEK_TYPE; 1800 case dwarf::DW_TAG_subprogram: 1801 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage); 1802 case dwarf::DW_TAG_variable: 1803 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage); 1804 case dwarf::DW_TAG_enumerator: 1805 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, 1806 dwarf::GIEL_STATIC); 1807 default: 1808 return dwarf::GIEK_NONE; 1809 } 1810 } 1811 1812 /// emitDebugPubSections - Emit visible names and types into debug pubnames and 1813 /// pubtypes sections. 1814 void DwarfDebug::emitDebugPubSections() { 1815 for (const auto &NU : CUMap) { 1816 DwarfCompileUnit *TheU = NU.second; 1817 if (!TheU->hasDwarfPubSections()) 1818 continue; 1819 1820 bool GnuStyle = TheU->getCUNode()->getNameTableKind() == 1821 DICompileUnit::DebugNameTableKind::GNU; 1822 1823 Asm->OutStreamer->SwitchSection( 1824 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection() 1825 : Asm->getObjFileLowering().getDwarfPubNamesSection()); 1826 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames()); 1827 1828 Asm->OutStreamer->SwitchSection( 1829 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection() 1830 : Asm->getObjFileLowering().getDwarfPubTypesSection()); 1831 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes()); 1832 } 1833 } 1834 1835 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) { 1836 if (useSectionsAsReferences()) 1837 Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(), 1838 CU.getDebugSectionOffset()); 1839 else 1840 Asm->emitDwarfSymbolReference(CU.getLabelBegin()); 1841 } 1842 1843 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name, 1844 DwarfCompileUnit *TheU, 1845 const StringMap<const DIE *> &Globals) { 1846 if (auto *Skeleton = TheU->getSkeleton()) 1847 TheU = Skeleton; 1848 1849 // Emit the header. 1850 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info"); 1851 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin"); 1852 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end"); 1853 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); 1854 1855 Asm->OutStreamer->EmitLabel(BeginLabel); 1856 1857 Asm->OutStreamer->AddComment("DWARF Version"); 1858 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); 1859 1860 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info"); 1861 emitSectionReference(*TheU); 1862 1863 Asm->OutStreamer->AddComment("Compilation Unit Length"); 1864 Asm->emitInt32(TheU->getLength()); 1865 1866 // Emit the pubnames for this compilation unit. 1867 for (const auto &GI : Globals) { 1868 const char *Name = GI.getKeyData(); 1869 const DIE *Entity = GI.second; 1870 1871 Asm->OutStreamer->AddComment("DIE offset"); 1872 Asm->emitInt32(Entity->getOffset()); 1873 1874 if (GnuStyle) { 1875 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity); 1876 Asm->OutStreamer->AddComment( 1877 Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + 1878 ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage)); 1879 Asm->emitInt8(Desc.toBits()); 1880 } 1881 1882 Asm->OutStreamer->AddComment("External Name"); 1883 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1)); 1884 } 1885 1886 Asm->OutStreamer->AddComment("End Mark"); 1887 Asm->emitInt32(0); 1888 Asm->OutStreamer->EmitLabel(EndLabel); 1889 } 1890 1891 /// Emit null-terminated strings into a debug str section. 1892 void DwarfDebug::emitDebugStr() { 1893 MCSection *StringOffsetsSection = nullptr; 1894 if (useSegmentedStringOffsetsTable()) { 1895 emitStringOffsetsTableHeader(); 1896 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection(); 1897 } 1898 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1899 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(), 1900 StringOffsetsSection, /* UseRelativeOffsets = */ true); 1901 } 1902 1903 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer, const 1904 DebugLocStream::Entry &Entry, 1905 const DwarfCompileUnit *CU) { 1906 auto &&Comments = DebugLocs.getComments(Entry); 1907 auto Comment = Comments.begin(); 1908 auto End = Comments.end(); 1909 1910 // The expressions are inserted into a byte stream rather early (see 1911 // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that 1912 // need to reference a base_type DIE the offset of that DIE is not yet known. 1913 // To deal with this we instead insert a placeholder early and then extract 1914 // it here and replace it with the real reference. 1915 unsigned PtrSize = Asm->MAI->getCodePointerSize(); 1916 DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(), 1917 DebugLocs.getBytes(Entry).size()), 1918 Asm->getDataLayout().isLittleEndian(), PtrSize); 1919 DWARFExpression Expr(Data, getDwarfVersion(), PtrSize); 1920 1921 using Encoding = DWARFExpression::Operation::Encoding; 1922 uint32_t Offset = 0; 1923 for (auto &Op : Expr) { 1924 assert(Op.getCode() != dwarf::DW_OP_const_type && 1925 "3 operand ops not yet supported"); 1926 Streamer.EmitInt8(Op.getCode(), Comment != End ? *(Comment++) : ""); 1927 Offset++; 1928 for (unsigned I = 0; I < 2; ++I) { 1929 if (Op.getDescription().Op[I] == Encoding::SizeNA) 1930 continue; 1931 if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) { 1932 if (CU) { 1933 uint64_t Offset = CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset(); 1934 assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit"); 1935 Asm->EmitULEB128(Offset, nullptr, ULEB128PadSize); 1936 } else { 1937 // Emit a reference to the 'generic type'. 1938 Asm->EmitULEB128(0, nullptr, ULEB128PadSize); 1939 } 1940 // Make sure comments stay aligned. 1941 for (unsigned J = 0; J < ULEB128PadSize; ++J) 1942 if (Comment != End) 1943 Comment++; 1944 } else { 1945 for (uint32_t J = Offset; J < Op.getOperandEndOffset(I); ++J) 1946 Streamer.EmitInt8(Data.getData()[J], Comment != End ? *(Comment++) : ""); 1947 } 1948 Offset = Op.getOperandEndOffset(I); 1949 } 1950 assert(Offset == Op.getEndOffset()); 1951 } 1952 } 1953 1954 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, 1955 const DebugLocEntry::Value &Value, 1956 DwarfExpression &DwarfExpr) { 1957 auto *DIExpr = Value.getExpression(); 1958 DIExpressionCursor ExprCursor(DIExpr); 1959 DwarfExpr.addFragmentOffset(DIExpr); 1960 // Regular entry. 1961 if (Value.isInt()) { 1962 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed || 1963 BT->getEncoding() == dwarf::DW_ATE_signed_char)) 1964 DwarfExpr.addSignedConstant(Value.getInt()); 1965 else 1966 DwarfExpr.addUnsignedConstant(Value.getInt()); 1967 } else if (Value.isLocation()) { 1968 MachineLocation Location = Value.getLoc(); 1969 if (Location.isIndirect()) 1970 DwarfExpr.setMemoryLocationKind(); 1971 DIExpressionCursor Cursor(DIExpr); 1972 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo(); 1973 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 1974 return; 1975 return DwarfExpr.addExpression(std::move(Cursor)); 1976 } else if (Value.isConstantFP()) { 1977 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt(); 1978 DwarfExpr.addUnsignedConstant(RawBytes); 1979 } 1980 DwarfExpr.addExpression(std::move(ExprCursor)); 1981 } 1982 1983 void DebugLocEntry::finalize(const AsmPrinter &AP, 1984 DebugLocStream::ListBuilder &List, 1985 const DIBasicType *BT, 1986 DwarfCompileUnit &TheCU) { 1987 assert(!Values.empty() && 1988 "location list entries without values are redundant"); 1989 assert(Begin != End && "unexpected location list entry with empty range"); 1990 DebugLocStream::EntryBuilder Entry(List, Begin, End); 1991 BufferByteStreamer Streamer = Entry.getStreamer(); 1992 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU); 1993 const DebugLocEntry::Value &Value = Values[0]; 1994 if (Value.isFragment()) { 1995 // Emit all fragments that belong to the same variable and range. 1996 assert(llvm::all_of(Values, [](DebugLocEntry::Value P) { 1997 return P.isFragment(); 1998 }) && "all values are expected to be fragments"); 1999 assert(std::is_sorted(Values.begin(), Values.end()) && 2000 "fragments are expected to be sorted"); 2001 2002 for (auto Fragment : Values) 2003 emitDebugLocValue(AP, BT, Fragment, DwarfExpr); 2004 2005 } else { 2006 assert(Values.size() == 1 && "only fragments may have >1 value"); 2007 emitDebugLocValue(AP, BT, Value, DwarfExpr); 2008 } 2009 DwarfExpr.finalize(); 2010 } 2011 2012 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry, 2013 const DwarfCompileUnit *CU) { 2014 // Emit the size. 2015 Asm->OutStreamer->AddComment("Loc expr size"); 2016 if (getDwarfVersion() >= 5) 2017 Asm->EmitULEB128(DebugLocs.getBytes(Entry).size()); 2018 else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max()) 2019 Asm->emitInt16(DebugLocs.getBytes(Entry).size()); 2020 else { 2021 // The entry is too big to fit into 16 bit, drop it as there is nothing we 2022 // can do. 2023 Asm->emitInt16(0); 2024 return; 2025 } 2026 // Emit the entry. 2027 APByteStreamer Streamer(*Asm); 2028 emitDebugLocEntry(Streamer, Entry, CU); 2029 } 2030 2031 // Emit the common part of the DWARF 5 range/locations list tables header. 2032 static void emitListsTableHeaderStart(AsmPrinter *Asm, const DwarfFile &Holder, 2033 MCSymbol *TableStart, 2034 MCSymbol *TableEnd) { 2035 // Build the table header, which starts with the length field. 2036 Asm->OutStreamer->AddComment("Length"); 2037 Asm->EmitLabelDifference(TableEnd, TableStart, 4); 2038 Asm->OutStreamer->EmitLabel(TableStart); 2039 // Version number (DWARF v5 and later). 2040 Asm->OutStreamer->AddComment("Version"); 2041 Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion()); 2042 // Address size. 2043 Asm->OutStreamer->AddComment("Address size"); 2044 Asm->emitInt8(Asm->MAI->getCodePointerSize()); 2045 // Segment selector size. 2046 Asm->OutStreamer->AddComment("Segment selector size"); 2047 Asm->emitInt8(0); 2048 } 2049 2050 // Emit the header of a DWARF 5 range list table list table. Returns the symbol 2051 // that designates the end of the table for the caller to emit when the table is 2052 // complete. 2053 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm, 2054 const DwarfFile &Holder) { 2055 MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start"); 2056 MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end"); 2057 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd); 2058 2059 Asm->OutStreamer->AddComment("Offset entry count"); 2060 Asm->emitInt32(Holder.getRangeLists().size()); 2061 Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym()); 2062 2063 for (const RangeSpanList &List : Holder.getRangeLists()) 2064 Asm->EmitLabelDifference(List.getSym(), Holder.getRnglistsTableBaseSym(), 2065 4); 2066 2067 return TableEnd; 2068 } 2069 2070 // Emit the header of a DWARF 5 locations list table. Returns the symbol that 2071 // designates the end of the table for the caller to emit when the table is 2072 // complete. 2073 static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm, 2074 const DwarfFile &Holder) { 2075 MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start"); 2076 MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end"); 2077 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd); 2078 2079 // FIXME: Generate the offsets table and use DW_FORM_loclistx with the 2080 // DW_AT_loclists_base attribute. Until then set the number of offsets to 0. 2081 Asm->OutStreamer->AddComment("Offset entry count"); 2082 Asm->emitInt32(0); 2083 Asm->OutStreamer->EmitLabel(Holder.getLoclistsTableBaseSym()); 2084 2085 return TableEnd; 2086 } 2087 2088 // Emit locations into the .debug_loc/.debug_rnglists section. 2089 void DwarfDebug::emitDebugLoc() { 2090 if (DebugLocs.getLists().empty()) 2091 return; 2092 2093 bool IsLocLists = getDwarfVersion() >= 5; 2094 MCSymbol *TableEnd = nullptr; 2095 if (IsLocLists) { 2096 Asm->OutStreamer->SwitchSection( 2097 Asm->getObjFileLowering().getDwarfLoclistsSection()); 2098 TableEnd = emitLoclistsTableHeader(Asm, useSplitDwarf() ? SkeletonHolder 2099 : InfoHolder); 2100 } else { 2101 Asm->OutStreamer->SwitchSection( 2102 Asm->getObjFileLowering().getDwarfLocSection()); 2103 } 2104 2105 unsigned char Size = Asm->MAI->getCodePointerSize(); 2106 for (const auto &List : DebugLocs.getLists()) { 2107 Asm->OutStreamer->EmitLabel(List.Label); 2108 2109 const DwarfCompileUnit *CU = List.CU; 2110 const MCSymbol *Base = CU->getBaseAddress(); 2111 for (const auto &Entry : DebugLocs.getEntries(List)) { 2112 if (Base) { 2113 // Set up the range. This range is relative to the entry point of the 2114 // compile unit. This is a hard coded 0 for low_pc when we're emitting 2115 // ranges, or the DW_AT_low_pc on the compile unit otherwise. 2116 if (IsLocLists) { 2117 Asm->OutStreamer->AddComment("DW_LLE_offset_pair"); 2118 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_offset_pair, 1); 2119 Asm->OutStreamer->AddComment(" starting offset"); 2120 Asm->EmitLabelDifferenceAsULEB128(Entry.BeginSym, Base); 2121 Asm->OutStreamer->AddComment(" ending offset"); 2122 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Base); 2123 } else { 2124 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size); 2125 Asm->EmitLabelDifference(Entry.EndSym, Base, Size); 2126 } 2127 2128 emitDebugLocEntryLocation(Entry, CU); 2129 continue; 2130 } 2131 2132 // We have no base address. 2133 if (IsLocLists) { 2134 // TODO: Use DW_LLE_base_addressx + DW_LLE_offset_pair, or 2135 // DW_LLE_startx_length in case if there is only a single range. 2136 // That should reduce the size of the debug data emited. 2137 // For now just use the DW_LLE_startx_length for all cases. 2138 Asm->OutStreamer->AddComment("DW_LLE_startx_length"); 2139 Asm->emitInt8(dwarf::DW_LLE_startx_length); 2140 Asm->OutStreamer->AddComment(" start idx"); 2141 Asm->EmitULEB128(AddrPool.getIndex(Entry.BeginSym)); 2142 Asm->OutStreamer->AddComment(" length"); 2143 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Entry.BeginSym); 2144 } else { 2145 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size); 2146 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size); 2147 } 2148 2149 emitDebugLocEntryLocation(Entry, CU); 2150 } 2151 2152 if (IsLocLists) { 2153 // .debug_loclists section ends with DW_LLE_end_of_list. 2154 Asm->OutStreamer->AddComment("DW_LLE_end_of_list"); 2155 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_end_of_list, 1); 2156 } else { 2157 // Terminate the .debug_loc list with two 0 values. 2158 Asm->OutStreamer->EmitIntValue(0, Size); 2159 Asm->OutStreamer->EmitIntValue(0, Size); 2160 } 2161 } 2162 2163 if (TableEnd) 2164 Asm->OutStreamer->EmitLabel(TableEnd); 2165 } 2166 2167 void DwarfDebug::emitDebugLocDWO() { 2168 for (const auto &List : DebugLocs.getLists()) { 2169 Asm->OutStreamer->SwitchSection( 2170 Asm->getObjFileLowering().getDwarfLocDWOSection()); 2171 Asm->OutStreamer->EmitLabel(List.Label); 2172 for (const auto &Entry : DebugLocs.getEntries(List)) { 2173 // GDB only supports startx_length in pre-standard split-DWARF. 2174 // (in v5 standard loclists, it currently* /only/ supports base_address + 2175 // offset_pair, so the implementations can't really share much since they 2176 // need to use different representations) 2177 // * as of October 2018, at least 2178 // Ideally/in v5, this could use SectionLabels to reuse existing addresses 2179 // in the address pool to minimize object size/relocations. 2180 Asm->emitInt8(dwarf::DW_LLE_startx_length); 2181 unsigned idx = AddrPool.getIndex(Entry.BeginSym); 2182 Asm->EmitULEB128(idx); 2183 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4); 2184 2185 emitDebugLocEntryLocation(Entry, List.CU); 2186 } 2187 Asm->emitInt8(dwarf::DW_LLE_end_of_list); 2188 } 2189 } 2190 2191 struct ArangeSpan { 2192 const MCSymbol *Start, *End; 2193 }; 2194 2195 // Emit a debug aranges section, containing a CU lookup for any 2196 // address we can tie back to a CU. 2197 void DwarfDebug::emitDebugARanges() { 2198 // Provides a unique id per text section. 2199 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap; 2200 2201 // Filter labels by section. 2202 for (const SymbolCU &SCU : ArangeLabels) { 2203 if (SCU.Sym->isInSection()) { 2204 // Make a note of this symbol and it's section. 2205 MCSection *Section = &SCU.Sym->getSection(); 2206 if (!Section->getKind().isMetadata()) 2207 SectionMap[Section].push_back(SCU); 2208 } else { 2209 // Some symbols (e.g. common/bss on mach-o) can have no section but still 2210 // appear in the output. This sucks as we rely on sections to build 2211 // arange spans. We can do it without, but it's icky. 2212 SectionMap[nullptr].push_back(SCU); 2213 } 2214 } 2215 2216 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans; 2217 2218 for (auto &I : SectionMap) { 2219 MCSection *Section = I.first; 2220 SmallVector<SymbolCU, 8> &List = I.second; 2221 if (List.size() < 1) 2222 continue; 2223 2224 // If we have no section (e.g. common), just write out 2225 // individual spans for each symbol. 2226 if (!Section) { 2227 for (const SymbolCU &Cur : List) { 2228 ArangeSpan Span; 2229 Span.Start = Cur.Sym; 2230 Span.End = nullptr; 2231 assert(Cur.CU); 2232 Spans[Cur.CU].push_back(Span); 2233 } 2234 continue; 2235 } 2236 2237 // Sort the symbols by offset within the section. 2238 llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) { 2239 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0; 2240 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0; 2241 2242 // Symbols with no order assigned should be placed at the end. 2243 // (e.g. section end labels) 2244 if (IA == 0) 2245 return false; 2246 if (IB == 0) 2247 return true; 2248 return IA < IB; 2249 }); 2250 2251 // Insert a final terminator. 2252 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section))); 2253 2254 // Build spans between each label. 2255 const MCSymbol *StartSym = List[0].Sym; 2256 for (size_t n = 1, e = List.size(); n < e; n++) { 2257 const SymbolCU &Prev = List[n - 1]; 2258 const SymbolCU &Cur = List[n]; 2259 2260 // Try and build the longest span we can within the same CU. 2261 if (Cur.CU != Prev.CU) { 2262 ArangeSpan Span; 2263 Span.Start = StartSym; 2264 Span.End = Cur.Sym; 2265 assert(Prev.CU); 2266 Spans[Prev.CU].push_back(Span); 2267 StartSym = Cur.Sym; 2268 } 2269 } 2270 } 2271 2272 // Start the dwarf aranges section. 2273 Asm->OutStreamer->SwitchSection( 2274 Asm->getObjFileLowering().getDwarfARangesSection()); 2275 2276 unsigned PtrSize = Asm->MAI->getCodePointerSize(); 2277 2278 // Build a list of CUs used. 2279 std::vector<DwarfCompileUnit *> CUs; 2280 for (const auto &it : Spans) { 2281 DwarfCompileUnit *CU = it.first; 2282 CUs.push_back(CU); 2283 } 2284 2285 // Sort the CU list (again, to ensure consistent output order). 2286 llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) { 2287 return A->getUniqueID() < B->getUniqueID(); 2288 }); 2289 2290 // Emit an arange table for each CU we used. 2291 for (DwarfCompileUnit *CU : CUs) { 2292 std::vector<ArangeSpan> &List = Spans[CU]; 2293 2294 // Describe the skeleton CU's offset and length, not the dwo file's. 2295 if (auto *Skel = CU->getSkeleton()) 2296 CU = Skel; 2297 2298 // Emit size of content not including length itself. 2299 unsigned ContentSize = 2300 sizeof(int16_t) + // DWARF ARange version number 2301 sizeof(int32_t) + // Offset of CU in the .debug_info section 2302 sizeof(int8_t) + // Pointer Size (in bytes) 2303 sizeof(int8_t); // Segment Size (in bytes) 2304 2305 unsigned TupleSize = PtrSize * 2; 2306 2307 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 2308 unsigned Padding = 2309 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize); 2310 2311 ContentSize += Padding; 2312 ContentSize += (List.size() + 1) * TupleSize; 2313 2314 // For each compile unit, write the list of spans it covers. 2315 Asm->OutStreamer->AddComment("Length of ARange Set"); 2316 Asm->emitInt32(ContentSize); 2317 Asm->OutStreamer->AddComment("DWARF Arange version number"); 2318 Asm->emitInt16(dwarf::DW_ARANGES_VERSION); 2319 Asm->OutStreamer->AddComment("Offset Into Debug Info Section"); 2320 emitSectionReference(*CU); 2321 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 2322 Asm->emitInt8(PtrSize); 2323 Asm->OutStreamer->AddComment("Segment Size (in bytes)"); 2324 Asm->emitInt8(0); 2325 2326 Asm->OutStreamer->emitFill(Padding, 0xff); 2327 2328 for (const ArangeSpan &Span : List) { 2329 Asm->EmitLabelReference(Span.Start, PtrSize); 2330 2331 // Calculate the size as being from the span start to it's end. 2332 if (Span.End) { 2333 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize); 2334 } else { 2335 // For symbols without an end marker (e.g. common), we 2336 // write a single arange entry containing just that one symbol. 2337 uint64_t Size = SymSize[Span.Start]; 2338 if (Size == 0) 2339 Size = 1; 2340 2341 Asm->OutStreamer->EmitIntValue(Size, PtrSize); 2342 } 2343 } 2344 2345 Asm->OutStreamer->AddComment("ARange terminator"); 2346 Asm->OutStreamer->EmitIntValue(0, PtrSize); 2347 Asm->OutStreamer->EmitIntValue(0, PtrSize); 2348 } 2349 } 2350 2351 /// Emit a single range list. We handle both DWARF v5 and earlier. 2352 static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, 2353 const RangeSpanList &List) { 2354 2355 auto DwarfVersion = DD.getDwarfVersion(); 2356 // Emit our symbol so we can find the beginning of the range. 2357 Asm->OutStreamer->EmitLabel(List.getSym()); 2358 // Gather all the ranges that apply to the same section so they can share 2359 // a base address entry. 2360 MapVector<const MCSection *, std::vector<const RangeSpan *>> SectionRanges; 2361 // Size for our labels. 2362 auto Size = Asm->MAI->getCodePointerSize(); 2363 2364 for (const RangeSpan &Range : List.getRanges()) 2365 SectionRanges[&Range.getStart()->getSection()].push_back(&Range); 2366 2367 const DwarfCompileUnit &CU = List.getCU(); 2368 const MCSymbol *CUBase = CU.getBaseAddress(); 2369 bool BaseIsSet = false; 2370 for (const auto &P : SectionRanges) { 2371 // Don't bother with a base address entry if there's only one range in 2372 // this section in this range list - for example ranges for a CU will 2373 // usually consist of single regions from each of many sections 2374 // (-ffunction-sections, or just C++ inline functions) except under LTO 2375 // or optnone where there may be holes in a single CU's section 2376 // contributions. 2377 auto *Base = CUBase; 2378 if (!Base && (P.second.size() > 1 || DwarfVersion < 5) && 2379 (CU.getCUNode()->getRangesBaseAddress() || DwarfVersion >= 5)) { 2380 BaseIsSet = true; 2381 // FIXME/use care: This may not be a useful base address if it's not 2382 // the lowest address/range in this object. 2383 Base = P.second.front()->getStart(); 2384 if (DwarfVersion >= 5) { 2385 Base = DD.getSectionLabel(&Base->getSection()); 2386 Asm->OutStreamer->AddComment("DW_RLE_base_addressx"); 2387 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_addressx, 1); 2388 Asm->OutStreamer->AddComment(" base address index"); 2389 Asm->EmitULEB128(DD.getAddressPool().getIndex(Base)); 2390 } else { 2391 Asm->OutStreamer->EmitIntValue(-1, Size); 2392 Asm->OutStreamer->AddComment(" base address"); 2393 Asm->OutStreamer->EmitSymbolValue(Base, Size); 2394 } 2395 } else if (BaseIsSet && DwarfVersion < 5) { 2396 BaseIsSet = false; 2397 assert(!Base); 2398 Asm->OutStreamer->EmitIntValue(-1, Size); 2399 Asm->OutStreamer->EmitIntValue(0, Size); 2400 } 2401 2402 for (const auto *RS : P.second) { 2403 const MCSymbol *Begin = RS->getStart(); 2404 const MCSymbol *End = RS->getEnd(); 2405 assert(Begin && "Range without a begin symbol?"); 2406 assert(End && "Range without an end symbol?"); 2407 if (Base) { 2408 if (DwarfVersion >= 5) { 2409 // Emit DW_RLE_offset_pair when we have a base. 2410 Asm->OutStreamer->AddComment("DW_RLE_offset_pair"); 2411 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1); 2412 Asm->OutStreamer->AddComment(" starting offset"); 2413 Asm->EmitLabelDifferenceAsULEB128(Begin, Base); 2414 Asm->OutStreamer->AddComment(" ending offset"); 2415 Asm->EmitLabelDifferenceAsULEB128(End, Base); 2416 } else { 2417 Asm->EmitLabelDifference(Begin, Base, Size); 2418 Asm->EmitLabelDifference(End, Base, Size); 2419 } 2420 } else if (DwarfVersion >= 5) { 2421 Asm->OutStreamer->AddComment("DW_RLE_startx_length"); 2422 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_startx_length, 1); 2423 Asm->OutStreamer->AddComment(" start index"); 2424 Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin)); 2425 Asm->OutStreamer->AddComment(" length"); 2426 Asm->EmitLabelDifferenceAsULEB128(End, Begin); 2427 } else { 2428 Asm->OutStreamer->EmitSymbolValue(Begin, Size); 2429 Asm->OutStreamer->EmitSymbolValue(End, Size); 2430 } 2431 } 2432 } 2433 if (DwarfVersion >= 5) { 2434 Asm->OutStreamer->AddComment("DW_RLE_end_of_list"); 2435 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1); 2436 } else { 2437 // Terminate the list with two 0 values. 2438 Asm->OutStreamer->EmitIntValue(0, Size); 2439 Asm->OutStreamer->EmitIntValue(0, Size); 2440 } 2441 } 2442 2443 static void emitDebugRangesImpl(DwarfDebug &DD, AsmPrinter *Asm, 2444 const DwarfFile &Holder, MCSymbol *TableEnd) { 2445 for (const RangeSpanList &List : Holder.getRangeLists()) 2446 emitRangeList(DD, Asm, List); 2447 2448 if (TableEnd) 2449 Asm->OutStreamer->EmitLabel(TableEnd); 2450 } 2451 2452 /// Emit address ranges into the .debug_ranges section or into the DWARF v5 2453 /// .debug_rnglists section. 2454 void DwarfDebug::emitDebugRanges() { 2455 if (CUMap.empty()) 2456 return; 2457 2458 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2459 2460 if (Holder.getRangeLists().empty()) 2461 return; 2462 2463 assert(useRangesSection()); 2464 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2465 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2466 })); 2467 2468 // Start the dwarf ranges section. 2469 MCSymbol *TableEnd = nullptr; 2470 if (getDwarfVersion() >= 5) { 2471 Asm->OutStreamer->SwitchSection( 2472 Asm->getObjFileLowering().getDwarfRnglistsSection()); 2473 TableEnd = emitRnglistsTableHeader(Asm, Holder); 2474 } else 2475 Asm->OutStreamer->SwitchSection( 2476 Asm->getObjFileLowering().getDwarfRangesSection()); 2477 2478 emitDebugRangesImpl(*this, Asm, Holder, TableEnd); 2479 } 2480 2481 void DwarfDebug::emitDebugRangesDWO() { 2482 assert(useSplitDwarf()); 2483 2484 if (CUMap.empty()) 2485 return; 2486 2487 const auto &Holder = InfoHolder; 2488 2489 if (Holder.getRangeLists().empty()) 2490 return; 2491 2492 assert(getDwarfVersion() >= 5); 2493 assert(useRangesSection()); 2494 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2495 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2496 })); 2497 2498 // Start the dwarf ranges section. 2499 Asm->OutStreamer->SwitchSection( 2500 Asm->getObjFileLowering().getDwarfRnglistsDWOSection()); 2501 MCSymbol *TableEnd = emitRnglistsTableHeader(Asm, Holder); 2502 2503 emitDebugRangesImpl(*this, Asm, Holder, TableEnd); 2504 } 2505 2506 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) { 2507 for (auto *MN : Nodes) { 2508 if (auto *M = dyn_cast<DIMacro>(MN)) 2509 emitMacro(*M); 2510 else if (auto *F = dyn_cast<DIMacroFile>(MN)) 2511 emitMacroFile(*F, U); 2512 else 2513 llvm_unreachable("Unexpected DI type!"); 2514 } 2515 } 2516 2517 void DwarfDebug::emitMacro(DIMacro &M) { 2518 Asm->EmitULEB128(M.getMacinfoType()); 2519 Asm->EmitULEB128(M.getLine()); 2520 StringRef Name = M.getName(); 2521 StringRef Value = M.getValue(); 2522 Asm->OutStreamer->EmitBytes(Name); 2523 if (!Value.empty()) { 2524 // There should be one space between macro name and macro value. 2525 Asm->emitInt8(' '); 2526 Asm->OutStreamer->EmitBytes(Value); 2527 } 2528 Asm->emitInt8('\0'); 2529 } 2530 2531 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) { 2532 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file); 2533 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file); 2534 Asm->EmitULEB128(F.getLine()); 2535 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile())); 2536 handleMacroNodes(F.getElements(), U); 2537 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file); 2538 } 2539 2540 /// Emit macros into a debug macinfo section. 2541 void DwarfDebug::emitDebugMacinfo() { 2542 if (CUMap.empty()) 2543 return; 2544 2545 if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2546 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2547 })) 2548 return; 2549 2550 // Start the dwarf macinfo section. 2551 Asm->OutStreamer->SwitchSection( 2552 Asm->getObjFileLowering().getDwarfMacinfoSection()); 2553 2554 for (const auto &P : CUMap) { 2555 auto &TheCU = *P.second; 2556 if (TheCU.getCUNode()->isDebugDirectivesOnly()) 2557 continue; 2558 auto *SkCU = TheCU.getSkeleton(); 2559 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 2560 auto *CUNode = cast<DICompileUnit>(P.first); 2561 DIMacroNodeArray Macros = CUNode->getMacros(); 2562 if (!Macros.empty()) { 2563 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin()); 2564 handleMacroNodes(Macros, U); 2565 } 2566 } 2567 Asm->OutStreamer->AddComment("End Of Macro List Mark"); 2568 Asm->emitInt8(0); 2569 } 2570 2571 // DWARF5 Experimental Separate Dwarf emitters. 2572 2573 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die, 2574 std::unique_ptr<DwarfCompileUnit> NewU) { 2575 2576 if (!CompilationDir.empty()) 2577 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 2578 2579 addGnuPubAttributes(*NewU, Die); 2580 2581 SkeletonHolder.addUnit(std::move(NewU)); 2582 } 2583 2584 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) { 2585 2586 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 2587 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder); 2588 DwarfCompileUnit &NewCU = *OwnedUnit; 2589 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 2590 2591 NewCU.initStmtList(); 2592 2593 if (useSegmentedStringOffsetsTable()) 2594 NewCU.addStringOffsetsStart(); 2595 2596 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit)); 2597 2598 return NewCU; 2599 } 2600 2601 // Emit the .debug_info.dwo section for separated dwarf. This contains the 2602 // compile units that would normally be in debug_info. 2603 void DwarfDebug::emitDebugInfoDWO() { 2604 assert(useSplitDwarf() && "No split dwarf debug info?"); 2605 // Don't emit relocations into the dwo file. 2606 InfoHolder.emitUnits(/* UseOffsets */ true); 2607 } 2608 2609 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 2610 // abbreviations for the .debug_info.dwo section. 2611 void DwarfDebug::emitDebugAbbrevDWO() { 2612 assert(useSplitDwarf() && "No split dwarf?"); 2613 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 2614 } 2615 2616 void DwarfDebug::emitDebugLineDWO() { 2617 assert(useSplitDwarf() && "No split dwarf?"); 2618 SplitTypeUnitFileTable.Emit( 2619 *Asm->OutStreamer, MCDwarfLineTableParams(), 2620 Asm->getObjFileLowering().getDwarfLineDWOSection()); 2621 } 2622 2623 void DwarfDebug::emitStringOffsetsTableHeaderDWO() { 2624 assert(useSplitDwarf() && "No split dwarf?"); 2625 InfoHolder.getStringPool().emitStringOffsetsTableHeader( 2626 *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(), 2627 InfoHolder.getStringOffsetsStartSym()); 2628 } 2629 2630 // Emit the .debug_str.dwo section for separated dwarf. This contains the 2631 // string section and is identical in format to traditional .debug_str 2632 // sections. 2633 void DwarfDebug::emitDebugStrDWO() { 2634 if (useSegmentedStringOffsetsTable()) 2635 emitStringOffsetsTableHeaderDWO(); 2636 assert(useSplitDwarf() && "No split dwarf?"); 2637 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 2638 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 2639 OffSec, /* UseRelativeOffsets = */ false); 2640 } 2641 2642 // Emit address pool. 2643 void DwarfDebug::emitDebugAddr() { 2644 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection()); 2645 } 2646 2647 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 2648 if (!useSplitDwarf()) 2649 return nullptr; 2650 const DICompileUnit *DIUnit = CU.getCUNode(); 2651 SplitTypeUnitFileTable.maybeSetRootFile( 2652 DIUnit->getDirectory(), DIUnit->getFilename(), 2653 CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource()); 2654 return &SplitTypeUnitFileTable; 2655 } 2656 2657 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) { 2658 MD5 Hash; 2659 Hash.update(Identifier); 2660 // ... take the least significant 8 bytes and return those. Our MD5 2661 // implementation always returns its results in little endian, so we actually 2662 // need the "high" word. 2663 MD5::MD5Result Result; 2664 Hash.final(Result); 2665 return Result.high(); 2666 } 2667 2668 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 2669 StringRef Identifier, DIE &RefDie, 2670 const DICompositeType *CTy) { 2671 // Fast path if we're building some type units and one has already used the 2672 // address pool we know we're going to throw away all this work anyway, so 2673 // don't bother building dependent types. 2674 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed()) 2675 return; 2676 2677 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0)); 2678 if (!Ins.second) { 2679 CU.addDIETypeSignature(RefDie, Ins.first->second); 2680 return; 2681 } 2682 2683 bool TopLevelType = TypeUnitsUnderConstruction.empty(); 2684 AddrPool.resetUsedFlag(); 2685 2686 auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder, 2687 getDwoLineTable(CU)); 2688 DwarfTypeUnit &NewTU = *OwnedUnit; 2689 DIE &UnitDie = NewTU.getUnitDie(); 2690 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy); 2691 2692 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 2693 CU.getLanguage()); 2694 2695 uint64_t Signature = makeTypeSignature(Identifier); 2696 NewTU.setTypeSignature(Signature); 2697 Ins.first->second = Signature; 2698 2699 if (useSplitDwarf()) { 2700 MCSection *Section = 2701 getDwarfVersion() <= 4 2702 ? Asm->getObjFileLowering().getDwarfTypesDWOSection() 2703 : Asm->getObjFileLowering().getDwarfInfoDWOSection(); 2704 NewTU.setSection(Section); 2705 } else { 2706 MCSection *Section = 2707 getDwarfVersion() <= 4 2708 ? Asm->getObjFileLowering().getDwarfTypesSection(Signature) 2709 : Asm->getObjFileLowering().getDwarfInfoSection(Signature); 2710 NewTU.setSection(Section); 2711 // Non-split type units reuse the compile unit's line table. 2712 CU.applyStmtList(UnitDie); 2713 } 2714 2715 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type 2716 // units. 2717 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 2718 NewTU.addStringOffsetsStart(); 2719 2720 NewTU.setType(NewTU.createTypeDIE(CTy)); 2721 2722 if (TopLevelType) { 2723 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction); 2724 TypeUnitsUnderConstruction.clear(); 2725 2726 // Types referencing entries in the address table cannot be placed in type 2727 // units. 2728 if (AddrPool.hasBeenUsed()) { 2729 2730 // Remove all the types built while building this type. 2731 // This is pessimistic as some of these types might not be dependent on 2732 // the type that used an address. 2733 for (const auto &TU : TypeUnitsToAdd) 2734 TypeSignatures.erase(TU.second); 2735 2736 // Construct this type in the CU directly. 2737 // This is inefficient because all the dependent types will be rebuilt 2738 // from scratch, including building them in type units, discovering that 2739 // they depend on addresses, throwing them out and rebuilding them. 2740 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy)); 2741 return; 2742 } 2743 2744 // If the type wasn't dependent on fission addresses, finish adding the type 2745 // and all its dependent types. 2746 for (auto &TU : TypeUnitsToAdd) { 2747 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get()); 2748 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf()); 2749 } 2750 } 2751 CU.addDIETypeSignature(RefDie, Signature); 2752 } 2753 2754 DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug *DD) 2755 : DD(DD), 2756 TypeUnitsUnderConstruction(std::move(DD->TypeUnitsUnderConstruction)) { 2757 DD->TypeUnitsUnderConstruction.clear(); 2758 assert(TypeUnitsUnderConstruction.empty() || !DD->AddrPool.hasBeenUsed()); 2759 } 2760 2761 DwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() { 2762 DD->TypeUnitsUnderConstruction = std::move(TypeUnitsUnderConstruction); 2763 DD->AddrPool.resetUsedFlag(); 2764 } 2765 2766 DwarfDebug::NonTypeUnitContext DwarfDebug::enterNonTypeUnitContext() { 2767 return NonTypeUnitContext(this); 2768 } 2769 2770 // Add the Name along with its companion DIE to the appropriate accelerator 2771 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for 2772 // AccelTableKind::Apple, we use the table we got as an argument). If 2773 // accelerator tables are disabled, this function does nothing. 2774 template <typename DataT> 2775 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU, 2776 AccelTable<DataT> &AppleAccel, StringRef Name, 2777 const DIE &Die) { 2778 if (getAccelTableKind() == AccelTableKind::None) 2779 return; 2780 2781 if (getAccelTableKind() != AccelTableKind::Apple && 2782 CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default) 2783 return; 2784 2785 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2786 DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name); 2787 2788 switch (getAccelTableKind()) { 2789 case AccelTableKind::Apple: 2790 AppleAccel.addName(Ref, Die); 2791 break; 2792 case AccelTableKind::Dwarf: 2793 AccelDebugNames.addName(Ref, Die); 2794 break; 2795 case AccelTableKind::Default: 2796 llvm_unreachable("Default should have already been resolved."); 2797 case AccelTableKind::None: 2798 llvm_unreachable("None handled above"); 2799 } 2800 } 2801 2802 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name, 2803 const DIE &Die) { 2804 addAccelNameImpl(CU, AccelNames, Name, Die); 2805 } 2806 2807 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name, 2808 const DIE &Die) { 2809 // ObjC names go only into the Apple accelerator tables. 2810 if (getAccelTableKind() == AccelTableKind::Apple) 2811 addAccelNameImpl(CU, AccelObjC, Name, Die); 2812 } 2813 2814 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name, 2815 const DIE &Die) { 2816 addAccelNameImpl(CU, AccelNamespace, Name, Die); 2817 } 2818 2819 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name, 2820 const DIE &Die, char Flags) { 2821 addAccelNameImpl(CU, AccelTypes, Name, Die); 2822 } 2823 2824 uint16_t DwarfDebug::getDwarfVersion() const { 2825 return Asm->OutStreamer->getContext().getDwarfVersion(); 2826 } 2827 2828 void DwarfDebug::addSectionLabel(const MCSymbol *Sym) { 2829 SectionLabels.insert(std::make_pair(&Sym->getSection(), Sym)); 2830 } 2831 2832 const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) { 2833 return SectionLabels.find(S)->second; 2834 } 2835