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