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