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