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