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