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