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