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