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