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