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