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 = DebugHandlerBase::fragmentCmp( 923 cast<DIExpression>(Values[i].Expression), 924 cast<DIExpression>(Next.Values[j].Expression)); 925 if (res == 0) // The two expressions overlap, we can't merge. 926 return false; 927 // Values[i] is entirely before Next.Values[j], 928 // so go back to the next entry of Values. 929 else if (res == -1) 930 break; 931 // Next.Values[j] is entirely before Values[i], so go on to the 932 // next entry of Next.Values. 933 } 934 } 935 936 addValues(Next.Values); 937 End = Next.End; 938 return true; 939 } 940 return false; 941 } 942 943 /// Build the location list for all DBG_VALUEs in the function that 944 /// describe the same variable. If the ranges of several independent 945 /// fragments of the same variable overlap partially, split them up and 946 /// combine the ranges. The resulting DebugLocEntries are will have 947 /// strict monotonically increasing begin addresses and will never 948 /// overlap. 949 // 950 // Input: 951 // 952 // Ranges History [var, loc, fragment ofs size] 953 // 0 | [x, (reg0, fragment 0, 32)] 954 // 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry 955 // 2 | | ... 956 // 3 | [clobber reg0] 957 // 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of 958 // x. 959 // 960 // Output: 961 // 962 // [0-1] [x, (reg0, fragment 0, 32)] 963 // [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)] 964 // [3-4] [x, (reg1, fragment 32, 32)] 965 // [4- ] [x, (mem, fragment 0, 64)] 966 void 967 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc, 968 const DbgValueHistoryMap::InstrRanges &Ranges) { 969 SmallVector<DebugLocEntry::Value, 4> OpenRanges; 970 971 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 972 const MachineInstr *Begin = I->first; 973 const MachineInstr *End = I->second; 974 assert(Begin->isDebugValue() && "Invalid History entry"); 975 976 // Check if a variable is inaccessible in this range. 977 if (Begin->getNumOperands() > 1 && 978 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) { 979 OpenRanges.clear(); 980 continue; 981 } 982 983 // If this fragment overlaps with any open ranges, truncate them. 984 const DIExpression *DIExpr = Begin->getDebugExpression(); 985 auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) { 986 return fragmentsOverlap(DIExpr, R.getExpression()); 987 }); 988 OpenRanges.erase(Last, OpenRanges.end()); 989 990 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin); 991 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!"); 992 993 const MCSymbol *EndLabel; 994 if (End != nullptr) 995 EndLabel = getLabelAfterInsn(End); 996 else if (std::next(I) == Ranges.end()) 997 EndLabel = Asm->getFunctionEnd(); 998 else 999 EndLabel = getLabelBeforeInsn(std::next(I)->first); 1000 assert(EndLabel && "Forgot label after instruction ending a range!"); 1001 1002 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n"); 1003 1004 auto Value = getDebugLocValue(Begin); 1005 DebugLocEntry Loc(StartLabel, EndLabel, Value); 1006 bool couldMerge = false; 1007 1008 // If this is a fragment, it may belong to the current DebugLocEntry. 1009 if (DIExpr->isFragment()) { 1010 // Add this value to the list of open ranges. 1011 OpenRanges.push_back(Value); 1012 1013 // Attempt to add the fragment to the last entry. 1014 if (!DebugLoc.empty()) 1015 if (DebugLoc.back().MergeValues(Loc)) 1016 couldMerge = true; 1017 } 1018 1019 if (!couldMerge) { 1020 // Need to add a new DebugLocEntry. Add all values from still 1021 // valid non-overlapping fragments. 1022 if (OpenRanges.size()) 1023 Loc.addValues(OpenRanges); 1024 1025 DebugLoc.push_back(std::move(Loc)); 1026 } 1027 1028 // Attempt to coalesce the ranges of two otherwise identical 1029 // DebugLocEntries. 1030 auto CurEntry = DebugLoc.rbegin(); 1031 DEBUG({ 1032 dbgs() << CurEntry->getValues().size() << " Values:\n"; 1033 for (auto &Value : CurEntry->getValues()) 1034 Value.dump(); 1035 dbgs() << "-----\n"; 1036 }); 1037 1038 auto PrevEntry = std::next(CurEntry); 1039 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry)) 1040 DebugLoc.pop_back(); 1041 } 1042 } 1043 1044 DbgVariable *DwarfDebug::createConcreteVariable(DwarfCompileUnit &TheCU, 1045 LexicalScope &Scope, 1046 InlinedVariable IV) { 1047 ensureAbstractVariableIsCreatedIfScoped(TheCU, IV, Scope.getScopeNode()); 1048 ConcreteVariables.push_back( 1049 llvm::make_unique<DbgVariable>(IV.first, IV.second)); 1050 InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get()); 1051 return ConcreteVariables.back().get(); 1052 } 1053 1054 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its 1055 /// enclosing lexical scope. The check ensures there are no other instructions 1056 /// in the same lexical scope preceding the DBG_VALUE and that its range is 1057 /// either open or otherwise rolls off the end of the scope. 1058 static bool validThroughout(LexicalScopes &LScopes, 1059 const MachineInstr *DbgValue, 1060 const MachineInstr *RangeEnd) { 1061 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location"); 1062 auto MBB = DbgValue->getParent(); 1063 auto DL = DbgValue->getDebugLoc(); 1064 auto *LScope = LScopes.findLexicalScope(DL); 1065 // Scope doesn't exist; this is a dead DBG_VALUE. 1066 if (!LScope) 1067 return false; 1068 auto &LSRange = LScope->getRanges(); 1069 if (LSRange.size() == 0) 1070 return false; 1071 1072 // Determine if the DBG_VALUE is valid at the beginning of its lexical block. 1073 const MachineInstr *LScopeBegin = LSRange.front().first; 1074 // Early exit if the lexical scope begins outside of the current block. 1075 if (LScopeBegin->getParent() != MBB) 1076 return false; 1077 MachineBasicBlock::const_reverse_iterator Pred(DbgValue); 1078 for (++Pred; Pred != MBB->rend(); ++Pred) { 1079 if (Pred->getFlag(MachineInstr::FrameSetup)) 1080 break; 1081 auto PredDL = Pred->getDebugLoc(); 1082 if (!PredDL || Pred->isMetaInstruction()) 1083 continue; 1084 // Check whether the instruction preceding the DBG_VALUE is in the same 1085 // (sub)scope as the DBG_VALUE. 1086 if (DL->getScope() == PredDL->getScope()) 1087 return false; 1088 auto *PredScope = LScopes.findLexicalScope(PredDL); 1089 if (!PredScope || LScope->dominates(PredScope)) 1090 return false; 1091 } 1092 1093 // If the range of the DBG_VALUE is open-ended, report success. 1094 if (!RangeEnd) 1095 return true; 1096 1097 // Fail if there are instructions belonging to our scope in another block. 1098 const MachineInstr *LScopeEnd = LSRange.back().second; 1099 if (LScopeEnd->getParent() != MBB) 1100 return false; 1101 1102 // Single, constant DBG_VALUEs in the prologue are promoted to be live 1103 // throughout the function. This is a hack, presumably for DWARF v2 and not 1104 // necessarily correct. It would be much better to use a dbg.declare instead 1105 // if we know the constant is live throughout the scope. 1106 if (DbgValue->getOperand(0).isImm() && MBB->pred_empty()) 1107 return true; 1108 1109 return false; 1110 } 1111 1112 // Find variables for each lexical scope. 1113 void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, 1114 const DISubprogram *SP, 1115 DenseSet<InlinedVariable> &Processed) { 1116 // Grab the variable info that was squirreled away in the MMI side-table. 1117 collectVariableInfoFromMFTable(TheCU, Processed); 1118 1119 for (const auto &I : DbgValues) { 1120 InlinedVariable IV = I.first; 1121 if (Processed.count(IV)) 1122 continue; 1123 1124 // Instruction ranges, specifying where IV is accessible. 1125 const auto &Ranges = I.second; 1126 if (Ranges.empty()) 1127 continue; 1128 1129 LexicalScope *Scope = nullptr; 1130 if (const DILocation *IA = IV.second) 1131 Scope = LScopes.findInlinedScope(IV.first->getScope(), IA); 1132 else 1133 Scope = LScopes.findLexicalScope(IV.first->getScope()); 1134 // If variable scope is not found then skip this variable. 1135 if (!Scope) 1136 continue; 1137 1138 Processed.insert(IV); 1139 DbgVariable *RegVar = createConcreteVariable(TheCU, *Scope, IV); 1140 1141 const MachineInstr *MInsn = Ranges.front().first; 1142 assert(MInsn->isDebugValue() && "History must begin with debug value"); 1143 1144 // Check if there is a single DBG_VALUE, valid throughout the var's scope. 1145 if (Ranges.size() == 1 && 1146 validThroughout(LScopes, MInsn, Ranges.front().second)) { 1147 RegVar->initializeDbgValue(MInsn); 1148 continue; 1149 } 1150 1151 // Handle multiple DBG_VALUE instructions describing one variable. 1152 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn); 1153 1154 // Build the location list for this variable. 1155 SmallVector<DebugLocEntry, 8> Entries; 1156 buildLocationList(Entries, Ranges); 1157 1158 // If the variable has a DIBasicType, extract it. Basic types cannot have 1159 // unique identifiers, so don't bother resolving the type with the 1160 // identifier map. 1161 const DIBasicType *BT = dyn_cast<DIBasicType>( 1162 static_cast<const Metadata *>(IV.first->getType())); 1163 1164 // Finalize the entry by lowering it into a DWARF bytestream. 1165 for (auto &Entry : Entries) 1166 Entry.finalize(*Asm, List, BT); 1167 } 1168 1169 // Collect info for variables that were optimized out. 1170 for (const DILocalVariable *DV : SP->getVariables()) { 1171 if (Processed.insert(InlinedVariable(DV, nullptr)).second) 1172 if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope())) 1173 createConcreteVariable(TheCU, *Scope, InlinedVariable(DV, nullptr)); 1174 } 1175 } 1176 1177 // Process beginning of an instruction. 1178 void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1179 DebugHandlerBase::beginInstruction(MI); 1180 assert(CurMI); 1181 1182 const auto *SP = MI->getMF()->getFunction().getSubprogram(); 1183 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1184 return; 1185 1186 // Check if source location changes, but ignore DBG_VALUE and CFI locations. 1187 // If the instruction is part of the function frame setup code, do not emit 1188 // any line record, as there is no correspondence with any user code. 1189 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup)) 1190 return; 1191 const DebugLoc &DL = MI->getDebugLoc(); 1192 // When we emit a line-0 record, we don't update PrevInstLoc; so look at 1193 // the last line number actually emitted, to see if it was line 0. 1194 unsigned LastAsmLine = 1195 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine(); 1196 1197 if (DL == PrevInstLoc) { 1198 // If we have an ongoing unspecified location, nothing to do here. 1199 if (!DL) 1200 return; 1201 // We have an explicit location, same as the previous location. 1202 // But we might be coming back to it after a line 0 record. 1203 if (LastAsmLine == 0 && DL.getLine() != 0) { 1204 // Reinstate the source location but not marked as a statement. 1205 const MDNode *Scope = DL.getScope(); 1206 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0); 1207 } 1208 return; 1209 } 1210 1211 if (!DL) { 1212 // We have an unspecified location, which might want to be line 0. 1213 // If we have already emitted a line-0 record, don't repeat it. 1214 if (LastAsmLine == 0) 1215 return; 1216 // If user said Don't Do That, don't do that. 1217 if (UnknownLocations == Disable) 1218 return; 1219 // See if we have a reason to emit a line-0 record now. 1220 // Reasons to emit a line-0 record include: 1221 // - User asked for it (UnknownLocations). 1222 // - Instruction has a label, so it's referenced from somewhere else, 1223 // possibly debug information; we want it to have a source location. 1224 // - Instruction is at the top of a block; we don't want to inherit the 1225 // location from the physically previous (maybe unrelated) block. 1226 if (UnknownLocations == Enable || PrevLabel || 1227 (PrevInstBB && PrevInstBB != MI->getParent())) { 1228 // Preserve the file and column numbers, if we can, to save space in 1229 // the encoded line table. 1230 // Do not update PrevInstLoc, it remembers the last non-0 line. 1231 const MDNode *Scope = nullptr; 1232 unsigned Column = 0; 1233 if (PrevInstLoc) { 1234 Scope = PrevInstLoc.getScope(); 1235 Column = PrevInstLoc.getCol(); 1236 } 1237 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0); 1238 } 1239 return; 1240 } 1241 1242 // We have an explicit location, different from the previous location. 1243 // Don't repeat a line-0 record, but otherwise emit the new location. 1244 // (The new location might be an explicit line 0, which we do emit.) 1245 if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0) 1246 return; 1247 unsigned Flags = 0; 1248 if (DL == PrologEndLoc) { 1249 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT; 1250 PrologEndLoc = DebugLoc(); 1251 } 1252 // If the line changed, we call that a new statement; unless we went to 1253 // line 0 and came back, in which case it is not a new statement. 1254 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine; 1255 if (DL.getLine() && DL.getLine() != OldLine) 1256 Flags |= DWARF2_FLAG_IS_STMT; 1257 1258 const MDNode *Scope = DL.getScope(); 1259 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1260 1261 // If we're not at line 0, remember this location. 1262 if (DL.getLine()) 1263 PrevInstLoc = DL; 1264 } 1265 1266 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) { 1267 // First known non-DBG_VALUE and non-frame setup location marks 1268 // the beginning of the function body. 1269 for (const auto &MBB : *MF) 1270 for (const auto &MI : MBB) 1271 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) && 1272 MI.getDebugLoc()) 1273 return MI.getDebugLoc(); 1274 return DebugLoc(); 1275 } 1276 1277 // Gather pre-function debug information. Assumes being called immediately 1278 // after the function entry point has been emitted. 1279 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) { 1280 CurFn = MF; 1281 1282 auto *SP = MF->getFunction().getSubprogram(); 1283 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode()); 1284 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1285 return; 1286 1287 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 1288 1289 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 1290 // belongs to so that we add to the correct per-cu line table in the 1291 // non-asm case. 1292 if (Asm->OutStreamer->hasRawTextSupport()) 1293 // Use a single line table if we are generating assembly. 1294 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1295 else 1296 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID()); 1297 1298 // Record beginning of function. 1299 PrologEndLoc = findPrologueEndLoc(MF); 1300 if (PrologEndLoc) { 1301 // We'd like to list the prologue as "not statements" but GDB behaves 1302 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 1303 auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram(); 1304 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT); 1305 } 1306 } 1307 1308 void DwarfDebug::skippedNonDebugFunction() { 1309 // If we don't have a subprogram for this function then there will be a hole 1310 // in the range information. Keep note of this by setting the previously used 1311 // section to nullptr. 1312 PrevCU = nullptr; 1313 CurFn = nullptr; 1314 } 1315 1316 // Gather and emit post-function debug information. 1317 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) { 1318 const DISubprogram *SP = MF->getFunction().getSubprogram(); 1319 1320 assert(CurFn == MF && 1321 "endFunction should be called with the same function as beginFunction"); 1322 1323 // Set DwarfDwarfCompileUnitID in MCContext to default value. 1324 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1325 1326 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1327 assert(!FnScope || SP == FnScope->getScopeNode()); 1328 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit()); 1329 1330 DenseSet<InlinedVariable> ProcessedVars; 1331 collectVariableInfo(TheCU, SP, ProcessedVars); 1332 1333 // Add the range of this function to the list of ranges for the CU. 1334 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd())); 1335 1336 // Under -gmlt, skip building the subprogram if there are no inlined 1337 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram 1338 // is still needed as we need its source location. 1339 if (!TheCU.getCUNode()->getDebugInfoForProfiling() && 1340 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly && 1341 LScopes.getAbstractScopesList().empty() && !IsDarwin) { 1342 assert(InfoHolder.getScopeVariables().empty()); 1343 PrevLabel = nullptr; 1344 CurFn = nullptr; 1345 return; 1346 } 1347 1348 #ifndef NDEBUG 1349 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size(); 1350 #endif 1351 // Construct abstract scopes. 1352 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) { 1353 auto *SP = cast<DISubprogram>(AScope->getScopeNode()); 1354 // Collect info for variables that were optimized out. 1355 for (const DILocalVariable *DV : SP->getVariables()) { 1356 if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second) 1357 continue; 1358 ensureAbstractVariableIsCreated(TheCU, InlinedVariable(DV, nullptr), 1359 DV->getScope()); 1360 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes 1361 && "ensureAbstractVariableIsCreated inserted abstract scopes"); 1362 } 1363 constructAbstractSubprogramScopeDIE(TheCU, AScope); 1364 } 1365 1366 ProcessedSPNodes.insert(SP); 1367 TheCU.constructSubprogramScopeDIE(SP, FnScope); 1368 if (auto *SkelCU = TheCU.getSkeleton()) 1369 if (!LScopes.getAbstractScopesList().empty() && 1370 TheCU.getCUNode()->getSplitDebugInlining()) 1371 SkelCU->constructSubprogramScopeDIE(SP, FnScope); 1372 1373 // Clear debug info 1374 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the 1375 // DbgVariables except those that are also in AbstractVariables (since they 1376 // can be used cross-function) 1377 InfoHolder.getScopeVariables().clear(); 1378 PrevLabel = nullptr; 1379 CurFn = nullptr; 1380 } 1381 1382 // Register a source line with debug info. Returns the unique label that was 1383 // emitted and which provides correspondence to the source line list. 1384 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1385 unsigned Flags) { 1386 StringRef Fn; 1387 unsigned FileNo = 1; 1388 unsigned Discriminator = 0; 1389 if (auto *Scope = cast_or_null<DIScope>(S)) { 1390 Fn = Scope->getFilename(); 1391 if (Line != 0 && getDwarfVersion() >= 4) 1392 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope)) 1393 Discriminator = LBF->getDiscriminator(); 1394 1395 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID(); 1396 FileNo = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID]) 1397 .getOrCreateSourceID(Scope->getFile()); 1398 } 1399 Asm->OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0, 1400 Discriminator, Fn); 1401 } 1402 1403 //===----------------------------------------------------------------------===// 1404 // Emit Methods 1405 //===----------------------------------------------------------------------===// 1406 1407 // Emit the debug info section. 1408 void DwarfDebug::emitDebugInfo() { 1409 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1410 Holder.emitUnits(/* UseOffsets */ false); 1411 } 1412 1413 // Emit the abbreviation section. 1414 void DwarfDebug::emitAbbreviations() { 1415 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1416 1417 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection()); 1418 } 1419 1420 void DwarfDebug::emitStringOffsetsTableHeader() { 1421 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1422 Holder.emitStringOffsetsTableHeader( 1423 Asm->getObjFileLowering().getDwarfStrOffSection()); 1424 } 1425 1426 template <typename AccelTableT> 1427 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section, 1428 StringRef TableName) { 1429 Asm->OutStreamer->SwitchSection(Section); 1430 1431 // Emit the full data. 1432 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol()); 1433 } 1434 1435 // Emit visible names into a hashed accelerator table section. 1436 void DwarfDebug::emitAccelNames() { 1437 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(), 1438 "Names"); 1439 } 1440 1441 // Emit objective C classes and categories into a hashed accelerator table 1442 // section. 1443 void DwarfDebug::emitAccelObjC() { 1444 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(), 1445 "ObjC"); 1446 } 1447 1448 // Emit namespace dies into a hashed accelerator table. 1449 void DwarfDebug::emitAccelNamespaces() { 1450 emitAccel(AccelNamespace, 1451 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(), 1452 "namespac"); 1453 } 1454 1455 // Emit type dies into a hashed accelerator table. 1456 void DwarfDebug::emitAccelTypes() { 1457 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(), 1458 "types"); 1459 } 1460 1461 // Public name handling. 1462 // The format for the various pubnames: 1463 // 1464 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU 1465 // for the DIE that is named. 1466 // 1467 // gnu pubnames - offset/index value/name tuples where the offset is the offset 1468 // into the CU and the index value is computed according to the type of value 1469 // for the DIE that is named. 1470 // 1471 // For type units the offset is the offset of the skeleton DIE. For split dwarf 1472 // it's the offset within the debug_info/debug_types dwo section, however, the 1473 // reference in the pubname header doesn't change. 1474 1475 /// computeIndexValue - Compute the gdb index value for the DIE and CU. 1476 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, 1477 const DIE *Die) { 1478 // Entities that ended up only in a Type Unit reference the CU instead (since 1479 // the pub entry has offsets within the CU there's no real offset that can be 1480 // provided anyway). As it happens all such entities (namespaces and types, 1481 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out 1482 // not to be true it would be necessary to persist this information from the 1483 // point at which the entry is added to the index data structure - since by 1484 // the time the index is built from that, the original type/namespace DIE in a 1485 // type unit has already been destroyed so it can't be queried for properties 1486 // like tag, etc. 1487 if (Die->getTag() == dwarf::DW_TAG_compile_unit) 1488 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, 1489 dwarf::GIEL_EXTERNAL); 1490 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC; 1491 1492 // We could have a specification DIE that has our most of our knowledge, 1493 // look for that now. 1494 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) { 1495 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry(); 1496 if (SpecDIE.findAttribute(dwarf::DW_AT_external)) 1497 Linkage = dwarf::GIEL_EXTERNAL; 1498 } else if (Die->findAttribute(dwarf::DW_AT_external)) 1499 Linkage = dwarf::GIEL_EXTERNAL; 1500 1501 switch (Die->getTag()) { 1502 case dwarf::DW_TAG_class_type: 1503 case dwarf::DW_TAG_structure_type: 1504 case dwarf::DW_TAG_union_type: 1505 case dwarf::DW_TAG_enumeration_type: 1506 return dwarf::PubIndexEntryDescriptor( 1507 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus 1508 ? dwarf::GIEL_STATIC 1509 : dwarf::GIEL_EXTERNAL); 1510 case dwarf::DW_TAG_typedef: 1511 case dwarf::DW_TAG_base_type: 1512 case dwarf::DW_TAG_subrange_type: 1513 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC); 1514 case dwarf::DW_TAG_namespace: 1515 return dwarf::GIEK_TYPE; 1516 case dwarf::DW_TAG_subprogram: 1517 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage); 1518 case dwarf::DW_TAG_variable: 1519 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage); 1520 case dwarf::DW_TAG_enumerator: 1521 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, 1522 dwarf::GIEL_STATIC); 1523 default: 1524 return dwarf::GIEK_NONE; 1525 } 1526 } 1527 1528 /// emitDebugPubSections - Emit visible names and types into debug pubnames and 1529 /// pubtypes sections. 1530 void DwarfDebug::emitDebugPubSections() { 1531 for (const auto &NU : CUMap) { 1532 DwarfCompileUnit *TheU = NU.second; 1533 if (!TheU->hasDwarfPubSections()) 1534 continue; 1535 1536 bool GnuStyle = TheU->getCUNode()->getGnuPubnames(); 1537 1538 Asm->OutStreamer->SwitchSection( 1539 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection() 1540 : Asm->getObjFileLowering().getDwarfPubNamesSection()); 1541 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames()); 1542 1543 Asm->OutStreamer->SwitchSection( 1544 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection() 1545 : Asm->getObjFileLowering().getDwarfPubTypesSection()); 1546 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes()); 1547 } 1548 } 1549 1550 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name, 1551 DwarfCompileUnit *TheU, 1552 const StringMap<const DIE *> &Globals) { 1553 if (auto *Skeleton = TheU->getSkeleton()) 1554 TheU = Skeleton; 1555 1556 // Emit the header. 1557 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info"); 1558 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin"); 1559 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end"); 1560 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); 1561 1562 Asm->OutStreamer->EmitLabel(BeginLabel); 1563 1564 Asm->OutStreamer->AddComment("DWARF Version"); 1565 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); 1566 1567 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info"); 1568 Asm->emitDwarfSymbolReference(TheU->getLabelBegin()); 1569 1570 Asm->OutStreamer->AddComment("Compilation Unit Length"); 1571 Asm->EmitInt32(TheU->getLength()); 1572 1573 // Emit the pubnames for this compilation unit. 1574 for (const auto &GI : Globals) { 1575 const char *Name = GI.getKeyData(); 1576 const DIE *Entity = GI.second; 1577 1578 Asm->OutStreamer->AddComment("DIE offset"); 1579 Asm->EmitInt32(Entity->getOffset()); 1580 1581 if (GnuStyle) { 1582 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity); 1583 Asm->OutStreamer->AddComment( 1584 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " + 1585 dwarf::GDBIndexEntryLinkageString(Desc.Linkage)); 1586 Asm->EmitInt8(Desc.toBits()); 1587 } 1588 1589 Asm->OutStreamer->AddComment("External Name"); 1590 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1)); 1591 } 1592 1593 Asm->OutStreamer->AddComment("End Mark"); 1594 Asm->EmitInt32(0); 1595 Asm->OutStreamer->EmitLabel(EndLabel); 1596 } 1597 1598 /// Emit null-terminated strings into a debug str section. 1599 void DwarfDebug::emitDebugStr() { 1600 MCSection *StringOffsetsSection = nullptr; 1601 if (useSegmentedStringOffsetsTable()) { 1602 emitStringOffsetsTableHeader(); 1603 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection(); 1604 } 1605 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1606 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(), 1607 StringOffsetsSection, /* UseRelativeOffsets = */ true); 1608 } 1609 1610 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer, 1611 const DebugLocStream::Entry &Entry) { 1612 auto &&Comments = DebugLocs.getComments(Entry); 1613 auto Comment = Comments.begin(); 1614 auto End = Comments.end(); 1615 for (uint8_t Byte : DebugLocs.getBytes(Entry)) 1616 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : ""); 1617 } 1618 1619 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, 1620 ByteStreamer &Streamer, 1621 const DebugLocEntry::Value &Value, 1622 DwarfExpression &DwarfExpr) { 1623 auto *DIExpr = Value.getExpression(); 1624 DIExpressionCursor ExprCursor(DIExpr); 1625 DwarfExpr.addFragmentOffset(DIExpr); 1626 // Regular entry. 1627 if (Value.isInt()) { 1628 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed || 1629 BT->getEncoding() == dwarf::DW_ATE_signed_char)) 1630 DwarfExpr.addSignedConstant(Value.getInt()); 1631 else 1632 DwarfExpr.addUnsignedConstant(Value.getInt()); 1633 } else if (Value.isLocation()) { 1634 MachineLocation Location = Value.getLoc(); 1635 if (Location.isIndirect()) 1636 DwarfExpr.setMemoryLocationKind(); 1637 DIExpressionCursor Cursor(DIExpr); 1638 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo(); 1639 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 1640 return; 1641 return DwarfExpr.addExpression(std::move(Cursor)); 1642 } else if (Value.isConstantFP()) { 1643 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt(); 1644 DwarfExpr.addUnsignedConstant(RawBytes); 1645 } 1646 DwarfExpr.addExpression(std::move(ExprCursor)); 1647 } 1648 1649 void DebugLocEntry::finalize(const AsmPrinter &AP, 1650 DebugLocStream::ListBuilder &List, 1651 const DIBasicType *BT) { 1652 DebugLocStream::EntryBuilder Entry(List, Begin, End); 1653 BufferByteStreamer Streamer = Entry.getStreamer(); 1654 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer); 1655 const DebugLocEntry::Value &Value = Values[0]; 1656 if (Value.isFragment()) { 1657 // Emit all fragments that belong to the same variable and range. 1658 assert(llvm::all_of(Values, [](DebugLocEntry::Value P) { 1659 return P.isFragment(); 1660 }) && "all values are expected to be fragments"); 1661 assert(std::is_sorted(Values.begin(), Values.end()) && 1662 "fragments are expected to be sorted"); 1663 1664 for (auto Fragment : Values) 1665 emitDebugLocValue(AP, BT, Streamer, Fragment, DwarfExpr); 1666 1667 } else { 1668 assert(Values.size() == 1 && "only fragments may have >1 value"); 1669 emitDebugLocValue(AP, BT, Streamer, Value, DwarfExpr); 1670 } 1671 DwarfExpr.finalize(); 1672 } 1673 1674 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) { 1675 // Emit the size. 1676 Asm->OutStreamer->AddComment("Loc expr size"); 1677 Asm->EmitInt16(DebugLocs.getBytes(Entry).size()); 1678 1679 // Emit the entry. 1680 APByteStreamer Streamer(*Asm); 1681 emitDebugLocEntry(Streamer, Entry); 1682 } 1683 1684 // Emit locations into the debug loc section. 1685 void DwarfDebug::emitDebugLoc() { 1686 if (DebugLocs.getLists().empty()) 1687 return; 1688 1689 // Start the dwarf loc section. 1690 Asm->OutStreamer->SwitchSection( 1691 Asm->getObjFileLowering().getDwarfLocSection()); 1692 unsigned char Size = Asm->MAI->getCodePointerSize(); 1693 for (const auto &List : DebugLocs.getLists()) { 1694 Asm->OutStreamer->EmitLabel(List.Label); 1695 const DwarfCompileUnit *CU = List.CU; 1696 for (const auto &Entry : DebugLocs.getEntries(List)) { 1697 // Set up the range. This range is relative to the entry point of the 1698 // compile unit. This is a hard coded 0 for low_pc when we're emitting 1699 // ranges, or the DW_AT_low_pc on the compile unit otherwise. 1700 if (auto *Base = CU->getBaseAddress()) { 1701 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size); 1702 Asm->EmitLabelDifference(Entry.EndSym, Base, Size); 1703 } else { 1704 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size); 1705 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size); 1706 } 1707 1708 emitDebugLocEntryLocation(Entry); 1709 } 1710 Asm->OutStreamer->EmitIntValue(0, Size); 1711 Asm->OutStreamer->EmitIntValue(0, Size); 1712 } 1713 } 1714 1715 void DwarfDebug::emitDebugLocDWO() { 1716 Asm->OutStreamer->SwitchSection( 1717 Asm->getObjFileLowering().getDwarfLocDWOSection()); 1718 for (const auto &List : DebugLocs.getLists()) { 1719 Asm->OutStreamer->EmitLabel(List.Label); 1720 for (const auto &Entry : DebugLocs.getEntries(List)) { 1721 // Just always use start_length for now - at least that's one address 1722 // rather than two. We could get fancier and try to, say, reuse an 1723 // address we know we've emitted elsewhere (the start of the function? 1724 // The start of the CU or CU subrange that encloses this range?) 1725 Asm->EmitInt8(dwarf::DW_LLE_startx_length); 1726 unsigned idx = AddrPool.getIndex(Entry.BeginSym); 1727 Asm->EmitULEB128(idx); 1728 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4); 1729 1730 emitDebugLocEntryLocation(Entry); 1731 } 1732 Asm->EmitInt8(dwarf::DW_LLE_end_of_list); 1733 } 1734 } 1735 1736 struct ArangeSpan { 1737 const MCSymbol *Start, *End; 1738 }; 1739 1740 // Emit a debug aranges section, containing a CU lookup for any 1741 // address we can tie back to a CU. 1742 void DwarfDebug::emitDebugARanges() { 1743 // Provides a unique id per text section. 1744 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap; 1745 1746 // Filter labels by section. 1747 for (const SymbolCU &SCU : ArangeLabels) { 1748 if (SCU.Sym->isInSection()) { 1749 // Make a note of this symbol and it's section. 1750 MCSection *Section = &SCU.Sym->getSection(); 1751 if (!Section->getKind().isMetadata()) 1752 SectionMap[Section].push_back(SCU); 1753 } else { 1754 // Some symbols (e.g. common/bss on mach-o) can have no section but still 1755 // appear in the output. This sucks as we rely on sections to build 1756 // arange spans. We can do it without, but it's icky. 1757 SectionMap[nullptr].push_back(SCU); 1758 } 1759 } 1760 1761 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans; 1762 1763 for (auto &I : SectionMap) { 1764 MCSection *Section = I.first; 1765 SmallVector<SymbolCU, 8> &List = I.second; 1766 if (List.size() < 1) 1767 continue; 1768 1769 // If we have no section (e.g. common), just write out 1770 // individual spans for each symbol. 1771 if (!Section) { 1772 for (const SymbolCU &Cur : List) { 1773 ArangeSpan Span; 1774 Span.Start = Cur.Sym; 1775 Span.End = nullptr; 1776 assert(Cur.CU); 1777 Spans[Cur.CU].push_back(Span); 1778 } 1779 continue; 1780 } 1781 1782 // Sort the symbols by offset within the section. 1783 std::stable_sort( 1784 List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) { 1785 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0; 1786 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0; 1787 1788 // Symbols with no order assigned should be placed at the end. 1789 // (e.g. section end labels) 1790 if (IA == 0) 1791 return false; 1792 if (IB == 0) 1793 return true; 1794 return IA < IB; 1795 }); 1796 1797 // Insert a final terminator. 1798 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section))); 1799 1800 // Build spans between each label. 1801 const MCSymbol *StartSym = List[0].Sym; 1802 for (size_t n = 1, e = List.size(); n < e; n++) { 1803 const SymbolCU &Prev = List[n - 1]; 1804 const SymbolCU &Cur = List[n]; 1805 1806 // Try and build the longest span we can within the same CU. 1807 if (Cur.CU != Prev.CU) { 1808 ArangeSpan Span; 1809 Span.Start = StartSym; 1810 Span.End = Cur.Sym; 1811 assert(Prev.CU); 1812 Spans[Prev.CU].push_back(Span); 1813 StartSym = Cur.Sym; 1814 } 1815 } 1816 } 1817 1818 // Start the dwarf aranges section. 1819 Asm->OutStreamer->SwitchSection( 1820 Asm->getObjFileLowering().getDwarfARangesSection()); 1821 1822 unsigned PtrSize = Asm->MAI->getCodePointerSize(); 1823 1824 // Build a list of CUs used. 1825 std::vector<DwarfCompileUnit *> CUs; 1826 for (const auto &it : Spans) { 1827 DwarfCompileUnit *CU = it.first; 1828 CUs.push_back(CU); 1829 } 1830 1831 // Sort the CU list (again, to ensure consistent output order). 1832 std::sort(CUs.begin(), CUs.end(), 1833 [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) { 1834 return A->getUniqueID() < B->getUniqueID(); 1835 }); 1836 1837 // Emit an arange table for each CU we used. 1838 for (DwarfCompileUnit *CU : CUs) { 1839 std::vector<ArangeSpan> &List = Spans[CU]; 1840 1841 // Describe the skeleton CU's offset and length, not the dwo file's. 1842 if (auto *Skel = CU->getSkeleton()) 1843 CU = Skel; 1844 1845 // Emit size of content not including length itself. 1846 unsigned ContentSize = 1847 sizeof(int16_t) + // DWARF ARange version number 1848 sizeof(int32_t) + // Offset of CU in the .debug_info section 1849 sizeof(int8_t) + // Pointer Size (in bytes) 1850 sizeof(int8_t); // Segment Size (in bytes) 1851 1852 unsigned TupleSize = PtrSize * 2; 1853 1854 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 1855 unsigned Padding = 1856 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize); 1857 1858 ContentSize += Padding; 1859 ContentSize += (List.size() + 1) * TupleSize; 1860 1861 // For each compile unit, write the list of spans it covers. 1862 Asm->OutStreamer->AddComment("Length of ARange Set"); 1863 Asm->EmitInt32(ContentSize); 1864 Asm->OutStreamer->AddComment("DWARF Arange version number"); 1865 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); 1866 Asm->OutStreamer->AddComment("Offset Into Debug Info Section"); 1867 Asm->emitDwarfSymbolReference(CU->getLabelBegin()); 1868 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 1869 Asm->EmitInt8(PtrSize); 1870 Asm->OutStreamer->AddComment("Segment Size (in bytes)"); 1871 Asm->EmitInt8(0); 1872 1873 Asm->OutStreamer->emitFill(Padding, 0xff); 1874 1875 for (const ArangeSpan &Span : List) { 1876 Asm->EmitLabelReference(Span.Start, PtrSize); 1877 1878 // Calculate the size as being from the span start to it's end. 1879 if (Span.End) { 1880 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize); 1881 } else { 1882 // For symbols without an end marker (e.g. common), we 1883 // write a single arange entry containing just that one symbol. 1884 uint64_t Size = SymSize[Span.Start]; 1885 if (Size == 0) 1886 Size = 1; 1887 1888 Asm->OutStreamer->EmitIntValue(Size, PtrSize); 1889 } 1890 } 1891 1892 Asm->OutStreamer->AddComment("ARange terminator"); 1893 Asm->OutStreamer->EmitIntValue(0, PtrSize); 1894 Asm->OutStreamer->EmitIntValue(0, PtrSize); 1895 } 1896 } 1897 1898 /// Emit address ranges into a debug ranges section. 1899 void DwarfDebug::emitDebugRanges() { 1900 if (CUMap.empty()) 1901 return; 1902 1903 // Start the dwarf ranges section. 1904 Asm->OutStreamer->SwitchSection( 1905 Asm->getObjFileLowering().getDwarfRangesSection()); 1906 1907 // Size for our labels. 1908 unsigned char Size = Asm->MAI->getCodePointerSize(); 1909 1910 // Grab the specific ranges for the compile units in the module. 1911 for (const auto &I : CUMap) { 1912 DwarfCompileUnit *TheCU = I.second; 1913 1914 if (auto *Skel = TheCU->getSkeleton()) 1915 TheCU = Skel; 1916 1917 // Iterate over the misc ranges for the compile units in the module. 1918 for (const RangeSpanList &List : TheCU->getRangeLists()) { 1919 // Emit our symbol so we can find the beginning of the range. 1920 Asm->OutStreamer->EmitLabel(List.getSym()); 1921 1922 // Gather all the ranges that apply to the same section so they can share 1923 // a base address entry. 1924 MapVector<const MCSection *, std::vector<const RangeSpan *>> MV; 1925 for (const RangeSpan &Range : List.getRanges()) { 1926 MV[&Range.getStart()->getSection()].push_back(&Range); 1927 } 1928 1929 auto *CUBase = TheCU->getBaseAddress(); 1930 bool BaseIsSet = false; 1931 for (const auto &P : MV) { 1932 // Don't bother with a base address entry if there's only one range in 1933 // this section in this range list - for example ranges for a CU will 1934 // usually consist of single regions from each of many sections 1935 // (-ffunction-sections, or just C++ inline functions) except under LTO 1936 // or optnone where there may be holes in a single CU's section 1937 // contrubutions. 1938 auto *Base = CUBase; 1939 if (!Base && P.second.size() > 1 && 1940 UseDwarfRangesBaseAddressSpecifier) { 1941 BaseIsSet = true; 1942 // FIXME/use care: This may not be a useful base address if it's not 1943 // the lowest address/range in this object. 1944 Base = P.second.front()->getStart(); 1945 Asm->OutStreamer->EmitIntValue(-1, Size); 1946 Asm->OutStreamer->EmitSymbolValue(Base, Size); 1947 } else if (BaseIsSet) { 1948 BaseIsSet = false; 1949 Asm->OutStreamer->EmitIntValue(-1, Size); 1950 Asm->OutStreamer->EmitIntValue(0, Size); 1951 } 1952 1953 for (const auto *RS : P.second) { 1954 const MCSymbol *Begin = RS->getStart(); 1955 const MCSymbol *End = RS->getEnd(); 1956 assert(Begin && "Range without a begin symbol?"); 1957 assert(End && "Range without an end symbol?"); 1958 if (Base) { 1959 Asm->EmitLabelDifference(Begin, Base, Size); 1960 Asm->EmitLabelDifference(End, Base, Size); 1961 } else { 1962 Asm->OutStreamer->EmitSymbolValue(Begin, Size); 1963 Asm->OutStreamer->EmitSymbolValue(End, Size); 1964 } 1965 } 1966 } 1967 1968 // And terminate the list with two 0 values. 1969 Asm->OutStreamer->EmitIntValue(0, Size); 1970 Asm->OutStreamer->EmitIntValue(0, Size); 1971 } 1972 } 1973 } 1974 1975 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) { 1976 for (auto *MN : Nodes) { 1977 if (auto *M = dyn_cast<DIMacro>(MN)) 1978 emitMacro(*M); 1979 else if (auto *F = dyn_cast<DIMacroFile>(MN)) 1980 emitMacroFile(*F, U); 1981 else 1982 llvm_unreachable("Unexpected DI type!"); 1983 } 1984 } 1985 1986 void DwarfDebug::emitMacro(DIMacro &M) { 1987 Asm->EmitULEB128(M.getMacinfoType()); 1988 Asm->EmitULEB128(M.getLine()); 1989 StringRef Name = M.getName(); 1990 StringRef Value = M.getValue(); 1991 Asm->OutStreamer->EmitBytes(Name); 1992 if (!Value.empty()) { 1993 // There should be one space between macro name and macro value. 1994 Asm->EmitInt8(' '); 1995 Asm->OutStreamer->EmitBytes(Value); 1996 } 1997 Asm->EmitInt8('\0'); 1998 } 1999 2000 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) { 2001 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file); 2002 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file); 2003 Asm->EmitULEB128(F.getLine()); 2004 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile())); 2005 handleMacroNodes(F.getElements(), U); 2006 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file); 2007 } 2008 2009 /// Emit macros into a debug macinfo section. 2010 void DwarfDebug::emitDebugMacinfo() { 2011 if (CUMap.empty()) 2012 return; 2013 2014 // Start the dwarf macinfo section. 2015 Asm->OutStreamer->SwitchSection( 2016 Asm->getObjFileLowering().getDwarfMacinfoSection()); 2017 2018 for (const auto &P : CUMap) { 2019 auto &TheCU = *P.second; 2020 auto *SkCU = TheCU.getSkeleton(); 2021 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 2022 auto *CUNode = cast<DICompileUnit>(P.first); 2023 DIMacroNodeArray Macros = CUNode->getMacros(); 2024 if (!Macros.empty()) { 2025 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin()); 2026 handleMacroNodes(Macros, U); 2027 } 2028 } 2029 Asm->OutStreamer->AddComment("End Of Macro List Mark"); 2030 Asm->EmitInt8(0); 2031 } 2032 2033 // DWARF5 Experimental Separate Dwarf emitters. 2034 2035 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die, 2036 std::unique_ptr<DwarfCompileUnit> NewU) { 2037 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name, 2038 Asm->TM.Options.MCOptions.SplitDwarfFile); 2039 2040 if (!CompilationDir.empty()) 2041 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 2042 2043 addGnuPubAttributes(*NewU, Die); 2044 2045 SkeletonHolder.addUnit(std::move(NewU)); 2046 } 2047 2048 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list, 2049 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id, 2050 // DW_AT_addr_base, DW_AT_ranges_base. 2051 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) { 2052 2053 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 2054 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder); 2055 DwarfCompileUnit &NewCU = *OwnedUnit; 2056 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 2057 2058 NewCU.initStmtList(); 2059 2060 if (useSegmentedStringOffsetsTable()) 2061 NewCU.addStringOffsetsStart(); 2062 2063 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit)); 2064 2065 return NewCU; 2066 } 2067 2068 // Emit the .debug_info.dwo section for separated dwarf. This contains the 2069 // compile units that would normally be in debug_info. 2070 void DwarfDebug::emitDebugInfoDWO() { 2071 assert(useSplitDwarf() && "No split dwarf debug info?"); 2072 // Don't emit relocations into the dwo file. 2073 InfoHolder.emitUnits(/* UseOffsets */ true); 2074 } 2075 2076 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 2077 // abbreviations for the .debug_info.dwo section. 2078 void DwarfDebug::emitDebugAbbrevDWO() { 2079 assert(useSplitDwarf() && "No split dwarf?"); 2080 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 2081 } 2082 2083 void DwarfDebug::emitDebugLineDWO() { 2084 assert(useSplitDwarf() && "No split dwarf?"); 2085 if (!HasSplitTypeUnits) 2086 return; 2087 Asm->OutStreamer->SwitchSection( 2088 Asm->getObjFileLowering().getDwarfLineDWOSection()); 2089 SplitTypeUnitFileTable.Emit(*Asm->OutStreamer, MCDwarfLineTableParams()); 2090 } 2091 2092 void DwarfDebug::emitStringOffsetsTableHeaderDWO() { 2093 assert(useSplitDwarf() && "No split dwarf?"); 2094 InfoHolder.emitStringOffsetsTableHeader( 2095 Asm->getObjFileLowering().getDwarfStrOffDWOSection()); 2096 } 2097 2098 // Emit the .debug_str.dwo section for separated dwarf. This contains the 2099 // string section and is identical in format to traditional .debug_str 2100 // sections. 2101 void DwarfDebug::emitDebugStrDWO() { 2102 if (useSegmentedStringOffsetsTable()) 2103 emitStringOffsetsTableHeaderDWO(); 2104 assert(useSplitDwarf() && "No split dwarf?"); 2105 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 2106 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 2107 OffSec, /* UseRelativeOffsets = */ false); 2108 } 2109 2110 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 2111 if (!useSplitDwarf()) 2112 return nullptr; 2113 if (SingleCU) 2114 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory()); 2115 return &SplitTypeUnitFileTable; 2116 } 2117 2118 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) { 2119 MD5 Hash; 2120 Hash.update(Identifier); 2121 // ... take the least significant 8 bytes and return those. Our MD5 2122 // implementation always returns its results in little endian, so we actually 2123 // need the "high" word. 2124 MD5::MD5Result Result; 2125 Hash.final(Result); 2126 return Result.high(); 2127 } 2128 2129 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 2130 StringRef Identifier, DIE &RefDie, 2131 const DICompositeType *CTy) { 2132 // Fast path if we're building some type units and one has already used the 2133 // address pool we know we're going to throw away all this work anyway, so 2134 // don't bother building dependent types. 2135 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed()) 2136 return; 2137 2138 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0)); 2139 if (!Ins.second) { 2140 CU.addDIETypeSignature(RefDie, Ins.first->second); 2141 return; 2142 } 2143 2144 bool TopLevelType = TypeUnitsUnderConstruction.empty(); 2145 AddrPool.resetUsedFlag(); 2146 2147 auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder, 2148 getDwoLineTable(CU)); 2149 DwarfTypeUnit &NewTU = *OwnedUnit; 2150 DIE &UnitDie = NewTU.getUnitDie(); 2151 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy); 2152 2153 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 2154 CU.getLanguage()); 2155 2156 uint64_t Signature = makeTypeSignature(Identifier); 2157 NewTU.setTypeSignature(Signature); 2158 Ins.first->second = Signature; 2159 2160 if (useSplitDwarf()) 2161 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesDWOSection()); 2162 else { 2163 CU.applyStmtList(UnitDie); 2164 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesSection(Signature)); 2165 } 2166 2167 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type 2168 // units. 2169 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 2170 NewTU.addStringOffsetsStart(); 2171 2172 NewTU.setType(NewTU.createTypeDIE(CTy)); 2173 2174 if (TopLevelType) { 2175 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction); 2176 TypeUnitsUnderConstruction.clear(); 2177 2178 // Types referencing entries in the address table cannot be placed in type 2179 // units. 2180 if (AddrPool.hasBeenUsed()) { 2181 2182 // Remove all the types built while building this type. 2183 // This is pessimistic as some of these types might not be dependent on 2184 // the type that used an address. 2185 for (const auto &TU : TypeUnitsToAdd) 2186 TypeSignatures.erase(TU.second); 2187 2188 // Construct this type in the CU directly. 2189 // This is inefficient because all the dependent types will be rebuilt 2190 // from scratch, including building them in type units, discovering that 2191 // they depend on addresses, throwing them out and rebuilding them. 2192 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy)); 2193 return; 2194 } 2195 2196 // If the type wasn't dependent on fission addresses, finish adding the type 2197 // and all its dependent types. 2198 for (auto &TU : TypeUnitsToAdd) { 2199 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get()); 2200 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf()); 2201 } 2202 HasSplitTypeUnits = useSplitDwarf(); 2203 } 2204 CU.addDIETypeSignature(RefDie, Signature); 2205 } 2206 2207 // Accelerator table mutators - add each name along with its companion 2208 // DIE to the proper table while ensuring that the name that we're going 2209 // to reference is in the string table. We do this since the names we 2210 // add may not only be identical to the names in the DIE. 2211 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) { 2212 if (!useDwarfAccelTables()) 2213 return; 2214 AccelNames.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 2215 } 2216 2217 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) { 2218 if (!useDwarfAccelTables()) 2219 return; 2220 AccelObjC.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 2221 } 2222 2223 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) { 2224 if (!useDwarfAccelTables()) 2225 return; 2226 AccelNamespace.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 2227 } 2228 2229 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) { 2230 if (!useDwarfAccelTables()) 2231 return; 2232 AccelTypes.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 2233 } 2234 2235 uint16_t DwarfDebug::getDwarfVersion() const { 2236 return Asm->OutStreamer->getContext().getDwarfVersion(); 2237 } 2238