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