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