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