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