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