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