1 //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains support for writing dwarf debug info into asm files. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "DwarfDebug.h" 15 #include "ByteStreamer.h" 16 #include "DIEHash.h" 17 #include "DebugLocEntry.h" 18 #include "DebugLocStream.h" 19 #include "DwarfCompileUnit.h" 20 #include "DwarfExpression.h" 21 #include "DwarfFile.h" 22 #include "DwarfUnit.h" 23 #include "llvm/ADT/APInt.h" 24 #include "llvm/ADT/DenseMap.h" 25 #include "llvm/ADT/DenseSet.h" 26 #include "llvm/ADT/MapVector.h" 27 #include "llvm/ADT/STLExtras.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/StringRef.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/TargetRegisterInfo.h" 43 #include "llvm/CodeGen/TargetSubtargetInfo.h" 44 #include "llvm/IR/Constants.h" 45 #include "llvm/IR/DebugInfoMetadata.h" 46 #include "llvm/IR/DebugLoc.h" 47 #include "llvm/IR/Function.h" 48 #include "llvm/IR/GlobalVariable.h" 49 #include "llvm/IR/Module.h" 50 #include "llvm/MC/MCAsmInfo.h" 51 #include "llvm/MC/MCContext.h" 52 #include "llvm/MC/MCDwarf.h" 53 #include "llvm/MC/MCSection.h" 54 #include "llvm/MC/MCStreamer.h" 55 #include "llvm/MC/MCSymbol.h" 56 #include "llvm/MC/MCTargetOptions.h" 57 #include "llvm/MC/MachineLocation.h" 58 #include "llvm/MC/SectionKind.h" 59 #include "llvm/Pass.h" 60 #include "llvm/Support/Casting.h" 61 #include "llvm/Support/CommandLine.h" 62 #include "llvm/Support/Debug.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/MD5.h" 65 #include "llvm/Support/MathExtras.h" 66 #include "llvm/Support/Timer.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include "llvm/Target/TargetLoweringObjectFile.h" 69 #include "llvm/Target/TargetMachine.h" 70 #include "llvm/Target/TargetOptions.h" 71 #include <algorithm> 72 #include <cassert> 73 #include <cstddef> 74 #include <cstdint> 75 #include <iterator> 76 #include <string> 77 #include <utility> 78 #include <vector> 79 80 using namespace llvm; 81 82 #define DEBUG_TYPE "dwarfdebug" 83 84 static cl::opt<bool> 85 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden, 86 cl::desc("Disable debug info printing")); 87 88 static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier( 89 "use-dwarf-ranges-base-address-specifier", cl::Hidden, 90 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false)); 91 92 static cl::opt<bool> GenerateARangeSection("generate-arange-section", 93 cl::Hidden, 94 cl::desc("Generate dwarf aranges"), 95 cl::init(false)); 96 97 static cl::opt<bool> 98 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden, 99 cl::desc("Generate DWARF4 type units."), 100 cl::init(false)); 101 102 static cl::opt<bool> SplitDwarfCrossCuReferences( 103 "split-dwarf-cross-cu-references", cl::Hidden, 104 cl::desc("Enable cross-cu references in DWO files"), cl::init(false)); 105 106 enum DefaultOnOff { Default, Enable, Disable }; 107 108 static cl::opt<DefaultOnOff> UnknownLocations( 109 "use-unknown-locations", cl::Hidden, 110 cl::desc("Make an absence of debug location information explicit."), 111 cl::values(clEnumVal(Default, "At top of block or after label"), 112 clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")), 113 cl::init(Default)); 114 115 static cl::opt<AccelTableKind> AccelTables( 116 "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."), 117 cl::values(clEnumValN(AccelTableKind::Default, "Default", 118 "Default for platform"), 119 clEnumValN(AccelTableKind::None, "Disable", "Disabled."), 120 clEnumValN(AccelTableKind::Apple, "Apple", "Apple"), 121 clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")), 122 cl::init(AccelTableKind::Default)); 123 124 static cl::opt<DefaultOnOff> 125 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden, 126 cl::desc("Use inlined strings rather than string section."), 127 cl::values(clEnumVal(Default, "Default for platform"), 128 clEnumVal(Enable, "Enabled"), 129 clEnumVal(Disable, "Disabled")), 130 cl::init(Default)); 131 132 static cl::opt<bool> 133 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden, 134 cl::desc("Disable emission .debug_ranges section."), 135 cl::init(false)); 136 137 static cl::opt<DefaultOnOff> DwarfSectionsAsReferences( 138 "dwarf-sections-as-references", cl::Hidden, 139 cl::desc("Use sections+offset as references rather than labels."), 140 cl::values(clEnumVal(Default, "Default for platform"), 141 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), 142 cl::init(Default)); 143 144 enum LinkageNameOption { 145 DefaultLinkageNames, 146 AllLinkageNames, 147 AbstractLinkageNames 148 }; 149 150 static cl::opt<LinkageNameOption> 151 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden, 152 cl::desc("Which DWARF linkage-name attributes to emit."), 153 cl::values(clEnumValN(DefaultLinkageNames, "Default", 154 "Default for platform"), 155 clEnumValN(AllLinkageNames, "All", "All"), 156 clEnumValN(AbstractLinkageNames, "Abstract", 157 "Abstract subprograms")), 158 cl::init(DefaultLinkageNames)); 159 160 static const char *const DWARFGroupName = "dwarf"; 161 static const char *const DWARFGroupDescription = "DWARF Emission"; 162 static const char *const DbgTimerName = "writer"; 163 static const char *const DbgTimerDescription = "DWARF Debug Writer"; 164 165 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) { 166 BS.EmitInt8( 167 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op) 168 : dwarf::OperationEncodingString(Op)); 169 } 170 171 void DebugLocDwarfExpression::emitSigned(int64_t Value) { 172 BS.EmitSLEB128(Value, Twine(Value)); 173 } 174 175 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) { 176 BS.EmitULEB128(Value, Twine(Value)); 177 } 178 179 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI, 180 unsigned MachineReg) { 181 // This information is not available while emitting .debug_loc entries. 182 return false; 183 } 184 185 bool DbgVariable::isBlockByrefVariable() const { 186 assert(getVariable() && "Invalid complex DbgVariable!"); 187 return getVariable()->getType().resolve()->isBlockByrefStruct(); 188 } 189 190 const DIType *DbgVariable::getType() const { 191 DIType *Ty = getVariable()->getType().resolve(); 192 // FIXME: isBlockByrefVariable should be reformulated in terms of complex 193 // addresses instead. 194 if (Ty->isBlockByrefStruct()) { 195 /* Byref variables, in Blocks, are declared by the programmer as 196 "SomeType VarName;", but the compiler creates a 197 __Block_byref_x_VarName struct, and gives the variable VarName 198 either the struct, or a pointer to the struct, as its type. This 199 is necessary for various behind-the-scenes things the compiler 200 needs to do with by-reference variables in blocks. 201 202 However, as far as the original *programmer* is concerned, the 203 variable should still have type 'SomeType', as originally declared. 204 205 The following function dives into the __Block_byref_x_VarName 206 struct to find the original type of the variable. This will be 207 passed back to the code generating the type for the Debug 208 Information Entry for the variable 'VarName'. 'VarName' will then 209 have the original type 'SomeType' in its debug information. 210 211 The original type 'SomeType' will be the type of the field named 212 'VarName' inside the __Block_byref_x_VarName struct. 213 214 NOTE: In order for this to not completely fail on the debugger 215 side, the Debug Information Entry for the variable VarName needs to 216 have a DW_AT_location that tells the debugger how to unwind through 217 the pointers and __Block_byref_x_VarName struct to find the actual 218 value of the variable. The function addBlockByrefType does this. */ 219 DIType *subType = Ty; 220 uint16_t tag = Ty->getTag(); 221 222 if (tag == dwarf::DW_TAG_pointer_type) 223 subType = resolve(cast<DIDerivedType>(Ty)->getBaseType()); 224 225 auto Elements = cast<DICompositeType>(subType)->getElements(); 226 for (unsigned i = 0, N = Elements.size(); i < N; ++i) { 227 auto *DT = cast<DIDerivedType>(Elements[i]); 228 if (getName() == DT->getName()) 229 return resolve(DT->getBaseType()); 230 } 231 } 232 return Ty; 233 } 234 235 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const { 236 if (FrameIndexExprs.size() == 1) 237 return FrameIndexExprs; 238 239 assert(llvm::all_of(FrameIndexExprs, 240 [](const FrameIndexExpr &A) { 241 return A.Expr->isFragment(); 242 }) && 243 "multiple FI expressions without DW_OP_LLVM_fragment"); 244 llvm::sort(FrameIndexExprs.begin(), FrameIndexExprs.end(), 245 [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool { 246 return A.Expr->getFragmentInfo()->OffsetInBits < 247 B.Expr->getFragmentInfo()->OffsetInBits; 248 }); 249 250 return FrameIndexExprs; 251 } 252 253 void DbgVariable::addMMIEntry(const DbgVariable &V) { 254 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry"); 255 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry"); 256 assert(V.getVariable() == getVariable() && "conflicting variable"); 257 assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location"); 258 259 assert(!FrameIndexExprs.empty() && "Expected an MMI entry"); 260 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry"); 261 262 // FIXME: This logic should not be necessary anymore, as we now have proper 263 // deduplication. However, without it, we currently run into the assertion 264 // below, which means that we are likely dealing with broken input, i.e. two 265 // non-fragment entries for the same variable at different frame indices. 266 if (FrameIndexExprs.size()) { 267 auto *Expr = FrameIndexExprs.back().Expr; 268 if (!Expr || !Expr->isFragment()) 269 return; 270 } 271 272 for (const auto &FIE : V.FrameIndexExprs) 273 // Ignore duplicate entries. 274 if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) { 275 return FIE.FI == Other.FI && FIE.Expr == Other.Expr; 276 })) 277 FrameIndexExprs.push_back(FIE); 278 279 assert((FrameIndexExprs.size() == 1 || 280 llvm::all_of(FrameIndexExprs, 281 [](FrameIndexExpr &FIE) { 282 return FIE.Expr && FIE.Expr->isFragment(); 283 })) && 284 "conflicting locations for variable"); 285 } 286 287 static AccelTableKind computeAccelTableKind(unsigned DwarfVersion, 288 bool GenerateTypeUnits, 289 DebuggerKind Tuning, 290 const Triple &TT) { 291 // Honor an explicit request. 292 if (AccelTables != AccelTableKind::Default) 293 return AccelTables; 294 295 // Accelerator tables with type units are currently not supported. 296 if (GenerateTypeUnits) 297 return AccelTableKind::None; 298 299 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5 300 // always implies debug_names. For lower standard versions we use apple 301 // accelerator tables on apple platforms and debug_names elsewhere. 302 if (DwarfVersion >= 5) 303 return AccelTableKind::Dwarf; 304 if (Tuning == DebuggerKind::LLDB) 305 return TT.isOSBinFormatMachO() ? AccelTableKind::Apple 306 : AccelTableKind::Dwarf; 307 return AccelTableKind::None; 308 } 309 310 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M) 311 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()), 312 InfoHolder(A, "info_string", DIEValueAllocator), 313 SkeletonHolder(A, "skel_string", DIEValueAllocator), 314 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) { 315 const Triple &TT = Asm->TM.getTargetTriple(); 316 317 // Make sure we know our "debugger tuning." The target option takes 318 // precedence; fall back to triple-based defaults. 319 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default) 320 DebuggerTuning = Asm->TM.Options.DebuggerTuning; 321 else if (IsDarwin) 322 DebuggerTuning = DebuggerKind::LLDB; 323 else if (TT.isPS4CPU()) 324 DebuggerTuning = DebuggerKind::SCE; 325 else 326 DebuggerTuning = DebuggerKind::GDB; 327 328 if (DwarfInlinedStrings == Default) 329 UseInlineStrings = TT.isNVPTX(); 330 else 331 UseInlineStrings = DwarfInlinedStrings == Enable; 332 333 UseLocSection = !TT.isNVPTX(); 334 335 HasAppleExtensionAttributes = tuneForLLDB(); 336 337 // Handle split DWARF. 338 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty(); 339 340 // SCE defaults to linkage names only for abstract subprograms. 341 if (DwarfLinkageNames == DefaultLinkageNames) 342 UseAllLinkageNames = !tuneForSCE(); 343 else 344 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames; 345 346 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion; 347 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber 348 : MMI->getModule()->getDwarfVersion(); 349 // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2. 350 DwarfVersion = 351 TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION); 352 353 UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX(); 354 355 // Use sections as references. Force for NVPTX. 356 if (DwarfSectionsAsReferences == Default) 357 UseSectionsAsReferences = TT.isNVPTX(); 358 else 359 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable; 360 361 // Don't generate type units for unsupported object file formats. 362 GenerateTypeUnits = 363 A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits; 364 365 TheAccelTableKind = computeAccelTableKind( 366 DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple()); 367 368 // Work around a GDB bug. GDB doesn't support the standard opcode; 369 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which 370 // is defined as of DWARF 3. 371 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented 372 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616 373 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3; 374 375 // GDB does not fully support the DWARF 4 representation for bitfields. 376 UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB(); 377 378 // The DWARF v5 string offsets table has - possibly shared - contributions 379 // from each compile and type unit each preceded by a header. The string 380 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses 381 // a monolithic string offsets table without any header. 382 UseSegmentedStringOffsetsTable = DwarfVersion >= 5; 383 384 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion); 385 } 386 387 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h. 388 DwarfDebug::~DwarfDebug() = default; 389 390 static bool isObjCClass(StringRef Name) { 391 return Name.startswith("+") || Name.startswith("-"); 392 } 393 394 static bool hasObjCCategory(StringRef Name) { 395 if (!isObjCClass(Name)) 396 return false; 397 398 return Name.find(") ") != StringRef::npos; 399 } 400 401 static void getObjCClassCategory(StringRef In, StringRef &Class, 402 StringRef &Category) { 403 if (!hasObjCCategory(In)) { 404 Class = In.slice(In.find('[') + 1, In.find(' ')); 405 Category = ""; 406 return; 407 } 408 409 Class = In.slice(In.find('[') + 1, In.find('(')); 410 Category = In.slice(In.find('[') + 1, In.find(' ')); 411 } 412 413 static StringRef getObjCMethodName(StringRef In) { 414 return In.slice(In.find(' ') + 1, In.find(']')); 415 } 416 417 // Add the various names to the Dwarf accelerator table names. 418 void DwarfDebug::addSubprogramNames(const DICompileUnit &CU, 419 const DISubprogram *SP, DIE &Die) { 420 if (getAccelTableKind() != AccelTableKind::Apple && 421 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None) 422 return; 423 424 if (!SP->isDefinition()) 425 return; 426 427 if (SP->getName() != "") 428 addAccelName(CU, SP->getName(), Die); 429 430 // If the linkage name is different than the name, go ahead and output that as 431 // well into the name table. Only do that if we are going to actually emit 432 // that name. 433 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() && 434 (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP))) 435 addAccelName(CU, SP->getLinkageName(), Die); 436 437 // If this is an Objective-C selector name add it to the ObjC accelerator 438 // too. 439 if (isObjCClass(SP->getName())) { 440 StringRef Class, Category; 441 getObjCClassCategory(SP->getName(), Class, Category); 442 addAccelObjC(CU, Class, Die); 443 if (Category != "") 444 addAccelObjC(CU, Category, Die); 445 // Also add the base method name to the name table. 446 addAccelName(CU, getObjCMethodName(SP->getName()), Die); 447 } 448 } 449 450 /// Check whether we should create a DIE for the given Scope, return true 451 /// if we don't create a DIE (the corresponding DIE is null). 452 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) { 453 if (Scope->isAbstractScope()) 454 return false; 455 456 // We don't create a DIE if there is no Range. 457 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges(); 458 if (Ranges.empty()) 459 return true; 460 461 if (Ranges.size() > 1) 462 return false; 463 464 // We don't create a DIE if we have a single Range and the end label 465 // is null. 466 return !getLabelAfterInsn(Ranges.front().second); 467 } 468 469 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) { 470 F(CU); 471 if (auto *SkelCU = CU.getSkeleton()) 472 if (CU.getCUNode()->getSplitDebugInlining()) 473 F(*SkelCU); 474 } 475 476 bool DwarfDebug::shareAcrossDWOCUs() const { 477 return SplitDwarfCrossCuReferences; 478 } 479 480 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, 481 LexicalScope *Scope) { 482 assert(Scope && Scope->getScopeNode()); 483 assert(Scope->isAbstractScope()); 484 assert(!Scope->getInlinedAt()); 485 486 auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 487 488 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 489 // was inlined from another compile unit. 490 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining()) 491 // Avoid building the original CU if it won't be used 492 SrcCU.constructAbstractSubprogramScopeDIE(Scope); 493 else { 494 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 495 if (auto *SkelCU = CU.getSkeleton()) { 496 (shareAcrossDWOCUs() ? CU : SrcCU) 497 .constructAbstractSubprogramScopeDIE(Scope); 498 if (CU.getCUNode()->getSplitDebugInlining()) 499 SkelCU->constructAbstractSubprogramScopeDIE(Scope); 500 } else 501 CU.constructAbstractSubprogramScopeDIE(Scope); 502 } 503 } 504 505 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const { 506 if (!U.hasDwarfPubSections()) 507 return; 508 509 U.addFlag(D, dwarf::DW_AT_GNU_pubnames); 510 } 511 512 // Create new DwarfCompileUnit for the given metadata node with tag 513 // DW_TAG_compile_unit. 514 DwarfCompileUnit & 515 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) { 516 if (auto *CU = CUMap.lookup(DIUnit)) 517 return *CU; 518 StringRef FN = DIUnit->getFilename(); 519 CompilationDir = DIUnit->getDirectory(); 520 521 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 522 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder); 523 DwarfCompileUnit &NewCU = *OwnedUnit; 524 DIE &Die = NewCU.getUnitDie(); 525 InfoHolder.addUnit(std::move(OwnedUnit)); 526 if (useSplitDwarf()) { 527 NewCU.setSkeleton(constructSkeletonCU(NewCU)); 528 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name, 529 Asm->TM.Options.MCOptions.SplitDwarfFile); 530 } 531 532 for (auto *IE : DIUnit->getImportedEntities()) 533 NewCU.addImportedEntity(IE); 534 535 // LTO with assembly output shares a single line table amongst multiple CUs. 536 // To avoid the compilation directory being ambiguous, let the line table 537 // explicitly describe the directory of all files, never relying on the 538 // compilation directory. 539 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU) 540 Asm->OutStreamer->emitDwarfFile0Directive( 541 CompilationDir, FN, NewCU.getMD5AsBytes(DIUnit->getFile()), 542 DIUnit->getSource(), NewCU.getUniqueID()); 543 544 StringRef Producer = DIUnit->getProducer(); 545 StringRef Flags = DIUnit->getFlags(); 546 if (!Flags.empty() && !useAppleExtensionAttributes()) { 547 std::string ProducerWithFlags = Producer.str() + " " + Flags.str(); 548 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags); 549 } else 550 NewCU.addString(Die, dwarf::DW_AT_producer, Producer); 551 552 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 553 DIUnit->getSourceLanguage()); 554 NewCU.addString(Die, dwarf::DW_AT_name, FN); 555 556 // Add DW_str_offsets_base to the unit DIE, except for split units. 557 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 558 NewCU.addStringOffsetsStart(); 559 560 if (!useSplitDwarf()) { 561 NewCU.initStmtList(); 562 563 // If we're using split dwarf the compilation dir is going to be in the 564 // skeleton CU and so we don't need to duplicate it here. 565 if (!CompilationDir.empty()) 566 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 567 568 addGnuPubAttributes(NewCU, Die); 569 } 570 571 if (useAppleExtensionAttributes()) { 572 if (DIUnit->isOptimized()) 573 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized); 574 575 StringRef Flags = DIUnit->getFlags(); 576 if (!Flags.empty()) 577 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags); 578 579 if (unsigned RVer = DIUnit->getRuntimeVersion()) 580 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 581 dwarf::DW_FORM_data1, RVer); 582 } 583 584 if (useSplitDwarf()) 585 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection()); 586 else 587 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 588 589 if (DIUnit->getDWOId()) { 590 // This CU is either a clang module DWO or a skeleton CU. 591 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 592 DIUnit->getDWOId()); 593 if (!DIUnit->getSplitDebugFilename().empty()) 594 // This is a prefabricated skeleton CU. 595 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name, 596 DIUnit->getSplitDebugFilename()); 597 } 598 599 CUMap.insert({DIUnit, &NewCU}); 600 CUDieMap.insert({&Die, &NewCU}); 601 return NewCU; 602 } 603 604 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU, 605 const DIImportedEntity *N) { 606 if (isa<DILocalScope>(N->getScope())) 607 return; 608 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope())) 609 D->addChild(TheCU.constructImportedEntityDIE(N)); 610 } 611 612 /// Sort and unique GVEs by comparing their fragment offset. 613 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> & 614 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) { 615 llvm::sort(GVEs.begin(), GVEs.end(), 616 [](DwarfCompileUnit::GlobalExpr A, 617 DwarfCompileUnit::GlobalExpr B) { 618 // Sort order: first null exprs, then exprs without fragment 619 // info, then sort by fragment offset in bits. 620 // FIXME: Come up with a more comprehensive comparator so 621 // the sorting isn't non-deterministic, and so the following 622 // std::unique call works correctly. 623 if (!A.Expr || !B.Expr) 624 return !!B.Expr; 625 auto FragmentA = A.Expr->getFragmentInfo(); 626 auto FragmentB = B.Expr->getFragmentInfo(); 627 if (!FragmentA || !FragmentB) 628 return !!FragmentB; 629 return FragmentA->OffsetInBits < FragmentB->OffsetInBits; 630 }); 631 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(), 632 [](DwarfCompileUnit::GlobalExpr A, 633 DwarfCompileUnit::GlobalExpr B) { 634 return A.Expr == B.Expr; 635 }), 636 GVEs.end()); 637 return GVEs; 638 } 639 640 // Emit all Dwarf sections that should come prior to the content. Create 641 // global DIEs and emit initial debug info sections. This is invoked by 642 // the target AsmPrinter. 643 void DwarfDebug::beginModule() { 644 NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName, 645 DWARFGroupDescription, TimePassesIsEnabled); 646 if (DisableDebugInfoPrinting) 647 return; 648 649 const Module *M = MMI->getModule(); 650 651 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(), 652 M->debug_compile_units_end()); 653 // Tell MMI whether we have debug info. 654 MMI->setDebugInfoAvailability(NumDebugCUs > 0); 655 SingleCU = NumDebugCUs == 1; 656 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>> 657 GVMap; 658 for (const GlobalVariable &Global : M->globals()) { 659 SmallVector<DIGlobalVariableExpression *, 1> GVs; 660 Global.getDebugInfo(GVs); 661 for (auto *GVE : GVs) 662 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()}); 663 } 664 665 // Create the symbol that designates the start of the unit's contribution 666 // to the string offsets table. In a split DWARF scenario, only the skeleton 667 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol). 668 if (useSegmentedStringOffsetsTable()) 669 (useSplitDwarf() ? SkeletonHolder : InfoHolder) 670 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base")); 671 672 // Create the symbol that designates the start of the DWARF v5 range list 673 // table. It is located past the header and before the offsets table. 674 if (getDwarfVersion() >= 5) 675 (useSplitDwarf() ? SkeletonHolder : InfoHolder) 676 .setRnglistsTableBaseSym(Asm->createTempSymbol("rnglists_table_base")); 677 678 // Create the symbol that points to the first entry following the debug 679 // address table (.debug_addr) header. 680 AddrPool.setLabel(Asm->createTempSymbol("addr_table_base")); 681 682 for (DICompileUnit *CUNode : M->debug_compile_units()) { 683 // FIXME: Move local imported entities into a list attached to the 684 // subprogram, then this search won't be needed and a 685 // getImportedEntities().empty() test should go below with the rest. 686 bool HasNonLocalImportedEntities = llvm::any_of( 687 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) { 688 return !isa<DILocalScope>(IE->getScope()); 689 }); 690 691 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() && 692 CUNode->getRetainedTypes().empty() && 693 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty()) 694 continue; 695 696 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode); 697 698 // Global Variables. 699 for (auto *GVE : CUNode->getGlobalVariables()) { 700 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we 701 // already know about the variable and it isn't adding a constant 702 // expression. 703 auto &GVMapEntry = GVMap[GVE->getVariable()]; 704 auto *Expr = GVE->getExpression(); 705 if (!GVMapEntry.size() || (Expr && Expr->isConstant())) 706 GVMapEntry.push_back({nullptr, Expr}); 707 } 708 DenseSet<DIGlobalVariable *> Processed; 709 for (auto *GVE : CUNode->getGlobalVariables()) { 710 DIGlobalVariable *GV = GVE->getVariable(); 711 if (Processed.insert(GV).second) 712 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV])); 713 } 714 715 for (auto *Ty : CUNode->getEnumTypes()) { 716 // The enum types array by design contains pointers to 717 // MDNodes rather than DIRefs. Unique them here. 718 CU.getOrCreateTypeDIE(cast<DIType>(Ty)); 719 } 720 for (auto *Ty : CUNode->getRetainedTypes()) { 721 // The retained types array by design contains pointers to 722 // MDNodes rather than DIRefs. Unique them here. 723 if (DIType *RT = dyn_cast<DIType>(Ty)) 724 // There is no point in force-emitting a forward declaration. 725 CU.getOrCreateTypeDIE(RT); 726 } 727 // Emit imported_modules last so that the relevant context is already 728 // available. 729 for (auto *IE : CUNode->getImportedEntities()) 730 constructAndAddImportedEntityDIE(CU, IE); 731 } 732 } 733 734 void DwarfDebug::finishEntityDefinitions() { 735 for (const auto &Entity : ConcreteEntities) { 736 DIE *Die = Entity->getDIE(); 737 assert(Die); 738 // FIXME: Consider the time-space tradeoff of just storing the unit pointer 739 // in the ConcreteEntities list, rather than looking it up again here. 740 // DIE::getUnit isn't simple - it walks parent pointers, etc. 741 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie()); 742 assert(Unit); 743 Unit->finishEntityDefinition(Entity.get()); 744 } 745 } 746 747 void DwarfDebug::finishSubprogramDefinitions() { 748 for (const DISubprogram *SP : ProcessedSPNodes) { 749 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug); 750 forBothCUs( 751 getOrCreateDwarfCompileUnit(SP->getUnit()), 752 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); }); 753 } 754 } 755 756 void DwarfDebug::finalizeModuleInfo() { 757 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 758 759 finishSubprogramDefinitions(); 760 761 finishEntityDefinitions(); 762 763 // Include the DWO file name in the hash if there's more than one CU. 764 // This handles ThinLTO's situation where imported CUs may very easily be 765 // duplicate with the same CU partially imported into another ThinLTO unit. 766 StringRef DWOName; 767 if (CUMap.size() > 1) 768 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile; 769 770 // Handle anything that needs to be done on a per-unit basis after 771 // all other generation. 772 for (const auto &P : CUMap) { 773 auto &TheCU = *P.second; 774 if (TheCU.getCUNode()->isDebugDirectivesOnly()) 775 continue; 776 // Emit DW_AT_containing_type attribute to connect types with their 777 // vtable holding type. 778 TheCU.constructContainingTypeDIEs(); 779 780 // Add CU specific attributes if we need to add any. 781 // If we're splitting the dwarf out now that we've got the entire 782 // CU then add the dwo id to it. 783 auto *SkCU = TheCU.getSkeleton(); 784 if (useSplitDwarf()) { 785 // Emit a unique identifier for this CU. 786 uint64_t ID = 787 DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie()); 788 if (getDwarfVersion() >= 5) { 789 TheCU.setDWOId(ID); 790 SkCU->setDWOId(ID); 791 } else { 792 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 793 dwarf::DW_FORM_data8, ID); 794 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 795 dwarf::DW_FORM_data8, ID); 796 } 797 // We don't keep track of which addresses are used in which CU so this 798 // is a bit pessimistic under LTO. 799 if (!AddrPool.isEmpty()) 800 SkCU->addAddrTableBase(); 801 802 if (getDwarfVersion() < 5 && !SkCU->getRangeLists().empty()) { 803 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol(); 804 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base, 805 Sym, Sym); 806 } 807 } 808 809 // If we have code split among multiple sections or non-contiguous 810 // ranges of code then emit a DW_AT_ranges attribute on the unit that will 811 // remain in the .o file, otherwise add a DW_AT_low_pc. 812 // FIXME: We should use ranges allow reordering of code ala 813 // .subsections_via_symbols in mach-o. This would mean turning on 814 // ranges for all subprogram DIEs for mach-o. 815 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 816 if (unsigned NumRanges = TheCU.getRanges().size()) { 817 if (NumRanges > 1 && useRangesSection()) 818 // A DW_AT_low_pc attribute may also be specified in combination with 819 // DW_AT_ranges to specify the default base address for use in 820 // location lists (see Section 2.6.2) and range lists (see Section 821 // 2.17.3). 822 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0); 823 else 824 U.setBaseAddress(TheCU.getRanges().front().getStart()); 825 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges()); 826 } 827 828 if (getDwarfVersion() >= 5 && !useSplitDwarf() && 829 !U.getRangeLists().empty()) 830 U.addRnglistsBase(); 831 832 auto *CUNode = cast<DICompileUnit>(P.first); 833 // If compile Unit has macros, emit "DW_AT_macro_info" attribute. 834 if (CUNode->getMacros()) 835 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info, 836 U.getMacroLabelBegin(), 837 TLOF.getDwarfMacinfoSection()->getBeginSymbol()); 838 } 839 840 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules. 841 for (auto *CUNode : MMI->getModule()->debug_compile_units()) 842 if (CUNode->getDWOId()) 843 getOrCreateDwarfCompileUnit(CUNode); 844 845 // Compute DIE offsets and sizes. 846 InfoHolder.computeSizeAndOffsets(); 847 if (useSplitDwarf()) 848 SkeletonHolder.computeSizeAndOffsets(); 849 } 850 851 // Emit all Dwarf sections that should come after the content. 852 void DwarfDebug::endModule() { 853 assert(CurFn == nullptr); 854 assert(CurMI == nullptr); 855 856 // If we aren't actually generating debug info (check beginModule - 857 // conditionalized on !DisableDebugInfoPrinting and the presence of the 858 // llvm.dbg.cu metadata node) 859 if (!MMI->hasDebugInfo()) 860 return; 861 862 // Finalize the debug info for the module. 863 finalizeModuleInfo(); 864 865 emitDebugStr(); 866 867 if (useSplitDwarf()) 868 emitDebugLocDWO(); 869 else 870 // Emit info into a debug loc section. 871 emitDebugLoc(); 872 873 // Corresponding abbreviations into a abbrev section. 874 emitAbbreviations(); 875 876 // Emit all the DIEs into a debug info section. 877 emitDebugInfo(); 878 879 // Emit info into a debug aranges section. 880 if (GenerateARangeSection) 881 emitDebugARanges(); 882 883 // Emit info into a debug ranges section. 884 emitDebugRanges(); 885 886 // Emit info into a debug macinfo section. 887 emitDebugMacinfo(); 888 889 if (useSplitDwarf()) { 890 emitDebugStrDWO(); 891 emitDebugInfoDWO(); 892 emitDebugAbbrevDWO(); 893 emitDebugLineDWO(); 894 emitDebugAddr(); 895 } 896 897 // Emit info into the dwarf accelerator table sections. 898 switch (getAccelTableKind()) { 899 case AccelTableKind::Apple: 900 emitAccelNames(); 901 emitAccelObjC(); 902 emitAccelNamespaces(); 903 emitAccelTypes(); 904 break; 905 case AccelTableKind::Dwarf: 906 emitAccelDebugNames(); 907 break; 908 case AccelTableKind::None: 909 break; 910 case AccelTableKind::Default: 911 llvm_unreachable("Default should have already been resolved."); 912 } 913 914 // Emit the pubnames and pubtypes sections if requested. 915 emitDebugPubSections(); 916 917 // clean up. 918 // FIXME: AbstractVariables.clear(); 919 } 920 921 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU, 922 const DINode *Node, 923 const MDNode *ScopeNode) { 924 if (CU.getExistingAbstractEntity(Node)) 925 return; 926 927 CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope( 928 cast<DILocalScope>(ScopeNode))); 929 } 930 931 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU, 932 const DINode *Node, const MDNode *ScopeNode) { 933 if (CU.getExistingAbstractEntity(Node)) 934 return; 935 936 if (LexicalScope *Scope = 937 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode))) 938 CU.createAbstractEntity(Node, Scope); 939 } 940 941 // Collect variable information from side table maintained by MF. 942 void DwarfDebug::collectVariableInfoFromMFTable( 943 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) { 944 SmallDenseMap<InlinedEntity, DbgVariable *> MFVars; 945 for (const auto &VI : Asm->MF->getVariableDbgInfo()) { 946 if (!VI.Var) 947 continue; 948 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 949 "Expected inlined-at fields to agree"); 950 951 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt()); 952 Processed.insert(Var); 953 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 954 955 // If variable scope is not found then skip this variable. 956 if (!Scope) 957 continue; 958 959 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode()); 960 auto RegVar = llvm::make_unique<DbgVariable>( 961 cast<DILocalVariable>(Var.first), Var.second); 962 RegVar->initializeMMI(VI.Expr, VI.Slot); 963 if (DbgVariable *DbgVar = MFVars.lookup(Var)) 964 DbgVar->addMMIEntry(*RegVar); 965 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) { 966 MFVars.insert({Var, RegVar.get()}); 967 ConcreteEntities.push_back(std::move(RegVar)); 968 } 969 } 970 } 971 972 // Get .debug_loc entry for the instruction range starting at MI. 973 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) { 974 const DIExpression *Expr = MI->getDebugExpression(); 975 assert(MI->getNumOperands() == 4); 976 if (MI->getOperand(0).isReg()) { 977 auto RegOp = MI->getOperand(0); 978 auto Op1 = MI->getOperand(1); 979 // If the second operand is an immediate, this is a 980 // register-indirect address. 981 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset"); 982 MachineLocation MLoc(RegOp.getReg(), Op1.isImm()); 983 return DebugLocEntry::Value(Expr, MLoc); 984 } 985 if (MI->getOperand(0).isImm()) 986 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm()); 987 if (MI->getOperand(0).isFPImm()) 988 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm()); 989 if (MI->getOperand(0).isCImm()) 990 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm()); 991 992 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!"); 993 } 994 995 /// If this and Next are describing different fragments of the same 996 /// variable, merge them by appending Next's values to the current 997 /// list of values. 998 /// Return true if the merge was successful. 999 bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) { 1000 if (Begin == Next.Begin) { 1001 auto *FirstExpr = cast<DIExpression>(Values[0].Expression); 1002 auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression); 1003 if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment()) 1004 return false; 1005 1006 // We can only merge entries if none of the fragments overlap any others. 1007 // In doing so, we can take advantage of the fact that both lists are 1008 // sorted. 1009 for (unsigned i = 0, j = 0; i < Values.size(); ++i) { 1010 for (; j < Next.Values.size(); ++j) { 1011 int res = cast<DIExpression>(Values[i].Expression)->fragmentCmp( 1012 cast<DIExpression>(Next.Values[j].Expression)); 1013 if (res == 0) // The two expressions overlap, we can't merge. 1014 return false; 1015 // Values[i] is entirely before Next.Values[j], 1016 // so go back to the next entry of Values. 1017 else if (res == -1) 1018 break; 1019 // Next.Values[j] is entirely before Values[i], so go on to the 1020 // next entry of Next.Values. 1021 } 1022 } 1023 1024 addValues(Next.Values); 1025 End = Next.End; 1026 return true; 1027 } 1028 return false; 1029 } 1030 1031 /// Build the location list for all DBG_VALUEs in the function that 1032 /// describe the same variable. If the ranges of several independent 1033 /// fragments of the same variable overlap partially, split them up and 1034 /// combine the ranges. The resulting DebugLocEntries are will have 1035 /// strict monotonically increasing begin addresses and will never 1036 /// overlap. 1037 // 1038 // Input: 1039 // 1040 // Ranges History [var, loc, fragment ofs size] 1041 // 0 | [x, (reg0, fragment 0, 32)] 1042 // 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry 1043 // 2 | | ... 1044 // 3 | [clobber reg0] 1045 // 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of 1046 // x. 1047 // 1048 // Output: 1049 // 1050 // [0-1] [x, (reg0, fragment 0, 32)] 1051 // [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)] 1052 // [3-4] [x, (reg1, fragment 32, 32)] 1053 // [4- ] [x, (mem, fragment 0, 64)] 1054 void 1055 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc, 1056 const DbgValueHistoryMap::InstrRanges &Ranges) { 1057 SmallVector<DebugLocEntry::Value, 4> OpenRanges; 1058 1059 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 1060 const MachineInstr *Begin = I->first; 1061 const MachineInstr *End = I->second; 1062 assert(Begin->isDebugValue() && "Invalid History entry"); 1063 1064 // Check if a variable is inaccessible in this range. 1065 if (Begin->getNumOperands() > 1 && 1066 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) { 1067 OpenRanges.clear(); 1068 continue; 1069 } 1070 1071 // If this fragment overlaps with any open ranges, truncate them. 1072 const DIExpression *DIExpr = Begin->getDebugExpression(); 1073 auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) { 1074 return DIExpr->fragmentsOverlap(R.getExpression()); 1075 }); 1076 OpenRanges.erase(Last, OpenRanges.end()); 1077 1078 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin); 1079 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!"); 1080 1081 const MCSymbol *EndLabel; 1082 if (End != nullptr) 1083 EndLabel = getLabelAfterInsn(End); 1084 else if (std::next(I) == Ranges.end()) 1085 EndLabel = Asm->getFunctionEnd(); 1086 else 1087 EndLabel = getLabelBeforeInsn(std::next(I)->first); 1088 assert(EndLabel && "Forgot label after instruction ending a range!"); 1089 1090 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n"); 1091 1092 auto Value = getDebugLocValue(Begin); 1093 DebugLocEntry Loc(StartLabel, EndLabel, Value); 1094 bool couldMerge = false; 1095 1096 // If this is a fragment, it may belong to the current DebugLocEntry. 1097 if (DIExpr->isFragment()) { 1098 // Add this value to the list of open ranges. 1099 OpenRanges.push_back(Value); 1100 1101 // Attempt to add the fragment to the last entry. 1102 if (!DebugLoc.empty()) 1103 if (DebugLoc.back().MergeValues(Loc)) 1104 couldMerge = true; 1105 } 1106 1107 if (!couldMerge) { 1108 // Need to add a new DebugLocEntry. Add all values from still 1109 // valid non-overlapping fragments. 1110 if (OpenRanges.size()) 1111 Loc.addValues(OpenRanges); 1112 1113 DebugLoc.push_back(std::move(Loc)); 1114 } 1115 1116 // Attempt to coalesce the ranges of two otherwise identical 1117 // DebugLocEntries. 1118 auto CurEntry = DebugLoc.rbegin(); 1119 LLVM_DEBUG({ 1120 dbgs() << CurEntry->getValues().size() << " Values:\n"; 1121 for (auto &Value : CurEntry->getValues()) 1122 Value.dump(); 1123 dbgs() << "-----\n"; 1124 }); 1125 1126 auto PrevEntry = std::next(CurEntry); 1127 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry)) 1128 DebugLoc.pop_back(); 1129 } 1130 } 1131 1132 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU, 1133 LexicalScope &Scope, 1134 const DINode *Node, 1135 const DILocation *Location, 1136 const MCSymbol *Sym) { 1137 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode()); 1138 if (isa<const DILocalVariable>(Node)) { 1139 ConcreteEntities.push_back( 1140 llvm::make_unique<DbgVariable>(cast<const DILocalVariable>(Node), 1141 Location)); 1142 InfoHolder.addScopeVariable(&Scope, 1143 cast<DbgVariable>(ConcreteEntities.back().get())); 1144 } else if (isa<const DILabel>(Node)) { 1145 ConcreteEntities.push_back( 1146 llvm::make_unique<DbgLabel>(cast<const DILabel>(Node), 1147 Location, Sym)); 1148 InfoHolder.addScopeLabel(&Scope, 1149 cast<DbgLabel>(ConcreteEntities.back().get())); 1150 } 1151 return ConcreteEntities.back().get(); 1152 } 1153 1154 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its 1155 /// enclosing lexical scope. The check ensures there are no other instructions 1156 /// in the same lexical scope preceding the DBG_VALUE and that its range is 1157 /// either open or otherwise rolls off the end of the scope. 1158 static bool validThroughout(LexicalScopes &LScopes, 1159 const MachineInstr *DbgValue, 1160 const MachineInstr *RangeEnd) { 1161 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location"); 1162 auto MBB = DbgValue->getParent(); 1163 auto DL = DbgValue->getDebugLoc(); 1164 auto *LScope = LScopes.findLexicalScope(DL); 1165 // Scope doesn't exist; this is a dead DBG_VALUE. 1166 if (!LScope) 1167 return false; 1168 auto &LSRange = LScope->getRanges(); 1169 if (LSRange.size() == 0) 1170 return false; 1171 1172 // Determine if the DBG_VALUE is valid at the beginning of its lexical block. 1173 const MachineInstr *LScopeBegin = LSRange.front().first; 1174 // Early exit if the lexical scope begins outside of the current block. 1175 if (LScopeBegin->getParent() != MBB) 1176 return false; 1177 MachineBasicBlock::const_reverse_iterator Pred(DbgValue); 1178 for (++Pred; Pred != MBB->rend(); ++Pred) { 1179 if (Pred->getFlag(MachineInstr::FrameSetup)) 1180 break; 1181 auto PredDL = Pred->getDebugLoc(); 1182 if (!PredDL || Pred->isMetaInstruction()) 1183 continue; 1184 // Check whether the instruction preceding the DBG_VALUE is in the same 1185 // (sub)scope as the DBG_VALUE. 1186 if (DL->getScope() == PredDL->getScope()) 1187 return false; 1188 auto *PredScope = LScopes.findLexicalScope(PredDL); 1189 if (!PredScope || LScope->dominates(PredScope)) 1190 return false; 1191 } 1192 1193 // If the range of the DBG_VALUE is open-ended, report success. 1194 if (!RangeEnd) 1195 return true; 1196 1197 // Fail if there are instructions belonging to our scope in another block. 1198 const MachineInstr *LScopeEnd = LSRange.back().second; 1199 if (LScopeEnd->getParent() != MBB) 1200 return false; 1201 1202 // Single, constant DBG_VALUEs in the prologue are promoted to be live 1203 // throughout the function. This is a hack, presumably for DWARF v2 and not 1204 // necessarily correct. It would be much better to use a dbg.declare instead 1205 // if we know the constant is live throughout the scope. 1206 if (DbgValue->getOperand(0).isImm() && MBB->pred_empty()) 1207 return true; 1208 1209 return false; 1210 } 1211 1212 // Find variables for each lexical scope. 1213 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU, 1214 const DISubprogram *SP, 1215 DenseSet<InlinedEntity> &Processed) { 1216 // Grab the variable info that was squirreled away in the MMI side-table. 1217 collectVariableInfoFromMFTable(TheCU, Processed); 1218 1219 for (const auto &I : DbgValues) { 1220 InlinedEntity IV = I.first; 1221 if (Processed.count(IV)) 1222 continue; 1223 1224 // Instruction ranges, specifying where IV is accessible. 1225 const auto &Ranges = I.second; 1226 if (Ranges.empty()) 1227 continue; 1228 1229 LexicalScope *Scope = nullptr; 1230 const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first); 1231 if (const DILocation *IA = IV.second) 1232 Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA); 1233 else 1234 Scope = LScopes.findLexicalScope(LocalVar->getScope()); 1235 // If variable scope is not found then skip this variable. 1236 if (!Scope) 1237 continue; 1238 1239 Processed.insert(IV); 1240 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU, 1241 *Scope, LocalVar, IV.second)); 1242 1243 const MachineInstr *MInsn = Ranges.front().first; 1244 assert(MInsn->isDebugValue() && "History must begin with debug value"); 1245 1246 // Check if there is a single DBG_VALUE, valid throughout the var's scope. 1247 if (Ranges.size() == 1 && 1248 validThroughout(LScopes, MInsn, Ranges.front().second)) { 1249 RegVar->initializeDbgValue(MInsn); 1250 continue; 1251 } 1252 // Do not emit location lists if .debug_loc secton is disabled. 1253 if (!useLocSection()) 1254 continue; 1255 1256 // Handle multiple DBG_VALUE instructions describing one variable. 1257 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn); 1258 1259 // Build the location list for this variable. 1260 SmallVector<DebugLocEntry, 8> Entries; 1261 buildLocationList(Entries, Ranges); 1262 1263 // If the variable has a DIBasicType, extract it. Basic types cannot have 1264 // unique identifiers, so don't bother resolving the type with the 1265 // identifier map. 1266 const DIBasicType *BT = dyn_cast<DIBasicType>( 1267 static_cast<const Metadata *>(LocalVar->getType())); 1268 1269 // Finalize the entry by lowering it into a DWARF bytestream. 1270 for (auto &Entry : Entries) 1271 Entry.finalize(*Asm, List, BT); 1272 } 1273 1274 // For each InlinedEntity collected from DBG_LABEL instructions, convert to 1275 // DWARF-related DbgLabel. 1276 for (const auto &I : DbgLabels) { 1277 InlinedEntity IL = I.first; 1278 const MachineInstr *MI = I.second; 1279 if (MI == nullptr) 1280 continue; 1281 1282 LexicalScope *Scope = nullptr; 1283 const DILabel *Label = cast<DILabel>(IL.first); 1284 // Get inlined DILocation if it is inlined label. 1285 if (const DILocation *IA = IL.second) 1286 Scope = LScopes.findInlinedScope(Label->getScope(), IA); 1287 else 1288 Scope = LScopes.findLexicalScope(Label->getScope()); 1289 // If label scope is not found then skip this label. 1290 if (!Scope) 1291 continue; 1292 1293 Processed.insert(IL); 1294 /// At this point, the temporary label is created. 1295 /// Save the temporary label to DbgLabel entity to get the 1296 /// actually address when generating Dwarf DIE. 1297 MCSymbol *Sym = getLabelBeforeInsn(MI); 1298 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym); 1299 } 1300 1301 // Collect info for variables/labels that were optimized out. 1302 for (const DINode *DN : SP->getRetainedNodes()) { 1303 if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 1304 continue; 1305 LexicalScope *Scope = nullptr; 1306 if (auto *DV = dyn_cast<DILocalVariable>(DN)) { 1307 Scope = LScopes.findLexicalScope(DV->getScope()); 1308 } else if (auto *DL = dyn_cast<DILabel>(DN)) { 1309 Scope = LScopes.findLexicalScope(DL->getScope()); 1310 } 1311 1312 if (Scope) 1313 createConcreteEntity(TheCU, *Scope, DN, nullptr); 1314 } 1315 } 1316 1317 // Process beginning of an instruction. 1318 void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1319 DebugHandlerBase::beginInstruction(MI); 1320 assert(CurMI); 1321 1322 const auto *SP = MI->getMF()->getFunction().getSubprogram(); 1323 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1324 return; 1325 1326 // Check if source location changes, but ignore DBG_VALUE and CFI locations. 1327 // If the instruction is part of the function frame setup code, do not emit 1328 // any line record, as there is no correspondence with any user code. 1329 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup)) 1330 return; 1331 const DebugLoc &DL = MI->getDebugLoc(); 1332 // When we emit a line-0 record, we don't update PrevInstLoc; so look at 1333 // the last line number actually emitted, to see if it was line 0. 1334 unsigned LastAsmLine = 1335 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine(); 1336 1337 if (DL == PrevInstLoc) { 1338 // If we have an ongoing unspecified location, nothing to do here. 1339 if (!DL) 1340 return; 1341 // We have an explicit location, same as the previous location. 1342 // But we might be coming back to it after a line 0 record. 1343 if (LastAsmLine == 0 && DL.getLine() != 0) { 1344 // Reinstate the source location but not marked as a statement. 1345 const MDNode *Scope = DL.getScope(); 1346 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0); 1347 } 1348 return; 1349 } 1350 1351 if (!DL) { 1352 // We have an unspecified location, which might want to be line 0. 1353 // If we have already emitted a line-0 record, don't repeat it. 1354 if (LastAsmLine == 0) 1355 return; 1356 // If user said Don't Do That, don't do that. 1357 if (UnknownLocations == Disable) 1358 return; 1359 // See if we have a reason to emit a line-0 record now. 1360 // Reasons to emit a line-0 record include: 1361 // - User asked for it (UnknownLocations). 1362 // - Instruction has a label, so it's referenced from somewhere else, 1363 // possibly debug information; we want it to have a source location. 1364 // - Instruction is at the top of a block; we don't want to inherit the 1365 // location from the physically previous (maybe unrelated) block. 1366 if (UnknownLocations == Enable || PrevLabel || 1367 (PrevInstBB && PrevInstBB != MI->getParent())) { 1368 // Preserve the file and column numbers, if we can, to save space in 1369 // the encoded line table. 1370 // Do not update PrevInstLoc, it remembers the last non-0 line. 1371 const MDNode *Scope = nullptr; 1372 unsigned Column = 0; 1373 if (PrevInstLoc) { 1374 Scope = PrevInstLoc.getScope(); 1375 Column = PrevInstLoc.getCol(); 1376 } 1377 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0); 1378 } 1379 return; 1380 } 1381 1382 // We have an explicit location, different from the previous location. 1383 // Don't repeat a line-0 record, but otherwise emit the new location. 1384 // (The new location might be an explicit line 0, which we do emit.) 1385 if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0) 1386 return; 1387 unsigned Flags = 0; 1388 if (DL == PrologEndLoc) { 1389 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT; 1390 PrologEndLoc = DebugLoc(); 1391 } 1392 // If the line changed, we call that a new statement; unless we went to 1393 // line 0 and came back, in which case it is not a new statement. 1394 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine; 1395 if (DL.getLine() && DL.getLine() != OldLine) 1396 Flags |= DWARF2_FLAG_IS_STMT; 1397 1398 const MDNode *Scope = DL.getScope(); 1399 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1400 1401 // If we're not at line 0, remember this location. 1402 if (DL.getLine()) 1403 PrevInstLoc = DL; 1404 } 1405 1406 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) { 1407 // First known non-DBG_VALUE and non-frame setup location marks 1408 // the beginning of the function body. 1409 for (const auto &MBB : *MF) 1410 for (const auto &MI : MBB) 1411 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) && 1412 MI.getDebugLoc()) 1413 return MI.getDebugLoc(); 1414 return DebugLoc(); 1415 } 1416 1417 // Gather pre-function debug information. Assumes being called immediately 1418 // after the function entry point has been emitted. 1419 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) { 1420 CurFn = MF; 1421 1422 auto *SP = MF->getFunction().getSubprogram(); 1423 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode()); 1424 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1425 return; 1426 1427 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 1428 1429 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 1430 // belongs to so that we add to the correct per-cu line table in the 1431 // non-asm case. 1432 if (Asm->OutStreamer->hasRawTextSupport()) 1433 // Use a single line table if we are generating assembly. 1434 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1435 else 1436 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID()); 1437 1438 // Record beginning of function. 1439 PrologEndLoc = findPrologueEndLoc(MF); 1440 if (PrologEndLoc) { 1441 // We'd like to list the prologue as "not statements" but GDB behaves 1442 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 1443 auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram(); 1444 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT); 1445 } 1446 } 1447 1448 void DwarfDebug::skippedNonDebugFunction() { 1449 // If we don't have a subprogram for this function then there will be a hole 1450 // in the range information. Keep note of this by setting the previously used 1451 // section to nullptr. 1452 PrevCU = nullptr; 1453 CurFn = nullptr; 1454 } 1455 1456 // Gather and emit post-function debug information. 1457 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) { 1458 const DISubprogram *SP = MF->getFunction().getSubprogram(); 1459 1460 assert(CurFn == MF && 1461 "endFunction should be called with the same function as beginFunction"); 1462 1463 // Set DwarfDwarfCompileUnitID in MCContext to default value. 1464 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1465 1466 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1467 assert(!FnScope || SP == FnScope->getScopeNode()); 1468 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit()); 1469 if (TheCU.getCUNode()->isDebugDirectivesOnly()) { 1470 PrevLabel = nullptr; 1471 CurFn = nullptr; 1472 return; 1473 } 1474 1475 DenseSet<InlinedEntity> Processed; 1476 collectEntityInfo(TheCU, SP, Processed); 1477 1478 // Add the range of this function to the list of ranges for the CU. 1479 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd())); 1480 1481 // Under -gmlt, skip building the subprogram if there are no inlined 1482 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram 1483 // is still needed as we need its source location. 1484 if (!TheCU.getCUNode()->getDebugInfoForProfiling() && 1485 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly && 1486 LScopes.getAbstractScopesList().empty() && !IsDarwin) { 1487 assert(InfoHolder.getScopeVariables().empty()); 1488 PrevLabel = nullptr; 1489 CurFn = nullptr; 1490 return; 1491 } 1492 1493 #ifndef NDEBUG 1494 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size(); 1495 #endif 1496 // Construct abstract scopes. 1497 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) { 1498 auto *SP = cast<DISubprogram>(AScope->getScopeNode()); 1499 for (const DINode *DN : SP->getRetainedNodes()) { 1500 if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 1501 continue; 1502 1503 const MDNode *Scope = nullptr; 1504 if (auto *DV = dyn_cast<DILocalVariable>(DN)) 1505 Scope = DV->getScope(); 1506 else if (auto *DL = dyn_cast<DILabel>(DN)) 1507 Scope = DL->getScope(); 1508 else 1509 llvm_unreachable("Unexpected DI type!"); 1510 1511 // Collect info for variables/labels that were optimized out. 1512 ensureAbstractEntityIsCreated(TheCU, DN, Scope); 1513 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes 1514 && "ensureAbstractEntityIsCreated inserted abstract scopes"); 1515 } 1516 constructAbstractSubprogramScopeDIE(TheCU, AScope); 1517 } 1518 1519 ProcessedSPNodes.insert(SP); 1520 TheCU.constructSubprogramScopeDIE(SP, FnScope); 1521 if (auto *SkelCU = TheCU.getSkeleton()) 1522 if (!LScopes.getAbstractScopesList().empty() && 1523 TheCU.getCUNode()->getSplitDebugInlining()) 1524 SkelCU->constructSubprogramScopeDIE(SP, FnScope); 1525 1526 // Clear debug info 1527 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the 1528 // DbgVariables except those that are also in AbstractVariables (since they 1529 // can be used cross-function) 1530 InfoHolder.getScopeVariables().clear(); 1531 InfoHolder.getScopeLabels().clear(); 1532 PrevLabel = nullptr; 1533 CurFn = nullptr; 1534 } 1535 1536 // Register a source line with debug info. Returns the unique label that was 1537 // emitted and which provides correspondence to the source line list. 1538 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1539 unsigned Flags) { 1540 StringRef Fn; 1541 unsigned FileNo = 1; 1542 unsigned Discriminator = 0; 1543 if (auto *Scope = cast_or_null<DIScope>(S)) { 1544 Fn = Scope->getFilename(); 1545 if (Line != 0 && getDwarfVersion() >= 4) 1546 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope)) 1547 Discriminator = LBF->getDiscriminator(); 1548 1549 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID(); 1550 FileNo = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID]) 1551 .getOrCreateSourceID(Scope->getFile()); 1552 } 1553 Asm->OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0, 1554 Discriminator, Fn); 1555 } 1556 1557 //===----------------------------------------------------------------------===// 1558 // Emit Methods 1559 //===----------------------------------------------------------------------===// 1560 1561 // Emit the debug info section. 1562 void DwarfDebug::emitDebugInfo() { 1563 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1564 Holder.emitUnits(/* UseOffsets */ false); 1565 } 1566 1567 // Emit the abbreviation section. 1568 void DwarfDebug::emitAbbreviations() { 1569 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1570 1571 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection()); 1572 } 1573 1574 void DwarfDebug::emitStringOffsetsTableHeader() { 1575 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1576 Holder.getStringPool().emitStringOffsetsTableHeader( 1577 *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(), 1578 Holder.getStringOffsetsStartSym()); 1579 } 1580 1581 template <typename AccelTableT> 1582 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section, 1583 StringRef TableName) { 1584 Asm->OutStreamer->SwitchSection(Section); 1585 1586 // Emit the full data. 1587 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol()); 1588 } 1589 1590 void DwarfDebug::emitAccelDebugNames() { 1591 // Don't emit anything if we have no compilation units to index. 1592 if (getUnits().empty()) 1593 return; 1594 1595 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits()); 1596 } 1597 1598 // Emit visible names into a hashed accelerator table section. 1599 void DwarfDebug::emitAccelNames() { 1600 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(), 1601 "Names"); 1602 } 1603 1604 // Emit objective C classes and categories into a hashed accelerator table 1605 // section. 1606 void DwarfDebug::emitAccelObjC() { 1607 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(), 1608 "ObjC"); 1609 } 1610 1611 // Emit namespace dies into a hashed accelerator table. 1612 void DwarfDebug::emitAccelNamespaces() { 1613 emitAccel(AccelNamespace, 1614 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(), 1615 "namespac"); 1616 } 1617 1618 // Emit type dies into a hashed accelerator table. 1619 void DwarfDebug::emitAccelTypes() { 1620 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(), 1621 "types"); 1622 } 1623 1624 // Public name handling. 1625 // The format for the various pubnames: 1626 // 1627 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU 1628 // for the DIE that is named. 1629 // 1630 // gnu pubnames - offset/index value/name tuples where the offset is the offset 1631 // into the CU and the index value is computed according to the type of value 1632 // for the DIE that is named. 1633 // 1634 // For type units the offset is the offset of the skeleton DIE. For split dwarf 1635 // it's the offset within the debug_info/debug_types dwo section, however, the 1636 // reference in the pubname header doesn't change. 1637 1638 /// computeIndexValue - Compute the gdb index value for the DIE and CU. 1639 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, 1640 const DIE *Die) { 1641 // Entities that ended up only in a Type Unit reference the CU instead (since 1642 // the pub entry has offsets within the CU there's no real offset that can be 1643 // provided anyway). As it happens all such entities (namespaces and types, 1644 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out 1645 // not to be true it would be necessary to persist this information from the 1646 // point at which the entry is added to the index data structure - since by 1647 // the time the index is built from that, the original type/namespace DIE in a 1648 // type unit has already been destroyed so it can't be queried for properties 1649 // like tag, etc. 1650 if (Die->getTag() == dwarf::DW_TAG_compile_unit) 1651 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, 1652 dwarf::GIEL_EXTERNAL); 1653 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC; 1654 1655 // We could have a specification DIE that has our most of our knowledge, 1656 // look for that now. 1657 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) { 1658 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry(); 1659 if (SpecDIE.findAttribute(dwarf::DW_AT_external)) 1660 Linkage = dwarf::GIEL_EXTERNAL; 1661 } else if (Die->findAttribute(dwarf::DW_AT_external)) 1662 Linkage = dwarf::GIEL_EXTERNAL; 1663 1664 switch (Die->getTag()) { 1665 case dwarf::DW_TAG_class_type: 1666 case dwarf::DW_TAG_structure_type: 1667 case dwarf::DW_TAG_union_type: 1668 case dwarf::DW_TAG_enumeration_type: 1669 return dwarf::PubIndexEntryDescriptor( 1670 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus 1671 ? dwarf::GIEL_STATIC 1672 : dwarf::GIEL_EXTERNAL); 1673 case dwarf::DW_TAG_typedef: 1674 case dwarf::DW_TAG_base_type: 1675 case dwarf::DW_TAG_subrange_type: 1676 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC); 1677 case dwarf::DW_TAG_namespace: 1678 return dwarf::GIEK_TYPE; 1679 case dwarf::DW_TAG_subprogram: 1680 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage); 1681 case dwarf::DW_TAG_variable: 1682 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage); 1683 case dwarf::DW_TAG_enumerator: 1684 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, 1685 dwarf::GIEL_STATIC); 1686 default: 1687 return dwarf::GIEK_NONE; 1688 } 1689 } 1690 1691 /// emitDebugPubSections - Emit visible names and types into debug pubnames and 1692 /// pubtypes sections. 1693 void DwarfDebug::emitDebugPubSections() { 1694 for (const auto &NU : CUMap) { 1695 DwarfCompileUnit *TheU = NU.second; 1696 if (!TheU->hasDwarfPubSections()) 1697 continue; 1698 1699 bool GnuStyle = TheU->getCUNode()->getNameTableKind() == 1700 DICompileUnit::DebugNameTableKind::GNU; 1701 1702 Asm->OutStreamer->SwitchSection( 1703 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection() 1704 : Asm->getObjFileLowering().getDwarfPubNamesSection()); 1705 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames()); 1706 1707 Asm->OutStreamer->SwitchSection( 1708 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection() 1709 : Asm->getObjFileLowering().getDwarfPubTypesSection()); 1710 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes()); 1711 } 1712 } 1713 1714 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) { 1715 if (useSectionsAsReferences()) 1716 Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(), 1717 CU.getDebugSectionOffset()); 1718 else 1719 Asm->emitDwarfSymbolReference(CU.getLabelBegin()); 1720 } 1721 1722 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name, 1723 DwarfCompileUnit *TheU, 1724 const StringMap<const DIE *> &Globals) { 1725 if (auto *Skeleton = TheU->getSkeleton()) 1726 TheU = Skeleton; 1727 1728 // Emit the header. 1729 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info"); 1730 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin"); 1731 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end"); 1732 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); 1733 1734 Asm->OutStreamer->EmitLabel(BeginLabel); 1735 1736 Asm->OutStreamer->AddComment("DWARF Version"); 1737 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); 1738 1739 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info"); 1740 emitSectionReference(*TheU); 1741 1742 Asm->OutStreamer->AddComment("Compilation Unit Length"); 1743 Asm->emitInt32(TheU->getLength()); 1744 1745 // Emit the pubnames for this compilation unit. 1746 for (const auto &GI : Globals) { 1747 const char *Name = GI.getKeyData(); 1748 const DIE *Entity = GI.second; 1749 1750 Asm->OutStreamer->AddComment("DIE offset"); 1751 Asm->emitInt32(Entity->getOffset()); 1752 1753 if (GnuStyle) { 1754 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity); 1755 Asm->OutStreamer->AddComment( 1756 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " + 1757 dwarf::GDBIndexEntryLinkageString(Desc.Linkage)); 1758 Asm->emitInt8(Desc.toBits()); 1759 } 1760 1761 Asm->OutStreamer->AddComment("External Name"); 1762 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1)); 1763 } 1764 1765 Asm->OutStreamer->AddComment("End Mark"); 1766 Asm->emitInt32(0); 1767 Asm->OutStreamer->EmitLabel(EndLabel); 1768 } 1769 1770 /// Emit null-terminated strings into a debug str section. 1771 void DwarfDebug::emitDebugStr() { 1772 MCSection *StringOffsetsSection = nullptr; 1773 if (useSegmentedStringOffsetsTable()) { 1774 emitStringOffsetsTableHeader(); 1775 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection(); 1776 } 1777 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1778 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(), 1779 StringOffsetsSection, /* UseRelativeOffsets = */ true); 1780 } 1781 1782 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer, 1783 const DebugLocStream::Entry &Entry) { 1784 auto &&Comments = DebugLocs.getComments(Entry); 1785 auto Comment = Comments.begin(); 1786 auto End = Comments.end(); 1787 for (uint8_t Byte : DebugLocs.getBytes(Entry)) 1788 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : ""); 1789 } 1790 1791 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, 1792 const DebugLocEntry::Value &Value, 1793 DwarfExpression &DwarfExpr) { 1794 auto *DIExpr = Value.getExpression(); 1795 DIExpressionCursor ExprCursor(DIExpr); 1796 DwarfExpr.addFragmentOffset(DIExpr); 1797 // Regular entry. 1798 if (Value.isInt()) { 1799 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed || 1800 BT->getEncoding() == dwarf::DW_ATE_signed_char)) 1801 DwarfExpr.addSignedConstant(Value.getInt()); 1802 else 1803 DwarfExpr.addUnsignedConstant(Value.getInt()); 1804 } else if (Value.isLocation()) { 1805 MachineLocation Location = Value.getLoc(); 1806 if (Location.isIndirect()) 1807 DwarfExpr.setMemoryLocationKind(); 1808 DIExpressionCursor Cursor(DIExpr); 1809 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo(); 1810 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 1811 return; 1812 return DwarfExpr.addExpression(std::move(Cursor)); 1813 } else if (Value.isConstantFP()) { 1814 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt(); 1815 DwarfExpr.addUnsignedConstant(RawBytes); 1816 } 1817 DwarfExpr.addExpression(std::move(ExprCursor)); 1818 } 1819 1820 void DebugLocEntry::finalize(const AsmPrinter &AP, 1821 DebugLocStream::ListBuilder &List, 1822 const DIBasicType *BT) { 1823 DebugLocStream::EntryBuilder Entry(List, Begin, End); 1824 BufferByteStreamer Streamer = Entry.getStreamer(); 1825 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer); 1826 const DebugLocEntry::Value &Value = Values[0]; 1827 if (Value.isFragment()) { 1828 // Emit all fragments that belong to the same variable and range. 1829 assert(llvm::all_of(Values, [](DebugLocEntry::Value P) { 1830 return P.isFragment(); 1831 }) && "all values are expected to be fragments"); 1832 assert(std::is_sorted(Values.begin(), Values.end()) && 1833 "fragments are expected to be sorted"); 1834 1835 for (auto Fragment : Values) 1836 emitDebugLocValue(AP, BT, Fragment, DwarfExpr); 1837 1838 } else { 1839 assert(Values.size() == 1 && "only fragments may have >1 value"); 1840 emitDebugLocValue(AP, BT, Value, DwarfExpr); 1841 } 1842 DwarfExpr.finalize(); 1843 } 1844 1845 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) { 1846 // Emit the size. 1847 Asm->OutStreamer->AddComment("Loc expr size"); 1848 Asm->emitInt16(DebugLocs.getBytes(Entry).size()); 1849 1850 // Emit the entry. 1851 APByteStreamer Streamer(*Asm); 1852 emitDebugLocEntry(Streamer, Entry); 1853 } 1854 1855 // Emit locations into the debug loc section. 1856 void DwarfDebug::emitDebugLoc() { 1857 if (DebugLocs.getLists().empty()) 1858 return; 1859 1860 // Start the dwarf loc section. 1861 Asm->OutStreamer->SwitchSection( 1862 Asm->getObjFileLowering().getDwarfLocSection()); 1863 unsigned char Size = Asm->MAI->getCodePointerSize(); 1864 for (const auto &List : DebugLocs.getLists()) { 1865 Asm->OutStreamer->EmitLabel(List.Label); 1866 const DwarfCompileUnit *CU = List.CU; 1867 for (const auto &Entry : DebugLocs.getEntries(List)) { 1868 // Set up the range. This range is relative to the entry point of the 1869 // compile unit. This is a hard coded 0 for low_pc when we're emitting 1870 // ranges, or the DW_AT_low_pc on the compile unit otherwise. 1871 if (auto *Base = CU->getBaseAddress()) { 1872 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size); 1873 Asm->EmitLabelDifference(Entry.EndSym, Base, Size); 1874 } else { 1875 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size); 1876 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size); 1877 } 1878 1879 emitDebugLocEntryLocation(Entry); 1880 } 1881 Asm->OutStreamer->EmitIntValue(0, Size); 1882 Asm->OutStreamer->EmitIntValue(0, Size); 1883 } 1884 } 1885 1886 void DwarfDebug::emitDebugLocDWO() { 1887 Asm->OutStreamer->SwitchSection( 1888 Asm->getObjFileLowering().getDwarfLocDWOSection()); 1889 for (const auto &List : DebugLocs.getLists()) { 1890 Asm->OutStreamer->EmitLabel(List.Label); 1891 for (const auto &Entry : DebugLocs.getEntries(List)) { 1892 // Just always use start_length for now - at least that's one address 1893 // rather than two. We could get fancier and try to, say, reuse an 1894 // address we know we've emitted elsewhere (the start of the function? 1895 // The start of the CU or CU subrange that encloses this range?) 1896 Asm->emitInt8(dwarf::DW_LLE_startx_length); 1897 unsigned idx = AddrPool.getIndex(Entry.BeginSym); 1898 Asm->EmitULEB128(idx); 1899 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4); 1900 1901 emitDebugLocEntryLocation(Entry); 1902 } 1903 Asm->emitInt8(dwarf::DW_LLE_end_of_list); 1904 } 1905 } 1906 1907 struct ArangeSpan { 1908 const MCSymbol *Start, *End; 1909 }; 1910 1911 // Emit a debug aranges section, containing a CU lookup for any 1912 // address we can tie back to a CU. 1913 void DwarfDebug::emitDebugARanges() { 1914 // Provides a unique id per text section. 1915 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap; 1916 1917 // Filter labels by section. 1918 for (const SymbolCU &SCU : ArangeLabels) { 1919 if (SCU.Sym->isInSection()) { 1920 // Make a note of this symbol and it's section. 1921 MCSection *Section = &SCU.Sym->getSection(); 1922 if (!Section->getKind().isMetadata()) 1923 SectionMap[Section].push_back(SCU); 1924 } else { 1925 // Some symbols (e.g. common/bss on mach-o) can have no section but still 1926 // appear in the output. This sucks as we rely on sections to build 1927 // arange spans. We can do it without, but it's icky. 1928 SectionMap[nullptr].push_back(SCU); 1929 } 1930 } 1931 1932 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans; 1933 1934 for (auto &I : SectionMap) { 1935 MCSection *Section = I.first; 1936 SmallVector<SymbolCU, 8> &List = I.second; 1937 if (List.size() < 1) 1938 continue; 1939 1940 // If we have no section (e.g. common), just write out 1941 // individual spans for each symbol. 1942 if (!Section) { 1943 for (const SymbolCU &Cur : List) { 1944 ArangeSpan Span; 1945 Span.Start = Cur.Sym; 1946 Span.End = nullptr; 1947 assert(Cur.CU); 1948 Spans[Cur.CU].push_back(Span); 1949 } 1950 continue; 1951 } 1952 1953 // Sort the symbols by offset within the section. 1954 std::stable_sort( 1955 List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) { 1956 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0; 1957 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0; 1958 1959 // Symbols with no order assigned should be placed at the end. 1960 // (e.g. section end labels) 1961 if (IA == 0) 1962 return false; 1963 if (IB == 0) 1964 return true; 1965 return IA < IB; 1966 }); 1967 1968 // Insert a final terminator. 1969 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section))); 1970 1971 // Build spans between each label. 1972 const MCSymbol *StartSym = List[0].Sym; 1973 for (size_t n = 1, e = List.size(); n < e; n++) { 1974 const SymbolCU &Prev = List[n - 1]; 1975 const SymbolCU &Cur = List[n]; 1976 1977 // Try and build the longest span we can within the same CU. 1978 if (Cur.CU != Prev.CU) { 1979 ArangeSpan Span; 1980 Span.Start = StartSym; 1981 Span.End = Cur.Sym; 1982 assert(Prev.CU); 1983 Spans[Prev.CU].push_back(Span); 1984 StartSym = Cur.Sym; 1985 } 1986 } 1987 } 1988 1989 // Start the dwarf aranges section. 1990 Asm->OutStreamer->SwitchSection( 1991 Asm->getObjFileLowering().getDwarfARangesSection()); 1992 1993 unsigned PtrSize = Asm->MAI->getCodePointerSize(); 1994 1995 // Build a list of CUs used. 1996 std::vector<DwarfCompileUnit *> CUs; 1997 for (const auto &it : Spans) { 1998 DwarfCompileUnit *CU = it.first; 1999 CUs.push_back(CU); 2000 } 2001 2002 // Sort the CU list (again, to ensure consistent output order). 2003 llvm::sort(CUs.begin(), CUs.end(), 2004 [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) { 2005 return A->getUniqueID() < B->getUniqueID(); 2006 }); 2007 2008 // Emit an arange table for each CU we used. 2009 for (DwarfCompileUnit *CU : CUs) { 2010 std::vector<ArangeSpan> &List = Spans[CU]; 2011 2012 // Describe the skeleton CU's offset and length, not the dwo file's. 2013 if (auto *Skel = CU->getSkeleton()) 2014 CU = Skel; 2015 2016 // Emit size of content not including length itself. 2017 unsigned ContentSize = 2018 sizeof(int16_t) + // DWARF ARange version number 2019 sizeof(int32_t) + // Offset of CU in the .debug_info section 2020 sizeof(int8_t) + // Pointer Size (in bytes) 2021 sizeof(int8_t); // Segment Size (in bytes) 2022 2023 unsigned TupleSize = PtrSize * 2; 2024 2025 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 2026 unsigned Padding = 2027 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize); 2028 2029 ContentSize += Padding; 2030 ContentSize += (List.size() + 1) * TupleSize; 2031 2032 // For each compile unit, write the list of spans it covers. 2033 Asm->OutStreamer->AddComment("Length of ARange Set"); 2034 Asm->emitInt32(ContentSize); 2035 Asm->OutStreamer->AddComment("DWARF Arange version number"); 2036 Asm->emitInt16(dwarf::DW_ARANGES_VERSION); 2037 Asm->OutStreamer->AddComment("Offset Into Debug Info Section"); 2038 emitSectionReference(*CU); 2039 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 2040 Asm->emitInt8(PtrSize); 2041 Asm->OutStreamer->AddComment("Segment Size (in bytes)"); 2042 Asm->emitInt8(0); 2043 2044 Asm->OutStreamer->emitFill(Padding, 0xff); 2045 2046 for (const ArangeSpan &Span : List) { 2047 Asm->EmitLabelReference(Span.Start, PtrSize); 2048 2049 // Calculate the size as being from the span start to it's end. 2050 if (Span.End) { 2051 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize); 2052 } else { 2053 // For symbols without an end marker (e.g. common), we 2054 // write a single arange entry containing just that one symbol. 2055 uint64_t Size = SymSize[Span.Start]; 2056 if (Size == 0) 2057 Size = 1; 2058 2059 Asm->OutStreamer->EmitIntValue(Size, PtrSize); 2060 } 2061 } 2062 2063 Asm->OutStreamer->AddComment("ARange terminator"); 2064 Asm->OutStreamer->EmitIntValue(0, PtrSize); 2065 Asm->OutStreamer->EmitIntValue(0, PtrSize); 2066 } 2067 } 2068 2069 /// Emit a single range list. We handle both DWARF v5 and earlier. 2070 static void emitRangeList(AsmPrinter *Asm, DwarfCompileUnit *CU, 2071 const RangeSpanList &List) { 2072 2073 auto DwarfVersion = CU->getDwarfVersion(); 2074 // Emit our symbol so we can find the beginning of the range. 2075 Asm->OutStreamer->EmitLabel(List.getSym()); 2076 // Gather all the ranges that apply to the same section so they can share 2077 // a base address entry. 2078 MapVector<const MCSection *, std::vector<const RangeSpan *>> SectionRanges; 2079 // Size for our labels. 2080 auto Size = Asm->MAI->getCodePointerSize(); 2081 2082 for (const RangeSpan &Range : List.getRanges()) 2083 SectionRanges[&Range.getStart()->getSection()].push_back(&Range); 2084 2085 auto *CUBase = CU->getBaseAddress(); 2086 bool BaseIsSet = false; 2087 for (const auto &P : SectionRanges) { 2088 // Don't bother with a base address entry if there's only one range in 2089 // this section in this range list - for example ranges for a CU will 2090 // usually consist of single regions from each of many sections 2091 // (-ffunction-sections, or just C++ inline functions) except under LTO 2092 // or optnone where there may be holes in a single CU's section 2093 // contributions. 2094 auto *Base = CUBase; 2095 if (!Base && P.second.size() > 1 && 2096 (UseDwarfRangesBaseAddressSpecifier || DwarfVersion >= 5)) { 2097 BaseIsSet = true; 2098 // FIXME/use care: This may not be a useful base address if it's not 2099 // the lowest address/range in this object. 2100 Base = P.second.front()->getStart(); 2101 if (DwarfVersion >= 5) { 2102 Asm->OutStreamer->AddComment("DW_RLE_base_address"); 2103 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_address, 1); 2104 } else 2105 Asm->OutStreamer->EmitIntValue(-1, Size); 2106 Asm->OutStreamer->AddComment(" base address"); 2107 Asm->OutStreamer->EmitSymbolValue(Base, Size); 2108 } else if (BaseIsSet && DwarfVersion < 5) { 2109 BaseIsSet = false; 2110 assert(!Base); 2111 Asm->OutStreamer->EmitIntValue(-1, Size); 2112 Asm->OutStreamer->EmitIntValue(0, Size); 2113 } 2114 2115 for (const auto *RS : P.second) { 2116 const MCSymbol *Begin = RS->getStart(); 2117 const MCSymbol *End = RS->getEnd(); 2118 assert(Begin && "Range without a begin symbol?"); 2119 assert(End && "Range without an end symbol?"); 2120 if (Base) { 2121 if (DwarfVersion >= 5) { 2122 // Emit DW_RLE_offset_pair when we have a base. 2123 Asm->OutStreamer->AddComment("DW_RLE_offset_pair"); 2124 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1); 2125 Asm->OutStreamer->AddComment(" starting offset"); 2126 Asm->EmitLabelDifferenceAsULEB128(Begin, Base); 2127 Asm->OutStreamer->AddComment(" ending offset"); 2128 Asm->EmitLabelDifferenceAsULEB128(End, Base); 2129 } else { 2130 Asm->EmitLabelDifference(Begin, Base, Size); 2131 Asm->EmitLabelDifference(End, Base, Size); 2132 } 2133 } else if (DwarfVersion >= 5) { 2134 Asm->OutStreamer->AddComment("DW_RLE_start_length"); 2135 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_start_length, 1); 2136 Asm->OutStreamer->AddComment(" start"); 2137 Asm->OutStreamer->EmitSymbolValue(Begin, Size); 2138 Asm->OutStreamer->AddComment(" length"); 2139 Asm->EmitLabelDifferenceAsULEB128(End, Begin); 2140 } else { 2141 Asm->OutStreamer->EmitSymbolValue(Begin, Size); 2142 Asm->OutStreamer->EmitSymbolValue(End, Size); 2143 } 2144 } 2145 } 2146 if (DwarfVersion >= 5) { 2147 Asm->OutStreamer->AddComment("DW_RLE_end_of_list"); 2148 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1); 2149 } else { 2150 // Terminate the list with two 0 values. 2151 Asm->OutStreamer->EmitIntValue(0, Size); 2152 Asm->OutStreamer->EmitIntValue(0, Size); 2153 } 2154 } 2155 2156 // Emit the header of a DWARF 5 range list table. Returns the symbol that 2157 // designates the end of the table for the caller to emit when the table is 2158 // complete. 2159 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm, DwarfFile &Holder) { 2160 // The length is described by a starting label right after the length field 2161 // and an end label. 2162 MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start"); 2163 MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end"); 2164 // Build the range table header, which starts with the length field. 2165 Asm->EmitLabelDifference(TableEnd, TableStart, 4); 2166 Asm->OutStreamer->EmitLabel(TableStart); 2167 // Version number (DWARF v5 and later). 2168 Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion()); 2169 // Address size. 2170 Asm->emitInt8(Asm->MAI->getCodePointerSize()); 2171 // Segment selector size. 2172 Asm->emitInt8(0); 2173 2174 MCSymbol *RnglistTableBaseSym = Holder.getRnglistsTableBaseSym(); 2175 2176 // FIXME: Generate the offsets table and use DW_FORM_rnglistx with the 2177 // DW_AT_ranges attribute. Until then set the number of offsets to 0. 2178 Asm->emitInt32(0); 2179 Asm->OutStreamer->EmitLabel(RnglistTableBaseSym); 2180 return TableEnd; 2181 } 2182 2183 /// Emit address ranges into the .debug_ranges section or into the DWARF v5 2184 /// .debug_rnglists section. 2185 void DwarfDebug::emitDebugRanges() { 2186 if (CUMap.empty()) 2187 return; 2188 2189 auto NoRangesPresent = [this]() { 2190 return llvm::all_of( 2191 CUMap, [](const decltype(CUMap)::value_type &Pair) { 2192 return Pair.second->getRangeLists().empty(); 2193 }); 2194 }; 2195 2196 if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2197 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2198 })) { 2199 assert(NoRangesPresent() && "No debug ranges expected."); 2200 return; 2201 } 2202 2203 if (!useRangesSection()) { 2204 assert(NoRangesPresent() && "No debug ranges expected."); 2205 return; 2206 } 2207 2208 if (NoRangesPresent()) 2209 return; 2210 2211 // Start the dwarf ranges section. 2212 MCSymbol *TableEnd = nullptr; 2213 if (getDwarfVersion() >= 5) { 2214 Asm->OutStreamer->SwitchSection( 2215 Asm->getObjFileLowering().getDwarfRnglistsSection()); 2216 TableEnd = emitRnglistsTableHeader(Asm, useSplitDwarf() ? SkeletonHolder 2217 : InfoHolder); 2218 } else 2219 Asm->OutStreamer->SwitchSection( 2220 Asm->getObjFileLowering().getDwarfRangesSection()); 2221 2222 // Grab the specific ranges for the compile units in the module. 2223 for (const auto &I : CUMap) { 2224 DwarfCompileUnit *TheCU = I.second; 2225 if (TheCU->getCUNode()->isDebugDirectivesOnly()) 2226 continue; 2227 2228 if (auto *Skel = TheCU->getSkeleton()) 2229 TheCU = Skel; 2230 2231 // Iterate over the misc ranges for the compile units in the module. 2232 for (const RangeSpanList &List : TheCU->getRangeLists()) 2233 emitRangeList(Asm, TheCU, List); 2234 } 2235 2236 if (TableEnd) 2237 Asm->OutStreamer->EmitLabel(TableEnd); 2238 } 2239 2240 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) { 2241 for (auto *MN : Nodes) { 2242 if (auto *M = dyn_cast<DIMacro>(MN)) 2243 emitMacro(*M); 2244 else if (auto *F = dyn_cast<DIMacroFile>(MN)) 2245 emitMacroFile(*F, U); 2246 else 2247 llvm_unreachable("Unexpected DI type!"); 2248 } 2249 } 2250 2251 void DwarfDebug::emitMacro(DIMacro &M) { 2252 Asm->EmitULEB128(M.getMacinfoType()); 2253 Asm->EmitULEB128(M.getLine()); 2254 StringRef Name = M.getName(); 2255 StringRef Value = M.getValue(); 2256 Asm->OutStreamer->EmitBytes(Name); 2257 if (!Value.empty()) { 2258 // There should be one space between macro name and macro value. 2259 Asm->emitInt8(' '); 2260 Asm->OutStreamer->EmitBytes(Value); 2261 } 2262 Asm->emitInt8('\0'); 2263 } 2264 2265 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) { 2266 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file); 2267 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file); 2268 Asm->EmitULEB128(F.getLine()); 2269 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile())); 2270 handleMacroNodes(F.getElements(), U); 2271 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file); 2272 } 2273 2274 /// Emit macros into a debug macinfo section. 2275 void DwarfDebug::emitDebugMacinfo() { 2276 if (CUMap.empty()) 2277 return; 2278 2279 if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2280 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2281 })) 2282 return; 2283 2284 // Start the dwarf macinfo section. 2285 Asm->OutStreamer->SwitchSection( 2286 Asm->getObjFileLowering().getDwarfMacinfoSection()); 2287 2288 for (const auto &P : CUMap) { 2289 auto &TheCU = *P.second; 2290 if (TheCU.getCUNode()->isDebugDirectivesOnly()) 2291 continue; 2292 auto *SkCU = TheCU.getSkeleton(); 2293 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 2294 auto *CUNode = cast<DICompileUnit>(P.first); 2295 DIMacroNodeArray Macros = CUNode->getMacros(); 2296 if (!Macros.empty()) { 2297 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin()); 2298 handleMacroNodes(Macros, U); 2299 } 2300 } 2301 Asm->OutStreamer->AddComment("End Of Macro List Mark"); 2302 Asm->emitInt8(0); 2303 } 2304 2305 // DWARF5 Experimental Separate Dwarf emitters. 2306 2307 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die, 2308 std::unique_ptr<DwarfCompileUnit> NewU) { 2309 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name, 2310 Asm->TM.Options.MCOptions.SplitDwarfFile); 2311 2312 if (!CompilationDir.empty()) 2313 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 2314 2315 addGnuPubAttributes(*NewU, Die); 2316 2317 SkeletonHolder.addUnit(std::move(NewU)); 2318 } 2319 2320 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) { 2321 2322 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 2323 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder); 2324 DwarfCompileUnit &NewCU = *OwnedUnit; 2325 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 2326 2327 NewCU.initStmtList(); 2328 2329 if (useSegmentedStringOffsetsTable()) 2330 NewCU.addStringOffsetsStart(); 2331 2332 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit)); 2333 2334 return NewCU; 2335 } 2336 2337 // Emit the .debug_info.dwo section for separated dwarf. This contains the 2338 // compile units that would normally be in debug_info. 2339 void DwarfDebug::emitDebugInfoDWO() { 2340 assert(useSplitDwarf() && "No split dwarf debug info?"); 2341 // Don't emit relocations into the dwo file. 2342 InfoHolder.emitUnits(/* UseOffsets */ true); 2343 } 2344 2345 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 2346 // abbreviations for the .debug_info.dwo section. 2347 void DwarfDebug::emitDebugAbbrevDWO() { 2348 assert(useSplitDwarf() && "No split dwarf?"); 2349 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 2350 } 2351 2352 void DwarfDebug::emitDebugLineDWO() { 2353 assert(useSplitDwarf() && "No split dwarf?"); 2354 SplitTypeUnitFileTable.Emit( 2355 *Asm->OutStreamer, MCDwarfLineTableParams(), 2356 Asm->getObjFileLowering().getDwarfLineDWOSection()); 2357 } 2358 2359 void DwarfDebug::emitStringOffsetsTableHeaderDWO() { 2360 assert(useSplitDwarf() && "No split dwarf?"); 2361 InfoHolder.getStringPool().emitStringOffsetsTableHeader( 2362 *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(), 2363 InfoHolder.getStringOffsetsStartSym()); 2364 } 2365 2366 // Emit the .debug_str.dwo section for separated dwarf. This contains the 2367 // string section and is identical in format to traditional .debug_str 2368 // sections. 2369 void DwarfDebug::emitDebugStrDWO() { 2370 if (useSegmentedStringOffsetsTable()) 2371 emitStringOffsetsTableHeaderDWO(); 2372 assert(useSplitDwarf() && "No split dwarf?"); 2373 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 2374 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 2375 OffSec, /* UseRelativeOffsets = */ false); 2376 } 2377 2378 // Emit DWO addresses. 2379 void DwarfDebug::emitDebugAddr() { 2380 assert(useSplitDwarf() && "No split dwarf?"); 2381 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection()); 2382 } 2383 2384 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 2385 if (!useSplitDwarf()) 2386 return nullptr; 2387 const DICompileUnit *DIUnit = CU.getCUNode(); 2388 SplitTypeUnitFileTable.maybeSetRootFile( 2389 DIUnit->getDirectory(), DIUnit->getFilename(), 2390 CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource()); 2391 return &SplitTypeUnitFileTable; 2392 } 2393 2394 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) { 2395 MD5 Hash; 2396 Hash.update(Identifier); 2397 // ... take the least significant 8 bytes and return those. Our MD5 2398 // implementation always returns its results in little endian, so we actually 2399 // need the "high" word. 2400 MD5::MD5Result Result; 2401 Hash.final(Result); 2402 return Result.high(); 2403 } 2404 2405 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 2406 StringRef Identifier, DIE &RefDie, 2407 const DICompositeType *CTy) { 2408 // Fast path if we're building some type units and one has already used the 2409 // address pool we know we're going to throw away all this work anyway, so 2410 // don't bother building dependent types. 2411 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed()) 2412 return; 2413 2414 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0)); 2415 if (!Ins.second) { 2416 CU.addDIETypeSignature(RefDie, Ins.first->second); 2417 return; 2418 } 2419 2420 bool TopLevelType = TypeUnitsUnderConstruction.empty(); 2421 AddrPool.resetUsedFlag(); 2422 2423 auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder, 2424 getDwoLineTable(CU)); 2425 DwarfTypeUnit &NewTU = *OwnedUnit; 2426 DIE &UnitDie = NewTU.getUnitDie(); 2427 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy); 2428 2429 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 2430 CU.getLanguage()); 2431 2432 uint64_t Signature = makeTypeSignature(Identifier); 2433 NewTU.setTypeSignature(Signature); 2434 Ins.first->second = Signature; 2435 2436 if (useSplitDwarf()) 2437 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesDWOSection()); 2438 else { 2439 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesSection(Signature)); 2440 // Non-split type units reuse the compile unit's line table. 2441 CU.applyStmtList(UnitDie); 2442 } 2443 2444 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type 2445 // units. 2446 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 2447 NewTU.addStringOffsetsStart(); 2448 2449 NewTU.setType(NewTU.createTypeDIE(CTy)); 2450 2451 if (TopLevelType) { 2452 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction); 2453 TypeUnitsUnderConstruction.clear(); 2454 2455 // Types referencing entries in the address table cannot be placed in type 2456 // units. 2457 if (AddrPool.hasBeenUsed()) { 2458 2459 // Remove all the types built while building this type. 2460 // This is pessimistic as some of these types might not be dependent on 2461 // the type that used an address. 2462 for (const auto &TU : TypeUnitsToAdd) 2463 TypeSignatures.erase(TU.second); 2464 2465 // Construct this type in the CU directly. 2466 // This is inefficient because all the dependent types will be rebuilt 2467 // from scratch, including building them in type units, discovering that 2468 // they depend on addresses, throwing them out and rebuilding them. 2469 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy)); 2470 return; 2471 } 2472 2473 // If the type wasn't dependent on fission addresses, finish adding the type 2474 // and all its dependent types. 2475 for (auto &TU : TypeUnitsToAdd) { 2476 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get()); 2477 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf()); 2478 } 2479 } 2480 CU.addDIETypeSignature(RefDie, Signature); 2481 } 2482 2483 // Add the Name along with its companion DIE to the appropriate accelerator 2484 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for 2485 // AccelTableKind::Apple, we use the table we got as an argument). If 2486 // accelerator tables are disabled, this function does nothing. 2487 template <typename DataT> 2488 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU, 2489 AccelTable<DataT> &AppleAccel, StringRef Name, 2490 const DIE &Die) { 2491 if (getAccelTableKind() == AccelTableKind::None) 2492 return; 2493 2494 if (getAccelTableKind() != AccelTableKind::Apple && 2495 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None) 2496 return; 2497 2498 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2499 DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name); 2500 2501 switch (getAccelTableKind()) { 2502 case AccelTableKind::Apple: 2503 AppleAccel.addName(Ref, Die); 2504 break; 2505 case AccelTableKind::Dwarf: 2506 AccelDebugNames.addName(Ref, Die); 2507 break; 2508 case AccelTableKind::Default: 2509 llvm_unreachable("Default should have already been resolved."); 2510 case AccelTableKind::None: 2511 llvm_unreachable("None handled above"); 2512 } 2513 } 2514 2515 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name, 2516 const DIE &Die) { 2517 addAccelNameImpl(CU, AccelNames, Name, Die); 2518 } 2519 2520 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name, 2521 const DIE &Die) { 2522 // ObjC names go only into the Apple accelerator tables. 2523 if (getAccelTableKind() == AccelTableKind::Apple) 2524 addAccelNameImpl(CU, AccelObjC, Name, Die); 2525 } 2526 2527 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name, 2528 const DIE &Die) { 2529 addAccelNameImpl(CU, AccelNamespace, Name, Die); 2530 } 2531 2532 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name, 2533 const DIE &Die, char Flags) { 2534 addAccelNameImpl(CU, AccelTypes, Name, Die); 2535 } 2536 2537 uint16_t DwarfDebug::getDwarfVersion() const { 2538 return Asm->OutStreamer->getContext().getDwarfVersion(); 2539 } 2540