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 "DwarfCompileUnit.h" 17 #include "DwarfExpression.h" 18 #include "DwarfUnit.h" 19 #include "llvm/ADT/APInt.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/ADT/Triple.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/CodeGen/AsmPrinter.h" 24 #include "llvm/CodeGen/DIE.h" 25 #include "llvm/CodeGen/LexicalScopes.h" 26 #include "llvm/CodeGen/MachineBasicBlock.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineModuleInfo.h" 29 #include "llvm/CodeGen/MachineOperand.h" 30 #include "llvm/CodeGen/TargetInstrInfo.h" 31 #include "llvm/CodeGen/TargetLowering.h" 32 #include "llvm/CodeGen/TargetRegisterInfo.h" 33 #include "llvm/CodeGen/TargetSubtargetInfo.h" 34 #include "llvm/DebugInfo/DWARF/DWARFExpression.h" 35 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h" 36 #include "llvm/IR/Constants.h" 37 #include "llvm/IR/Function.h" 38 #include "llvm/IR/GlobalVariable.h" 39 #include "llvm/IR/Module.h" 40 #include "llvm/MC/MCAsmInfo.h" 41 #include "llvm/MC/MCContext.h" 42 #include "llvm/MC/MCSection.h" 43 #include "llvm/MC/MCStreamer.h" 44 #include "llvm/MC/MCSymbol.h" 45 #include "llvm/MC/MCTargetOptions.h" 46 #include "llvm/MC/MachineLocation.h" 47 #include "llvm/MC/SectionKind.h" 48 #include "llvm/Pass.h" 49 #include "llvm/Support/Casting.h" 50 #include "llvm/Support/CommandLine.h" 51 #include "llvm/Support/Debug.h" 52 #include "llvm/Support/ErrorHandling.h" 53 #include "llvm/Support/MD5.h" 54 #include "llvm/Support/MathExtras.h" 55 #include "llvm/Support/Timer.h" 56 #include "llvm/Support/raw_ostream.h" 57 #include "llvm/Target/TargetLoweringObjectFile.h" 58 #include "llvm/Target/TargetMachine.h" 59 #include <algorithm> 60 #include <cstddef> 61 #include <iterator> 62 #include <string> 63 64 using namespace llvm; 65 66 #define DEBUG_TYPE "dwarfdebug" 67 68 STATISTIC(NumCSParams, "Number of dbg call site params created"); 69 70 static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier( 71 "use-dwarf-ranges-base-address-specifier", cl::Hidden, 72 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false)); 73 74 static cl::opt<bool> GenerateARangeSection("generate-arange-section", 75 cl::Hidden, 76 cl::desc("Generate dwarf aranges"), 77 cl::init(false)); 78 79 static cl::opt<bool> 80 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden, 81 cl::desc("Generate DWARF4 type units."), 82 cl::init(false)); 83 84 static cl::opt<bool> SplitDwarfCrossCuReferences( 85 "split-dwarf-cross-cu-references", cl::Hidden, 86 cl::desc("Enable cross-cu references in DWO files"), cl::init(false)); 87 88 enum DefaultOnOff { Default, Enable, Disable }; 89 90 static cl::opt<DefaultOnOff> UnknownLocations( 91 "use-unknown-locations", cl::Hidden, 92 cl::desc("Make an absence of debug location information explicit."), 93 cl::values(clEnumVal(Default, "At top of block or after label"), 94 clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")), 95 cl::init(Default)); 96 97 static cl::opt<AccelTableKind> AccelTables( 98 "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."), 99 cl::values(clEnumValN(AccelTableKind::Default, "Default", 100 "Default for platform"), 101 clEnumValN(AccelTableKind::None, "Disable", "Disabled."), 102 clEnumValN(AccelTableKind::Apple, "Apple", "Apple"), 103 clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")), 104 cl::init(AccelTableKind::Default)); 105 106 static cl::opt<DefaultOnOff> 107 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden, 108 cl::desc("Use inlined strings rather than string section."), 109 cl::values(clEnumVal(Default, "Default for platform"), 110 clEnumVal(Enable, "Enabled"), 111 clEnumVal(Disable, "Disabled")), 112 cl::init(Default)); 113 114 static cl::opt<bool> 115 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden, 116 cl::desc("Disable emission .debug_ranges section."), 117 cl::init(false)); 118 119 static cl::opt<DefaultOnOff> DwarfSectionsAsReferences( 120 "dwarf-sections-as-references", cl::Hidden, 121 cl::desc("Use sections+offset as references rather than labels."), 122 cl::values(clEnumVal(Default, "Default for platform"), 123 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), 124 cl::init(Default)); 125 126 static cl::opt<bool> 127 UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden, 128 cl::desc("Emit the GNU .debug_macro format with DWARF <5"), 129 cl::init(false)); 130 131 static cl::opt<DefaultOnOff> DwarfOpConvert( 132 "dwarf-op-convert", cl::Hidden, 133 cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"), 134 cl::values(clEnumVal(Default, "Default for platform"), 135 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), 136 cl::init(Default)); 137 138 enum LinkageNameOption { 139 DefaultLinkageNames, 140 AllLinkageNames, 141 AbstractLinkageNames 142 }; 143 144 static cl::opt<LinkageNameOption> 145 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden, 146 cl::desc("Which DWARF linkage-name attributes to emit."), 147 cl::values(clEnumValN(DefaultLinkageNames, "Default", 148 "Default for platform"), 149 clEnumValN(AllLinkageNames, "All", "All"), 150 clEnumValN(AbstractLinkageNames, "Abstract", 151 "Abstract subprograms")), 152 cl::init(DefaultLinkageNames)); 153 154 static cl::opt<DwarfDebug::MinimizeAddrInV5> MinimizeAddrInV5Option( 155 "minimize-addr-in-v5", cl::Hidden, 156 cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more " 157 "address pool entry sharing to reduce relocations/object size"), 158 cl::values(clEnumValN(DwarfDebug::MinimizeAddrInV5::Default, "Default", 159 "Default address minimization strategy"), 160 clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges, "Ranges", 161 "Use rnglists for contiguous ranges if that allows " 162 "using a pre-existing base address"), 163 clEnumValN(DwarfDebug::MinimizeAddrInV5::Expressions, 164 "Expressions", 165 "Use exprloc addrx+offset expressions for any " 166 "address with a prior base address"), 167 clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled, "Disabled", 168 "Stuff")), 169 cl::init(DwarfDebug::MinimizeAddrInV5::Default)); 170 171 static constexpr unsigned ULEB128PadSize = 4; 172 173 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) { 174 getActiveStreamer().emitInt8( 175 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op) 176 : dwarf::OperationEncodingString(Op)); 177 } 178 179 void DebugLocDwarfExpression::emitSigned(int64_t Value) { 180 getActiveStreamer().emitSLEB128(Value, Twine(Value)); 181 } 182 183 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) { 184 getActiveStreamer().emitULEB128(Value, Twine(Value)); 185 } 186 187 void DebugLocDwarfExpression::emitData1(uint8_t Value) { 188 getActiveStreamer().emitInt8(Value, Twine(Value)); 189 } 190 191 void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) { 192 assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit"); 193 getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize); 194 } 195 196 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI, 197 llvm::Register MachineReg) { 198 // This information is not available while emitting .debug_loc entries. 199 return false; 200 } 201 202 void DebugLocDwarfExpression::enableTemporaryBuffer() { 203 assert(!IsBuffering && "Already buffering?"); 204 if (!TmpBuf) 205 TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments); 206 IsBuffering = true; 207 } 208 209 void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; } 210 211 unsigned DebugLocDwarfExpression::getTemporaryBufferSize() { 212 return TmpBuf ? TmpBuf->Bytes.size() : 0; 213 } 214 215 void DebugLocDwarfExpression::commitTemporaryBuffer() { 216 if (!TmpBuf) 217 return; 218 for (auto Byte : enumerate(TmpBuf->Bytes)) { 219 const char *Comment = (Byte.index() < TmpBuf->Comments.size()) 220 ? TmpBuf->Comments[Byte.index()].c_str() 221 : ""; 222 OutBS.emitInt8(Byte.value(), Comment); 223 } 224 TmpBuf->Bytes.clear(); 225 TmpBuf->Comments.clear(); 226 } 227 228 const DIType *DbgVariable::getType() const { 229 return getVariable()->getType(); 230 } 231 232 /// Get .debug_loc entry for the instruction range starting at MI. 233 static DbgValueLoc getDebugLocValue(const MachineInstr *MI) { 234 const DIExpression *Expr = MI->getDebugExpression(); 235 assert(MI->getNumOperands() == 4); 236 if (MI->getDebugOperand(0).isReg()) { 237 const auto &RegOp = MI->getDebugOperand(0); 238 const auto &Op1 = MI->getDebugOffset(); 239 // If the second operand is an immediate, this is a 240 // register-indirect address. 241 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset"); 242 MachineLocation MLoc(RegOp.getReg(), Op1.isImm()); 243 return DbgValueLoc(Expr, MLoc); 244 } 245 if (MI->getDebugOperand(0).isTargetIndex()) { 246 const auto &Op = MI->getDebugOperand(0); 247 return DbgValueLoc(Expr, 248 TargetIndexLocation(Op.getIndex(), Op.getOffset())); 249 } 250 if (MI->getDebugOperand(0).isImm()) 251 return DbgValueLoc(Expr, MI->getDebugOperand(0).getImm()); 252 if (MI->getDebugOperand(0).isFPImm()) 253 return DbgValueLoc(Expr, MI->getDebugOperand(0).getFPImm()); 254 if (MI->getDebugOperand(0).isCImm()) 255 return DbgValueLoc(Expr, MI->getDebugOperand(0).getCImm()); 256 257 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!"); 258 } 259 260 void DbgVariable::initializeDbgValue(const MachineInstr *DbgValue) { 261 assert(FrameIndexExprs.empty() && "Already initialized?"); 262 assert(!ValueLoc.get() && "Already initialized?"); 263 264 assert(getVariable() == DbgValue->getDebugVariable() && "Wrong variable"); 265 assert(getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() && 266 "Wrong inlined-at"); 267 268 ValueLoc = std::make_unique<DbgValueLoc>(getDebugLocValue(DbgValue)); 269 if (auto *E = DbgValue->getDebugExpression()) 270 if (E->getNumElements()) 271 FrameIndexExprs.push_back({0, E}); 272 } 273 274 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const { 275 if (FrameIndexExprs.size() == 1) 276 return FrameIndexExprs; 277 278 assert(llvm::all_of(FrameIndexExprs, 279 [](const FrameIndexExpr &A) { 280 return A.Expr->isFragment(); 281 }) && 282 "multiple FI expressions without DW_OP_LLVM_fragment"); 283 llvm::sort(FrameIndexExprs, 284 [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool { 285 return A.Expr->getFragmentInfo()->OffsetInBits < 286 B.Expr->getFragmentInfo()->OffsetInBits; 287 }); 288 289 return FrameIndexExprs; 290 } 291 292 void DbgVariable::addMMIEntry(const DbgVariable &V) { 293 assert(DebugLocListIndex == ~0U && !ValueLoc.get() && "not an MMI entry"); 294 assert(V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && "not an MMI entry"); 295 assert(V.getVariable() == getVariable() && "conflicting variable"); 296 assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location"); 297 298 assert(!FrameIndexExprs.empty() && "Expected an MMI entry"); 299 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry"); 300 301 // FIXME: This logic should not be necessary anymore, as we now have proper 302 // deduplication. However, without it, we currently run into the assertion 303 // below, which means that we are likely dealing with broken input, i.e. two 304 // non-fragment entries for the same variable at different frame indices. 305 if (FrameIndexExprs.size()) { 306 auto *Expr = FrameIndexExprs.back().Expr; 307 if (!Expr || !Expr->isFragment()) 308 return; 309 } 310 311 for (const auto &FIE : V.FrameIndexExprs) 312 // Ignore duplicate entries. 313 if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) { 314 return FIE.FI == Other.FI && FIE.Expr == Other.Expr; 315 })) 316 FrameIndexExprs.push_back(FIE); 317 318 assert((FrameIndexExprs.size() == 1 || 319 llvm::all_of(FrameIndexExprs, 320 [](FrameIndexExpr &FIE) { 321 return FIE.Expr && FIE.Expr->isFragment(); 322 })) && 323 "conflicting locations for variable"); 324 } 325 326 static AccelTableKind computeAccelTableKind(unsigned DwarfVersion, 327 bool GenerateTypeUnits, 328 DebuggerKind Tuning, 329 const Triple &TT) { 330 // Honor an explicit request. 331 if (AccelTables != AccelTableKind::Default) 332 return AccelTables; 333 334 // Accelerator tables with type units are currently not supported. 335 if (GenerateTypeUnits) 336 return AccelTableKind::None; 337 338 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5 339 // always implies debug_names. For lower standard versions we use apple 340 // accelerator tables on apple platforms and debug_names elsewhere. 341 if (DwarfVersion >= 5) 342 return AccelTableKind::Dwarf; 343 if (Tuning == DebuggerKind::LLDB) 344 return TT.isOSBinFormatMachO() ? AccelTableKind::Apple 345 : AccelTableKind::Dwarf; 346 return AccelTableKind::None; 347 } 348 349 DwarfDebug::DwarfDebug(AsmPrinter *A) 350 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()), 351 InfoHolder(A, "info_string", DIEValueAllocator), 352 SkeletonHolder(A, "skel_string", DIEValueAllocator), 353 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) { 354 const Triple &TT = Asm->TM.getTargetTriple(); 355 356 // Make sure we know our "debugger tuning". The target option takes 357 // precedence; fall back to triple-based defaults. 358 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default) 359 DebuggerTuning = Asm->TM.Options.DebuggerTuning; 360 else if (IsDarwin) 361 DebuggerTuning = DebuggerKind::LLDB; 362 else if (TT.isPS4CPU()) 363 DebuggerTuning = DebuggerKind::SCE; 364 else 365 DebuggerTuning = DebuggerKind::GDB; 366 367 if (DwarfInlinedStrings == Default) 368 UseInlineStrings = TT.isNVPTX(); 369 else 370 UseInlineStrings = DwarfInlinedStrings == Enable; 371 372 UseLocSection = !TT.isNVPTX(); 373 374 HasAppleExtensionAttributes = tuneForLLDB(); 375 376 // Handle split DWARF. 377 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty(); 378 379 // SCE defaults to linkage names only for abstract subprograms. 380 if (DwarfLinkageNames == DefaultLinkageNames) 381 UseAllLinkageNames = !tuneForSCE(); 382 else 383 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames; 384 385 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion; 386 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber 387 : MMI->getModule()->getDwarfVersion(); 388 // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2. 389 DwarfVersion = 390 TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION); 391 392 bool Dwarf64 = Asm->TM.Options.MCOptions.Dwarf64 && 393 DwarfVersion >= 3 && // DWARF64 was introduced in DWARFv3. 394 TT.isArch64Bit() && // DWARF64 requires 64-bit relocations. 395 TT.isOSBinFormatELF(); // Support only ELF for now. 396 397 UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX(); 398 399 // Use sections as references. Force for NVPTX. 400 if (DwarfSectionsAsReferences == Default) 401 UseSectionsAsReferences = TT.isNVPTX(); 402 else 403 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable; 404 405 // Don't generate type units for unsupported object file formats. 406 GenerateTypeUnits = (A->TM.getTargetTriple().isOSBinFormatELF() || 407 A->TM.getTargetTriple().isOSBinFormatWasm()) && 408 GenerateDwarfTypeUnits; 409 410 TheAccelTableKind = computeAccelTableKind( 411 DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple()); 412 413 // Work around a GDB bug. GDB doesn't support the standard opcode; 414 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which 415 // is defined as of DWARF 3. 416 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented 417 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616 418 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3; 419 420 // GDB does not fully support the DWARF 4 representation for bitfields. 421 UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB(); 422 423 // The DWARF v5 string offsets table has - possibly shared - contributions 424 // from each compile and type unit each preceded by a header. The string 425 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses 426 // a monolithic string offsets table without any header. 427 UseSegmentedStringOffsetsTable = DwarfVersion >= 5; 428 429 // Emit call-site-param debug info for GDB and LLDB, if the target supports 430 // the debug entry values feature. It can also be enabled explicitly. 431 EmitDebugEntryValues = Asm->TM.Options.ShouldEmitDebugEntryValues(); 432 433 // It is unclear if the GCC .debug_macro extension is well-specified 434 // for split DWARF. For now, do not allow LLVM to emit it. 435 UseDebugMacroSection = 436 DwarfVersion >= 5 || (UseGNUDebugMacro && !useSplitDwarf()); 437 if (DwarfOpConvert == Default) 438 EnableOpConvert = !((tuneForGDB() && useSplitDwarf()) || (tuneForLLDB() && !TT.isOSBinFormatMachO())); 439 else 440 EnableOpConvert = (DwarfOpConvert == Enable); 441 442 // Split DWARF would benefit object size significantly by trading reductions 443 // in address pool usage for slightly increased range list encodings. 444 if (DwarfVersion >= 5) { 445 MinimizeAddr = MinimizeAddrInV5Option; 446 // FIXME: In the future, enable this by default for Split DWARF where the 447 // tradeoff is more pronounced due to being able to offload the range 448 // lists to the dwo file and shrink object files/reduce relocations there. 449 if (MinimizeAddr == MinimizeAddrInV5::Default) 450 MinimizeAddr = MinimizeAddrInV5::Disabled; 451 } 452 453 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion); 454 Asm->OutStreamer->getContext().setDwarfFormat(Dwarf64 ? dwarf::DWARF64 455 : dwarf::DWARF32); 456 } 457 458 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h. 459 DwarfDebug::~DwarfDebug() = default; 460 461 static bool isObjCClass(StringRef Name) { 462 return Name.startswith("+") || Name.startswith("-"); 463 } 464 465 static bool hasObjCCategory(StringRef Name) { 466 if (!isObjCClass(Name)) 467 return false; 468 469 return Name.find(") ") != StringRef::npos; 470 } 471 472 static void getObjCClassCategory(StringRef In, StringRef &Class, 473 StringRef &Category) { 474 if (!hasObjCCategory(In)) { 475 Class = In.slice(In.find('[') + 1, In.find(' ')); 476 Category = ""; 477 return; 478 } 479 480 Class = In.slice(In.find('[') + 1, In.find('(')); 481 Category = In.slice(In.find('[') + 1, In.find(' ')); 482 } 483 484 static StringRef getObjCMethodName(StringRef In) { 485 return In.slice(In.find(' ') + 1, In.find(']')); 486 } 487 488 // Add the various names to the Dwarf accelerator table names. 489 void DwarfDebug::addSubprogramNames(const DICompileUnit &CU, 490 const DISubprogram *SP, DIE &Die) { 491 if (getAccelTableKind() != AccelTableKind::Apple && 492 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None) 493 return; 494 495 if (!SP->isDefinition()) 496 return; 497 498 if (SP->getName() != "") 499 addAccelName(CU, SP->getName(), Die); 500 501 // If the linkage name is different than the name, go ahead and output that as 502 // well into the name table. Only do that if we are going to actually emit 503 // that name. 504 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() && 505 (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP))) 506 addAccelName(CU, SP->getLinkageName(), Die); 507 508 // If this is an Objective-C selector name add it to the ObjC accelerator 509 // too. 510 if (isObjCClass(SP->getName())) { 511 StringRef Class, Category; 512 getObjCClassCategory(SP->getName(), Class, Category); 513 addAccelObjC(CU, Class, Die); 514 if (Category != "") 515 addAccelObjC(CU, Category, Die); 516 // Also add the base method name to the name table. 517 addAccelName(CU, getObjCMethodName(SP->getName()), Die); 518 } 519 } 520 521 /// Check whether we should create a DIE for the given Scope, return true 522 /// if we don't create a DIE (the corresponding DIE is null). 523 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) { 524 if (Scope->isAbstractScope()) 525 return false; 526 527 // We don't create a DIE if there is no Range. 528 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges(); 529 if (Ranges.empty()) 530 return true; 531 532 if (Ranges.size() > 1) 533 return false; 534 535 // We don't create a DIE if we have a single Range and the end label 536 // is null. 537 return !getLabelAfterInsn(Ranges.front().second); 538 } 539 540 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) { 541 F(CU); 542 if (auto *SkelCU = CU.getSkeleton()) 543 if (CU.getCUNode()->getSplitDebugInlining()) 544 F(*SkelCU); 545 } 546 547 bool DwarfDebug::shareAcrossDWOCUs() const { 548 return SplitDwarfCrossCuReferences; 549 } 550 551 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, 552 LexicalScope *Scope) { 553 assert(Scope && Scope->getScopeNode()); 554 assert(Scope->isAbstractScope()); 555 assert(!Scope->getInlinedAt()); 556 557 auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 558 559 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 560 // was inlined from another compile unit. 561 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining()) 562 // Avoid building the original CU if it won't be used 563 SrcCU.constructAbstractSubprogramScopeDIE(Scope); 564 else { 565 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 566 if (auto *SkelCU = CU.getSkeleton()) { 567 (shareAcrossDWOCUs() ? CU : SrcCU) 568 .constructAbstractSubprogramScopeDIE(Scope); 569 if (CU.getCUNode()->getSplitDebugInlining()) 570 SkelCU->constructAbstractSubprogramScopeDIE(Scope); 571 } else 572 CU.constructAbstractSubprogramScopeDIE(Scope); 573 } 574 } 575 576 DIE &DwarfDebug::constructSubprogramDefinitionDIE(const DISubprogram *SP) { 577 DICompileUnit *Unit = SP->getUnit(); 578 assert(SP->isDefinition() && "Subprogram not a definition"); 579 assert(Unit && "Subprogram definition without parent unit"); 580 auto &CU = getOrCreateDwarfCompileUnit(Unit); 581 return *CU.getOrCreateSubprogramDIE(SP); 582 } 583 584 /// Represents a parameter whose call site value can be described by applying a 585 /// debug expression to a register in the forwarded register worklist. 586 struct FwdRegParamInfo { 587 /// The described parameter register. 588 unsigned ParamReg; 589 590 /// Debug expression that has been built up when walking through the 591 /// instruction chain that produces the parameter's value. 592 const DIExpression *Expr; 593 }; 594 595 /// Register worklist for finding call site values. 596 using FwdRegWorklist = MapVector<unsigned, SmallVector<FwdRegParamInfo, 2>>; 597 598 /// Append the expression \p Addition to \p Original and return the result. 599 static const DIExpression *combineDIExpressions(const DIExpression *Original, 600 const DIExpression *Addition) { 601 std::vector<uint64_t> Elts = Addition->getElements().vec(); 602 // Avoid multiple DW_OP_stack_values. 603 if (Original->isImplicit() && Addition->isImplicit()) 604 erase_value(Elts, dwarf::DW_OP_stack_value); 605 const DIExpression *CombinedExpr = 606 (Elts.size() > 0) ? DIExpression::append(Original, Elts) : Original; 607 return CombinedExpr; 608 } 609 610 /// Emit call site parameter entries that are described by the given value and 611 /// debug expression. 612 template <typename ValT> 613 static void finishCallSiteParams(ValT Val, const DIExpression *Expr, 614 ArrayRef<FwdRegParamInfo> DescribedParams, 615 ParamSet &Params) { 616 for (auto Param : DescribedParams) { 617 bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0; 618 619 // TODO: Entry value operations can currently not be combined with any 620 // other expressions, so we can't emit call site entries in those cases. 621 if (ShouldCombineExpressions && Expr->isEntryValue()) 622 continue; 623 624 // If a parameter's call site value is produced by a chain of 625 // instructions we may have already created an expression for the 626 // parameter when walking through the instructions. Append that to the 627 // base expression. 628 const DIExpression *CombinedExpr = 629 ShouldCombineExpressions ? combineDIExpressions(Expr, Param.Expr) 630 : Expr; 631 assert((!CombinedExpr || CombinedExpr->isValid()) && 632 "Combined debug expression is invalid"); 633 634 DbgValueLoc DbgLocVal(CombinedExpr, Val); 635 DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal); 636 Params.push_back(CSParm); 637 ++NumCSParams; 638 } 639 } 640 641 /// Add \p Reg to the worklist, if it's not already present, and mark that the 642 /// given parameter registers' values can (potentially) be described using 643 /// that register and an debug expression. 644 static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg, 645 const DIExpression *Expr, 646 ArrayRef<FwdRegParamInfo> ParamsToAdd) { 647 auto I = Worklist.insert({Reg, {}}); 648 auto &ParamsForFwdReg = I.first->second; 649 for (auto Param : ParamsToAdd) { 650 assert(none_of(ParamsForFwdReg, 651 [Param](const FwdRegParamInfo &D) { 652 return D.ParamReg == Param.ParamReg; 653 }) && 654 "Same parameter described twice by forwarding reg"); 655 656 // If a parameter's call site value is produced by a chain of 657 // instructions we may have already created an expression for the 658 // parameter when walking through the instructions. Append that to the 659 // new expression. 660 const DIExpression *CombinedExpr = combineDIExpressions(Expr, Param.Expr); 661 ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr}); 662 } 663 } 664 665 /// Interpret values loaded into registers by \p CurMI. 666 static void interpretValues(const MachineInstr *CurMI, 667 FwdRegWorklist &ForwardedRegWorklist, 668 ParamSet &Params) { 669 670 const MachineFunction *MF = CurMI->getMF(); 671 const DIExpression *EmptyExpr = 672 DIExpression::get(MF->getFunction().getContext(), {}); 673 const auto &TRI = *MF->getSubtarget().getRegisterInfo(); 674 const auto &TII = *MF->getSubtarget().getInstrInfo(); 675 const auto &TLI = *MF->getSubtarget().getTargetLowering(); 676 677 // If an instruction defines more than one item in the worklist, we may run 678 // into situations where a worklist register's value is (potentially) 679 // described by the previous value of another register that is also defined 680 // by that instruction. 681 // 682 // This can for example occur in cases like this: 683 // 684 // $r1 = mov 123 685 // $r0, $r1 = mvrr $r1, 456 686 // call @foo, $r0, $r1 687 // 688 // When describing $r1's value for the mvrr instruction, we need to make sure 689 // that we don't finalize an entry value for $r0, as that is dependent on the 690 // previous value of $r1 (123 rather than 456). 691 // 692 // In order to not have to distinguish between those cases when finalizing 693 // entry values, we simply postpone adding new parameter registers to the 694 // worklist, by first keeping them in this temporary container until the 695 // instruction has been handled. 696 FwdRegWorklist TmpWorklistItems; 697 698 // If the MI is an instruction defining one or more parameters' forwarding 699 // registers, add those defines. 700 auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI, 701 SmallSetVector<unsigned, 4> &Defs) { 702 if (MI.isDebugInstr()) 703 return; 704 705 for (const MachineOperand &MO : MI.operands()) { 706 if (MO.isReg() && MO.isDef() && 707 Register::isPhysicalRegister(MO.getReg())) { 708 for (auto FwdReg : ForwardedRegWorklist) 709 if (TRI.regsOverlap(FwdReg.first, MO.getReg())) 710 Defs.insert(FwdReg.first); 711 } 712 } 713 }; 714 715 // Set of worklist registers that are defined by this instruction. 716 SmallSetVector<unsigned, 4> FwdRegDefs; 717 718 getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs); 719 if (FwdRegDefs.empty()) 720 return; 721 722 for (auto ParamFwdReg : FwdRegDefs) { 723 if (auto ParamValue = TII.describeLoadedValue(*CurMI, ParamFwdReg)) { 724 if (ParamValue->first.isImm()) { 725 int64_t Val = ParamValue->first.getImm(); 726 finishCallSiteParams(Val, ParamValue->second, 727 ForwardedRegWorklist[ParamFwdReg], Params); 728 } else if (ParamValue->first.isReg()) { 729 Register RegLoc = ParamValue->first.getReg(); 730 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 731 Register FP = TRI.getFrameRegister(*MF); 732 bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP); 733 if (TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP) { 734 MachineLocation MLoc(RegLoc, /*Indirect=*/IsSPorFP); 735 finishCallSiteParams(MLoc, ParamValue->second, 736 ForwardedRegWorklist[ParamFwdReg], Params); 737 } else { 738 // ParamFwdReg was described by the non-callee saved register 739 // RegLoc. Mark that the call site values for the parameters are 740 // dependent on that register instead of ParamFwdReg. Since RegLoc 741 // may be a register that will be handled in this iteration, we 742 // postpone adding the items to the worklist, and instead keep them 743 // in a temporary container. 744 addToFwdRegWorklist(TmpWorklistItems, RegLoc, ParamValue->second, 745 ForwardedRegWorklist[ParamFwdReg]); 746 } 747 } 748 } 749 } 750 751 // Remove all registers that this instruction defines from the worklist. 752 for (auto ParamFwdReg : FwdRegDefs) 753 ForwardedRegWorklist.erase(ParamFwdReg); 754 755 // Now that we are done handling this instruction, add items from the 756 // temporary worklist to the real one. 757 for (auto New : TmpWorklistItems) 758 addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr, New.second); 759 TmpWorklistItems.clear(); 760 } 761 762 static bool interpretNextInstr(const MachineInstr *CurMI, 763 FwdRegWorklist &ForwardedRegWorklist, 764 ParamSet &Params) { 765 // Skip bundle headers. 766 if (CurMI->isBundle()) 767 return true; 768 769 // If the next instruction is a call we can not interpret parameter's 770 // forwarding registers or we finished the interpretation of all 771 // parameters. 772 if (CurMI->isCall()) 773 return false; 774 775 if (ForwardedRegWorklist.empty()) 776 return false; 777 778 // Avoid NOP description. 779 if (CurMI->getNumOperands() == 0) 780 return true; 781 782 interpretValues(CurMI, ForwardedRegWorklist, Params); 783 784 return true; 785 } 786 787 /// Try to interpret values loaded into registers that forward parameters 788 /// for \p CallMI. Store parameters with interpreted value into \p Params. 789 static void collectCallSiteParameters(const MachineInstr *CallMI, 790 ParamSet &Params) { 791 const MachineFunction *MF = CallMI->getMF(); 792 auto CalleesMap = MF->getCallSitesInfo(); 793 auto CallFwdRegsInfo = CalleesMap.find(CallMI); 794 795 // There is no information for the call instruction. 796 if (CallFwdRegsInfo == CalleesMap.end()) 797 return; 798 799 const MachineBasicBlock *MBB = CallMI->getParent(); 800 801 // Skip the call instruction. 802 auto I = std::next(CallMI->getReverseIterator()); 803 804 FwdRegWorklist ForwardedRegWorklist; 805 806 const DIExpression *EmptyExpr = 807 DIExpression::get(MF->getFunction().getContext(), {}); 808 809 // Add all the forwarding registers into the ForwardedRegWorklist. 810 for (auto ArgReg : CallFwdRegsInfo->second) { 811 bool InsertedReg = 812 ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}}) 813 .second; 814 assert(InsertedReg && "Single register used to forward two arguments?"); 815 (void)InsertedReg; 816 } 817 818 // Do not emit CSInfo for undef forwarding registers. 819 for (auto &MO : CallMI->uses()) 820 if (MO.isReg() && MO.isUndef()) 821 ForwardedRegWorklist.erase(MO.getReg()); 822 823 // We erase, from the ForwardedRegWorklist, those forwarding registers for 824 // which we successfully describe a loaded value (by using 825 // the describeLoadedValue()). For those remaining arguments in the working 826 // list, for which we do not describe a loaded value by 827 // the describeLoadedValue(), we try to generate an entry value expression 828 // for their call site value description, if the call is within the entry MBB. 829 // TODO: Handle situations when call site parameter value can be described 830 // as the entry value within basic blocks other than the first one. 831 bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin(); 832 833 // Search for a loading value in forwarding registers inside call delay slot. 834 if (CallMI->hasDelaySlot()) { 835 auto Suc = std::next(CallMI->getIterator()); 836 // Only one-instruction delay slot is supported. 837 auto BundleEnd = llvm::getBundleEnd(CallMI->getIterator()); 838 (void)BundleEnd; 839 assert(std::next(Suc) == BundleEnd && 840 "More than one instruction in call delay slot"); 841 // Try to interpret value loaded by instruction. 842 if (!interpretNextInstr(&*Suc, ForwardedRegWorklist, Params)) 843 return; 844 } 845 846 // Search for a loading value in forwarding registers. 847 for (; I != MBB->rend(); ++I) { 848 // Try to interpret values loaded by instruction. 849 if (!interpretNextInstr(&*I, ForwardedRegWorklist, Params)) 850 return; 851 } 852 853 // Emit the call site parameter's value as an entry value. 854 if (ShouldTryEmitEntryVals) { 855 // Create an expression where the register's entry value is used. 856 DIExpression *EntryExpr = DIExpression::get( 857 MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1}); 858 for (auto RegEntry : ForwardedRegWorklist) { 859 MachineLocation MLoc(RegEntry.first); 860 finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params); 861 } 862 } 863 } 864 865 void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP, 866 DwarfCompileUnit &CU, DIE &ScopeDIE, 867 const MachineFunction &MF) { 868 // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if 869 // the subprogram is required to have one. 870 if (!SP.areAllCallsDescribed() || !SP.isDefinition()) 871 return; 872 873 // Use DW_AT_call_all_calls to express that call site entries are present 874 // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls 875 // because one of its requirements is not met: call site entries for 876 // optimized-out calls are elided. 877 CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls)); 878 879 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 880 assert(TII && "TargetInstrInfo not found: cannot label tail calls"); 881 882 // Delay slot support check. 883 auto delaySlotSupported = [&](const MachineInstr &MI) { 884 if (!MI.isBundledWithSucc()) 885 return false; 886 auto Suc = std::next(MI.getIterator()); 887 auto CallInstrBundle = getBundleStart(MI.getIterator()); 888 (void)CallInstrBundle; 889 auto DelaySlotBundle = getBundleStart(Suc); 890 (void)DelaySlotBundle; 891 // Ensure that label after call is following delay slot instruction. 892 // Ex. CALL_INSTRUCTION { 893 // DELAY_SLOT_INSTRUCTION } 894 // LABEL_AFTER_CALL 895 assert(getLabelAfterInsn(&*CallInstrBundle) == 896 getLabelAfterInsn(&*DelaySlotBundle) && 897 "Call and its successor instruction don't have same label after."); 898 return true; 899 }; 900 901 // Emit call site entries for each call or tail call in the function. 902 for (const MachineBasicBlock &MBB : MF) { 903 for (const MachineInstr &MI : MBB.instrs()) { 904 // Bundles with call in them will pass the isCall() test below but do not 905 // have callee operand information so skip them here. Iterator will 906 // eventually reach the call MI. 907 if (MI.isBundle()) 908 continue; 909 910 // Skip instructions which aren't calls. Both calls and tail-calling jump 911 // instructions (e.g TAILJMPd64) are classified correctly here. 912 if (!MI.isCandidateForCallSiteEntry()) 913 continue; 914 915 // Skip instructions marked as frame setup, as they are not interesting to 916 // the user. 917 if (MI.getFlag(MachineInstr::FrameSetup)) 918 continue; 919 920 // Check if delay slot support is enabled. 921 if (MI.hasDelaySlot() && !delaySlotSupported(*&MI)) 922 return; 923 924 // If this is a direct call, find the callee's subprogram. 925 // In the case of an indirect call find the register that holds 926 // the callee. 927 const MachineOperand &CalleeOp = MI.getOperand(0); 928 if (!CalleeOp.isGlobal() && !CalleeOp.isReg()) 929 continue; 930 931 unsigned CallReg = 0; 932 DIE *CalleeDIE = nullptr; 933 const Function *CalleeDecl = nullptr; 934 if (CalleeOp.isReg()) { 935 CallReg = CalleeOp.getReg(); 936 if (!CallReg) 937 continue; 938 } else { 939 CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal()); 940 if (!CalleeDecl || !CalleeDecl->getSubprogram()) 941 continue; 942 const DISubprogram *CalleeSP = CalleeDecl->getSubprogram(); 943 944 if (CalleeSP->isDefinition()) { 945 // Ensure that a subprogram DIE for the callee is available in the 946 // appropriate CU. 947 CalleeDIE = &constructSubprogramDefinitionDIE(CalleeSP); 948 } else { 949 // Create the declaration DIE if it is missing. This is required to 950 // support compilation of old bitcode with an incomplete list of 951 // retained metadata. 952 CalleeDIE = CU.getOrCreateSubprogramDIE(CalleeSP); 953 } 954 assert(CalleeDIE && "Must have a DIE for the callee"); 955 } 956 957 // TODO: Omit call site entries for runtime calls (objc_msgSend, etc). 958 959 bool IsTail = TII->isTailCall(MI); 960 961 // If MI is in a bundle, the label was created after the bundle since 962 // EmitFunctionBody iterates over top-level MIs. Get that top-level MI 963 // to search for that label below. 964 const MachineInstr *TopLevelCallMI = 965 MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI; 966 967 // For non-tail calls, the return PC is needed to disambiguate paths in 968 // the call graph which could lead to some target function. For tail 969 // calls, no return PC information is needed, unless tuning for GDB in 970 // DWARF4 mode in which case we fake a return PC for compatibility. 971 const MCSymbol *PCAddr = 972 (!IsTail || CU.useGNUAnalogForDwarf5Feature()) 973 ? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI)) 974 : nullptr; 975 976 // For tail calls, it's necessary to record the address of the branch 977 // instruction so that the debugger can show where the tail call occurred. 978 const MCSymbol *CallAddr = 979 IsTail ? getLabelBeforeInsn(TopLevelCallMI) : nullptr; 980 981 assert((IsTail || PCAddr) && "Non-tail call without return PC"); 982 983 LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> " 984 << (CalleeDecl ? CalleeDecl->getName() 985 : StringRef(MF.getSubtarget() 986 .getRegisterInfo() 987 ->getName(CallReg))) 988 << (IsTail ? " [IsTail]" : "") << "\n"); 989 990 DIE &CallSiteDIE = CU.constructCallSiteEntryDIE( 991 ScopeDIE, CalleeDIE, IsTail, PCAddr, CallAddr, CallReg); 992 993 // Optionally emit call-site-param debug info. 994 if (emitDebugEntryValues()) { 995 ParamSet Params; 996 // Try to interpret values of call site parameters. 997 collectCallSiteParameters(&MI, Params); 998 CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params); 999 } 1000 } 1001 } 1002 } 1003 1004 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const { 1005 if (!U.hasDwarfPubSections()) 1006 return; 1007 1008 U.addFlag(D, dwarf::DW_AT_GNU_pubnames); 1009 } 1010 1011 void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit, 1012 DwarfCompileUnit &NewCU) { 1013 DIE &Die = NewCU.getUnitDie(); 1014 StringRef FN = DIUnit->getFilename(); 1015 1016 StringRef Producer = DIUnit->getProducer(); 1017 StringRef Flags = DIUnit->getFlags(); 1018 if (!Flags.empty() && !useAppleExtensionAttributes()) { 1019 std::string ProducerWithFlags = Producer.str() + " " + Flags.str(); 1020 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags); 1021 } else 1022 NewCU.addString(Die, dwarf::DW_AT_producer, Producer); 1023 1024 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 1025 DIUnit->getSourceLanguage()); 1026 NewCU.addString(Die, dwarf::DW_AT_name, FN); 1027 StringRef SysRoot = DIUnit->getSysRoot(); 1028 if (!SysRoot.empty()) 1029 NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot); 1030 StringRef SDK = DIUnit->getSDK(); 1031 if (!SDK.empty()) 1032 NewCU.addString(Die, dwarf::DW_AT_APPLE_sdk, SDK); 1033 1034 // Add DW_str_offsets_base to the unit DIE, except for split units. 1035 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 1036 NewCU.addStringOffsetsStart(); 1037 1038 if (!useSplitDwarf()) { 1039 NewCU.initStmtList(); 1040 1041 // If we're using split dwarf the compilation dir is going to be in the 1042 // skeleton CU and so we don't need to duplicate it here. 1043 if (!CompilationDir.empty()) 1044 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 1045 addGnuPubAttributes(NewCU, Die); 1046 } 1047 1048 if (useAppleExtensionAttributes()) { 1049 if (DIUnit->isOptimized()) 1050 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized); 1051 1052 StringRef Flags = DIUnit->getFlags(); 1053 if (!Flags.empty()) 1054 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags); 1055 1056 if (unsigned RVer = DIUnit->getRuntimeVersion()) 1057 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 1058 dwarf::DW_FORM_data1, RVer); 1059 } 1060 1061 if (DIUnit->getDWOId()) { 1062 // This CU is either a clang module DWO or a skeleton CU. 1063 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 1064 DIUnit->getDWOId()); 1065 if (!DIUnit->getSplitDebugFilename().empty()) { 1066 // This is a prefabricated skeleton CU. 1067 dwarf::Attribute attrDWOName = getDwarfVersion() >= 5 1068 ? dwarf::DW_AT_dwo_name 1069 : dwarf::DW_AT_GNU_dwo_name; 1070 NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename()); 1071 } 1072 } 1073 } 1074 // Create new DwarfCompileUnit for the given metadata node with tag 1075 // DW_TAG_compile_unit. 1076 DwarfCompileUnit & 1077 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) { 1078 if (auto *CU = CUMap.lookup(DIUnit)) 1079 return *CU; 1080 1081 CompilationDir = DIUnit->getDirectory(); 1082 1083 auto OwnedUnit = std::make_unique<DwarfCompileUnit>( 1084 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder); 1085 DwarfCompileUnit &NewCU = *OwnedUnit; 1086 InfoHolder.addUnit(std::move(OwnedUnit)); 1087 1088 for (auto *IE : DIUnit->getImportedEntities()) 1089 NewCU.addImportedEntity(IE); 1090 1091 // LTO with assembly output shares a single line table amongst multiple CUs. 1092 // To avoid the compilation directory being ambiguous, let the line table 1093 // explicitly describe the directory of all files, never relying on the 1094 // compilation directory. 1095 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU) 1096 Asm->OutStreamer->emitDwarfFile0Directive( 1097 CompilationDir, DIUnit->getFilename(), getMD5AsBytes(DIUnit->getFile()), 1098 DIUnit->getSource(), NewCU.getUniqueID()); 1099 1100 if (useSplitDwarf()) { 1101 NewCU.setSkeleton(constructSkeletonCU(NewCU)); 1102 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection()); 1103 } else { 1104 finishUnitAttributes(DIUnit, NewCU); 1105 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 1106 } 1107 1108 CUMap.insert({DIUnit, &NewCU}); 1109 CUDieMap.insert({&NewCU.getUnitDie(), &NewCU}); 1110 return NewCU; 1111 } 1112 1113 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU, 1114 const DIImportedEntity *N) { 1115 if (isa<DILocalScope>(N->getScope())) 1116 return; 1117 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope())) 1118 D->addChild(TheCU.constructImportedEntityDIE(N)); 1119 } 1120 1121 /// Sort and unique GVEs by comparing their fragment offset. 1122 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> & 1123 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) { 1124 llvm::sort( 1125 GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) { 1126 // Sort order: first null exprs, then exprs without fragment 1127 // info, then sort by fragment offset in bits. 1128 // FIXME: Come up with a more comprehensive comparator so 1129 // the sorting isn't non-deterministic, and so the following 1130 // std::unique call works correctly. 1131 if (!A.Expr || !B.Expr) 1132 return !!B.Expr; 1133 auto FragmentA = A.Expr->getFragmentInfo(); 1134 auto FragmentB = B.Expr->getFragmentInfo(); 1135 if (!FragmentA || !FragmentB) 1136 return !!FragmentB; 1137 return FragmentA->OffsetInBits < FragmentB->OffsetInBits; 1138 }); 1139 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(), 1140 [](DwarfCompileUnit::GlobalExpr A, 1141 DwarfCompileUnit::GlobalExpr B) { 1142 return A.Expr == B.Expr; 1143 }), 1144 GVEs.end()); 1145 return GVEs; 1146 } 1147 1148 // Emit all Dwarf sections that should come prior to the content. Create 1149 // global DIEs and emit initial debug info sections. This is invoked by 1150 // the target AsmPrinter. 1151 void DwarfDebug::beginModule(Module *M) { 1152 DebugHandlerBase::beginModule(M); 1153 1154 if (!Asm || !MMI->hasDebugInfo()) 1155 return; 1156 1157 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(), 1158 M->debug_compile_units_end()); 1159 assert(NumDebugCUs > 0 && "Asm unexpectedly initialized"); 1160 assert(MMI->hasDebugInfo() && 1161 "DebugInfoAvailabilty unexpectedly not initialized"); 1162 SingleCU = NumDebugCUs == 1; 1163 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>> 1164 GVMap; 1165 for (const GlobalVariable &Global : M->globals()) { 1166 SmallVector<DIGlobalVariableExpression *, 1> GVs; 1167 Global.getDebugInfo(GVs); 1168 for (auto *GVE : GVs) 1169 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()}); 1170 } 1171 1172 // Create the symbol that designates the start of the unit's contribution 1173 // to the string offsets table. In a split DWARF scenario, only the skeleton 1174 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol). 1175 if (useSegmentedStringOffsetsTable()) 1176 (useSplitDwarf() ? SkeletonHolder : InfoHolder) 1177 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base")); 1178 1179 1180 // Create the symbols that designates the start of the DWARF v5 range list 1181 // and locations list tables. They are located past the table headers. 1182 if (getDwarfVersion() >= 5) { 1183 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1184 Holder.setRnglistsTableBaseSym( 1185 Asm->createTempSymbol("rnglists_table_base")); 1186 1187 if (useSplitDwarf()) 1188 InfoHolder.setRnglistsTableBaseSym( 1189 Asm->createTempSymbol("rnglists_dwo_table_base")); 1190 } 1191 1192 // Create the symbol that points to the first entry following the debug 1193 // address table (.debug_addr) header. 1194 AddrPool.setLabel(Asm->createTempSymbol("addr_table_base")); 1195 DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base")); 1196 1197 for (DICompileUnit *CUNode : M->debug_compile_units()) { 1198 // FIXME: Move local imported entities into a list attached to the 1199 // subprogram, then this search won't be needed and a 1200 // getImportedEntities().empty() test should go below with the rest. 1201 bool HasNonLocalImportedEntities = llvm::any_of( 1202 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) { 1203 return !isa<DILocalScope>(IE->getScope()); 1204 }); 1205 1206 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() && 1207 CUNode->getRetainedTypes().empty() && 1208 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty()) 1209 continue; 1210 1211 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode); 1212 1213 // Global Variables. 1214 for (auto *GVE : CUNode->getGlobalVariables()) { 1215 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we 1216 // already know about the variable and it isn't adding a constant 1217 // expression. 1218 auto &GVMapEntry = GVMap[GVE->getVariable()]; 1219 auto *Expr = GVE->getExpression(); 1220 if (!GVMapEntry.size() || (Expr && Expr->isConstant())) 1221 GVMapEntry.push_back({nullptr, Expr}); 1222 } 1223 DenseSet<DIGlobalVariable *> Processed; 1224 for (auto *GVE : CUNode->getGlobalVariables()) { 1225 DIGlobalVariable *GV = GVE->getVariable(); 1226 if (Processed.insert(GV).second) 1227 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV])); 1228 } 1229 1230 for (auto *Ty : CUNode->getEnumTypes()) { 1231 // The enum types array by design contains pointers to 1232 // MDNodes rather than DIRefs. Unique them here. 1233 CU.getOrCreateTypeDIE(cast<DIType>(Ty)); 1234 } 1235 for (auto *Ty : CUNode->getRetainedTypes()) { 1236 // The retained types array by design contains pointers to 1237 // MDNodes rather than DIRefs. Unique them here. 1238 if (DIType *RT = dyn_cast<DIType>(Ty)) 1239 // There is no point in force-emitting a forward declaration. 1240 CU.getOrCreateTypeDIE(RT); 1241 } 1242 // Emit imported_modules last so that the relevant context is already 1243 // available. 1244 for (auto *IE : CUNode->getImportedEntities()) 1245 constructAndAddImportedEntityDIE(CU, IE); 1246 } 1247 } 1248 1249 void DwarfDebug::finishEntityDefinitions() { 1250 for (const auto &Entity : ConcreteEntities) { 1251 DIE *Die = Entity->getDIE(); 1252 assert(Die); 1253 // FIXME: Consider the time-space tradeoff of just storing the unit pointer 1254 // in the ConcreteEntities list, rather than looking it up again here. 1255 // DIE::getUnit isn't simple - it walks parent pointers, etc. 1256 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie()); 1257 assert(Unit); 1258 Unit->finishEntityDefinition(Entity.get()); 1259 } 1260 } 1261 1262 void DwarfDebug::finishSubprogramDefinitions() { 1263 for (const DISubprogram *SP : ProcessedSPNodes) { 1264 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug); 1265 forBothCUs( 1266 getOrCreateDwarfCompileUnit(SP->getUnit()), 1267 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); }); 1268 } 1269 } 1270 1271 void DwarfDebug::finalizeModuleInfo() { 1272 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 1273 1274 finishSubprogramDefinitions(); 1275 1276 finishEntityDefinitions(); 1277 1278 // Include the DWO file name in the hash if there's more than one CU. 1279 // This handles ThinLTO's situation where imported CUs may very easily be 1280 // duplicate with the same CU partially imported into another ThinLTO unit. 1281 StringRef DWOName; 1282 if (CUMap.size() > 1) 1283 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile; 1284 1285 // Handle anything that needs to be done on a per-unit basis after 1286 // all other generation. 1287 for (const auto &P : CUMap) { 1288 auto &TheCU = *P.second; 1289 if (TheCU.getCUNode()->isDebugDirectivesOnly()) 1290 continue; 1291 // Emit DW_AT_containing_type attribute to connect types with their 1292 // vtable holding type. 1293 TheCU.constructContainingTypeDIEs(); 1294 1295 // Add CU specific attributes if we need to add any. 1296 // If we're splitting the dwarf out now that we've got the entire 1297 // CU then add the dwo id to it. 1298 auto *SkCU = TheCU.getSkeleton(); 1299 1300 bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty(); 1301 1302 if (HasSplitUnit) { 1303 dwarf::Attribute attrDWOName = getDwarfVersion() >= 5 1304 ? dwarf::DW_AT_dwo_name 1305 : dwarf::DW_AT_GNU_dwo_name; 1306 finishUnitAttributes(TheCU.getCUNode(), TheCU); 1307 TheCU.addString(TheCU.getUnitDie(), attrDWOName, 1308 Asm->TM.Options.MCOptions.SplitDwarfFile); 1309 SkCU->addString(SkCU->getUnitDie(), attrDWOName, 1310 Asm->TM.Options.MCOptions.SplitDwarfFile); 1311 // Emit a unique identifier for this CU. 1312 uint64_t ID = 1313 DIEHash(Asm, &TheCU).computeCUSignature(DWOName, TheCU.getUnitDie()); 1314 if (getDwarfVersion() >= 5) { 1315 TheCU.setDWOId(ID); 1316 SkCU->setDWOId(ID); 1317 } else { 1318 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 1319 dwarf::DW_FORM_data8, ID); 1320 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 1321 dwarf::DW_FORM_data8, ID); 1322 } 1323 1324 if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) { 1325 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol(); 1326 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base, 1327 Sym, Sym); 1328 } 1329 } else if (SkCU) { 1330 finishUnitAttributes(SkCU->getCUNode(), *SkCU); 1331 } 1332 1333 // If we have code split among multiple sections or non-contiguous 1334 // ranges of code then emit a DW_AT_ranges attribute on the unit that will 1335 // remain in the .o file, otherwise add a DW_AT_low_pc. 1336 // FIXME: We should use ranges allow reordering of code ala 1337 // .subsections_via_symbols in mach-o. This would mean turning on 1338 // ranges for all subprogram DIEs for mach-o. 1339 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 1340 1341 if (unsigned NumRanges = TheCU.getRanges().size()) { 1342 if (NumRanges > 1 && useRangesSection()) 1343 // A DW_AT_low_pc attribute may also be specified in combination with 1344 // DW_AT_ranges to specify the default base address for use in 1345 // location lists (see Section 2.6.2) and range lists (see Section 1346 // 2.17.3). 1347 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0); 1348 else 1349 U.setBaseAddress(TheCU.getRanges().front().Begin); 1350 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges()); 1351 } 1352 1353 // We don't keep track of which addresses are used in which CU so this 1354 // is a bit pessimistic under LTO. 1355 if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty()) 1356 U.addAddrTableBase(); 1357 1358 if (getDwarfVersion() >= 5) { 1359 if (U.hasRangeLists()) 1360 U.addRnglistsBase(); 1361 1362 if (!DebugLocs.getLists().empty()) { 1363 if (!useSplitDwarf()) 1364 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base, 1365 DebugLocs.getSym(), 1366 TLOF.getDwarfLoclistsSection()->getBeginSymbol()); 1367 } 1368 } 1369 1370 auto *CUNode = cast<DICompileUnit>(P.first); 1371 // If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros" 1372 // attribute. 1373 if (CUNode->getMacros()) { 1374 if (UseDebugMacroSection) { 1375 if (useSplitDwarf()) 1376 TheCU.addSectionDelta( 1377 TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(), 1378 TLOF.getDwarfMacroDWOSection()->getBeginSymbol()); 1379 else { 1380 dwarf::Attribute MacrosAttr = getDwarfVersion() >= 5 1381 ? dwarf::DW_AT_macros 1382 : dwarf::DW_AT_GNU_macros; 1383 U.addSectionLabel(U.getUnitDie(), MacrosAttr, U.getMacroLabelBegin(), 1384 TLOF.getDwarfMacroSection()->getBeginSymbol()); 1385 } 1386 } else { 1387 if (useSplitDwarf()) 1388 TheCU.addSectionDelta( 1389 TheCU.getUnitDie(), dwarf::DW_AT_macro_info, 1390 U.getMacroLabelBegin(), 1391 TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol()); 1392 else 1393 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info, 1394 U.getMacroLabelBegin(), 1395 TLOF.getDwarfMacinfoSection()->getBeginSymbol()); 1396 } 1397 } 1398 } 1399 1400 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules. 1401 for (auto *CUNode : MMI->getModule()->debug_compile_units()) 1402 if (CUNode->getDWOId()) 1403 getOrCreateDwarfCompileUnit(CUNode); 1404 1405 // Compute DIE offsets and sizes. 1406 InfoHolder.computeSizeAndOffsets(); 1407 if (useSplitDwarf()) 1408 SkeletonHolder.computeSizeAndOffsets(); 1409 } 1410 1411 // Emit all Dwarf sections that should come after the content. 1412 void DwarfDebug::endModule() { 1413 assert(CurFn == nullptr); 1414 assert(CurMI == nullptr); 1415 1416 for (const auto &P : CUMap) { 1417 auto &CU = *P.second; 1418 CU.createBaseTypeDIEs(); 1419 } 1420 1421 // If we aren't actually generating debug info (check beginModule - 1422 // conditionalized on the presence of the llvm.dbg.cu metadata node) 1423 if (!Asm || !MMI->hasDebugInfo()) 1424 return; 1425 1426 // Finalize the debug info for the module. 1427 finalizeModuleInfo(); 1428 1429 if (useSplitDwarf()) 1430 // Emit debug_loc.dwo/debug_loclists.dwo section. 1431 emitDebugLocDWO(); 1432 else 1433 // Emit debug_loc/debug_loclists section. 1434 emitDebugLoc(); 1435 1436 // Corresponding abbreviations into a abbrev section. 1437 emitAbbreviations(); 1438 1439 // Emit all the DIEs into a debug info section. 1440 emitDebugInfo(); 1441 1442 // Emit info into a debug aranges section. 1443 if (GenerateARangeSection) 1444 emitDebugARanges(); 1445 1446 // Emit info into a debug ranges section. 1447 emitDebugRanges(); 1448 1449 if (useSplitDwarf()) 1450 // Emit info into a debug macinfo.dwo section. 1451 emitDebugMacinfoDWO(); 1452 else 1453 // Emit info into a debug macinfo/macro section. 1454 emitDebugMacinfo(); 1455 1456 emitDebugStr(); 1457 1458 if (useSplitDwarf()) { 1459 emitDebugStrDWO(); 1460 emitDebugInfoDWO(); 1461 emitDebugAbbrevDWO(); 1462 emitDebugLineDWO(); 1463 emitDebugRangesDWO(); 1464 } 1465 1466 emitDebugAddr(); 1467 1468 // Emit info into the dwarf accelerator table sections. 1469 switch (getAccelTableKind()) { 1470 case AccelTableKind::Apple: 1471 emitAccelNames(); 1472 emitAccelObjC(); 1473 emitAccelNamespaces(); 1474 emitAccelTypes(); 1475 break; 1476 case AccelTableKind::Dwarf: 1477 emitAccelDebugNames(); 1478 break; 1479 case AccelTableKind::None: 1480 break; 1481 case AccelTableKind::Default: 1482 llvm_unreachable("Default should have already been resolved."); 1483 } 1484 1485 // Emit the pubnames and pubtypes sections if requested. 1486 emitDebugPubSections(); 1487 1488 // clean up. 1489 // FIXME: AbstractVariables.clear(); 1490 } 1491 1492 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU, 1493 const DINode *Node, 1494 const MDNode *ScopeNode) { 1495 if (CU.getExistingAbstractEntity(Node)) 1496 return; 1497 1498 CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope( 1499 cast<DILocalScope>(ScopeNode))); 1500 } 1501 1502 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU, 1503 const DINode *Node, const MDNode *ScopeNode) { 1504 if (CU.getExistingAbstractEntity(Node)) 1505 return; 1506 1507 if (LexicalScope *Scope = 1508 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode))) 1509 CU.createAbstractEntity(Node, Scope); 1510 } 1511 1512 // Collect variable information from side table maintained by MF. 1513 void DwarfDebug::collectVariableInfoFromMFTable( 1514 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) { 1515 SmallDenseMap<InlinedEntity, DbgVariable *> MFVars; 1516 LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n"); 1517 for (const auto &VI : Asm->MF->getVariableDbgInfo()) { 1518 if (!VI.Var) 1519 continue; 1520 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 1521 "Expected inlined-at fields to agree"); 1522 1523 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt()); 1524 Processed.insert(Var); 1525 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 1526 1527 // If variable scope is not found then skip this variable. 1528 if (!Scope) { 1529 LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName() 1530 << ", no variable scope found\n"); 1531 continue; 1532 } 1533 1534 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode()); 1535 auto RegVar = std::make_unique<DbgVariable>( 1536 cast<DILocalVariable>(Var.first), Var.second); 1537 RegVar->initializeMMI(VI.Expr, VI.Slot); 1538 LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName() 1539 << "\n"); 1540 if (DbgVariable *DbgVar = MFVars.lookup(Var)) 1541 DbgVar->addMMIEntry(*RegVar); 1542 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) { 1543 MFVars.insert({Var, RegVar.get()}); 1544 ConcreteEntities.push_back(std::move(RegVar)); 1545 } 1546 } 1547 } 1548 1549 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its 1550 /// enclosing lexical scope. The check ensures there are no other instructions 1551 /// in the same lexical scope preceding the DBG_VALUE and that its range is 1552 /// either open or otherwise rolls off the end of the scope. 1553 static bool validThroughout(LexicalScopes &LScopes, 1554 const MachineInstr *DbgValue, 1555 const MachineInstr *RangeEnd, 1556 const InstructionOrdering &Ordering) { 1557 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location"); 1558 auto MBB = DbgValue->getParent(); 1559 auto DL = DbgValue->getDebugLoc(); 1560 auto *LScope = LScopes.findLexicalScope(DL); 1561 // Scope doesn't exist; this is a dead DBG_VALUE. 1562 if (!LScope) 1563 return false; 1564 auto &LSRange = LScope->getRanges(); 1565 if (LSRange.size() == 0) 1566 return false; 1567 1568 const MachineInstr *LScopeBegin = LSRange.front().first; 1569 // If the scope starts before the DBG_VALUE then we may have a negative 1570 // result. Otherwise the location is live coming into the scope and we 1571 // can skip the following checks. 1572 if (!Ordering.isBefore(DbgValue, LScopeBegin)) { 1573 // Exit if the lexical scope begins outside of the current block. 1574 if (LScopeBegin->getParent() != MBB) 1575 return false; 1576 1577 MachineBasicBlock::const_reverse_iterator Pred(DbgValue); 1578 for (++Pred; Pred != MBB->rend(); ++Pred) { 1579 if (Pred->getFlag(MachineInstr::FrameSetup)) 1580 break; 1581 auto PredDL = Pred->getDebugLoc(); 1582 if (!PredDL || Pred->isMetaInstruction()) 1583 continue; 1584 // Check whether the instruction preceding the DBG_VALUE is in the same 1585 // (sub)scope as the DBG_VALUE. 1586 if (DL->getScope() == PredDL->getScope()) 1587 return false; 1588 auto *PredScope = LScopes.findLexicalScope(PredDL); 1589 if (!PredScope || LScope->dominates(PredScope)) 1590 return false; 1591 } 1592 } 1593 1594 // If the range of the DBG_VALUE is open-ended, report success. 1595 if (!RangeEnd) 1596 return true; 1597 1598 // Single, constant DBG_VALUEs in the prologue are promoted to be live 1599 // throughout the function. This is a hack, presumably for DWARF v2 and not 1600 // necessarily correct. It would be much better to use a dbg.declare instead 1601 // if we know the constant is live throughout the scope. 1602 if (DbgValue->getDebugOperand(0).isImm() && MBB->pred_empty()) 1603 return true; 1604 1605 // Test if the location terminates before the end of the scope. 1606 const MachineInstr *LScopeEnd = LSRange.back().second; 1607 if (Ordering.isBefore(RangeEnd, LScopeEnd)) 1608 return false; 1609 1610 // There's a single location which starts at the scope start, and ends at or 1611 // after the scope end. 1612 return true; 1613 } 1614 1615 /// Build the location list for all DBG_VALUEs in the function that 1616 /// describe the same variable. The resulting DebugLocEntries will have 1617 /// strict monotonically increasing begin addresses and will never 1618 /// overlap. If the resulting list has only one entry that is valid 1619 /// throughout variable's scope return true. 1620 // 1621 // See the definition of DbgValueHistoryMap::Entry for an explanation of the 1622 // different kinds of history map entries. One thing to be aware of is that if 1623 // a debug value is ended by another entry (rather than being valid until the 1624 // end of the function), that entry's instruction may or may not be included in 1625 // the range, depending on if the entry is a clobbering entry (it has an 1626 // instruction that clobbers one or more preceding locations), or if it is an 1627 // (overlapping) debug value entry. This distinction can be seen in the example 1628 // below. The first debug value is ended by the clobbering entry 2, and the 1629 // second and third debug values are ended by the overlapping debug value entry 1630 // 4. 1631 // 1632 // Input: 1633 // 1634 // History map entries [type, end index, mi] 1635 // 1636 // 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)] 1637 // 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)] 1638 // 2 | | [Clobber, $reg0 = [...], -, -] 1639 // 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)] 1640 // 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)] 1641 // 1642 // Output [start, end) [Value...]: 1643 // 1644 // [0-1) [(reg0, fragment 0, 32)] 1645 // [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)] 1646 // [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)] 1647 // [4-) [(@g, fragment 0, 96)] 1648 bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc, 1649 const DbgValueHistoryMap::Entries &Entries) { 1650 using OpenRange = 1651 std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>; 1652 SmallVector<OpenRange, 4> OpenRanges; 1653 bool isSafeForSingleLocation = true; 1654 const MachineInstr *StartDebugMI = nullptr; 1655 const MachineInstr *EndMI = nullptr; 1656 1657 for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) { 1658 const MachineInstr *Instr = EI->getInstr(); 1659 1660 // Remove all values that are no longer live. 1661 size_t Index = std::distance(EB, EI); 1662 erase_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; }); 1663 1664 // If we are dealing with a clobbering entry, this iteration will result in 1665 // a location list entry starting after the clobbering instruction. 1666 const MCSymbol *StartLabel = 1667 EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr); 1668 assert(StartLabel && 1669 "Forgot label before/after instruction starting a range!"); 1670 1671 const MCSymbol *EndLabel; 1672 if (std::next(EI) == Entries.end()) { 1673 const MachineBasicBlock &EndMBB = Asm->MF->back(); 1674 EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionIDNum()].EndLabel; 1675 if (EI->isClobber()) 1676 EndMI = EI->getInstr(); 1677 } 1678 else if (std::next(EI)->isClobber()) 1679 EndLabel = getLabelAfterInsn(std::next(EI)->getInstr()); 1680 else 1681 EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr()); 1682 assert(EndLabel && "Forgot label after instruction ending a range!"); 1683 1684 if (EI->isDbgValue()) 1685 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n"); 1686 1687 // If this history map entry has a debug value, add that to the list of 1688 // open ranges and check if its location is valid for a single value 1689 // location. 1690 if (EI->isDbgValue()) { 1691 // Do not add undef debug values, as they are redundant information in 1692 // the location list entries. An undef debug results in an empty location 1693 // description. If there are any non-undef fragments then padding pieces 1694 // with empty location descriptions will automatically be inserted, and if 1695 // all fragments are undef then the whole location list entry is 1696 // redundant. 1697 if (!Instr->isUndefDebugValue()) { 1698 auto Value = getDebugLocValue(Instr); 1699 OpenRanges.emplace_back(EI->getEndIndex(), Value); 1700 1701 // TODO: Add support for single value fragment locations. 1702 if (Instr->getDebugExpression()->isFragment()) 1703 isSafeForSingleLocation = false; 1704 1705 if (!StartDebugMI) 1706 StartDebugMI = Instr; 1707 } else { 1708 isSafeForSingleLocation = false; 1709 } 1710 } 1711 1712 // Location list entries with empty location descriptions are redundant 1713 // information in DWARF, so do not emit those. 1714 if (OpenRanges.empty()) 1715 continue; 1716 1717 // Omit entries with empty ranges as they do not have any effect in DWARF. 1718 if (StartLabel == EndLabel) { 1719 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n"); 1720 continue; 1721 } 1722 1723 SmallVector<DbgValueLoc, 4> Values; 1724 for (auto &R : OpenRanges) 1725 Values.push_back(R.second); 1726 DebugLoc.emplace_back(StartLabel, EndLabel, Values); 1727 1728 // Attempt to coalesce the ranges of two otherwise identical 1729 // DebugLocEntries. 1730 auto CurEntry = DebugLoc.rbegin(); 1731 LLVM_DEBUG({ 1732 dbgs() << CurEntry->getValues().size() << " Values:\n"; 1733 for (auto &Value : CurEntry->getValues()) 1734 Value.dump(); 1735 dbgs() << "-----\n"; 1736 }); 1737 1738 auto PrevEntry = std::next(CurEntry); 1739 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry)) 1740 DebugLoc.pop_back(); 1741 } 1742 1743 return DebugLoc.size() == 1 && isSafeForSingleLocation && 1744 validThroughout(LScopes, StartDebugMI, EndMI, getInstOrdering()); 1745 } 1746 1747 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU, 1748 LexicalScope &Scope, 1749 const DINode *Node, 1750 const DILocation *Location, 1751 const MCSymbol *Sym) { 1752 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode()); 1753 if (isa<const DILocalVariable>(Node)) { 1754 ConcreteEntities.push_back( 1755 std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node), 1756 Location)); 1757 InfoHolder.addScopeVariable(&Scope, 1758 cast<DbgVariable>(ConcreteEntities.back().get())); 1759 } else if (isa<const DILabel>(Node)) { 1760 ConcreteEntities.push_back( 1761 std::make_unique<DbgLabel>(cast<const DILabel>(Node), 1762 Location, Sym)); 1763 InfoHolder.addScopeLabel(&Scope, 1764 cast<DbgLabel>(ConcreteEntities.back().get())); 1765 } 1766 return ConcreteEntities.back().get(); 1767 } 1768 1769 // Find variables for each lexical scope. 1770 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU, 1771 const DISubprogram *SP, 1772 DenseSet<InlinedEntity> &Processed) { 1773 // Grab the variable info that was squirreled away in the MMI side-table. 1774 collectVariableInfoFromMFTable(TheCU, Processed); 1775 1776 for (const auto &I : DbgValues) { 1777 InlinedEntity IV = I.first; 1778 if (Processed.count(IV)) 1779 continue; 1780 1781 // Instruction ranges, specifying where IV is accessible. 1782 const auto &HistoryMapEntries = I.second; 1783 if (HistoryMapEntries.empty()) 1784 continue; 1785 1786 LexicalScope *Scope = nullptr; 1787 const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first); 1788 if (const DILocation *IA = IV.second) 1789 Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA); 1790 else 1791 Scope = LScopes.findLexicalScope(LocalVar->getScope()); 1792 // If variable scope is not found then skip this variable. 1793 if (!Scope) 1794 continue; 1795 1796 Processed.insert(IV); 1797 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU, 1798 *Scope, LocalVar, IV.second)); 1799 1800 const MachineInstr *MInsn = HistoryMapEntries.front().getInstr(); 1801 assert(MInsn->isDebugValue() && "History must begin with debug value"); 1802 1803 // Check if there is a single DBG_VALUE, valid throughout the var's scope. 1804 // If the history map contains a single debug value, there may be an 1805 // additional entry which clobbers the debug value. 1806 size_t HistSize = HistoryMapEntries.size(); 1807 bool SingleValueWithClobber = 1808 HistSize == 2 && HistoryMapEntries[1].isClobber(); 1809 if (HistSize == 1 || SingleValueWithClobber) { 1810 const auto *End = 1811 SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr; 1812 if (validThroughout(LScopes, MInsn, End, getInstOrdering())) { 1813 RegVar->initializeDbgValue(MInsn); 1814 continue; 1815 } 1816 } 1817 1818 // Do not emit location lists if .debug_loc secton is disabled. 1819 if (!useLocSection()) 1820 continue; 1821 1822 // Handle multiple DBG_VALUE instructions describing one variable. 1823 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn); 1824 1825 // Build the location list for this variable. 1826 SmallVector<DebugLocEntry, 8> Entries; 1827 bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries); 1828 1829 // Check whether buildLocationList managed to merge all locations to one 1830 // that is valid throughout the variable's scope. If so, produce single 1831 // value location. 1832 if (isValidSingleLocation) { 1833 RegVar->initializeDbgValue(Entries[0].getValues()[0]); 1834 continue; 1835 } 1836 1837 // If the variable has a DIBasicType, extract it. Basic types cannot have 1838 // unique identifiers, so don't bother resolving the type with the 1839 // identifier map. 1840 const DIBasicType *BT = dyn_cast<DIBasicType>( 1841 static_cast<const Metadata *>(LocalVar->getType())); 1842 1843 // Finalize the entry by lowering it into a DWARF bytestream. 1844 for (auto &Entry : Entries) 1845 Entry.finalize(*Asm, List, BT, TheCU); 1846 } 1847 1848 // For each InlinedEntity collected from DBG_LABEL instructions, convert to 1849 // DWARF-related DbgLabel. 1850 for (const auto &I : DbgLabels) { 1851 InlinedEntity IL = I.first; 1852 const MachineInstr *MI = I.second; 1853 if (MI == nullptr) 1854 continue; 1855 1856 LexicalScope *Scope = nullptr; 1857 const DILabel *Label = cast<DILabel>(IL.first); 1858 // The scope could have an extra lexical block file. 1859 const DILocalScope *LocalScope = 1860 Label->getScope()->getNonLexicalBlockFileScope(); 1861 // Get inlined DILocation if it is inlined label. 1862 if (const DILocation *IA = IL.second) 1863 Scope = LScopes.findInlinedScope(LocalScope, IA); 1864 else 1865 Scope = LScopes.findLexicalScope(LocalScope); 1866 // If label scope is not found then skip this label. 1867 if (!Scope) 1868 continue; 1869 1870 Processed.insert(IL); 1871 /// At this point, the temporary label is created. 1872 /// Save the temporary label to DbgLabel entity to get the 1873 /// actually address when generating Dwarf DIE. 1874 MCSymbol *Sym = getLabelBeforeInsn(MI); 1875 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym); 1876 } 1877 1878 // Collect info for variables/labels that were optimized out. 1879 for (const DINode *DN : SP->getRetainedNodes()) { 1880 if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 1881 continue; 1882 LexicalScope *Scope = nullptr; 1883 if (auto *DV = dyn_cast<DILocalVariable>(DN)) { 1884 Scope = LScopes.findLexicalScope(DV->getScope()); 1885 } else if (auto *DL = dyn_cast<DILabel>(DN)) { 1886 Scope = LScopes.findLexicalScope(DL->getScope()); 1887 } 1888 1889 if (Scope) 1890 createConcreteEntity(TheCU, *Scope, DN, nullptr); 1891 } 1892 } 1893 1894 // Process beginning of an instruction. 1895 void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1896 const MachineFunction &MF = *MI->getMF(); 1897 const auto *SP = MF.getFunction().getSubprogram(); 1898 bool NoDebug = 1899 !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug; 1900 1901 // Delay slot support check. 1902 auto delaySlotSupported = [](const MachineInstr &MI) { 1903 if (!MI.isBundledWithSucc()) 1904 return false; 1905 auto Suc = std::next(MI.getIterator()); 1906 (void)Suc; 1907 // Ensure that delay slot instruction is successor of the call instruction. 1908 // Ex. CALL_INSTRUCTION { 1909 // DELAY_SLOT_INSTRUCTION } 1910 assert(Suc->isBundledWithPred() && 1911 "Call bundle instructions are out of order"); 1912 return true; 1913 }; 1914 1915 // When describing calls, we need a label for the call instruction. 1916 if (!NoDebug && SP->areAllCallsDescribed() && 1917 MI->isCandidateForCallSiteEntry(MachineInstr::AnyInBundle) && 1918 (!MI->hasDelaySlot() || delaySlotSupported(*MI))) { 1919 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 1920 bool IsTail = TII->isTailCall(*MI); 1921 // For tail calls, we need the address of the branch instruction for 1922 // DW_AT_call_pc. 1923 if (IsTail) 1924 requestLabelBeforeInsn(MI); 1925 // For non-tail calls, we need the return address for the call for 1926 // DW_AT_call_return_pc. Under GDB tuning, this information is needed for 1927 // tail calls as well. 1928 requestLabelAfterInsn(MI); 1929 } 1930 1931 DebugHandlerBase::beginInstruction(MI); 1932 if (!CurMI) 1933 return; 1934 1935 if (NoDebug) 1936 return; 1937 1938 // Check if source location changes, but ignore DBG_VALUE and CFI locations. 1939 // If the instruction is part of the function frame setup code, do not emit 1940 // any line record, as there is no correspondence with any user code. 1941 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup)) 1942 return; 1943 const DebugLoc &DL = MI->getDebugLoc(); 1944 // When we emit a line-0 record, we don't update PrevInstLoc; so look at 1945 // the last line number actually emitted, to see if it was line 0. 1946 unsigned LastAsmLine = 1947 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine(); 1948 1949 if (DL == PrevInstLoc) { 1950 // If we have an ongoing unspecified location, nothing to do here. 1951 if (!DL) 1952 return; 1953 // We have an explicit location, same as the previous location. 1954 // But we might be coming back to it after a line 0 record. 1955 if (LastAsmLine == 0 && DL.getLine() != 0) { 1956 // Reinstate the source location but not marked as a statement. 1957 const MDNode *Scope = DL.getScope(); 1958 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0); 1959 } 1960 return; 1961 } 1962 1963 if (!DL) { 1964 // We have an unspecified location, which might want to be line 0. 1965 // If we have already emitted a line-0 record, don't repeat it. 1966 if (LastAsmLine == 0) 1967 return; 1968 // If user said Don't Do That, don't do that. 1969 if (UnknownLocations == Disable) 1970 return; 1971 // See if we have a reason to emit a line-0 record now. 1972 // Reasons to emit a line-0 record include: 1973 // - User asked for it (UnknownLocations). 1974 // - Instruction has a label, so it's referenced from somewhere else, 1975 // possibly debug information; we want it to have a source location. 1976 // - Instruction is at the top of a block; we don't want to inherit the 1977 // location from the physically previous (maybe unrelated) block. 1978 if (UnknownLocations == Enable || PrevLabel || 1979 (PrevInstBB && PrevInstBB != MI->getParent())) { 1980 // Preserve the file and column numbers, if we can, to save space in 1981 // the encoded line table. 1982 // Do not update PrevInstLoc, it remembers the last non-0 line. 1983 const MDNode *Scope = nullptr; 1984 unsigned Column = 0; 1985 if (PrevInstLoc) { 1986 Scope = PrevInstLoc.getScope(); 1987 Column = PrevInstLoc.getCol(); 1988 } 1989 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0); 1990 } 1991 return; 1992 } 1993 1994 // We have an explicit location, different from the previous location. 1995 // Don't repeat a line-0 record, but otherwise emit the new location. 1996 // (The new location might be an explicit line 0, which we do emit.) 1997 if (DL.getLine() == 0 && LastAsmLine == 0) 1998 return; 1999 unsigned Flags = 0; 2000 if (DL == PrologEndLoc) { 2001 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT; 2002 PrologEndLoc = DebugLoc(); 2003 } 2004 // If the line changed, we call that a new statement; unless we went to 2005 // line 0 and came back, in which case it is not a new statement. 2006 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine; 2007 if (DL.getLine() && DL.getLine() != OldLine) 2008 Flags |= DWARF2_FLAG_IS_STMT; 2009 2010 const MDNode *Scope = DL.getScope(); 2011 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 2012 2013 // If we're not at line 0, remember this location. 2014 if (DL.getLine()) 2015 PrevInstLoc = DL; 2016 } 2017 2018 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) { 2019 // First known non-DBG_VALUE and non-frame setup location marks 2020 // the beginning of the function body. 2021 for (const auto &MBB : *MF) 2022 for (const auto &MI : MBB) 2023 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) && 2024 MI.getDebugLoc()) 2025 return MI.getDebugLoc(); 2026 return DebugLoc(); 2027 } 2028 2029 /// Register a source line with debug info. Returns the unique label that was 2030 /// emitted and which provides correspondence to the source line list. 2031 static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col, 2032 const MDNode *S, unsigned Flags, unsigned CUID, 2033 uint16_t DwarfVersion, 2034 ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) { 2035 StringRef Fn; 2036 unsigned FileNo = 1; 2037 unsigned Discriminator = 0; 2038 if (auto *Scope = cast_or_null<DIScope>(S)) { 2039 Fn = Scope->getFilename(); 2040 if (Line != 0 && DwarfVersion >= 4) 2041 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope)) 2042 Discriminator = LBF->getDiscriminator(); 2043 2044 FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID]) 2045 .getOrCreateSourceID(Scope->getFile()); 2046 } 2047 Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0, 2048 Discriminator, Fn); 2049 } 2050 2051 DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF, 2052 unsigned CUID) { 2053 // Get beginning of function. 2054 if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) { 2055 // Ensure the compile unit is created if the function is called before 2056 // beginFunction(). 2057 (void)getOrCreateDwarfCompileUnit( 2058 MF.getFunction().getSubprogram()->getUnit()); 2059 // We'd like to list the prologue as "not statements" but GDB behaves 2060 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 2061 const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram(); 2062 ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT, 2063 CUID, getDwarfVersion(), getUnits()); 2064 return PrologEndLoc; 2065 } 2066 return DebugLoc(); 2067 } 2068 2069 // Gather pre-function debug information. Assumes being called immediately 2070 // after the function entry point has been emitted. 2071 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) { 2072 CurFn = MF; 2073 2074 auto *SP = MF->getFunction().getSubprogram(); 2075 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode()); 2076 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 2077 return; 2078 2079 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 2080 2081 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 2082 // belongs to so that we add to the correct per-cu line table in the 2083 // non-asm case. 2084 if (Asm->OutStreamer->hasRawTextSupport()) 2085 // Use a single line table if we are generating assembly. 2086 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 2087 else 2088 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID()); 2089 2090 // Record beginning of function. 2091 PrologEndLoc = emitInitialLocDirective( 2092 *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID()); 2093 } 2094 2095 void DwarfDebug::skippedNonDebugFunction() { 2096 // If we don't have a subprogram for this function then there will be a hole 2097 // in the range information. Keep note of this by setting the previously used 2098 // section to nullptr. 2099 PrevCU = nullptr; 2100 CurFn = nullptr; 2101 } 2102 2103 // Gather and emit post-function debug information. 2104 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) { 2105 const DISubprogram *SP = MF->getFunction().getSubprogram(); 2106 2107 assert(CurFn == MF && 2108 "endFunction should be called with the same function as beginFunction"); 2109 2110 // Set DwarfDwarfCompileUnitID in MCContext to default value. 2111 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 2112 2113 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 2114 assert(!FnScope || SP == FnScope->getScopeNode()); 2115 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit()); 2116 if (TheCU.getCUNode()->isDebugDirectivesOnly()) { 2117 PrevLabel = nullptr; 2118 CurFn = nullptr; 2119 return; 2120 } 2121 2122 DenseSet<InlinedEntity> Processed; 2123 collectEntityInfo(TheCU, SP, Processed); 2124 2125 // Add the range of this function to the list of ranges for the CU. 2126 // With basic block sections, add ranges for all basic block sections. 2127 for (const auto &R : Asm->MBBSectionRanges) 2128 TheCU.addRange({R.second.BeginLabel, R.second.EndLabel}); 2129 2130 // Under -gmlt, skip building the subprogram if there are no inlined 2131 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram 2132 // is still needed as we need its source location. 2133 if (!TheCU.getCUNode()->getDebugInfoForProfiling() && 2134 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly && 2135 LScopes.getAbstractScopesList().empty() && !IsDarwin) { 2136 assert(InfoHolder.getScopeVariables().empty()); 2137 PrevLabel = nullptr; 2138 CurFn = nullptr; 2139 return; 2140 } 2141 2142 #ifndef NDEBUG 2143 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size(); 2144 #endif 2145 // Construct abstract scopes. 2146 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) { 2147 auto *SP = cast<DISubprogram>(AScope->getScopeNode()); 2148 for (const DINode *DN : SP->getRetainedNodes()) { 2149 if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 2150 continue; 2151 2152 const MDNode *Scope = nullptr; 2153 if (auto *DV = dyn_cast<DILocalVariable>(DN)) 2154 Scope = DV->getScope(); 2155 else if (auto *DL = dyn_cast<DILabel>(DN)) 2156 Scope = DL->getScope(); 2157 else 2158 llvm_unreachable("Unexpected DI type!"); 2159 2160 // Collect info for variables/labels that were optimized out. 2161 ensureAbstractEntityIsCreated(TheCU, DN, Scope); 2162 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes 2163 && "ensureAbstractEntityIsCreated inserted abstract scopes"); 2164 } 2165 constructAbstractSubprogramScopeDIE(TheCU, AScope); 2166 } 2167 2168 ProcessedSPNodes.insert(SP); 2169 DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope); 2170 if (auto *SkelCU = TheCU.getSkeleton()) 2171 if (!LScopes.getAbstractScopesList().empty() && 2172 TheCU.getCUNode()->getSplitDebugInlining()) 2173 SkelCU->constructSubprogramScopeDIE(SP, FnScope); 2174 2175 // Construct call site entries. 2176 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF); 2177 2178 // Clear debug info 2179 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the 2180 // DbgVariables except those that are also in AbstractVariables (since they 2181 // can be used cross-function) 2182 InfoHolder.getScopeVariables().clear(); 2183 InfoHolder.getScopeLabels().clear(); 2184 PrevLabel = nullptr; 2185 CurFn = nullptr; 2186 } 2187 2188 // Register a source line with debug info. Returns the unique label that was 2189 // emitted and which provides correspondence to the source line list. 2190 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 2191 unsigned Flags) { 2192 ::recordSourceLine(*Asm, Line, Col, S, Flags, 2193 Asm->OutStreamer->getContext().getDwarfCompileUnitID(), 2194 getDwarfVersion(), getUnits()); 2195 } 2196 2197 //===----------------------------------------------------------------------===// 2198 // Emit Methods 2199 //===----------------------------------------------------------------------===// 2200 2201 // Emit the debug info section. 2202 void DwarfDebug::emitDebugInfo() { 2203 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2204 Holder.emitUnits(/* UseOffsets */ false); 2205 } 2206 2207 // Emit the abbreviation section. 2208 void DwarfDebug::emitAbbreviations() { 2209 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2210 2211 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection()); 2212 } 2213 2214 void DwarfDebug::emitStringOffsetsTableHeader() { 2215 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2216 Holder.getStringPool().emitStringOffsetsTableHeader( 2217 *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(), 2218 Holder.getStringOffsetsStartSym()); 2219 } 2220 2221 template <typename AccelTableT> 2222 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section, 2223 StringRef TableName) { 2224 Asm->OutStreamer->SwitchSection(Section); 2225 2226 // Emit the full data. 2227 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol()); 2228 } 2229 2230 void DwarfDebug::emitAccelDebugNames() { 2231 // Don't emit anything if we have no compilation units to index. 2232 if (getUnits().empty()) 2233 return; 2234 2235 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits()); 2236 } 2237 2238 // Emit visible names into a hashed accelerator table section. 2239 void DwarfDebug::emitAccelNames() { 2240 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(), 2241 "Names"); 2242 } 2243 2244 // Emit objective C classes and categories into a hashed accelerator table 2245 // section. 2246 void DwarfDebug::emitAccelObjC() { 2247 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(), 2248 "ObjC"); 2249 } 2250 2251 // Emit namespace dies into a hashed accelerator table. 2252 void DwarfDebug::emitAccelNamespaces() { 2253 emitAccel(AccelNamespace, 2254 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(), 2255 "namespac"); 2256 } 2257 2258 // Emit type dies into a hashed accelerator table. 2259 void DwarfDebug::emitAccelTypes() { 2260 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(), 2261 "types"); 2262 } 2263 2264 // Public name handling. 2265 // The format for the various pubnames: 2266 // 2267 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU 2268 // for the DIE that is named. 2269 // 2270 // gnu pubnames - offset/index value/name tuples where the offset is the offset 2271 // into the CU and the index value is computed according to the type of value 2272 // for the DIE that is named. 2273 // 2274 // For type units the offset is the offset of the skeleton DIE. For split dwarf 2275 // it's the offset within the debug_info/debug_types dwo section, however, the 2276 // reference in the pubname header doesn't change. 2277 2278 /// computeIndexValue - Compute the gdb index value for the DIE and CU. 2279 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, 2280 const DIE *Die) { 2281 // Entities that ended up only in a Type Unit reference the CU instead (since 2282 // the pub entry has offsets within the CU there's no real offset that can be 2283 // provided anyway). As it happens all such entities (namespaces and types, 2284 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out 2285 // not to be true it would be necessary to persist this information from the 2286 // point at which the entry is added to the index data structure - since by 2287 // the time the index is built from that, the original type/namespace DIE in a 2288 // type unit has already been destroyed so it can't be queried for properties 2289 // like tag, etc. 2290 if (Die->getTag() == dwarf::DW_TAG_compile_unit) 2291 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, 2292 dwarf::GIEL_EXTERNAL); 2293 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC; 2294 2295 // We could have a specification DIE that has our most of our knowledge, 2296 // look for that now. 2297 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) { 2298 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry(); 2299 if (SpecDIE.findAttribute(dwarf::DW_AT_external)) 2300 Linkage = dwarf::GIEL_EXTERNAL; 2301 } else if (Die->findAttribute(dwarf::DW_AT_external)) 2302 Linkage = dwarf::GIEL_EXTERNAL; 2303 2304 switch (Die->getTag()) { 2305 case dwarf::DW_TAG_class_type: 2306 case dwarf::DW_TAG_structure_type: 2307 case dwarf::DW_TAG_union_type: 2308 case dwarf::DW_TAG_enumeration_type: 2309 return dwarf::PubIndexEntryDescriptor( 2310 dwarf::GIEK_TYPE, 2311 dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage()) 2312 ? dwarf::GIEL_EXTERNAL 2313 : dwarf::GIEL_STATIC); 2314 case dwarf::DW_TAG_typedef: 2315 case dwarf::DW_TAG_base_type: 2316 case dwarf::DW_TAG_subrange_type: 2317 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC); 2318 case dwarf::DW_TAG_namespace: 2319 return dwarf::GIEK_TYPE; 2320 case dwarf::DW_TAG_subprogram: 2321 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage); 2322 case dwarf::DW_TAG_variable: 2323 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage); 2324 case dwarf::DW_TAG_enumerator: 2325 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, 2326 dwarf::GIEL_STATIC); 2327 default: 2328 return dwarf::GIEK_NONE; 2329 } 2330 } 2331 2332 /// emitDebugPubSections - Emit visible names and types into debug pubnames and 2333 /// pubtypes sections. 2334 void DwarfDebug::emitDebugPubSections() { 2335 for (const auto &NU : CUMap) { 2336 DwarfCompileUnit *TheU = NU.second; 2337 if (!TheU->hasDwarfPubSections()) 2338 continue; 2339 2340 bool GnuStyle = TheU->getCUNode()->getNameTableKind() == 2341 DICompileUnit::DebugNameTableKind::GNU; 2342 2343 Asm->OutStreamer->SwitchSection( 2344 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection() 2345 : Asm->getObjFileLowering().getDwarfPubNamesSection()); 2346 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames()); 2347 2348 Asm->OutStreamer->SwitchSection( 2349 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection() 2350 : Asm->getObjFileLowering().getDwarfPubTypesSection()); 2351 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes()); 2352 } 2353 } 2354 2355 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) { 2356 if (useSectionsAsReferences()) 2357 Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(), 2358 CU.getDebugSectionOffset()); 2359 else 2360 Asm->emitDwarfSymbolReference(CU.getLabelBegin()); 2361 } 2362 2363 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name, 2364 DwarfCompileUnit *TheU, 2365 const StringMap<const DIE *> &Globals) { 2366 if (auto *Skeleton = TheU->getSkeleton()) 2367 TheU = Skeleton; 2368 2369 // Emit the header. 2370 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin"); 2371 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end"); 2372 Asm->emitDwarfUnitLength(EndLabel, BeginLabel, 2373 "Length of Public " + Name + " Info"); 2374 2375 Asm->OutStreamer->emitLabel(BeginLabel); 2376 2377 Asm->OutStreamer->AddComment("DWARF Version"); 2378 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); 2379 2380 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info"); 2381 emitSectionReference(*TheU); 2382 2383 Asm->OutStreamer->AddComment("Compilation Unit Length"); 2384 Asm->emitDwarfLengthOrOffset(TheU->getLength()); 2385 2386 // Emit the pubnames for this compilation unit. 2387 for (const auto &GI : Globals) { 2388 const char *Name = GI.getKeyData(); 2389 const DIE *Entity = GI.second; 2390 2391 Asm->OutStreamer->AddComment("DIE offset"); 2392 Asm->emitDwarfLengthOrOffset(Entity->getOffset()); 2393 2394 if (GnuStyle) { 2395 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity); 2396 Asm->OutStreamer->AddComment( 2397 Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + 2398 ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage)); 2399 Asm->emitInt8(Desc.toBits()); 2400 } 2401 2402 Asm->OutStreamer->AddComment("External Name"); 2403 Asm->OutStreamer->emitBytes(StringRef(Name, GI.getKeyLength() + 1)); 2404 } 2405 2406 Asm->OutStreamer->AddComment("End Mark"); 2407 Asm->emitDwarfLengthOrOffset(0); 2408 Asm->OutStreamer->emitLabel(EndLabel); 2409 } 2410 2411 /// Emit null-terminated strings into a debug str section. 2412 void DwarfDebug::emitDebugStr() { 2413 MCSection *StringOffsetsSection = nullptr; 2414 if (useSegmentedStringOffsetsTable()) { 2415 emitStringOffsetsTableHeader(); 2416 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection(); 2417 } 2418 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2419 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(), 2420 StringOffsetsSection, /* UseRelativeOffsets = */ true); 2421 } 2422 2423 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer, 2424 const DebugLocStream::Entry &Entry, 2425 const DwarfCompileUnit *CU) { 2426 auto &&Comments = DebugLocs.getComments(Entry); 2427 auto Comment = Comments.begin(); 2428 auto End = Comments.end(); 2429 2430 // The expressions are inserted into a byte stream rather early (see 2431 // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that 2432 // need to reference a base_type DIE the offset of that DIE is not yet known. 2433 // To deal with this we instead insert a placeholder early and then extract 2434 // it here and replace it with the real reference. 2435 unsigned PtrSize = Asm->MAI->getCodePointerSize(); 2436 DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(), 2437 DebugLocs.getBytes(Entry).size()), 2438 Asm->getDataLayout().isLittleEndian(), PtrSize); 2439 DWARFExpression Expr(Data, PtrSize, Asm->OutContext.getDwarfFormat()); 2440 2441 using Encoding = DWARFExpression::Operation::Encoding; 2442 uint64_t Offset = 0; 2443 for (auto &Op : Expr) { 2444 assert(Op.getCode() != dwarf::DW_OP_const_type && 2445 "3 operand ops not yet supported"); 2446 Streamer.emitInt8(Op.getCode(), Comment != End ? *(Comment++) : ""); 2447 Offset++; 2448 for (unsigned I = 0; I < 2; ++I) { 2449 if (Op.getDescription().Op[I] == Encoding::SizeNA) 2450 continue; 2451 if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) { 2452 uint64_t Offset = 2453 CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset(); 2454 assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit"); 2455 Streamer.emitULEB128(Offset, "", ULEB128PadSize); 2456 // Make sure comments stay aligned. 2457 for (unsigned J = 0; J < ULEB128PadSize; ++J) 2458 if (Comment != End) 2459 Comment++; 2460 } else { 2461 for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J) 2462 Streamer.emitInt8(Data.getData()[J], Comment != End ? *(Comment++) : ""); 2463 } 2464 Offset = Op.getOperandEndOffset(I); 2465 } 2466 assert(Offset == Op.getEndOffset()); 2467 } 2468 } 2469 2470 void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, 2471 const DbgValueLoc &Value, 2472 DwarfExpression &DwarfExpr) { 2473 auto *DIExpr = Value.getExpression(); 2474 DIExpressionCursor ExprCursor(DIExpr); 2475 DwarfExpr.addFragmentOffset(DIExpr); 2476 // Regular entry. 2477 if (Value.isInt()) { 2478 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed || 2479 BT->getEncoding() == dwarf::DW_ATE_signed_char)) 2480 DwarfExpr.addSignedConstant(Value.getInt()); 2481 else 2482 DwarfExpr.addUnsignedConstant(Value.getInt()); 2483 } else if (Value.isLocation()) { 2484 MachineLocation Location = Value.getLoc(); 2485 DwarfExpr.setLocation(Location, DIExpr); 2486 DIExpressionCursor Cursor(DIExpr); 2487 2488 if (DIExpr->isEntryValue()) 2489 DwarfExpr.beginEntryValueExpression(Cursor); 2490 2491 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo(); 2492 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 2493 return; 2494 return DwarfExpr.addExpression(std::move(Cursor)); 2495 } else if (Value.isTargetIndexLocation()) { 2496 TargetIndexLocation Loc = Value.getTargetIndexLocation(); 2497 // TODO TargetIndexLocation is a target-independent. Currently only the WebAssembly-specific 2498 // encoding is supported. 2499 assert(AP.TM.getTargetTriple().isWasm()); 2500 DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset)); 2501 DwarfExpr.addExpression(std::move(ExprCursor)); 2502 return; 2503 } else if (Value.isConstantFP()) { 2504 if (AP.getDwarfVersion() >= 4 && !AP.getDwarfDebug()->tuneForSCE() && 2505 !ExprCursor) { 2506 DwarfExpr.addConstantFP(Value.getConstantFP()->getValueAPF(), AP); 2507 return; 2508 } 2509 if (Value.getConstantFP()->getValueAPF().bitcastToAPInt().getBitWidth() <= 2510 64 /*bits*/) 2511 DwarfExpr.addUnsignedConstant( 2512 Value.getConstantFP()->getValueAPF().bitcastToAPInt()); 2513 else 2514 LLVM_DEBUG( 2515 dbgs() 2516 << "Skipped DwarfExpression creation for ConstantFP of size" 2517 << Value.getConstantFP()->getValueAPF().bitcastToAPInt().getBitWidth() 2518 << " bits\n"); 2519 } 2520 DwarfExpr.addExpression(std::move(ExprCursor)); 2521 } 2522 2523 void DebugLocEntry::finalize(const AsmPrinter &AP, 2524 DebugLocStream::ListBuilder &List, 2525 const DIBasicType *BT, 2526 DwarfCompileUnit &TheCU) { 2527 assert(!Values.empty() && 2528 "location list entries without values are redundant"); 2529 assert(Begin != End && "unexpected location list entry with empty range"); 2530 DebugLocStream::EntryBuilder Entry(List, Begin, End); 2531 BufferByteStreamer Streamer = Entry.getStreamer(); 2532 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU); 2533 const DbgValueLoc &Value = Values[0]; 2534 if (Value.isFragment()) { 2535 // Emit all fragments that belong to the same variable and range. 2536 assert(llvm::all_of(Values, [](DbgValueLoc P) { 2537 return P.isFragment(); 2538 }) && "all values are expected to be fragments"); 2539 assert(llvm::is_sorted(Values) && "fragments are expected to be sorted"); 2540 2541 for (const auto &Fragment : Values) 2542 DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr); 2543 2544 } else { 2545 assert(Values.size() == 1 && "only fragments may have >1 value"); 2546 DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr); 2547 } 2548 DwarfExpr.finalize(); 2549 if (DwarfExpr.TagOffset) 2550 List.setTagOffset(*DwarfExpr.TagOffset); 2551 } 2552 2553 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry, 2554 const DwarfCompileUnit *CU) { 2555 // Emit the size. 2556 Asm->OutStreamer->AddComment("Loc expr size"); 2557 if (getDwarfVersion() >= 5) 2558 Asm->emitULEB128(DebugLocs.getBytes(Entry).size()); 2559 else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max()) 2560 Asm->emitInt16(DebugLocs.getBytes(Entry).size()); 2561 else { 2562 // The entry is too big to fit into 16 bit, drop it as there is nothing we 2563 // can do. 2564 Asm->emitInt16(0); 2565 return; 2566 } 2567 // Emit the entry. 2568 APByteStreamer Streamer(*Asm); 2569 emitDebugLocEntry(Streamer, Entry, CU); 2570 } 2571 2572 // Emit the header of a DWARF 5 range list table list table. Returns the symbol 2573 // that designates the end of the table for the caller to emit when the table is 2574 // complete. 2575 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm, 2576 const DwarfFile &Holder) { 2577 MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer); 2578 2579 Asm->OutStreamer->AddComment("Offset entry count"); 2580 Asm->emitInt32(Holder.getRangeLists().size()); 2581 Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym()); 2582 2583 for (const RangeSpanList &List : Holder.getRangeLists()) 2584 Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(), 2585 Asm->getDwarfOffsetByteSize()); 2586 2587 return TableEnd; 2588 } 2589 2590 // Emit the header of a DWARF 5 locations list table. Returns the symbol that 2591 // designates the end of the table for the caller to emit when the table is 2592 // complete. 2593 static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm, 2594 const DwarfDebug &DD) { 2595 MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer); 2596 2597 const auto &DebugLocs = DD.getDebugLocs(); 2598 2599 Asm->OutStreamer->AddComment("Offset entry count"); 2600 Asm->emitInt32(DebugLocs.getLists().size()); 2601 Asm->OutStreamer->emitLabel(DebugLocs.getSym()); 2602 2603 for (const auto &List : DebugLocs.getLists()) 2604 Asm->emitLabelDifference(List.Label, DebugLocs.getSym(), 2605 Asm->getDwarfOffsetByteSize()); 2606 2607 return TableEnd; 2608 } 2609 2610 template <typename Ranges, typename PayloadEmitter> 2611 static void emitRangeList( 2612 DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R, 2613 const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair, 2614 unsigned StartxLength, unsigned EndOfList, 2615 StringRef (*StringifyEnum)(unsigned), 2616 bool ShouldUseBaseAddress, 2617 PayloadEmitter EmitPayload) { 2618 2619 auto Size = Asm->MAI->getCodePointerSize(); 2620 bool UseDwarf5 = DD.getDwarfVersion() >= 5; 2621 2622 // Emit our symbol so we can find the beginning of the range. 2623 Asm->OutStreamer->emitLabel(Sym); 2624 2625 // Gather all the ranges that apply to the same section so they can share 2626 // a base address entry. 2627 MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges; 2628 2629 for (const auto &Range : R) 2630 SectionRanges[&Range.Begin->getSection()].push_back(&Range); 2631 2632 const MCSymbol *CUBase = CU.getBaseAddress(); 2633 bool BaseIsSet = false; 2634 for (const auto &P : SectionRanges) { 2635 auto *Base = CUBase; 2636 if (!Base && ShouldUseBaseAddress) { 2637 const MCSymbol *Begin = P.second.front()->Begin; 2638 const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection()); 2639 if (!UseDwarf5) { 2640 Base = NewBase; 2641 BaseIsSet = true; 2642 Asm->OutStreamer->emitIntValue(-1, Size); 2643 Asm->OutStreamer->AddComment(" base address"); 2644 Asm->OutStreamer->emitSymbolValue(Base, Size); 2645 } else if (NewBase != Begin || P.second.size() > 1) { 2646 // Only use a base address if 2647 // * the existing pool address doesn't match (NewBase != Begin) 2648 // * or, there's more than one entry to share the base address 2649 Base = NewBase; 2650 BaseIsSet = true; 2651 Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx)); 2652 Asm->emitInt8(BaseAddressx); 2653 Asm->OutStreamer->AddComment(" base address index"); 2654 Asm->emitULEB128(DD.getAddressPool().getIndex(Base)); 2655 } 2656 } else if (BaseIsSet && !UseDwarf5) { 2657 BaseIsSet = false; 2658 assert(!Base); 2659 Asm->OutStreamer->emitIntValue(-1, Size); 2660 Asm->OutStreamer->emitIntValue(0, Size); 2661 } 2662 2663 for (const auto *RS : P.second) { 2664 const MCSymbol *Begin = RS->Begin; 2665 const MCSymbol *End = RS->End; 2666 assert(Begin && "Range without a begin symbol?"); 2667 assert(End && "Range without an end symbol?"); 2668 if (Base) { 2669 if (UseDwarf5) { 2670 // Emit offset_pair when we have a base. 2671 Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair)); 2672 Asm->emitInt8(OffsetPair); 2673 Asm->OutStreamer->AddComment(" starting offset"); 2674 Asm->emitLabelDifferenceAsULEB128(Begin, Base); 2675 Asm->OutStreamer->AddComment(" ending offset"); 2676 Asm->emitLabelDifferenceAsULEB128(End, Base); 2677 } else { 2678 Asm->emitLabelDifference(Begin, Base, Size); 2679 Asm->emitLabelDifference(End, Base, Size); 2680 } 2681 } else if (UseDwarf5) { 2682 Asm->OutStreamer->AddComment(StringifyEnum(StartxLength)); 2683 Asm->emitInt8(StartxLength); 2684 Asm->OutStreamer->AddComment(" start index"); 2685 Asm->emitULEB128(DD.getAddressPool().getIndex(Begin)); 2686 Asm->OutStreamer->AddComment(" length"); 2687 Asm->emitLabelDifferenceAsULEB128(End, Begin); 2688 } else { 2689 Asm->OutStreamer->emitSymbolValue(Begin, Size); 2690 Asm->OutStreamer->emitSymbolValue(End, Size); 2691 } 2692 EmitPayload(*RS); 2693 } 2694 } 2695 2696 if (UseDwarf5) { 2697 Asm->OutStreamer->AddComment(StringifyEnum(EndOfList)); 2698 Asm->emitInt8(EndOfList); 2699 } else { 2700 // Terminate the list with two 0 values. 2701 Asm->OutStreamer->emitIntValue(0, Size); 2702 Asm->OutStreamer->emitIntValue(0, Size); 2703 } 2704 } 2705 2706 // Handles emission of both debug_loclist / debug_loclist.dwo 2707 static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) { 2708 emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List), 2709 *List.CU, dwarf::DW_LLE_base_addressx, 2710 dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length, 2711 dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString, 2712 /* ShouldUseBaseAddress */ true, 2713 [&](const DebugLocStream::Entry &E) { 2714 DD.emitDebugLocEntryLocation(E, List.CU); 2715 }); 2716 } 2717 2718 void DwarfDebug::emitDebugLocImpl(MCSection *Sec) { 2719 if (DebugLocs.getLists().empty()) 2720 return; 2721 2722 Asm->OutStreamer->SwitchSection(Sec); 2723 2724 MCSymbol *TableEnd = nullptr; 2725 if (getDwarfVersion() >= 5) 2726 TableEnd = emitLoclistsTableHeader(Asm, *this); 2727 2728 for (const auto &List : DebugLocs.getLists()) 2729 emitLocList(*this, Asm, List); 2730 2731 if (TableEnd) 2732 Asm->OutStreamer->emitLabel(TableEnd); 2733 } 2734 2735 // Emit locations into the .debug_loc/.debug_loclists section. 2736 void DwarfDebug::emitDebugLoc() { 2737 emitDebugLocImpl( 2738 getDwarfVersion() >= 5 2739 ? Asm->getObjFileLowering().getDwarfLoclistsSection() 2740 : Asm->getObjFileLowering().getDwarfLocSection()); 2741 } 2742 2743 // Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section. 2744 void DwarfDebug::emitDebugLocDWO() { 2745 if (getDwarfVersion() >= 5) { 2746 emitDebugLocImpl( 2747 Asm->getObjFileLowering().getDwarfLoclistsDWOSection()); 2748 2749 return; 2750 } 2751 2752 for (const auto &List : DebugLocs.getLists()) { 2753 Asm->OutStreamer->SwitchSection( 2754 Asm->getObjFileLowering().getDwarfLocDWOSection()); 2755 Asm->OutStreamer->emitLabel(List.Label); 2756 2757 for (const auto &Entry : DebugLocs.getEntries(List)) { 2758 // GDB only supports startx_length in pre-standard split-DWARF. 2759 // (in v5 standard loclists, it currently* /only/ supports base_address + 2760 // offset_pair, so the implementations can't really share much since they 2761 // need to use different representations) 2762 // * as of October 2018, at least 2763 // 2764 // In v5 (see emitLocList), this uses SectionLabels to reuse existing 2765 // addresses in the address pool to minimize object size/relocations. 2766 Asm->emitInt8(dwarf::DW_LLE_startx_length); 2767 unsigned idx = AddrPool.getIndex(Entry.Begin); 2768 Asm->emitULEB128(idx); 2769 // Also the pre-standard encoding is slightly different, emitting this as 2770 // an address-length entry here, but its a ULEB128 in DWARFv5 loclists. 2771 Asm->emitLabelDifference(Entry.End, Entry.Begin, 4); 2772 emitDebugLocEntryLocation(Entry, List.CU); 2773 } 2774 Asm->emitInt8(dwarf::DW_LLE_end_of_list); 2775 } 2776 } 2777 2778 struct ArangeSpan { 2779 const MCSymbol *Start, *End; 2780 }; 2781 2782 // Emit a debug aranges section, containing a CU lookup for any 2783 // address we can tie back to a CU. 2784 void DwarfDebug::emitDebugARanges() { 2785 // Provides a unique id per text section. 2786 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap; 2787 2788 // Filter labels by section. 2789 for (const SymbolCU &SCU : ArangeLabels) { 2790 if (SCU.Sym->isInSection()) { 2791 // Make a note of this symbol and it's section. 2792 MCSection *Section = &SCU.Sym->getSection(); 2793 if (!Section->getKind().isMetadata()) 2794 SectionMap[Section].push_back(SCU); 2795 } else { 2796 // Some symbols (e.g. common/bss on mach-o) can have no section but still 2797 // appear in the output. This sucks as we rely on sections to build 2798 // arange spans. We can do it without, but it's icky. 2799 SectionMap[nullptr].push_back(SCU); 2800 } 2801 } 2802 2803 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans; 2804 2805 for (auto &I : SectionMap) { 2806 MCSection *Section = I.first; 2807 SmallVector<SymbolCU, 8> &List = I.second; 2808 if (List.size() < 1) 2809 continue; 2810 2811 // If we have no section (e.g. common), just write out 2812 // individual spans for each symbol. 2813 if (!Section) { 2814 for (const SymbolCU &Cur : List) { 2815 ArangeSpan Span; 2816 Span.Start = Cur.Sym; 2817 Span.End = nullptr; 2818 assert(Cur.CU); 2819 Spans[Cur.CU].push_back(Span); 2820 } 2821 continue; 2822 } 2823 2824 // Sort the symbols by offset within the section. 2825 llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) { 2826 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0; 2827 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0; 2828 2829 // Symbols with no order assigned should be placed at the end. 2830 // (e.g. section end labels) 2831 if (IA == 0) 2832 return false; 2833 if (IB == 0) 2834 return true; 2835 return IA < IB; 2836 }); 2837 2838 // Insert a final terminator. 2839 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section))); 2840 2841 // Build spans between each label. 2842 const MCSymbol *StartSym = List[0].Sym; 2843 for (size_t n = 1, e = List.size(); n < e; n++) { 2844 const SymbolCU &Prev = List[n - 1]; 2845 const SymbolCU &Cur = List[n]; 2846 2847 // Try and build the longest span we can within the same CU. 2848 if (Cur.CU != Prev.CU) { 2849 ArangeSpan Span; 2850 Span.Start = StartSym; 2851 Span.End = Cur.Sym; 2852 assert(Prev.CU); 2853 Spans[Prev.CU].push_back(Span); 2854 StartSym = Cur.Sym; 2855 } 2856 } 2857 } 2858 2859 // Start the dwarf aranges section. 2860 Asm->OutStreamer->SwitchSection( 2861 Asm->getObjFileLowering().getDwarfARangesSection()); 2862 2863 unsigned PtrSize = Asm->MAI->getCodePointerSize(); 2864 2865 // Build a list of CUs used. 2866 std::vector<DwarfCompileUnit *> CUs; 2867 for (const auto &it : Spans) { 2868 DwarfCompileUnit *CU = it.first; 2869 CUs.push_back(CU); 2870 } 2871 2872 // Sort the CU list (again, to ensure consistent output order). 2873 llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) { 2874 return A->getUniqueID() < B->getUniqueID(); 2875 }); 2876 2877 // Emit an arange table for each CU we used. 2878 for (DwarfCompileUnit *CU : CUs) { 2879 std::vector<ArangeSpan> &List = Spans[CU]; 2880 2881 // Describe the skeleton CU's offset and length, not the dwo file's. 2882 if (auto *Skel = CU->getSkeleton()) 2883 CU = Skel; 2884 2885 // Emit size of content not including length itself. 2886 unsigned ContentSize = 2887 sizeof(int16_t) + // DWARF ARange version number 2888 Asm->getDwarfOffsetByteSize() + // Offset of CU in the .debug_info 2889 // section 2890 sizeof(int8_t) + // Pointer Size (in bytes) 2891 sizeof(int8_t); // Segment Size (in bytes) 2892 2893 unsigned TupleSize = PtrSize * 2; 2894 2895 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 2896 unsigned Padding = offsetToAlignment( 2897 Asm->getUnitLengthFieldByteSize() + ContentSize, Align(TupleSize)); 2898 2899 ContentSize += Padding; 2900 ContentSize += (List.size() + 1) * TupleSize; 2901 2902 // For each compile unit, write the list of spans it covers. 2903 Asm->emitDwarfUnitLength(ContentSize, "Length of ARange Set"); 2904 Asm->OutStreamer->AddComment("DWARF Arange version number"); 2905 Asm->emitInt16(dwarf::DW_ARANGES_VERSION); 2906 Asm->OutStreamer->AddComment("Offset Into Debug Info Section"); 2907 emitSectionReference(*CU); 2908 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 2909 Asm->emitInt8(PtrSize); 2910 Asm->OutStreamer->AddComment("Segment Size (in bytes)"); 2911 Asm->emitInt8(0); 2912 2913 Asm->OutStreamer->emitFill(Padding, 0xff); 2914 2915 for (const ArangeSpan &Span : List) { 2916 Asm->emitLabelReference(Span.Start, PtrSize); 2917 2918 // Calculate the size as being from the span start to it's end. 2919 if (Span.End) { 2920 Asm->emitLabelDifference(Span.End, Span.Start, PtrSize); 2921 } else { 2922 // For symbols without an end marker (e.g. common), we 2923 // write a single arange entry containing just that one symbol. 2924 uint64_t Size = SymSize[Span.Start]; 2925 if (Size == 0) 2926 Size = 1; 2927 2928 Asm->OutStreamer->emitIntValue(Size, PtrSize); 2929 } 2930 } 2931 2932 Asm->OutStreamer->AddComment("ARange terminator"); 2933 Asm->OutStreamer->emitIntValue(0, PtrSize); 2934 Asm->OutStreamer->emitIntValue(0, PtrSize); 2935 } 2936 } 2937 2938 /// Emit a single range list. We handle both DWARF v5 and earlier. 2939 static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, 2940 const RangeSpanList &List) { 2941 emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU, 2942 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair, 2943 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list, 2944 llvm::dwarf::RangeListEncodingString, 2945 List.CU->getCUNode()->getRangesBaseAddress() || 2946 DD.getDwarfVersion() >= 5, 2947 [](auto) {}); 2948 } 2949 2950 void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) { 2951 if (Holder.getRangeLists().empty()) 2952 return; 2953 2954 assert(useRangesSection()); 2955 assert(!CUMap.empty()); 2956 assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2957 return !Pair.second->getCUNode()->isDebugDirectivesOnly(); 2958 })); 2959 2960 Asm->OutStreamer->SwitchSection(Section); 2961 2962 MCSymbol *TableEnd = nullptr; 2963 if (getDwarfVersion() >= 5) 2964 TableEnd = emitRnglistsTableHeader(Asm, Holder); 2965 2966 for (const RangeSpanList &List : Holder.getRangeLists()) 2967 emitRangeList(*this, Asm, List); 2968 2969 if (TableEnd) 2970 Asm->OutStreamer->emitLabel(TableEnd); 2971 } 2972 2973 /// Emit address ranges into the .debug_ranges section or into the DWARF v5 2974 /// .debug_rnglists section. 2975 void DwarfDebug::emitDebugRanges() { 2976 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2977 2978 emitDebugRangesImpl(Holder, 2979 getDwarfVersion() >= 5 2980 ? Asm->getObjFileLowering().getDwarfRnglistsSection() 2981 : Asm->getObjFileLowering().getDwarfRangesSection()); 2982 } 2983 2984 void DwarfDebug::emitDebugRangesDWO() { 2985 emitDebugRangesImpl(InfoHolder, 2986 Asm->getObjFileLowering().getDwarfRnglistsDWOSection()); 2987 } 2988 2989 /// Emit the header of a DWARF 5 macro section, or the GNU extension for 2990 /// DWARF 4. 2991 static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD, 2992 const DwarfCompileUnit &CU, uint16_t DwarfVersion) { 2993 enum HeaderFlagMask { 2994 #define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID, 2995 #include "llvm/BinaryFormat/Dwarf.def" 2996 }; 2997 Asm->OutStreamer->AddComment("Macro information version"); 2998 Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4); 2999 // We emit the line offset flag unconditionally here, since line offset should 3000 // be mostly present. 3001 if (Asm->isDwarf64()) { 3002 Asm->OutStreamer->AddComment("Flags: 64 bit, debug_line_offset present"); 3003 Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET); 3004 } else { 3005 Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present"); 3006 Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET); 3007 } 3008 Asm->OutStreamer->AddComment("debug_line_offset"); 3009 if (DD.useSplitDwarf()) 3010 Asm->emitDwarfLengthOrOffset(0); 3011 else 3012 Asm->emitDwarfSymbolReference(CU.getLineTableStartSym()); 3013 } 3014 3015 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) { 3016 for (auto *MN : Nodes) { 3017 if (auto *M = dyn_cast<DIMacro>(MN)) 3018 emitMacro(*M); 3019 else if (auto *F = dyn_cast<DIMacroFile>(MN)) 3020 emitMacroFile(*F, U); 3021 else 3022 llvm_unreachable("Unexpected DI type!"); 3023 } 3024 } 3025 3026 void DwarfDebug::emitMacro(DIMacro &M) { 3027 StringRef Name = M.getName(); 3028 StringRef Value = M.getValue(); 3029 3030 // There should be one space between the macro name and the macro value in 3031 // define entries. In undef entries, only the macro name is emitted. 3032 std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str(); 3033 3034 if (UseDebugMacroSection) { 3035 if (getDwarfVersion() >= 5) { 3036 unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define 3037 ? dwarf::DW_MACRO_define_strx 3038 : dwarf::DW_MACRO_undef_strx; 3039 Asm->OutStreamer->AddComment(dwarf::MacroString(Type)); 3040 Asm->emitULEB128(Type); 3041 Asm->OutStreamer->AddComment("Line Number"); 3042 Asm->emitULEB128(M.getLine()); 3043 Asm->OutStreamer->AddComment("Macro String"); 3044 Asm->emitULEB128( 3045 InfoHolder.getStringPool().getIndexedEntry(*Asm, Str).getIndex()); 3046 } else { 3047 unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define 3048 ? dwarf::DW_MACRO_GNU_define_indirect 3049 : dwarf::DW_MACRO_GNU_undef_indirect; 3050 Asm->OutStreamer->AddComment(dwarf::GnuMacroString(Type)); 3051 Asm->emitULEB128(Type); 3052 Asm->OutStreamer->AddComment("Line Number"); 3053 Asm->emitULEB128(M.getLine()); 3054 Asm->OutStreamer->AddComment("Macro String"); 3055 Asm->emitDwarfSymbolReference( 3056 InfoHolder.getStringPool().getEntry(*Asm, Str).getSymbol()); 3057 } 3058 } else { 3059 Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType())); 3060 Asm->emitULEB128(M.getMacinfoType()); 3061 Asm->OutStreamer->AddComment("Line Number"); 3062 Asm->emitULEB128(M.getLine()); 3063 Asm->OutStreamer->AddComment("Macro String"); 3064 Asm->OutStreamer->emitBytes(Str); 3065 Asm->emitInt8('\0'); 3066 } 3067 } 3068 3069 void DwarfDebug::emitMacroFileImpl( 3070 DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile, 3071 StringRef (*MacroFormToString)(unsigned Form)) { 3072 3073 Asm->OutStreamer->AddComment(MacroFormToString(StartFile)); 3074 Asm->emitULEB128(StartFile); 3075 Asm->OutStreamer->AddComment("Line Number"); 3076 Asm->emitULEB128(MF.getLine()); 3077 Asm->OutStreamer->AddComment("File Number"); 3078 DIFile &F = *MF.getFile(); 3079 if (useSplitDwarf()) 3080 Asm->emitULEB128(getDwoLineTable(U)->getFile( 3081 F.getDirectory(), F.getFilename(), getMD5AsBytes(&F), 3082 Asm->OutContext.getDwarfVersion(), F.getSource())); 3083 else 3084 Asm->emitULEB128(U.getOrCreateSourceID(&F)); 3085 handleMacroNodes(MF.getElements(), U); 3086 Asm->OutStreamer->AddComment(MacroFormToString(EndFile)); 3087 Asm->emitULEB128(EndFile); 3088 } 3089 3090 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) { 3091 // DWARFv5 macro and DWARFv4 macinfo share some common encodings, 3092 // so for readibility/uniformity, We are explicitly emitting those. 3093 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file); 3094 if (UseDebugMacroSection) 3095 emitMacroFileImpl( 3096 F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file, 3097 (getDwarfVersion() >= 5) ? dwarf::MacroString : dwarf::GnuMacroString); 3098 else 3099 emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file, 3100 dwarf::DW_MACINFO_end_file, dwarf::MacinfoString); 3101 } 3102 3103 void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) { 3104 for (const auto &P : CUMap) { 3105 auto &TheCU = *P.second; 3106 auto *SkCU = TheCU.getSkeleton(); 3107 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 3108 auto *CUNode = cast<DICompileUnit>(P.first); 3109 DIMacroNodeArray Macros = CUNode->getMacros(); 3110 if (Macros.empty()) 3111 continue; 3112 Asm->OutStreamer->SwitchSection(Section); 3113 Asm->OutStreamer->emitLabel(U.getMacroLabelBegin()); 3114 if (UseDebugMacroSection) 3115 emitMacroHeader(Asm, *this, U, getDwarfVersion()); 3116 handleMacroNodes(Macros, U); 3117 Asm->OutStreamer->AddComment("End Of Macro List Mark"); 3118 Asm->emitInt8(0); 3119 } 3120 } 3121 3122 /// Emit macros into a debug macinfo/macro section. 3123 void DwarfDebug::emitDebugMacinfo() { 3124 auto &ObjLower = Asm->getObjFileLowering(); 3125 emitDebugMacinfoImpl(UseDebugMacroSection 3126 ? ObjLower.getDwarfMacroSection() 3127 : ObjLower.getDwarfMacinfoSection()); 3128 } 3129 3130 void DwarfDebug::emitDebugMacinfoDWO() { 3131 auto &ObjLower = Asm->getObjFileLowering(); 3132 emitDebugMacinfoImpl(UseDebugMacroSection 3133 ? ObjLower.getDwarfMacroDWOSection() 3134 : ObjLower.getDwarfMacinfoDWOSection()); 3135 } 3136 3137 // DWARF5 Experimental Separate Dwarf emitters. 3138 3139 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die, 3140 std::unique_ptr<DwarfCompileUnit> NewU) { 3141 3142 if (!CompilationDir.empty()) 3143 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 3144 addGnuPubAttributes(*NewU, Die); 3145 3146 SkeletonHolder.addUnit(std::move(NewU)); 3147 } 3148 3149 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) { 3150 3151 auto OwnedUnit = std::make_unique<DwarfCompileUnit>( 3152 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder, 3153 UnitKind::Skeleton); 3154 DwarfCompileUnit &NewCU = *OwnedUnit; 3155 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 3156 3157 NewCU.initStmtList(); 3158 3159 if (useSegmentedStringOffsetsTable()) 3160 NewCU.addStringOffsetsStart(); 3161 3162 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit)); 3163 3164 return NewCU; 3165 } 3166 3167 // Emit the .debug_info.dwo section for separated dwarf. This contains the 3168 // compile units that would normally be in debug_info. 3169 void DwarfDebug::emitDebugInfoDWO() { 3170 assert(useSplitDwarf() && "No split dwarf debug info?"); 3171 // Don't emit relocations into the dwo file. 3172 InfoHolder.emitUnits(/* UseOffsets */ true); 3173 } 3174 3175 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 3176 // abbreviations for the .debug_info.dwo section. 3177 void DwarfDebug::emitDebugAbbrevDWO() { 3178 assert(useSplitDwarf() && "No split dwarf?"); 3179 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 3180 } 3181 3182 void DwarfDebug::emitDebugLineDWO() { 3183 assert(useSplitDwarf() && "No split dwarf?"); 3184 SplitTypeUnitFileTable.Emit( 3185 *Asm->OutStreamer, MCDwarfLineTableParams(), 3186 Asm->getObjFileLowering().getDwarfLineDWOSection()); 3187 } 3188 3189 void DwarfDebug::emitStringOffsetsTableHeaderDWO() { 3190 assert(useSplitDwarf() && "No split dwarf?"); 3191 InfoHolder.getStringPool().emitStringOffsetsTableHeader( 3192 *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(), 3193 InfoHolder.getStringOffsetsStartSym()); 3194 } 3195 3196 // Emit the .debug_str.dwo section for separated dwarf. This contains the 3197 // string section and is identical in format to traditional .debug_str 3198 // sections. 3199 void DwarfDebug::emitDebugStrDWO() { 3200 if (useSegmentedStringOffsetsTable()) 3201 emitStringOffsetsTableHeaderDWO(); 3202 assert(useSplitDwarf() && "No split dwarf?"); 3203 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 3204 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 3205 OffSec, /* UseRelativeOffsets = */ false); 3206 } 3207 3208 // Emit address pool. 3209 void DwarfDebug::emitDebugAddr() { 3210 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection()); 3211 } 3212 3213 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 3214 if (!useSplitDwarf()) 3215 return nullptr; 3216 const DICompileUnit *DIUnit = CU.getCUNode(); 3217 SplitTypeUnitFileTable.maybeSetRootFile( 3218 DIUnit->getDirectory(), DIUnit->getFilename(), 3219 getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource()); 3220 return &SplitTypeUnitFileTable; 3221 } 3222 3223 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) { 3224 MD5 Hash; 3225 Hash.update(Identifier); 3226 // ... take the least significant 8 bytes and return those. Our MD5 3227 // implementation always returns its results in little endian, so we actually 3228 // need the "high" word. 3229 MD5::MD5Result Result; 3230 Hash.final(Result); 3231 return Result.high(); 3232 } 3233 3234 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 3235 StringRef Identifier, DIE &RefDie, 3236 const DICompositeType *CTy) { 3237 // Fast path if we're building some type units and one has already used the 3238 // address pool we know we're going to throw away all this work anyway, so 3239 // don't bother building dependent types. 3240 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed()) 3241 return; 3242 3243 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0)); 3244 if (!Ins.second) { 3245 CU.addDIETypeSignature(RefDie, Ins.first->second); 3246 return; 3247 } 3248 3249 bool TopLevelType = TypeUnitsUnderConstruction.empty(); 3250 AddrPool.resetUsedFlag(); 3251 3252 auto OwnedUnit = std::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder, 3253 getDwoLineTable(CU)); 3254 DwarfTypeUnit &NewTU = *OwnedUnit; 3255 DIE &UnitDie = NewTU.getUnitDie(); 3256 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy); 3257 3258 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 3259 CU.getLanguage()); 3260 3261 uint64_t Signature = makeTypeSignature(Identifier); 3262 NewTU.setTypeSignature(Signature); 3263 Ins.first->second = Signature; 3264 3265 if (useSplitDwarf()) { 3266 MCSection *Section = 3267 getDwarfVersion() <= 4 3268 ? Asm->getObjFileLowering().getDwarfTypesDWOSection() 3269 : Asm->getObjFileLowering().getDwarfInfoDWOSection(); 3270 NewTU.setSection(Section); 3271 } else { 3272 MCSection *Section = 3273 getDwarfVersion() <= 4 3274 ? Asm->getObjFileLowering().getDwarfTypesSection(Signature) 3275 : Asm->getObjFileLowering().getDwarfInfoSection(Signature); 3276 NewTU.setSection(Section); 3277 // Non-split type units reuse the compile unit's line table. 3278 CU.applyStmtList(UnitDie); 3279 } 3280 3281 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type 3282 // units. 3283 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 3284 NewTU.addStringOffsetsStart(); 3285 3286 NewTU.setType(NewTU.createTypeDIE(CTy)); 3287 3288 if (TopLevelType) { 3289 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction); 3290 TypeUnitsUnderConstruction.clear(); 3291 3292 // Types referencing entries in the address table cannot be placed in type 3293 // units. 3294 if (AddrPool.hasBeenUsed()) { 3295 3296 // Remove all the types built while building this type. 3297 // This is pessimistic as some of these types might not be dependent on 3298 // the type that used an address. 3299 for (const auto &TU : TypeUnitsToAdd) 3300 TypeSignatures.erase(TU.second); 3301 3302 // Construct this type in the CU directly. 3303 // This is inefficient because all the dependent types will be rebuilt 3304 // from scratch, including building them in type units, discovering that 3305 // they depend on addresses, throwing them out and rebuilding them. 3306 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy)); 3307 return; 3308 } 3309 3310 // If the type wasn't dependent on fission addresses, finish adding the type 3311 // and all its dependent types. 3312 for (auto &TU : TypeUnitsToAdd) { 3313 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get()); 3314 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf()); 3315 } 3316 } 3317 CU.addDIETypeSignature(RefDie, Signature); 3318 } 3319 3320 DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug *DD) 3321 : DD(DD), 3322 TypeUnitsUnderConstruction(std::move(DD->TypeUnitsUnderConstruction)), AddrPoolUsed(DD->AddrPool.hasBeenUsed()) { 3323 DD->TypeUnitsUnderConstruction.clear(); 3324 DD->AddrPool.resetUsedFlag(); 3325 } 3326 3327 DwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() { 3328 DD->TypeUnitsUnderConstruction = std::move(TypeUnitsUnderConstruction); 3329 DD->AddrPool.resetUsedFlag(AddrPoolUsed); 3330 } 3331 3332 DwarfDebug::NonTypeUnitContext DwarfDebug::enterNonTypeUnitContext() { 3333 return NonTypeUnitContext(this); 3334 } 3335 3336 // Add the Name along with its companion DIE to the appropriate accelerator 3337 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for 3338 // AccelTableKind::Apple, we use the table we got as an argument). If 3339 // accelerator tables are disabled, this function does nothing. 3340 template <typename DataT> 3341 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU, 3342 AccelTable<DataT> &AppleAccel, StringRef Name, 3343 const DIE &Die) { 3344 if (getAccelTableKind() == AccelTableKind::None) 3345 return; 3346 3347 if (getAccelTableKind() != AccelTableKind::Apple && 3348 CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default) 3349 return; 3350 3351 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 3352 DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name); 3353 3354 switch (getAccelTableKind()) { 3355 case AccelTableKind::Apple: 3356 AppleAccel.addName(Ref, Die); 3357 break; 3358 case AccelTableKind::Dwarf: 3359 AccelDebugNames.addName(Ref, Die); 3360 break; 3361 case AccelTableKind::Default: 3362 llvm_unreachable("Default should have already been resolved."); 3363 case AccelTableKind::None: 3364 llvm_unreachable("None handled above"); 3365 } 3366 } 3367 3368 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name, 3369 const DIE &Die) { 3370 addAccelNameImpl(CU, AccelNames, Name, Die); 3371 } 3372 3373 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name, 3374 const DIE &Die) { 3375 // ObjC names go only into the Apple accelerator tables. 3376 if (getAccelTableKind() == AccelTableKind::Apple) 3377 addAccelNameImpl(CU, AccelObjC, Name, Die); 3378 } 3379 3380 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name, 3381 const DIE &Die) { 3382 addAccelNameImpl(CU, AccelNamespace, Name, Die); 3383 } 3384 3385 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name, 3386 const DIE &Die, char Flags) { 3387 addAccelNameImpl(CU, AccelTypes, Name, Die); 3388 } 3389 3390 uint16_t DwarfDebug::getDwarfVersion() const { 3391 return Asm->OutStreamer->getContext().getDwarfVersion(); 3392 } 3393 3394 dwarf::Form DwarfDebug::getDwarfSectionOffsetForm() const { 3395 if (Asm->getDwarfVersion() >= 4) 3396 return dwarf::Form::DW_FORM_sec_offset; 3397 assert((!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) && 3398 "DWARF64 is not defined prior DWARFv3"); 3399 return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data8 3400 : dwarf::Form::DW_FORM_data4; 3401 } 3402 3403 const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) { 3404 auto I = SectionLabels.find(S); 3405 if (I == SectionLabels.end()) 3406 return nullptr; 3407 return I->second; 3408 } 3409 void DwarfDebug::insertSectionLabel(const MCSymbol *S) { 3410 if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second) 3411 if (useSplitDwarf() || getDwarfVersion() >= 5) 3412 AddrPool.getIndex(S); 3413 } 3414 3415 Optional<MD5::MD5Result> DwarfDebug::getMD5AsBytes(const DIFile *File) const { 3416 assert(File); 3417 if (getDwarfVersion() < 5) 3418 return None; 3419 Optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum(); 3420 if (!Checksum || Checksum->Kind != DIFile::CSK_MD5) 3421 return None; 3422 3423 // Convert the string checksum to an MD5Result for the streamer. 3424 // The verifier validates the checksum so we assume it's okay. 3425 // An MD5 checksum is 16 bytes. 3426 std::string ChecksumString = fromHex(Checksum->Value); 3427 MD5::MD5Result CKMem; 3428 std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.Bytes.data()); 3429 return CKMem; 3430 } 3431