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