1 //=== DWARFLinker.cpp -----------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/DWARFLinker/DWARFLinker.h" 10 #include "llvm/ADT/ArrayRef.h" 11 #include "llvm/ADT/BitVector.h" 12 #include "llvm/ADT/STLExtras.h" 13 #include "llvm/ADT/Triple.h" 14 #include "llvm/CodeGen/NonRelocatableStringpool.h" 15 #include "llvm/DWARFLinker/DWARFLinkerDeclContext.h" 16 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h" 17 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 18 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h" 19 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h" 20 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h" 21 #include "llvm/DebugInfo/DWARF/DWARFDie.h" 22 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h" 23 #include "llvm/DebugInfo/DWARF/DWARFSection.h" 24 #include "llvm/DebugInfo/DWARF/DWARFUnit.h" 25 #include "llvm/Support/DataExtractor.h" 26 #include "llvm/Support/Error.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/ErrorOr.h" 29 #include "llvm/Support/FormatVariadic.h" 30 #include "llvm/Support/LEB128.h" 31 #include "llvm/Support/Path.h" 32 #include "llvm/Support/ThreadPool.h" 33 #include <vector> 34 35 namespace llvm { 36 37 /// Hold the input and output of the debug info size in bytes. 38 struct DebugInfoSize { 39 uint64_t Input; 40 uint64_t Output; 41 }; 42 43 /// Compute the total size of the debug info. 44 static uint64_t getDebugInfoSize(DWARFContext &Dwarf) { 45 uint64_t Size = 0; 46 for (auto &Unit : Dwarf.compile_units()) { 47 Size += Unit->getLength(); 48 } 49 return Size; 50 } 51 52 /// Similar to DWARFUnitSection::getUnitForOffset(), but returning our 53 /// CompileUnit object instead. 54 static CompileUnit *getUnitForOffset(const UnitListTy &Units, uint64_t Offset) { 55 auto CU = llvm::upper_bound( 56 Units, Offset, [](uint64_t LHS, const std::unique_ptr<CompileUnit> &RHS) { 57 return LHS < RHS->getOrigUnit().getNextUnitOffset(); 58 }); 59 return CU != Units.end() ? CU->get() : nullptr; 60 } 61 62 /// Resolve the DIE attribute reference that has been extracted in \p RefValue. 63 /// The resulting DIE might be in another CompileUnit which is stored into \p 64 /// ReferencedCU. \returns null if resolving fails for any reason. 65 DWARFDie DWARFLinker::resolveDIEReference(const DWARFFile &File, 66 const UnitListTy &Units, 67 const DWARFFormValue &RefValue, 68 const DWARFDie &DIE, 69 CompileUnit *&RefCU) { 70 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference)); 71 uint64_t RefOffset = *RefValue.getAsReference(); 72 if ((RefCU = getUnitForOffset(Units, RefOffset))) 73 if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) { 74 // In a file with broken references, an attribute might point to a NULL 75 // DIE. 76 if (!RefDie.isNULL()) 77 return RefDie; 78 } 79 80 reportWarning("could not find referenced DIE", File, &DIE); 81 return DWARFDie(); 82 } 83 84 /// \returns whether the passed \a Attr type might contain a DIE reference 85 /// suitable for ODR uniquing. 86 static bool isODRAttribute(uint16_t Attr) { 87 switch (Attr) { 88 default: 89 return false; 90 case dwarf::DW_AT_type: 91 case dwarf::DW_AT_containing_type: 92 case dwarf::DW_AT_specification: 93 case dwarf::DW_AT_abstract_origin: 94 case dwarf::DW_AT_import: 95 return true; 96 } 97 llvm_unreachable("Improper attribute."); 98 } 99 100 static bool isTypeTag(uint16_t Tag) { 101 switch (Tag) { 102 case dwarf::DW_TAG_array_type: 103 case dwarf::DW_TAG_class_type: 104 case dwarf::DW_TAG_enumeration_type: 105 case dwarf::DW_TAG_pointer_type: 106 case dwarf::DW_TAG_reference_type: 107 case dwarf::DW_TAG_string_type: 108 case dwarf::DW_TAG_structure_type: 109 case dwarf::DW_TAG_subroutine_type: 110 case dwarf::DW_TAG_typedef: 111 case dwarf::DW_TAG_union_type: 112 case dwarf::DW_TAG_ptr_to_member_type: 113 case dwarf::DW_TAG_set_type: 114 case dwarf::DW_TAG_subrange_type: 115 case dwarf::DW_TAG_base_type: 116 case dwarf::DW_TAG_const_type: 117 case dwarf::DW_TAG_constant: 118 case dwarf::DW_TAG_file_type: 119 case dwarf::DW_TAG_namelist: 120 case dwarf::DW_TAG_packed_type: 121 case dwarf::DW_TAG_volatile_type: 122 case dwarf::DW_TAG_restrict_type: 123 case dwarf::DW_TAG_atomic_type: 124 case dwarf::DW_TAG_interface_type: 125 case dwarf::DW_TAG_unspecified_type: 126 case dwarf::DW_TAG_shared_type: 127 return true; 128 default: 129 break; 130 } 131 return false; 132 } 133 134 AddressesMap::~AddressesMap() {} 135 136 DwarfEmitter::~DwarfEmitter() {} 137 138 static Optional<StringRef> StripTemplateParameters(StringRef Name) { 139 // We are looking for template parameters to strip from Name. e.g. 140 // 141 // operator<<B> 142 // 143 // We look for > at the end but if it does not contain any < then we 144 // have something like operator>>. We check for the operator<=> case. 145 if (!Name.endswith(">") || Name.count("<") == 0 || Name.endswith("<=>")) 146 return {}; 147 148 // How many < until we have the start of the template parameters. 149 size_t NumLeftAnglesToSkip = 1; 150 151 // If we have operator<=> then we need to skip its < as well. 152 NumLeftAnglesToSkip += Name.count("<=>"); 153 154 size_t RightAngleCount = Name.count('>'); 155 size_t LeftAngleCount = Name.count('<'); 156 157 // If we have more < than > we have operator< or operator<< 158 // we to account for their < as well. 159 if (LeftAngleCount > RightAngleCount) 160 NumLeftAnglesToSkip += LeftAngleCount - RightAngleCount; 161 162 size_t StartOfTemplate = 0; 163 while (NumLeftAnglesToSkip--) 164 StartOfTemplate = Name.find('<', StartOfTemplate) + 1; 165 166 return Name.substr(0, StartOfTemplate - 1); 167 } 168 169 bool DWARFLinker::DIECloner::getDIENames(const DWARFDie &Die, 170 AttributesInfo &Info, 171 OffsetsStringPool &StringPool, 172 bool StripTemplate) { 173 // This function will be called on DIEs having low_pcs and 174 // ranges. As getting the name might be more expansive, filter out 175 // blocks directly. 176 if (Die.getTag() == dwarf::DW_TAG_lexical_block) 177 return false; 178 179 if (!Info.MangledName) 180 if (const char *MangledName = Die.getLinkageName()) 181 Info.MangledName = StringPool.getEntry(MangledName); 182 183 if (!Info.Name) 184 if (const char *Name = Die.getShortName()) 185 Info.Name = StringPool.getEntry(Name); 186 187 if (!Info.MangledName) 188 Info.MangledName = Info.Name; 189 190 if (StripTemplate && Info.Name && Info.MangledName != Info.Name) { 191 StringRef Name = Info.Name.getString(); 192 if (Optional<StringRef> StrippedName = StripTemplateParameters(Name)) 193 Info.NameWithoutTemplate = StringPool.getEntry(*StrippedName); 194 } 195 196 return Info.Name || Info.MangledName; 197 } 198 199 /// Resolve the relative path to a build artifact referenced by DWARF by 200 /// applying DW_AT_comp_dir. 201 static void resolveRelativeObjectPath(SmallVectorImpl<char> &Buf, DWARFDie CU) { 202 sys::path::append(Buf, dwarf::toString(CU.find(dwarf::DW_AT_comp_dir), "")); 203 } 204 205 /// Collect references to parseable Swift interfaces in imported 206 /// DW_TAG_module blocks. 207 static void analyzeImportedModule( 208 const DWARFDie &DIE, CompileUnit &CU, 209 swiftInterfacesMap *ParseableSwiftInterfaces, 210 std::function<void(const Twine &, const DWARFDie &)> ReportWarning) { 211 if (CU.getLanguage() != dwarf::DW_LANG_Swift) 212 return; 213 214 if (!ParseableSwiftInterfaces) 215 return; 216 217 StringRef Path = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_include_path)); 218 if (!Path.endswith(".swiftinterface")) 219 return; 220 // Don't track interfaces that are part of the SDK. 221 StringRef SysRoot = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_sysroot)); 222 if (SysRoot.empty()) 223 SysRoot = CU.getSysRoot(); 224 if (!SysRoot.empty() && Path.startswith(SysRoot)) 225 return; 226 if (Optional<DWARFFormValue> Val = DIE.find(dwarf::DW_AT_name)) 227 if (Optional<const char *> Name = Val->getAsCString()) { 228 auto &Entry = (*ParseableSwiftInterfaces)[*Name]; 229 // The prepend path is applied later when copying. 230 DWARFDie CUDie = CU.getOrigUnit().getUnitDIE(); 231 SmallString<128> ResolvedPath; 232 if (sys::path::is_relative(Path)) 233 resolveRelativeObjectPath(ResolvedPath, CUDie); 234 sys::path::append(ResolvedPath, Path); 235 if (!Entry.empty() && Entry != ResolvedPath) 236 ReportWarning( 237 Twine("Conflicting parseable interfaces for Swift Module ") + 238 *Name + ": " + Entry + " and " + Path, 239 DIE); 240 Entry = std::string(ResolvedPath.str()); 241 } 242 } 243 244 /// The distinct types of work performed by the work loop in 245 /// analyzeContextInfo. 246 enum class ContextWorklistItemType : uint8_t { 247 AnalyzeContextInfo, 248 UpdateChildPruning, 249 UpdatePruning, 250 }; 251 252 /// This class represents an item in the work list. The type defines what kind 253 /// of work needs to be performed when processing the current item. Everything 254 /// but the Type and Die fields are optional based on the type. 255 struct ContextWorklistItem { 256 DWARFDie Die; 257 unsigned ParentIdx; 258 union { 259 CompileUnit::DIEInfo *OtherInfo; 260 DeclContext *Context; 261 }; 262 ContextWorklistItemType Type; 263 bool InImportedModule; 264 265 ContextWorklistItem(DWARFDie Die, ContextWorklistItemType T, 266 CompileUnit::DIEInfo *OtherInfo = nullptr) 267 : Die(Die), ParentIdx(0), OtherInfo(OtherInfo), Type(T), 268 InImportedModule(false) {} 269 270 ContextWorklistItem(DWARFDie Die, DeclContext *Context, unsigned ParentIdx, 271 bool InImportedModule) 272 : Die(Die), ParentIdx(ParentIdx), Context(Context), 273 Type(ContextWorklistItemType::AnalyzeContextInfo), 274 InImportedModule(InImportedModule) {} 275 }; 276 277 static bool updatePruning(const DWARFDie &Die, CompileUnit &CU, 278 uint64_t ModulesEndOffset) { 279 CompileUnit::DIEInfo &Info = CU.getInfo(Die); 280 281 // Prune this DIE if it is either a forward declaration inside a 282 // DW_TAG_module or a DW_TAG_module that contains nothing but 283 // forward declarations. 284 Info.Prune &= (Die.getTag() == dwarf::DW_TAG_module) || 285 (isTypeTag(Die.getTag()) && 286 dwarf::toUnsigned(Die.find(dwarf::DW_AT_declaration), 0)); 287 288 // Only prune forward declarations inside a DW_TAG_module for which a 289 // definition exists elsewhere. 290 if (ModulesEndOffset == 0) 291 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset(); 292 else 293 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 && 294 Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset; 295 296 return Info.Prune; 297 } 298 299 static void updateChildPruning(const DWARFDie &Die, CompileUnit &CU, 300 CompileUnit::DIEInfo &ChildInfo) { 301 CompileUnit::DIEInfo &Info = CU.getInfo(Die); 302 Info.Prune &= ChildInfo.Prune; 303 } 304 305 /// Recursive helper to build the global DeclContext information and 306 /// gather the child->parent relationships in the original compile unit. 307 /// 308 /// This function uses the same work list approach as lookForDIEsToKeep. 309 /// 310 /// \return true when this DIE and all of its children are only 311 /// forward declarations to types defined in external clang modules 312 /// (i.e., forward declarations that are children of a DW_TAG_module). 313 static bool analyzeContextInfo( 314 const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU, 315 DeclContext *CurrentDeclContext, DeclContextTree &Contexts, 316 uint64_t ModulesEndOffset, swiftInterfacesMap *ParseableSwiftInterfaces, 317 std::function<void(const Twine &, const DWARFDie &)> ReportWarning, 318 bool InImportedModule = false) { 319 // LIFO work list. 320 std::vector<ContextWorklistItem> Worklist; 321 Worklist.emplace_back(DIE, CurrentDeclContext, ParentIdx, InImportedModule); 322 323 while (!Worklist.empty()) { 324 ContextWorklistItem Current = Worklist.back(); 325 Worklist.pop_back(); 326 327 switch (Current.Type) { 328 case ContextWorklistItemType::UpdatePruning: 329 updatePruning(Current.Die, CU, ModulesEndOffset); 330 continue; 331 case ContextWorklistItemType::UpdateChildPruning: 332 updateChildPruning(Current.Die, CU, *Current.OtherInfo); 333 continue; 334 case ContextWorklistItemType::AnalyzeContextInfo: 335 break; 336 } 337 338 unsigned Idx = CU.getOrigUnit().getDIEIndex(Current.Die); 339 CompileUnit::DIEInfo &Info = CU.getInfo(Idx); 340 341 // Clang imposes an ODR on modules(!) regardless of the language: 342 // "The module-id should consist of only a single identifier, 343 // which provides the name of the module being defined. Each 344 // module shall have a single definition." 345 // 346 // This does not extend to the types inside the modules: 347 // "[I]n C, this implies that if two structs are defined in 348 // different submodules with the same name, those two types are 349 // distinct types (but may be compatible types if their 350 // definitions match)." 351 // 352 // We treat non-C++ modules like namespaces for this reason. 353 if (Current.Die.getTag() == dwarf::DW_TAG_module && 354 Current.ParentIdx == 0 && 355 dwarf::toString(Current.Die.find(dwarf::DW_AT_name), "") != 356 CU.getClangModuleName()) { 357 Current.InImportedModule = true; 358 analyzeImportedModule(Current.Die, CU, ParseableSwiftInterfaces, 359 ReportWarning); 360 } 361 362 Info.ParentIdx = Current.ParentIdx; 363 bool InClangModule = CU.isClangModule() || Current.InImportedModule; 364 if (CU.hasODR() || InClangModule) { 365 if (Current.Context) { 366 auto PtrInvalidPair = Contexts.getChildDeclContext( 367 *Current.Context, Current.Die, CU, InClangModule); 368 Current.Context = PtrInvalidPair.getPointer(); 369 Info.Ctxt = 370 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer(); 371 if (Info.Ctxt) 372 Info.Ctxt->setDefinedInClangModule(InClangModule); 373 } else 374 Info.Ctxt = Current.Context = nullptr; 375 } 376 377 Info.Prune = Current.InImportedModule; 378 // Add children in reverse order to the worklist to effectively process 379 // them in order. 380 Worklist.emplace_back(Current.Die, ContextWorklistItemType::UpdatePruning); 381 for (auto Child : reverse(Current.Die.children())) { 382 CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child); 383 Worklist.emplace_back( 384 Current.Die, ContextWorklistItemType::UpdateChildPruning, &ChildInfo); 385 Worklist.emplace_back(Child, Current.Context, Idx, 386 Current.InImportedModule); 387 } 388 } 389 390 return CU.getInfo(DIE).Prune; 391 } 392 393 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) { 394 switch (Tag) { 395 default: 396 return false; 397 case dwarf::DW_TAG_class_type: 398 case dwarf::DW_TAG_common_block: 399 case dwarf::DW_TAG_lexical_block: 400 case dwarf::DW_TAG_structure_type: 401 case dwarf::DW_TAG_subprogram: 402 case dwarf::DW_TAG_subroutine_type: 403 case dwarf::DW_TAG_union_type: 404 return true; 405 } 406 llvm_unreachable("Invalid Tag"); 407 } 408 409 void DWARFLinker::cleanupAuxiliarryData(LinkContext &Context) { 410 Context.clear(); 411 412 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I) 413 (*I)->~DIEBlock(); 414 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I) 415 (*I)->~DIELoc(); 416 417 DIEBlocks.clear(); 418 DIELocs.clear(); 419 DIEAlloc.Reset(); 420 } 421 422 /// Check if a variable describing DIE should be kept. 423 /// \returns updated TraversalFlags. 424 unsigned DWARFLinker::shouldKeepVariableDIE(AddressesMap &RelocMgr, 425 const DWARFDie &DIE, 426 CompileUnit::DIEInfo &MyInfo, 427 unsigned Flags) { 428 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr(); 429 430 // Global variables with constant value can always be kept. 431 if (!(Flags & TF_InFunctionScope) && 432 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) { 433 MyInfo.InDebugMap = true; 434 return Flags | TF_Keep; 435 } 436 437 // See if there is a relocation to a valid debug map entry inside 438 // this variable's location. The order is important here. We want to 439 // always check if the variable has a valid relocation, so that the 440 // DIEInfo is filled. However, we don't want a static variable in a 441 // function to force us to keep the enclosing function. 442 if (!RelocMgr.hasLiveMemoryLocation(DIE, MyInfo) || 443 (Flags & TF_InFunctionScope)) 444 return Flags; 445 446 if (Options.Verbose) { 447 outs() << "Keeping variable DIE:"; 448 DIDumpOptions DumpOpts; 449 DumpOpts.ChildRecurseDepth = 0; 450 DumpOpts.Verbose = Options.Verbose; 451 DIE.dump(outs(), 8 /* Indent */, DumpOpts); 452 } 453 454 return Flags | TF_Keep; 455 } 456 457 /// Check if a function describing DIE should be kept. 458 /// \returns updated TraversalFlags. 459 unsigned DWARFLinker::shouldKeepSubprogramDIE( 460 AddressesMap &RelocMgr, RangesTy &Ranges, const DWARFDie &DIE, 461 const DWARFFile &File, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo, 462 unsigned Flags) { 463 Flags |= TF_InFunctionScope; 464 465 auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc)); 466 if (!LowPc) 467 return Flags; 468 469 assert(LowPc.hasValue() && "low_pc attribute is not an address."); 470 if (!RelocMgr.hasLiveAddressRange(DIE, MyInfo)) 471 return Flags; 472 473 if (Options.Verbose) { 474 outs() << "Keeping subprogram DIE:"; 475 DIDumpOptions DumpOpts; 476 DumpOpts.ChildRecurseDepth = 0; 477 DumpOpts.Verbose = Options.Verbose; 478 DIE.dump(outs(), 8 /* Indent */, DumpOpts); 479 } 480 481 if (DIE.getTag() == dwarf::DW_TAG_label) { 482 if (Unit.hasLabelAt(*LowPc)) 483 return Flags; 484 485 DWARFUnit &OrigUnit = Unit.getOrigUnit(); 486 // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels 487 // that don't fall into the CU's aranges. This is wrong IMO. Debug info 488 // generation bugs aside, this is really wrong in the case of labels, where 489 // a label marking the end of a function will have a PC == CU's high_pc. 490 if (dwarf::toAddress(OrigUnit.getUnitDIE().find(dwarf::DW_AT_high_pc)) 491 .getValueOr(UINT64_MAX) <= LowPc) 492 return Flags; 493 Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust); 494 return Flags | TF_Keep; 495 } 496 497 Flags |= TF_Keep; 498 499 Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc); 500 if (!HighPc) { 501 reportWarning("Function without high_pc. Range will be discarded.\n", File, 502 &DIE); 503 return Flags; 504 } 505 506 // Replace the debug map range with a more accurate one. 507 Ranges[*LowPc] = ObjFileAddressRange(*HighPc, MyInfo.AddrAdjust); 508 Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust); 509 return Flags; 510 } 511 512 /// Check if a DIE should be kept. 513 /// \returns updated TraversalFlags. 514 unsigned DWARFLinker::shouldKeepDIE(AddressesMap &RelocMgr, RangesTy &Ranges, 515 const DWARFDie &DIE, const DWARFFile &File, 516 CompileUnit &Unit, 517 CompileUnit::DIEInfo &MyInfo, 518 unsigned Flags) { 519 switch (DIE.getTag()) { 520 case dwarf::DW_TAG_constant: 521 case dwarf::DW_TAG_variable: 522 return shouldKeepVariableDIE(RelocMgr, DIE, MyInfo, Flags); 523 case dwarf::DW_TAG_subprogram: 524 case dwarf::DW_TAG_label: 525 return shouldKeepSubprogramDIE(RelocMgr, Ranges, DIE, File, Unit, MyInfo, 526 Flags); 527 case dwarf::DW_TAG_base_type: 528 // DWARF Expressions may reference basic types, but scanning them 529 // is expensive. Basic types are tiny, so just keep all of them. 530 case dwarf::DW_TAG_imported_module: 531 case dwarf::DW_TAG_imported_declaration: 532 case dwarf::DW_TAG_imported_unit: 533 // We always want to keep these. 534 return Flags | TF_Keep; 535 default: 536 break; 537 } 538 539 return Flags; 540 } 541 542 /// Helper that updates the completeness of the current DIE based on the 543 /// completeness of one of its children. It depends on the incompleteness of 544 /// the children already being computed. 545 static void updateChildIncompleteness(const DWARFDie &Die, CompileUnit &CU, 546 CompileUnit::DIEInfo &ChildInfo) { 547 switch (Die.getTag()) { 548 case dwarf::DW_TAG_structure_type: 549 case dwarf::DW_TAG_class_type: 550 break; 551 default: 552 return; 553 } 554 555 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die); 556 557 if (ChildInfo.Incomplete || ChildInfo.Prune) 558 MyInfo.Incomplete = true; 559 } 560 561 /// Helper that updates the completeness of the current DIE based on the 562 /// completeness of the DIEs it references. It depends on the incompleteness of 563 /// the referenced DIE already being computed. 564 static void updateRefIncompleteness(const DWARFDie &Die, CompileUnit &CU, 565 CompileUnit::DIEInfo &RefInfo) { 566 switch (Die.getTag()) { 567 case dwarf::DW_TAG_typedef: 568 case dwarf::DW_TAG_member: 569 case dwarf::DW_TAG_reference_type: 570 case dwarf::DW_TAG_ptr_to_member_type: 571 case dwarf::DW_TAG_pointer_type: 572 break; 573 default: 574 return; 575 } 576 577 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die); 578 579 if (MyInfo.Incomplete) 580 return; 581 582 if (RefInfo.Incomplete) 583 MyInfo.Incomplete = true; 584 } 585 586 /// Look at the children of the given DIE and decide whether they should be 587 /// kept. 588 void DWARFLinker::lookForChildDIEsToKeep( 589 const DWARFDie &Die, CompileUnit &CU, unsigned Flags, 590 SmallVectorImpl<WorklistItem> &Worklist) { 591 // The TF_ParentWalk flag tells us that we are currently walking up the 592 // parent chain of a required DIE, and we don't want to mark all the children 593 // of the parents as kept (consider for example a DW_TAG_namespace node in 594 // the parent chain). There are however a set of DIE types for which we want 595 // to ignore that directive and still walk their children. 596 if (dieNeedsChildrenToBeMeaningful(Die.getTag())) 597 Flags &= ~DWARFLinker::TF_ParentWalk; 598 599 // We're finished if this DIE has no children or we're walking the parent 600 // chain. 601 if (!Die.hasChildren() || (Flags & DWARFLinker::TF_ParentWalk)) 602 return; 603 604 // Add children in reverse order to the worklist to effectively process them 605 // in order. 606 for (auto Child : reverse(Die.children())) { 607 // Add a worklist item before every child to calculate incompleteness right 608 // after the current child is processed. 609 CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child); 610 Worklist.emplace_back(Die, CU, WorklistItemType::UpdateChildIncompleteness, 611 &ChildInfo); 612 Worklist.emplace_back(Child, CU, Flags); 613 } 614 } 615 616 /// Look at DIEs referenced by the given DIE and decide whether they should be 617 /// kept. All DIEs referenced though attributes should be kept. 618 void DWARFLinker::lookForRefDIEsToKeep( 619 const DWARFDie &Die, CompileUnit &CU, unsigned Flags, 620 const UnitListTy &Units, const DWARFFile &File, 621 SmallVectorImpl<WorklistItem> &Worklist) { 622 bool UseOdr = (Flags & DWARFLinker::TF_DependencyWalk) 623 ? (Flags & DWARFLinker::TF_ODR) 624 : CU.hasODR(); 625 DWARFUnit &Unit = CU.getOrigUnit(); 626 DWARFDataExtractor Data = Unit.getDebugInfoExtractor(); 627 const auto *Abbrev = Die.getAbbreviationDeclarationPtr(); 628 uint64_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode()); 629 630 SmallVector<std::pair<DWARFDie, CompileUnit &>, 4> ReferencedDIEs; 631 for (const auto &AttrSpec : Abbrev->attributes()) { 632 DWARFFormValue Val(AttrSpec.Form); 633 if (!Val.isFormClass(DWARFFormValue::FC_Reference) || 634 AttrSpec.Attr == dwarf::DW_AT_sibling) { 635 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, 636 Unit.getFormParams()); 637 continue; 638 } 639 640 Val.extractValue(Data, &Offset, Unit.getFormParams(), &Unit); 641 CompileUnit *ReferencedCU; 642 if (auto RefDie = 643 resolveDIEReference(File, Units, Val, Die, ReferencedCU)) { 644 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefDie); 645 bool IsModuleRef = Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() && 646 Info.Ctxt->isDefinedInClangModule(); 647 // If the referenced DIE has a DeclContext that has already been 648 // emitted, then do not keep the one in this CU. We'll link to 649 // the canonical DIE in cloneDieReferenceAttribute. 650 // 651 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't 652 // be necessary and could be advantageously replaced by 653 // ReferencedCU->hasODR() && CU.hasODR(). 654 // 655 // FIXME: compatibility with dsymutil-classic. There is no 656 // reason not to unique ref_addr references. 657 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && (UseOdr || IsModuleRef) && 658 Info.Ctxt && 659 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt && 660 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr)) 661 continue; 662 663 // Keep a module forward declaration if there is no definition. 664 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt && 665 Info.Ctxt->getCanonicalDIEOffset())) 666 Info.Prune = false; 667 ReferencedDIEs.emplace_back(RefDie, *ReferencedCU); 668 } 669 } 670 671 unsigned ODRFlag = UseOdr ? DWARFLinker::TF_ODR : 0; 672 673 // Add referenced DIEs in reverse order to the worklist to effectively 674 // process them in order. 675 for (auto &P : reverse(ReferencedDIEs)) { 676 // Add a worklist item before every child to calculate incompleteness right 677 // after the current child is processed. 678 CompileUnit::DIEInfo &Info = P.second.getInfo(P.first); 679 Worklist.emplace_back(Die, CU, WorklistItemType::UpdateRefIncompleteness, 680 &Info); 681 Worklist.emplace_back(P.first, P.second, 682 DWARFLinker::TF_Keep | 683 DWARFLinker::TF_DependencyWalk | ODRFlag); 684 } 685 } 686 687 /// Look at the parent of the given DIE and decide whether they should be kept. 688 void DWARFLinker::lookForParentDIEsToKeep( 689 unsigned AncestorIdx, CompileUnit &CU, unsigned Flags, 690 SmallVectorImpl<WorklistItem> &Worklist) { 691 // Stop if we encounter an ancestor that's already marked as kept. 692 if (CU.getInfo(AncestorIdx).Keep) 693 return; 694 695 DWARFUnit &Unit = CU.getOrigUnit(); 696 DWARFDie ParentDIE = Unit.getDIEAtIndex(AncestorIdx); 697 Worklist.emplace_back(CU.getInfo(AncestorIdx).ParentIdx, CU, Flags); 698 Worklist.emplace_back(ParentDIE, CU, Flags); 699 } 700 701 /// Recursively walk the \p DIE tree and look for DIEs to keep. Store that 702 /// information in \p CU's DIEInfo. 703 /// 704 /// This function is the entry point of the DIE selection algorithm. It is 705 /// expected to walk the DIE tree in file order and (though the mediation of 706 /// its helper) call hasValidRelocation() on each DIE that might be a 'root 707 /// DIE' (See DwarfLinker class comment). 708 /// 709 /// While walking the dependencies of root DIEs, this function is also called, 710 /// but during these dependency walks the file order is not respected. The 711 /// TF_DependencyWalk flag tells us which kind of traversal we are currently 712 /// doing. 713 /// 714 /// The recursive algorithm is implemented iteratively as a work list because 715 /// very deep recursion could exhaust the stack for large projects. The work 716 /// list acts as a scheduler for different types of work that need to be 717 /// performed. 718 /// 719 /// The recursive nature of the algorithm is simulated by running the "main" 720 /// algorithm (LookForDIEsToKeep) followed by either looking at more DIEs 721 /// (LookForChildDIEsToKeep, LookForRefDIEsToKeep, LookForParentDIEsToKeep) or 722 /// fixing up a computed property (UpdateChildIncompleteness, 723 /// UpdateRefIncompleteness). 724 /// 725 /// The return value indicates whether the DIE is incomplete. 726 void DWARFLinker::lookForDIEsToKeep(AddressesMap &AddressesMap, 727 RangesTy &Ranges, const UnitListTy &Units, 728 const DWARFDie &Die, const DWARFFile &File, 729 CompileUnit &Cu, unsigned Flags) { 730 // LIFO work list. 731 SmallVector<WorklistItem, 4> Worklist; 732 Worklist.emplace_back(Die, Cu, Flags); 733 734 while (!Worklist.empty()) { 735 WorklistItem Current = Worklist.back(); 736 Worklist.pop_back(); 737 738 // Look at the worklist type to decide what kind of work to perform. 739 switch (Current.Type) { 740 case WorklistItemType::UpdateChildIncompleteness: 741 updateChildIncompleteness(Current.Die, Current.CU, *Current.OtherInfo); 742 continue; 743 case WorklistItemType::UpdateRefIncompleteness: 744 updateRefIncompleteness(Current.Die, Current.CU, *Current.OtherInfo); 745 continue; 746 case WorklistItemType::LookForChildDIEsToKeep: 747 lookForChildDIEsToKeep(Current.Die, Current.CU, Current.Flags, Worklist); 748 continue; 749 case WorklistItemType::LookForRefDIEsToKeep: 750 lookForRefDIEsToKeep(Current.Die, Current.CU, Current.Flags, Units, File, 751 Worklist); 752 continue; 753 case WorklistItemType::LookForParentDIEsToKeep: 754 lookForParentDIEsToKeep(Current.AncestorIdx, Current.CU, Current.Flags, 755 Worklist); 756 continue; 757 case WorklistItemType::LookForDIEsToKeep: 758 break; 759 } 760 761 unsigned Idx = Current.CU.getOrigUnit().getDIEIndex(Current.Die); 762 CompileUnit::DIEInfo &MyInfo = Current.CU.getInfo(Idx); 763 764 if (MyInfo.Prune) 765 continue; 766 767 // If the Keep flag is set, we are marking a required DIE's dependencies. 768 // If our target is already marked as kept, we're all set. 769 bool AlreadyKept = MyInfo.Keep; 770 if ((Current.Flags & TF_DependencyWalk) && AlreadyKept) 771 continue; 772 773 // We must not call shouldKeepDIE while called from keepDIEAndDependencies, 774 // because it would screw up the relocation finding logic. 775 if (!(Current.Flags & TF_DependencyWalk)) 776 Current.Flags = shouldKeepDIE(AddressesMap, Ranges, Current.Die, File, 777 Current.CU, MyInfo, Current.Flags); 778 779 // Finish by looking for child DIEs. Because of the LIFO worklist we need 780 // to schedule that work before any subsequent items are added to the 781 // worklist. 782 Worklist.emplace_back(Current.Die, Current.CU, Current.Flags, 783 WorklistItemType::LookForChildDIEsToKeep); 784 785 if (AlreadyKept || !(Current.Flags & TF_Keep)) 786 continue; 787 788 // If it is a newly kept DIE mark it as well as all its dependencies as 789 // kept. 790 MyInfo.Keep = true; 791 792 // We're looking for incomplete types. 793 MyInfo.Incomplete = 794 Current.Die.getTag() != dwarf::DW_TAG_subprogram && 795 Current.Die.getTag() != dwarf::DW_TAG_member && 796 dwarf::toUnsigned(Current.Die.find(dwarf::DW_AT_declaration), 0); 797 798 // After looking at the parent chain, look for referenced DIEs. Because of 799 // the LIFO worklist we need to schedule that work before any subsequent 800 // items are added to the worklist. 801 Worklist.emplace_back(Current.Die, Current.CU, Current.Flags, 802 WorklistItemType::LookForRefDIEsToKeep); 803 804 bool UseOdr = (Current.Flags & TF_DependencyWalk) ? (Current.Flags & TF_ODR) 805 : Current.CU.hasODR(); 806 unsigned ODRFlag = UseOdr ? TF_ODR : 0; 807 unsigned ParFlags = TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag; 808 809 // Now schedule the parent walk. 810 Worklist.emplace_back(MyInfo.ParentIdx, Current.CU, ParFlags); 811 } 812 } 813 814 /// Assign an abbreviation number to \p Abbrev. 815 /// 816 /// Our DIEs get freed after every DebugMapObject has been processed, 817 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to 818 /// the instances hold by the DIEs. When we encounter an abbreviation 819 /// that we don't know, we create a permanent copy of it. 820 void DWARFLinker::assignAbbrev(DIEAbbrev &Abbrev) { 821 // Check the set for priors. 822 FoldingSetNodeID ID; 823 Abbrev.Profile(ID); 824 void *InsertToken; 825 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken); 826 827 // If it's newly added. 828 if (InSet) { 829 // Assign existing abbreviation number. 830 Abbrev.setNumber(InSet->getNumber()); 831 } else { 832 // Add to abbreviation list. 833 Abbreviations.push_back( 834 std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren())); 835 for (const auto &Attr : Abbrev.getData()) 836 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm()); 837 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken); 838 // Assign the unique abbreviation number. 839 Abbrev.setNumber(Abbreviations.size()); 840 Abbreviations.back()->setNumber(Abbreviations.size()); 841 } 842 } 843 844 unsigned DWARFLinker::DIECloner::cloneStringAttribute( 845 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val, 846 const DWARFUnit &U, OffsetsStringPool &StringPool, AttributesInfo &Info) { 847 Optional<const char *> String = Val.getAsCString(); 848 if (!String) 849 return 0; 850 851 // Switch everything to out of line strings. 852 auto StringEntry = StringPool.getEntry(*String); 853 854 // Update attributes info. 855 if (AttrSpec.Attr == dwarf::DW_AT_name) 856 Info.Name = StringEntry; 857 else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name || 858 AttrSpec.Attr == dwarf::DW_AT_linkage_name) 859 Info.MangledName = StringEntry; 860 861 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp, 862 DIEInteger(StringEntry.getOffset())); 863 864 return 4; 865 } 866 867 unsigned DWARFLinker::DIECloner::cloneDieReferenceAttribute( 868 DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec, 869 unsigned AttrSize, const DWARFFormValue &Val, const DWARFFile &File, 870 CompileUnit &Unit) { 871 const DWARFUnit &U = Unit.getOrigUnit(); 872 uint64_t Ref = *Val.getAsReference(); 873 874 DIE *NewRefDie = nullptr; 875 CompileUnit *RefUnit = nullptr; 876 DeclContext *Ctxt = nullptr; 877 878 DWARFDie RefDie = 879 Linker.resolveDIEReference(File, CompileUnits, Val, InputDIE, RefUnit); 880 881 // If the referenced DIE is not found, drop the attribute. 882 if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling) 883 return 0; 884 885 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(RefDie); 886 887 // If we already have emitted an equivalent DeclContext, just point 888 // at it. 889 if (isODRAttribute(AttrSpec.Attr)) { 890 Ctxt = RefInfo.Ctxt; 891 if (Ctxt && Ctxt->getCanonicalDIEOffset()) { 892 DIEInteger Attr(Ctxt->getCanonicalDIEOffset()); 893 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), 894 dwarf::DW_FORM_ref_addr, Attr); 895 return U.getRefAddrByteSize(); 896 } 897 } 898 899 if (!RefInfo.Clone) { 900 assert(Ref > InputDIE.getOffset()); 901 // We haven't cloned this DIE yet. Just create an empty one and 902 // store it. It'll get really cloned when we process it. 903 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag())); 904 } 905 NewRefDie = RefInfo.Clone; 906 907 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr || 908 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) { 909 // We cannot currently rely on a DIEEntry to emit ref_addr 910 // references, because the implementation calls back to DwarfDebug 911 // to find the unit offset. (We don't have a DwarfDebug) 912 // FIXME: we should be able to design DIEEntry reliance on 913 // DwarfDebug away. 914 uint64_t Attr; 915 if (Ref < InputDIE.getOffset()) { 916 // We must have already cloned that DIE. 917 uint32_t NewRefOffset = 918 RefUnit->getStartOffset() + NewRefDie->getOffset(); 919 Attr = NewRefOffset; 920 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), 921 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)); 922 } else { 923 // A forward reference. Note and fixup later. 924 Attr = 0xBADDEF; 925 Unit.noteForwardReference( 926 NewRefDie, RefUnit, Ctxt, 927 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), 928 dwarf::DW_FORM_ref_addr, DIEInteger(Attr))); 929 } 930 return U.getRefAddrByteSize(); 931 } 932 933 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), 934 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie)); 935 936 return AttrSize; 937 } 938 939 void DWARFLinker::DIECloner::cloneExpression( 940 DataExtractor &Data, DWARFExpression Expression, const DWARFFile &File, 941 CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer) { 942 using Encoding = DWARFExpression::Operation::Encoding; 943 944 uint64_t OpOffset = 0; 945 for (auto &Op : Expression) { 946 auto Description = Op.getDescription(); 947 // DW_OP_const_type is variable-length and has 3 948 // operands. DWARFExpression thus far only supports 2. 949 auto Op0 = Description.Op[0]; 950 auto Op1 = Description.Op[1]; 951 if ((Op0 == Encoding::BaseTypeRef && Op1 != Encoding::SizeNA) || 952 (Op1 == Encoding::BaseTypeRef && Op0 != Encoding::Size1)) 953 Linker.reportWarning("Unsupported DW_OP encoding.", File); 954 955 if ((Op0 == Encoding::BaseTypeRef && Op1 == Encoding::SizeNA) || 956 (Op1 == Encoding::BaseTypeRef && Op0 == Encoding::Size1)) { 957 // This code assumes that the other non-typeref operand fits into 1 byte. 958 assert(OpOffset < Op.getEndOffset()); 959 uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1; 960 assert(ULEBsize <= 16); 961 962 // Copy over the operation. 963 OutputBuffer.push_back(Op.getCode()); 964 uint64_t RefOffset; 965 if (Op1 == Encoding::SizeNA) { 966 RefOffset = Op.getRawOperand(0); 967 } else { 968 OutputBuffer.push_back(Op.getRawOperand(0)); 969 RefOffset = Op.getRawOperand(1); 970 } 971 uint32_t Offset = 0; 972 // Look up the base type. For DW_OP_convert, the operand may be 0 to 973 // instead indicate the generic type. The same holds for 974 // DW_OP_reinterpret, which is currently not supported. 975 if (RefOffset > 0 || Op.getCode() != dwarf::DW_OP_convert) { 976 auto RefDie = Unit.getOrigUnit().getDIEForOffset(RefOffset); 977 CompileUnit::DIEInfo &Info = Unit.getInfo(RefDie); 978 if (DIE *Clone = Info.Clone) 979 Offset = Clone->getOffset(); 980 else 981 Linker.reportWarning( 982 "base type ref doesn't point to DW_TAG_base_type.", File); 983 } 984 uint8_t ULEB[16]; 985 unsigned RealSize = encodeULEB128(Offset, ULEB, ULEBsize); 986 if (RealSize > ULEBsize) { 987 // Emit the generic type as a fallback. 988 RealSize = encodeULEB128(0, ULEB, ULEBsize); 989 Linker.reportWarning("base type ref doesn't fit.", File); 990 } 991 assert(RealSize == ULEBsize && "padding failed"); 992 ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize); 993 OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end()); 994 } else { 995 // Copy over everything else unmodified. 996 StringRef Bytes = Data.getData().slice(OpOffset, Op.getEndOffset()); 997 OutputBuffer.append(Bytes.begin(), Bytes.end()); 998 } 999 OpOffset = Op.getEndOffset(); 1000 } 1001 } 1002 1003 unsigned DWARFLinker::DIECloner::cloneBlockAttribute( 1004 DIE &Die, const DWARFFile &File, CompileUnit &Unit, AttributeSpec AttrSpec, 1005 const DWARFFormValue &Val, unsigned AttrSize, bool IsLittleEndian) { 1006 DIEValueList *Attr; 1007 DIEValue Value; 1008 DIELoc *Loc = nullptr; 1009 DIEBlock *Block = nullptr; 1010 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) { 1011 Loc = new (DIEAlloc) DIELoc; 1012 Linker.DIELocs.push_back(Loc); 1013 } else { 1014 Block = new (DIEAlloc) DIEBlock; 1015 Linker.DIEBlocks.push_back(Block); 1016 } 1017 Attr = Loc ? static_cast<DIEValueList *>(Loc) 1018 : static_cast<DIEValueList *>(Block); 1019 1020 if (Loc) 1021 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr), 1022 dwarf::Form(AttrSpec.Form), Loc); 1023 else 1024 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr), 1025 dwarf::Form(AttrSpec.Form), Block); 1026 1027 // If the block is a DWARF Expression, clone it into the temporary 1028 // buffer using cloneExpression(), otherwise copy the data directly. 1029 SmallVector<uint8_t, 32> Buffer; 1030 ArrayRef<uint8_t> Bytes = *Val.getAsBlock(); 1031 if (DWARFAttribute::mayHaveLocationDescription(AttrSpec.Attr) && 1032 (Val.isFormClass(DWARFFormValue::FC_Block) || 1033 Val.isFormClass(DWARFFormValue::FC_Exprloc))) { 1034 DWARFUnit &OrigUnit = Unit.getOrigUnit(); 1035 DataExtractor Data(StringRef((const char *)Bytes.data(), Bytes.size()), 1036 IsLittleEndian, OrigUnit.getAddressByteSize()); 1037 DWARFExpression Expr(Data, OrigUnit.getAddressByteSize(), 1038 OrigUnit.getFormParams().Format); 1039 cloneExpression(Data, Expr, File, Unit, Buffer); 1040 Bytes = Buffer; 1041 } 1042 for (auto Byte : Bytes) 1043 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0), 1044 dwarf::DW_FORM_data1, DIEInteger(Byte)); 1045 1046 // FIXME: If DIEBlock and DIELoc just reuses the Size field of 1047 // the DIE class, this "if" could be replaced by 1048 // Attr->setSize(Bytes.size()). 1049 if (Loc) 1050 Loc->setSize(Bytes.size()); 1051 else 1052 Block->setSize(Bytes.size()); 1053 1054 Die.addValue(DIEAlloc, Value); 1055 return AttrSize; 1056 } 1057 1058 unsigned DWARFLinker::DIECloner::cloneAddressAttribute( 1059 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val, 1060 const CompileUnit &Unit, AttributesInfo &Info) { 1061 dwarf::Form Form = AttrSpec.Form; 1062 uint64_t Addr = *Val.getAsAddress(); 1063 1064 if (LLVM_UNLIKELY(Linker.Options.Update)) { 1065 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) 1066 Info.HasLowPc = true; 1067 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), 1068 dwarf::Form(AttrSpec.Form), DIEInteger(Addr)); 1069 return Unit.getOrigUnit().getAddressByteSize(); 1070 } 1071 1072 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) { 1073 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine || 1074 Die.getTag() == dwarf::DW_TAG_lexical_block) 1075 // The low_pc of a block or inline subroutine might get 1076 // relocated because it happens to match the low_pc of the 1077 // enclosing subprogram. To prevent issues with that, always use 1078 // the low_pc from the input DIE if relocations have been applied. 1079 Addr = (Info.OrigLowPc != std::numeric_limits<uint64_t>::max() 1080 ? Info.OrigLowPc 1081 : Addr) + 1082 Info.PCOffset; 1083 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) { 1084 Addr = Unit.getLowPc(); 1085 if (Addr == std::numeric_limits<uint64_t>::max()) 1086 return 0; 1087 } 1088 Info.HasLowPc = true; 1089 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) { 1090 if (Die.getTag() == dwarf::DW_TAG_compile_unit) { 1091 if (uint64_t HighPc = Unit.getHighPc()) 1092 Addr = HighPc; 1093 else 1094 return 0; 1095 } else 1096 // If we have a high_pc recorded for the input DIE, use 1097 // it. Otherwise (when no relocations where applied) just use the 1098 // one we just decoded. 1099 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset; 1100 } else if (AttrSpec.Attr == dwarf::DW_AT_call_return_pc) { 1101 // Relocate a return PC address within a call site entry. 1102 if (Die.getTag() == dwarf::DW_TAG_call_site) 1103 Addr = (Info.OrigCallReturnPc ? Info.OrigCallReturnPc : Addr) + 1104 Info.PCOffset; 1105 } else if (AttrSpec.Attr == dwarf::DW_AT_call_pc) { 1106 // Relocate the address of a branch instruction within a call site entry. 1107 if (Die.getTag() == dwarf::DW_TAG_call_site) 1108 Addr = (Info.OrigCallPc ? Info.OrigCallPc : Addr) + Info.PCOffset; 1109 } 1110 1111 // If this is an indexed address emit the relocated address. 1112 if (Form == dwarf::DW_FORM_addrx) { 1113 if (llvm::Expected<uint64_t> RelocAddr = 1114 ObjFile.Addresses->relocateIndexedAddr(Addr)) { 1115 Addr = *RelocAddr; 1116 Form = dwarf::DW_FORM_addr; 1117 } else { 1118 Linker.reportWarning(toString(RelocAddr.takeError()), ObjFile); 1119 } 1120 } 1121 1122 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr), 1123 static_cast<dwarf::Form>(Form), DIEInteger(Addr)); 1124 return Unit.getOrigUnit().getAddressByteSize(); 1125 } 1126 1127 unsigned DWARFLinker::DIECloner::cloneScalarAttribute( 1128 DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File, 1129 CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val, 1130 unsigned AttrSize, AttributesInfo &Info) { 1131 uint64_t Value; 1132 1133 if (LLVM_UNLIKELY(Linker.Options.Update)) { 1134 if (auto OptionalValue = Val.getAsUnsignedConstant()) 1135 Value = *OptionalValue; 1136 else if (auto OptionalValue = Val.getAsSignedConstant()) 1137 Value = *OptionalValue; 1138 else if (auto OptionalValue = Val.getAsSectionOffset()) 1139 Value = *OptionalValue; 1140 else { 1141 Linker.reportWarning( 1142 "Unsupported scalar attribute form. Dropping attribute.", File, 1143 &InputDIE); 1144 return 0; 1145 } 1146 if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value) 1147 Info.IsDeclaration = true; 1148 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), 1149 dwarf::Form(AttrSpec.Form), DIEInteger(Value)); 1150 return AttrSize; 1151 } 1152 1153 if (AttrSpec.Attr == dwarf::DW_AT_high_pc && 1154 Die.getTag() == dwarf::DW_TAG_compile_unit) { 1155 if (Unit.getLowPc() == -1ULL) 1156 return 0; 1157 // Dwarf >= 4 high_pc is an size, not an address. 1158 Value = Unit.getHighPc() - Unit.getLowPc(); 1159 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset) 1160 Value = *Val.getAsSectionOffset(); 1161 else if (AttrSpec.Form == dwarf::DW_FORM_sdata) 1162 Value = *Val.getAsSignedConstant(); 1163 else if (auto OptionalValue = Val.getAsUnsignedConstant()) 1164 Value = *OptionalValue; 1165 else { 1166 Linker.reportWarning( 1167 "Unsupported scalar attribute form. Dropping attribute.", File, 1168 &InputDIE); 1169 return 0; 1170 } 1171 PatchLocation Patch = 1172 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), 1173 dwarf::Form(AttrSpec.Form), DIEInteger(Value)); 1174 if (AttrSpec.Attr == dwarf::DW_AT_ranges) { 1175 Unit.noteRangeAttribute(Die, Patch); 1176 Info.HasRanges = true; 1177 } 1178 1179 // A more generic way to check for location attributes would be 1180 // nice, but it's very unlikely that any other attribute needs a 1181 // location list. 1182 // FIXME: use DWARFAttribute::mayHaveLocationDescription(). 1183 else if (AttrSpec.Attr == dwarf::DW_AT_location || 1184 AttrSpec.Attr == dwarf::DW_AT_frame_base) { 1185 Unit.noteLocationAttribute(Patch, Info.PCOffset); 1186 } else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value) 1187 Info.IsDeclaration = true; 1188 1189 return AttrSize; 1190 } 1191 1192 /// Clone \p InputDIE's attribute described by \p AttrSpec with 1193 /// value \p Val, and add it to \p Die. 1194 /// \returns the size of the cloned attribute. 1195 unsigned DWARFLinker::DIECloner::cloneAttribute( 1196 DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File, 1197 CompileUnit &Unit, OffsetsStringPool &StringPool, const DWARFFormValue &Val, 1198 const AttributeSpec AttrSpec, unsigned AttrSize, AttributesInfo &Info, 1199 bool IsLittleEndian) { 1200 const DWARFUnit &U = Unit.getOrigUnit(); 1201 1202 switch (AttrSpec.Form) { 1203 case dwarf::DW_FORM_strp: 1204 case dwarf::DW_FORM_string: 1205 case dwarf::DW_FORM_strx: 1206 case dwarf::DW_FORM_strx1: 1207 case dwarf::DW_FORM_strx2: 1208 case dwarf::DW_FORM_strx3: 1209 case dwarf::DW_FORM_strx4: 1210 return cloneStringAttribute(Die, AttrSpec, Val, U, StringPool, Info); 1211 case dwarf::DW_FORM_ref_addr: 1212 case dwarf::DW_FORM_ref1: 1213 case dwarf::DW_FORM_ref2: 1214 case dwarf::DW_FORM_ref4: 1215 case dwarf::DW_FORM_ref8: 1216 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val, 1217 File, Unit); 1218 case dwarf::DW_FORM_block: 1219 case dwarf::DW_FORM_block1: 1220 case dwarf::DW_FORM_block2: 1221 case dwarf::DW_FORM_block4: 1222 case dwarf::DW_FORM_exprloc: 1223 return cloneBlockAttribute(Die, File, Unit, AttrSpec, Val, AttrSize, 1224 IsLittleEndian); 1225 case dwarf::DW_FORM_addr: 1226 case dwarf::DW_FORM_addrx: 1227 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info); 1228 case dwarf::DW_FORM_data1: 1229 case dwarf::DW_FORM_data2: 1230 case dwarf::DW_FORM_data4: 1231 case dwarf::DW_FORM_data8: 1232 case dwarf::DW_FORM_udata: 1233 case dwarf::DW_FORM_sdata: 1234 case dwarf::DW_FORM_sec_offset: 1235 case dwarf::DW_FORM_flag: 1236 case dwarf::DW_FORM_flag_present: 1237 return cloneScalarAttribute(Die, InputDIE, File, Unit, AttrSpec, Val, 1238 AttrSize, Info); 1239 default: 1240 Linker.reportWarning("Unsupported attribute form " + 1241 dwarf::FormEncodingString(AttrSpec.Form) + 1242 " in cloneAttribute. Dropping.", 1243 File, &InputDIE); 1244 } 1245 1246 return 0; 1247 } 1248 1249 static bool isObjCSelector(StringRef Name) { 1250 return Name.size() > 2 && (Name[0] == '-' || Name[0] == '+') && 1251 (Name[1] == '['); 1252 } 1253 1254 void DWARFLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit, 1255 const DIE *Die, 1256 DwarfStringPoolEntryRef Name, 1257 OffsetsStringPool &StringPool, 1258 bool SkipPubSection) { 1259 assert(isObjCSelector(Name.getString()) && "not an objc selector"); 1260 // Objective C method or class function. 1261 // "- [Class(Category) selector :withArg ...]" 1262 StringRef ClassNameStart(Name.getString().drop_front(2)); 1263 size_t FirstSpace = ClassNameStart.find(' '); 1264 if (FirstSpace == StringRef::npos) 1265 return; 1266 1267 StringRef SelectorStart(ClassNameStart.data() + FirstSpace + 1); 1268 if (!SelectorStart.size()) 1269 return; 1270 1271 StringRef Selector(SelectorStart.data(), SelectorStart.size() - 1); 1272 Unit.addNameAccelerator(Die, StringPool.getEntry(Selector), SkipPubSection); 1273 1274 // Add an entry for the class name that points to this 1275 // method/class function. 1276 StringRef ClassName(ClassNameStart.data(), FirstSpace); 1277 Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassName), SkipPubSection); 1278 1279 if (ClassName[ClassName.size() - 1] == ')') { 1280 size_t OpenParens = ClassName.find('('); 1281 if (OpenParens != StringRef::npos) { 1282 StringRef ClassNameNoCategory(ClassName.data(), OpenParens); 1283 Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassNameNoCategory), 1284 SkipPubSection); 1285 1286 std::string MethodNameNoCategory(Name.getString().data(), OpenParens + 2); 1287 // FIXME: The missing space here may be a bug, but 1288 // dsymutil-classic also does it this way. 1289 MethodNameNoCategory.append(std::string(SelectorStart)); 1290 Unit.addNameAccelerator(Die, StringPool.getEntry(MethodNameNoCategory), 1291 SkipPubSection); 1292 } 1293 } 1294 } 1295 1296 static bool 1297 shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec, 1298 uint16_t Tag, bool InDebugMap, bool SkipPC, 1299 bool InFunctionScope) { 1300 switch (AttrSpec.Attr) { 1301 default: 1302 return false; 1303 case dwarf::DW_AT_low_pc: 1304 case dwarf::DW_AT_high_pc: 1305 case dwarf::DW_AT_ranges: 1306 return SkipPC; 1307 case dwarf::DW_AT_str_offsets_base: 1308 // FIXME: Use the string offset table with Dwarf 5. 1309 return true; 1310 case dwarf::DW_AT_location: 1311 case dwarf::DW_AT_frame_base: 1312 // FIXME: for some reason dsymutil-classic keeps the location attributes 1313 // when they are of block type (i.e. not location lists). This is totally 1314 // wrong for globals where we will keep a wrong address. It is mostly 1315 // harmless for locals, but there is no point in keeping these anyway when 1316 // the function wasn't linked. 1317 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable && 1318 !InDebugMap)) && 1319 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block); 1320 } 1321 } 1322 1323 DIE *DWARFLinker::DIECloner::cloneDIE(const DWARFDie &InputDIE, 1324 const DWARFFile &File, CompileUnit &Unit, 1325 OffsetsStringPool &StringPool, 1326 int64_t PCOffset, uint32_t OutOffset, 1327 unsigned Flags, bool IsLittleEndian, 1328 DIE *Die) { 1329 DWARFUnit &U = Unit.getOrigUnit(); 1330 unsigned Idx = U.getDIEIndex(InputDIE); 1331 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx); 1332 1333 // Should the DIE appear in the output? 1334 if (!Unit.getInfo(Idx).Keep) 1335 return nullptr; 1336 1337 uint64_t Offset = InputDIE.getOffset(); 1338 assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE"); 1339 if (!Die) { 1340 // The DIE might have been already created by a forward reference 1341 // (see cloneDieReferenceAttribute()). 1342 if (!Info.Clone) 1343 Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag())); 1344 Die = Info.Clone; 1345 } 1346 1347 assert(Die->getTag() == InputDIE.getTag()); 1348 Die->setOffset(OutOffset); 1349 if ((Unit.hasODR() || Unit.isClangModule()) && !Info.Incomplete && 1350 Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt && 1351 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt && 1352 !Info.Ctxt->getCanonicalDIEOffset()) { 1353 // We are about to emit a DIE that is the root of its own valid 1354 // DeclContext tree. Make the current offset the canonical offset 1355 // for this context. 1356 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset()); 1357 } 1358 1359 // Extract and clone every attribute. 1360 DWARFDataExtractor Data = U.getDebugInfoExtractor(); 1361 // Point to the next DIE (generally there is always at least a NULL 1362 // entry after the current one). If this is a lone 1363 // DW_TAG_compile_unit without any children, point to the next unit. 1364 uint64_t NextOffset = (Idx + 1 < U.getNumDIEs()) 1365 ? U.getDIEAtIndex(Idx + 1).getOffset() 1366 : U.getNextUnitOffset(); 1367 AttributesInfo AttrInfo; 1368 1369 // We could copy the data only if we need to apply a relocation to it. After 1370 // testing, it seems there is no performance downside to doing the copy 1371 // unconditionally, and it makes the code simpler. 1372 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset)); 1373 Data = 1374 DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize()); 1375 1376 // Modify the copy with relocated addresses. 1377 if (ObjFile.Addresses->areRelocationsResolved() && 1378 ObjFile.Addresses->applyValidRelocs(DIECopy, Offset, 1379 Data.isLittleEndian())) { 1380 // If we applied relocations, we store the value of high_pc that was 1381 // potentially stored in the input DIE. If high_pc is an address 1382 // (Dwarf version == 2), then it might have been relocated to a 1383 // totally unrelated value (because the end address in the object 1384 // file might be start address of another function which got moved 1385 // independently by the linker). The computation of the actual 1386 // high_pc value is done in cloneAddressAttribute(). 1387 AttrInfo.OrigHighPc = 1388 dwarf::toAddress(InputDIE.find(dwarf::DW_AT_high_pc), 0); 1389 // Also store the low_pc. It might get relocated in an 1390 // inline_subprogram that happens at the beginning of its 1391 // inlining function. 1392 AttrInfo.OrigLowPc = dwarf::toAddress(InputDIE.find(dwarf::DW_AT_low_pc), 1393 std::numeric_limits<uint64_t>::max()); 1394 AttrInfo.OrigCallReturnPc = 1395 dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_return_pc), 0); 1396 AttrInfo.OrigCallPc = 1397 dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_pc), 0); 1398 } 1399 1400 // Reset the Offset to 0 as we will be working on the local copy of 1401 // the data. 1402 Offset = 0; 1403 1404 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr(); 1405 Offset += getULEB128Size(Abbrev->getCode()); 1406 1407 // We are entering a subprogram. Get and propagate the PCOffset. 1408 if (Die->getTag() == dwarf::DW_TAG_subprogram) 1409 PCOffset = Info.AddrAdjust; 1410 AttrInfo.PCOffset = PCOffset; 1411 1412 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) { 1413 Flags |= TF_InFunctionScope; 1414 if (!Info.InDebugMap && LLVM_LIKELY(!Update)) 1415 Flags |= TF_SkipPC; 1416 } 1417 1418 bool Copied = false; 1419 for (const auto &AttrSpec : Abbrev->attributes()) { 1420 if (LLVM_LIKELY(!Update) && 1421 shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap, 1422 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) { 1423 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, 1424 U.getFormParams()); 1425 // FIXME: dsymutil-classic keeps the old abbreviation around 1426 // even if it's not used. We can remove this (and the copyAbbrev 1427 // helper) as soon as bit-for-bit compatibility is not a goal anymore. 1428 if (!Copied) { 1429 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR()); 1430 Copied = true; 1431 } 1432 continue; 1433 } 1434 1435 DWARFFormValue Val(AttrSpec.Form); 1436 uint64_t AttrSize = Offset; 1437 Val.extractValue(Data, &Offset, U.getFormParams(), &U); 1438 AttrSize = Offset - AttrSize; 1439 1440 OutOffset += cloneAttribute(*Die, InputDIE, File, Unit, StringPool, Val, 1441 AttrSpec, AttrSize, AttrInfo, IsLittleEndian); 1442 } 1443 1444 // Look for accelerator entries. 1445 uint16_t Tag = InputDIE.getTag(); 1446 // FIXME: This is slightly wrong. An inline_subroutine without a 1447 // low_pc, but with AT_ranges might be interesting to get into the 1448 // accelerator tables too. For now stick with dsymutil's behavior. 1449 if ((Info.InDebugMap || AttrInfo.HasLowPc || AttrInfo.HasRanges) && 1450 Tag != dwarf::DW_TAG_compile_unit && 1451 getDIENames(InputDIE, AttrInfo, StringPool, 1452 Tag != dwarf::DW_TAG_inlined_subroutine)) { 1453 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name) 1454 Unit.addNameAccelerator(Die, AttrInfo.MangledName, 1455 Tag == dwarf::DW_TAG_inlined_subroutine); 1456 if (AttrInfo.Name) { 1457 if (AttrInfo.NameWithoutTemplate) 1458 Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate, 1459 /* SkipPubSection */ true); 1460 Unit.addNameAccelerator(Die, AttrInfo.Name, 1461 Tag == dwarf::DW_TAG_inlined_subroutine); 1462 } 1463 if (AttrInfo.Name && isObjCSelector(AttrInfo.Name.getString())) 1464 addObjCAccelerator(Unit, Die, AttrInfo.Name, StringPool, 1465 /* SkipPubSection =*/true); 1466 1467 } else if (Tag == dwarf::DW_TAG_namespace) { 1468 if (!AttrInfo.Name) 1469 AttrInfo.Name = StringPool.getEntry("(anonymous namespace)"); 1470 Unit.addNamespaceAccelerator(Die, AttrInfo.Name); 1471 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration && 1472 getDIENames(InputDIE, AttrInfo, StringPool) && AttrInfo.Name && 1473 AttrInfo.Name.getString()[0]) { 1474 uint32_t Hash = hashFullyQualifiedName(InputDIE, Unit, File); 1475 uint64_t RuntimeLang = 1476 dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_runtime_class)) 1477 .getValueOr(0); 1478 bool ObjCClassIsImplementation = 1479 (RuntimeLang == dwarf::DW_LANG_ObjC || 1480 RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) && 1481 dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_objc_complete_type)) 1482 .getValueOr(0); 1483 Unit.addTypeAccelerator(Die, AttrInfo.Name, ObjCClassIsImplementation, 1484 Hash); 1485 } 1486 1487 // Determine whether there are any children that we want to keep. 1488 bool HasChildren = false; 1489 for (auto Child : InputDIE.children()) { 1490 unsigned Idx = U.getDIEIndex(Child); 1491 if (Unit.getInfo(Idx).Keep) { 1492 HasChildren = true; 1493 break; 1494 } 1495 } 1496 1497 DIEAbbrev NewAbbrev = Die->generateAbbrev(); 1498 if (HasChildren) 1499 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes); 1500 // Assign a permanent abbrev number 1501 Linker.assignAbbrev(NewAbbrev); 1502 Die->setAbbrevNumber(NewAbbrev.getNumber()); 1503 1504 // Add the size of the abbreviation number to the output offset. 1505 OutOffset += getULEB128Size(Die->getAbbrevNumber()); 1506 1507 if (!HasChildren) { 1508 // Update our size. 1509 Die->setSize(OutOffset - Die->getOffset()); 1510 return Die; 1511 } 1512 1513 // Recursively clone children. 1514 for (auto Child : InputDIE.children()) { 1515 if (DIE *Clone = cloneDIE(Child, File, Unit, StringPool, PCOffset, 1516 OutOffset, Flags, IsLittleEndian)) { 1517 Die->addChild(Clone); 1518 OutOffset = Clone->getOffset() + Clone->getSize(); 1519 } 1520 } 1521 1522 // Account for the end of children marker. 1523 OutOffset += sizeof(int8_t); 1524 // Update our size. 1525 Die->setSize(OutOffset - Die->getOffset()); 1526 return Die; 1527 } 1528 1529 /// Patch the input object file relevant debug_ranges entries 1530 /// and emit them in the output file. Update the relevant attributes 1531 /// to point at the new entries. 1532 void DWARFLinker::patchRangesForUnit(const CompileUnit &Unit, 1533 DWARFContext &OrigDwarf, 1534 const DWARFFile &File) const { 1535 DWARFDebugRangeList RangeList; 1536 const auto &FunctionRanges = Unit.getFunctionRanges(); 1537 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize(); 1538 DWARFDataExtractor RangeExtractor(OrigDwarf.getDWARFObj(), 1539 OrigDwarf.getDWARFObj().getRangesSection(), 1540 OrigDwarf.isLittleEndian(), AddressSize); 1541 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange; 1542 DWARFUnit &OrigUnit = Unit.getOrigUnit(); 1543 auto OrigUnitDie = OrigUnit.getUnitDIE(false); 1544 uint64_t OrigLowPc = 1545 dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc), -1ULL); 1546 // Ranges addresses are based on the unit's low_pc. Compute the 1547 // offset we need to apply to adapt to the new unit's low_pc. 1548 int64_t UnitPcOffset = 0; 1549 if (OrigLowPc != -1ULL) 1550 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc(); 1551 1552 for (const auto &RangeAttribute : Unit.getRangesAttributes()) { 1553 uint64_t Offset = RangeAttribute.get(); 1554 RangeAttribute.set(TheDwarfEmitter->getRangesSectionSize()); 1555 if (Error E = RangeList.extract(RangeExtractor, &Offset)) { 1556 llvm::consumeError(std::move(E)); 1557 reportWarning("invalid range list ignored.", File); 1558 RangeList.clear(); 1559 } 1560 const auto &Entries = RangeList.getEntries(); 1561 if (!Entries.empty()) { 1562 const DWARFDebugRangeList::RangeListEntry &First = Entries.front(); 1563 1564 if (CurrRange == InvalidRange || 1565 First.StartAddress + OrigLowPc < CurrRange.start() || 1566 First.StartAddress + OrigLowPc >= CurrRange.stop()) { 1567 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc); 1568 if (CurrRange == InvalidRange || 1569 CurrRange.start() > First.StartAddress + OrigLowPc) { 1570 reportWarning("no mapping for range.", File); 1571 continue; 1572 } 1573 } 1574 } 1575 1576 TheDwarfEmitter->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, 1577 Entries, AddressSize); 1578 } 1579 } 1580 1581 /// Generate the debug_aranges entries for \p Unit and if the 1582 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges 1583 /// contribution for this attribute. 1584 /// FIXME: this could actually be done right in patchRangesForUnit, 1585 /// but for the sake of initial bit-for-bit compatibility with legacy 1586 /// dsymutil, we have to do it in a delayed pass. 1587 void DWARFLinker::generateUnitRanges(CompileUnit &Unit) const { 1588 auto Attr = Unit.getUnitRangesAttribute(); 1589 if (Attr) 1590 Attr->set(TheDwarfEmitter->getRangesSectionSize()); 1591 TheDwarfEmitter->emitUnitRangesEntries(Unit, static_cast<bool>(Attr)); 1592 } 1593 1594 /// Insert the new line info sequence \p Seq into the current 1595 /// set of already linked line info \p Rows. 1596 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq, 1597 std::vector<DWARFDebugLine::Row> &Rows) { 1598 if (Seq.empty()) 1599 return; 1600 1601 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) { 1602 llvm::append_range(Rows, Seq); 1603 Seq.clear(); 1604 return; 1605 } 1606 1607 object::SectionedAddress Front = Seq.front().Address; 1608 auto InsertPoint = partition_point( 1609 Rows, [=](const DWARFDebugLine::Row &O) { return O.Address < Front; }); 1610 1611 // FIXME: this only removes the unneeded end_sequence if the 1612 // sequences have been inserted in order. Using a global sort like 1613 // described in patchLineTableForUnit() and delaying the end_sequene 1614 // elimination to emitLineTableForUnit() we can get rid of all of them. 1615 if (InsertPoint != Rows.end() && InsertPoint->Address == Front && 1616 InsertPoint->EndSequence) { 1617 *InsertPoint = Seq.front(); 1618 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end()); 1619 } else { 1620 Rows.insert(InsertPoint, Seq.begin(), Seq.end()); 1621 } 1622 1623 Seq.clear(); 1624 } 1625 1626 static void patchStmtList(DIE &Die, DIEInteger Offset) { 1627 for (auto &V : Die.values()) 1628 if (V.getAttribute() == dwarf::DW_AT_stmt_list) { 1629 V = DIEValue(V.getAttribute(), V.getForm(), Offset); 1630 return; 1631 } 1632 1633 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!"); 1634 } 1635 1636 /// Extract the line table for \p Unit from \p OrigDwarf, and 1637 /// recreate a relocated version of these for the address ranges that 1638 /// are present in the binary. 1639 void DWARFLinker::patchLineTableForUnit(CompileUnit &Unit, 1640 DWARFContext &OrigDwarf, 1641 const DWARFFile &File) { 1642 DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE(); 1643 auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list)); 1644 if (!StmtList) 1645 return; 1646 1647 // Update the cloned DW_AT_stmt_list with the correct debug_line offset. 1648 if (auto *OutputDIE = Unit.getOutputUnitDIE()) 1649 patchStmtList(*OutputDIE, 1650 DIEInteger(TheDwarfEmitter->getLineSectionSize())); 1651 1652 RangesTy &Ranges = File.Addresses->getValidAddressRanges(); 1653 1654 // Parse the original line info for the unit. 1655 DWARFDebugLine::LineTable LineTable; 1656 uint64_t StmtOffset = *StmtList; 1657 DWARFDataExtractor LineExtractor( 1658 OrigDwarf.getDWARFObj(), OrigDwarf.getDWARFObj().getLineSection(), 1659 OrigDwarf.isLittleEndian(), Unit.getOrigUnit().getAddressByteSize()); 1660 if (needToTranslateStrings()) 1661 return TheDwarfEmitter->translateLineTable(LineExtractor, StmtOffset); 1662 1663 if (Error Err = 1664 LineTable.parse(LineExtractor, &StmtOffset, OrigDwarf, 1665 &Unit.getOrigUnit(), OrigDwarf.getWarningHandler())) 1666 OrigDwarf.getWarningHandler()(std::move(Err)); 1667 1668 // This vector is the output line table. 1669 std::vector<DWARFDebugLine::Row> NewRows; 1670 NewRows.reserve(LineTable.Rows.size()); 1671 1672 // Current sequence of rows being extracted, before being inserted 1673 // in NewRows. 1674 std::vector<DWARFDebugLine::Row> Seq; 1675 const auto &FunctionRanges = Unit.getFunctionRanges(); 1676 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange; 1677 1678 // FIXME: This logic is meant to generate exactly the same output as 1679 // Darwin's classic dsymutil. There is a nicer way to implement this 1680 // by simply putting all the relocated line info in NewRows and simply 1681 // sorting NewRows before passing it to emitLineTableForUnit. This 1682 // should be correct as sequences for a function should stay 1683 // together in the sorted output. There are a few corner cases that 1684 // look suspicious though, and that required to implement the logic 1685 // this way. Revisit that once initial validation is finished. 1686 1687 // Iterate over the object file line info and extract the sequences 1688 // that correspond to linked functions. 1689 for (auto &Row : LineTable.Rows) { 1690 // Check whether we stepped out of the range. The range is 1691 // half-open, but consider accept the end address of the range if 1692 // it is marked as end_sequence in the input (because in that 1693 // case, the relocation offset is accurate and that entry won't 1694 // serve as the start of another function). 1695 if (CurrRange == InvalidRange || Row.Address.Address < CurrRange.start() || 1696 Row.Address.Address > CurrRange.stop() || 1697 (Row.Address.Address == CurrRange.stop() && !Row.EndSequence)) { 1698 // We just stepped out of a known range. Insert a end_sequence 1699 // corresponding to the end of the range. 1700 uint64_t StopAddress = CurrRange != InvalidRange 1701 ? CurrRange.stop() + CurrRange.value() 1702 : -1ULL; 1703 CurrRange = FunctionRanges.find(Row.Address.Address); 1704 bool CurrRangeValid = 1705 CurrRange != InvalidRange && CurrRange.start() <= Row.Address.Address; 1706 if (!CurrRangeValid) { 1707 CurrRange = InvalidRange; 1708 if (StopAddress != -1ULL) { 1709 // Try harder by looking in the Address ranges map. 1710 // There are corner cases where this finds a 1711 // valid entry. It's unclear if this is right or wrong, but 1712 // for now do as dsymutil. 1713 // FIXME: Understand exactly what cases this addresses and 1714 // potentially remove it along with the Ranges map. 1715 auto Range = Ranges.lower_bound(Row.Address.Address); 1716 if (Range != Ranges.begin() && Range != Ranges.end()) 1717 --Range; 1718 1719 if (Range != Ranges.end() && Range->first <= Row.Address.Address && 1720 Range->second.HighPC >= Row.Address.Address) { 1721 StopAddress = Row.Address.Address + Range->second.Offset; 1722 } 1723 } 1724 } 1725 if (StopAddress != -1ULL && !Seq.empty()) { 1726 // Insert end sequence row with the computed end address, but 1727 // the same line as the previous one. 1728 auto NextLine = Seq.back(); 1729 NextLine.Address.Address = StopAddress; 1730 NextLine.EndSequence = 1; 1731 NextLine.PrologueEnd = 0; 1732 NextLine.BasicBlock = 0; 1733 NextLine.EpilogueBegin = 0; 1734 Seq.push_back(NextLine); 1735 insertLineSequence(Seq, NewRows); 1736 } 1737 1738 if (!CurrRangeValid) 1739 continue; 1740 } 1741 1742 // Ignore empty sequences. 1743 if (Row.EndSequence && Seq.empty()) 1744 continue; 1745 1746 // Relocate row address and add it to the current sequence. 1747 Row.Address.Address += CurrRange.value(); 1748 Seq.emplace_back(Row); 1749 1750 if (Row.EndSequence) 1751 insertLineSequence(Seq, NewRows); 1752 } 1753 1754 // Finished extracting, now emit the line tables. 1755 // FIXME: LLVM hard-codes its prologue values. We just copy the 1756 // prologue over and that works because we act as both producer and 1757 // consumer. It would be nicer to have a real configurable line 1758 // table emitter. 1759 if (LineTable.Prologue.getVersion() < 2 || 1760 LineTable.Prologue.getVersion() > 5 || 1761 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT || 1762 LineTable.Prologue.OpcodeBase > 13) 1763 reportWarning("line table parameters mismatch. Cannot emit.", File); 1764 else { 1765 uint32_t PrologueEnd = *StmtList + 10 + LineTable.Prologue.PrologueLength; 1766 // DWARF v5 has an extra 2 bytes of information before the header_length 1767 // field. 1768 if (LineTable.Prologue.getVersion() == 5) 1769 PrologueEnd += 2; 1770 StringRef LineData = OrigDwarf.getDWARFObj().getLineSection().Data; 1771 MCDwarfLineTableParams Params; 1772 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase; 1773 Params.DWARF2LineBase = LineTable.Prologue.LineBase; 1774 Params.DWARF2LineRange = LineTable.Prologue.LineRange; 1775 TheDwarfEmitter->emitLineTableForUnit( 1776 Params, LineData.slice(*StmtList + 4, PrologueEnd), 1777 LineTable.Prologue.MinInstLength, NewRows, 1778 Unit.getOrigUnit().getAddressByteSize()); 1779 } 1780 } 1781 1782 void DWARFLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) { 1783 switch (Options.TheAccelTableKind) { 1784 case AccelTableKind::Apple: 1785 emitAppleAcceleratorEntriesForUnit(Unit); 1786 break; 1787 case AccelTableKind::Dwarf: 1788 emitDwarfAcceleratorEntriesForUnit(Unit); 1789 break; 1790 case AccelTableKind::Default: 1791 llvm_unreachable("The default must be updated to a concrete value."); 1792 break; 1793 } 1794 } 1795 1796 void DWARFLinker::emitAppleAcceleratorEntriesForUnit(CompileUnit &Unit) { 1797 // Add namespaces. 1798 for (const auto &Namespace : Unit.getNamespaces()) 1799 AppleNamespaces.addName(Namespace.Name, 1800 Namespace.Die->getOffset() + Unit.getStartOffset()); 1801 1802 /// Add names. 1803 TheDwarfEmitter->emitPubNamesForUnit(Unit); 1804 for (const auto &Pubname : Unit.getPubnames()) 1805 AppleNames.addName(Pubname.Name, 1806 Pubname.Die->getOffset() + Unit.getStartOffset()); 1807 1808 /// Add types. 1809 TheDwarfEmitter->emitPubTypesForUnit(Unit); 1810 for (const auto &Pubtype : Unit.getPubtypes()) 1811 AppleTypes.addName( 1812 Pubtype.Name, Pubtype.Die->getOffset() + Unit.getStartOffset(), 1813 Pubtype.Die->getTag(), 1814 Pubtype.ObjcClassImplementation ? dwarf::DW_FLAG_type_implementation 1815 : 0, 1816 Pubtype.QualifiedNameHash); 1817 1818 /// Add ObjC names. 1819 for (const auto &ObjC : Unit.getObjC()) 1820 AppleObjc.addName(ObjC.Name, ObjC.Die->getOffset() + Unit.getStartOffset()); 1821 } 1822 1823 void DWARFLinker::emitDwarfAcceleratorEntriesForUnit(CompileUnit &Unit) { 1824 for (const auto &Namespace : Unit.getNamespaces()) 1825 DebugNames.addName(Namespace.Name, Namespace.Die->getOffset(), 1826 Namespace.Die->getTag(), Unit.getUniqueID()); 1827 for (const auto &Pubname : Unit.getPubnames()) 1828 DebugNames.addName(Pubname.Name, Pubname.Die->getOffset(), 1829 Pubname.Die->getTag(), Unit.getUniqueID()); 1830 for (const auto &Pubtype : Unit.getPubtypes()) 1831 DebugNames.addName(Pubtype.Name, Pubtype.Die->getOffset(), 1832 Pubtype.Die->getTag(), Unit.getUniqueID()); 1833 } 1834 1835 /// Read the frame info stored in the object, and emit the 1836 /// patched frame descriptions for the resulting file. 1837 /// 1838 /// This is actually pretty easy as the data of the CIEs and FDEs can 1839 /// be considered as black boxes and moved as is. The only thing to do 1840 /// is to patch the addresses in the headers. 1841 void DWARFLinker::patchFrameInfoForObject(const DWARFFile &File, 1842 RangesTy &Ranges, 1843 DWARFContext &OrigDwarf, 1844 unsigned AddrSize) { 1845 StringRef FrameData = OrigDwarf.getDWARFObj().getFrameSection().Data; 1846 if (FrameData.empty()) 1847 return; 1848 1849 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0); 1850 uint64_t InputOffset = 0; 1851 1852 // Store the data of the CIEs defined in this object, keyed by their 1853 // offsets. 1854 DenseMap<uint64_t, StringRef> LocalCIES; 1855 1856 while (Data.isValidOffset(InputOffset)) { 1857 uint64_t EntryOffset = InputOffset; 1858 uint32_t InitialLength = Data.getU32(&InputOffset); 1859 if (InitialLength == 0xFFFFFFFF) 1860 return reportWarning("Dwarf64 bits no supported", File); 1861 1862 uint32_t CIEId = Data.getU32(&InputOffset); 1863 if (CIEId == 0xFFFFFFFF) { 1864 // This is a CIE, store it. 1865 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4); 1866 LocalCIES[EntryOffset] = CIEData; 1867 // The -4 is to account for the CIEId we just read. 1868 InputOffset += InitialLength - 4; 1869 continue; 1870 } 1871 1872 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize); 1873 1874 // Some compilers seem to emit frame info that doesn't start at 1875 // the function entry point, thus we can't just lookup the address 1876 // in the debug map. Use the AddressInfo's range map to see if the FDE 1877 // describes something that we can relocate. 1878 auto Range = Ranges.upper_bound(Loc); 1879 if (Range != Ranges.begin()) 1880 --Range; 1881 if (Range == Ranges.end() || Range->first > Loc || 1882 Range->second.HighPC <= Loc) { 1883 // The +4 is to account for the size of the InitialLength field itself. 1884 InputOffset = EntryOffset + InitialLength + 4; 1885 continue; 1886 } 1887 1888 // This is an FDE, and we have a mapping. 1889 // Have we already emitted a corresponding CIE? 1890 StringRef CIEData = LocalCIES[CIEId]; 1891 if (CIEData.empty()) 1892 return reportWarning("Inconsistent debug_frame content. Dropping.", File); 1893 1894 // Look if we already emitted a CIE that corresponds to the 1895 // referenced one (the CIE data is the key of that lookup). 1896 auto IteratorInserted = EmittedCIEs.insert( 1897 std::make_pair(CIEData, TheDwarfEmitter->getFrameSectionSize())); 1898 // If there is no CIE yet for this ID, emit it. 1899 if (IteratorInserted.second || 1900 // FIXME: dsymutil-classic only caches the last used CIE for 1901 // reuse. Mimic that behavior for now. Just removing that 1902 // second half of the condition and the LastCIEOffset variable 1903 // makes the code DTRT. 1904 LastCIEOffset != IteratorInserted.first->getValue()) { 1905 LastCIEOffset = TheDwarfEmitter->getFrameSectionSize(); 1906 IteratorInserted.first->getValue() = LastCIEOffset; 1907 TheDwarfEmitter->emitCIE(CIEData); 1908 } 1909 1910 // Emit the FDE with updated address and CIE pointer. 1911 // (4 + AddrSize) is the size of the CIEId + initial_location 1912 // fields that will get reconstructed by emitFDE(). 1913 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize); 1914 TheDwarfEmitter->emitFDE(IteratorInserted.first->getValue(), AddrSize, 1915 Loc + Range->second.Offset, 1916 FrameData.substr(InputOffset, FDERemainingBytes)); 1917 InputOffset += FDERemainingBytes; 1918 } 1919 } 1920 1921 void DWARFLinker::DIECloner::copyAbbrev( 1922 const DWARFAbbreviationDeclaration &Abbrev, bool HasODR) { 1923 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()), 1924 dwarf::Form(Abbrev.hasChildren())); 1925 1926 for (const auto &Attr : Abbrev.attributes()) { 1927 uint16_t Form = Attr.Form; 1928 if (HasODR && isODRAttribute(Attr.Attr)) 1929 Form = dwarf::DW_FORM_ref_addr; 1930 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form)); 1931 } 1932 1933 Linker.assignAbbrev(Copy); 1934 } 1935 1936 uint32_t DWARFLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE, 1937 CompileUnit &U, 1938 const DWARFFile &File, 1939 int ChildRecurseDepth) { 1940 const char *Name = nullptr; 1941 DWARFUnit *OrigUnit = &U.getOrigUnit(); 1942 CompileUnit *CU = &U; 1943 Optional<DWARFFormValue> Ref; 1944 1945 while (1) { 1946 if (const char *CurrentName = DIE.getName(DINameKind::ShortName)) 1947 Name = CurrentName; 1948 1949 if (!(Ref = DIE.find(dwarf::DW_AT_specification)) && 1950 !(Ref = DIE.find(dwarf::DW_AT_abstract_origin))) 1951 break; 1952 1953 if (!Ref->isFormClass(DWARFFormValue::FC_Reference)) 1954 break; 1955 1956 CompileUnit *RefCU; 1957 if (auto RefDIE = 1958 Linker.resolveDIEReference(File, CompileUnits, *Ref, DIE, RefCU)) { 1959 CU = RefCU; 1960 OrigUnit = &RefCU->getOrigUnit(); 1961 DIE = RefDIE; 1962 } 1963 } 1964 1965 unsigned Idx = OrigUnit->getDIEIndex(DIE); 1966 if (!Name && DIE.getTag() == dwarf::DW_TAG_namespace) 1967 Name = "(anonymous namespace)"; 1968 1969 if (CU->getInfo(Idx).ParentIdx == 0 || 1970 // FIXME: dsymutil-classic compatibility. Ignore modules. 1971 CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx).getTag() == 1972 dwarf::DW_TAG_module) 1973 return djbHash(Name ? Name : "", djbHash(ChildRecurseDepth ? "" : "::")); 1974 1975 DWARFDie Die = OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx); 1976 return djbHash( 1977 (Name ? Name : ""), 1978 djbHash((Name ? "::" : ""), 1979 hashFullyQualifiedName(Die, *CU, File, ++ChildRecurseDepth))); 1980 } 1981 1982 static uint64_t getDwoId(const DWARFDie &CUDie, const DWARFUnit &Unit) { 1983 auto DwoId = dwarf::toUnsigned( 1984 CUDie.find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id})); 1985 if (DwoId) 1986 return *DwoId; 1987 return 0; 1988 } 1989 1990 static std::string remapPath(StringRef Path, 1991 const objectPrefixMap &ObjectPrefixMap) { 1992 if (ObjectPrefixMap.empty()) 1993 return Path.str(); 1994 1995 SmallString<256> p = Path; 1996 for (const auto &Entry : ObjectPrefixMap) 1997 if (llvm::sys::path::replace_path_prefix(p, Entry.first, Entry.second)) 1998 break; 1999 return p.str().str(); 2000 } 2001 2002 bool DWARFLinker::registerModuleReference(DWARFDie CUDie, const DWARFUnit &Unit, 2003 const DWARFFile &File, 2004 OffsetsStringPool &StringPool, 2005 DeclContextTree &ODRContexts, 2006 uint64_t ModulesEndOffset, 2007 unsigned &UnitID, bool IsLittleEndian, 2008 unsigned Indent, bool Quiet) { 2009 std::string PCMfile = dwarf::toString( 2010 CUDie.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), ""); 2011 if (PCMfile.empty()) 2012 return false; 2013 if (Options.ObjectPrefixMap) 2014 PCMfile = remapPath(PCMfile, *Options.ObjectPrefixMap); 2015 2016 // Clang module DWARF skeleton CUs abuse this for the path to the module. 2017 uint64_t DwoId = getDwoId(CUDie, Unit); 2018 2019 std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), ""); 2020 if (Name.empty()) { 2021 if (!Quiet) 2022 reportWarning("Anonymous module skeleton CU for " + PCMfile, File); 2023 return true; 2024 } 2025 2026 if (!Quiet && Options.Verbose) { 2027 outs().indent(Indent); 2028 outs() << "Found clang module reference " << PCMfile; 2029 } 2030 2031 auto Cached = ClangModules.find(PCMfile); 2032 if (Cached != ClangModules.end()) { 2033 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is 2034 // fixed in clang, only warn about DWO_id mismatches in verbose mode. 2035 // ASTFileSignatures will change randomly when a module is rebuilt. 2036 if (!Quiet && Options.Verbose && (Cached->second != DwoId)) 2037 reportWarning(Twine("hash mismatch: this object file was built against a " 2038 "different version of the module ") + 2039 PCMfile, 2040 File); 2041 if (!Quiet && Options.Verbose) 2042 outs() << " [cached].\n"; 2043 return true; 2044 } 2045 if (!Quiet && Options.Verbose) 2046 outs() << " ...\n"; 2047 2048 // Cyclic dependencies are disallowed by Clang, but we still 2049 // shouldn't run into an infinite loop, so mark it as processed now. 2050 ClangModules.insert({PCMfile, DwoId}); 2051 2052 if (Error E = loadClangModule(CUDie, PCMfile, Name, DwoId, File, StringPool, 2053 ODRContexts, ModulesEndOffset, UnitID, 2054 IsLittleEndian, Indent + 2, Quiet)) { 2055 consumeError(std::move(E)); 2056 return false; 2057 } 2058 return true; 2059 } 2060 2061 Error DWARFLinker::loadClangModule( 2062 DWARFDie CUDie, StringRef Filename, StringRef ModuleName, uint64_t DwoId, 2063 const DWARFFile &File, OffsetsStringPool &StringPool, 2064 DeclContextTree &ODRContexts, uint64_t ModulesEndOffset, unsigned &UnitID, 2065 bool IsLittleEndian, unsigned Indent, bool Quiet) { 2066 /// Using a SmallString<0> because loadClangModule() is recursive. 2067 SmallString<0> Path(Options.PrependPath); 2068 if (sys::path::is_relative(Filename)) 2069 resolveRelativeObjectPath(Path, CUDie); 2070 sys::path::append(Path, Filename); 2071 // Don't use the cached binary holder because we have no thread-safety 2072 // guarantee and the lifetime is limited. 2073 2074 if (Options.ObjFileLoader == nullptr) 2075 return Error::success(); 2076 2077 auto ErrOrObj = Options.ObjFileLoader(File.FileName, Path); 2078 if (!ErrOrObj) 2079 return Error::success(); 2080 2081 std::unique_ptr<CompileUnit> Unit; 2082 2083 for (const auto &CU : ErrOrObj->Dwarf->compile_units()) { 2084 updateDwarfVersion(CU->getVersion()); 2085 // Recursively get all modules imported by this one. 2086 auto CUDie = CU->getUnitDIE(false); 2087 if (!CUDie) 2088 continue; 2089 if (!registerModuleReference(CUDie, *CU, File, StringPool, ODRContexts, 2090 ModulesEndOffset, UnitID, IsLittleEndian, 2091 Indent, Quiet)) { 2092 if (Unit) { 2093 std::string Err = 2094 (Filename + 2095 ": Clang modules are expected to have exactly 1 compile unit.\n") 2096 .str(); 2097 reportError(Err, File); 2098 return make_error<StringError>(Err, inconvertibleErrorCode()); 2099 } 2100 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is 2101 // fixed in clang, only warn about DWO_id mismatches in verbose mode. 2102 // ASTFileSignatures will change randomly when a module is rebuilt. 2103 uint64_t PCMDwoId = getDwoId(CUDie, *CU); 2104 if (PCMDwoId != DwoId) { 2105 if (!Quiet && Options.Verbose) 2106 reportWarning( 2107 Twine("hash mismatch: this object file was built against a " 2108 "different version of the module ") + 2109 Filename, 2110 File); 2111 // Update the cache entry with the DwoId of the module loaded from disk. 2112 ClangModules[Filename] = PCMDwoId; 2113 } 2114 2115 // Add this module. 2116 Unit = std::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR, 2117 ModuleName); 2118 Unit->setHasInterestingContent(); 2119 analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), ODRContexts, 2120 ModulesEndOffset, Options.ParseableSwiftInterfaces, 2121 [&](const Twine &Warning, const DWARFDie &DIE) { 2122 reportWarning(Warning, File, &DIE); 2123 }); 2124 // Keep everything. 2125 Unit->markEverythingAsKept(); 2126 } 2127 } 2128 if (!Unit->getOrigUnit().getUnitDIE().hasChildren()) 2129 return Error::success(); 2130 if (!Quiet && Options.Verbose) { 2131 outs().indent(Indent); 2132 outs() << "cloning .debug_info from " << Filename << "\n"; 2133 } 2134 2135 UnitListTy CompileUnits; 2136 CompileUnits.push_back(std::move(Unit)); 2137 assert(TheDwarfEmitter); 2138 DIECloner(*this, TheDwarfEmitter, *ErrOrObj, DIEAlloc, CompileUnits, 2139 Options.Update) 2140 .cloneAllCompileUnits(*(ErrOrObj->Dwarf), File, StringPool, 2141 IsLittleEndian); 2142 return Error::success(); 2143 } 2144 2145 uint64_t DWARFLinker::DIECloner::cloneAllCompileUnits( 2146 DWARFContext &DwarfContext, const DWARFFile &File, 2147 OffsetsStringPool &StringPool, bool IsLittleEndian) { 2148 uint64_t OutputDebugInfoSize = 2149 Linker.Options.NoOutput ? 0 : Emitter->getDebugInfoSectionSize(); 2150 const uint64_t StartOutputDebugInfoSize = OutputDebugInfoSize; 2151 2152 for (auto &CurrentUnit : CompileUnits) { 2153 const uint16_t DwarfVersion = CurrentUnit->getOrigUnit().getVersion(); 2154 const uint32_t UnitHeaderSize = DwarfVersion >= 5 ? 12 : 11; 2155 auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE(); 2156 CurrentUnit->setStartOffset(OutputDebugInfoSize); 2157 if (!InputDIE) { 2158 OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion); 2159 continue; 2160 } 2161 if (CurrentUnit->getInfo(0).Keep) { 2162 // Clone the InputDIE into your Unit DIE in our compile unit since it 2163 // already has a DIE inside of it. 2164 CurrentUnit->createOutputDIE(); 2165 cloneDIE(InputDIE, File, *CurrentUnit, StringPool, 0 /* PC offset */, 2166 UnitHeaderSize, 0, IsLittleEndian, 2167 CurrentUnit->getOutputUnitDIE()); 2168 } 2169 2170 OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion); 2171 2172 if (!Linker.Options.NoOutput) { 2173 assert(Emitter); 2174 2175 if (LLVM_LIKELY(!Linker.Options.Update) || 2176 Linker.needToTranslateStrings()) 2177 Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext, File); 2178 2179 Linker.emitAcceleratorEntriesForUnit(*CurrentUnit); 2180 2181 if (LLVM_UNLIKELY(Linker.Options.Update)) 2182 continue; 2183 2184 Linker.patchRangesForUnit(*CurrentUnit, DwarfContext, File); 2185 auto ProcessExpr = [&](StringRef Bytes, 2186 SmallVectorImpl<uint8_t> &Buffer) { 2187 DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit(); 2188 DataExtractor Data(Bytes, IsLittleEndian, 2189 OrigUnit.getAddressByteSize()); 2190 cloneExpression(Data, 2191 DWARFExpression(Data, OrigUnit.getAddressByteSize(), 2192 OrigUnit.getFormParams().Format), 2193 File, *CurrentUnit, Buffer); 2194 }; 2195 Emitter->emitLocationsForUnit(*CurrentUnit, DwarfContext, ProcessExpr); 2196 } 2197 } 2198 2199 if (!Linker.Options.NoOutput) { 2200 assert(Emitter); 2201 // Emit all the compile unit's debug information. 2202 for (auto &CurrentUnit : CompileUnits) { 2203 if (LLVM_LIKELY(!Linker.Options.Update)) 2204 Linker.generateUnitRanges(*CurrentUnit); 2205 2206 CurrentUnit->fixupForwardReferences(); 2207 2208 if (!CurrentUnit->getOutputUnitDIE()) 2209 continue; 2210 2211 unsigned DwarfVersion = CurrentUnit->getOrigUnit().getVersion(); 2212 2213 assert(Emitter->getDebugInfoSectionSize() == 2214 CurrentUnit->getStartOffset()); 2215 Emitter->emitCompileUnitHeader(*CurrentUnit, DwarfVersion); 2216 Emitter->emitDIE(*CurrentUnit->getOutputUnitDIE()); 2217 assert(Emitter->getDebugInfoSectionSize() == 2218 CurrentUnit->computeNextUnitOffset(DwarfVersion)); 2219 } 2220 } 2221 2222 return OutputDebugInfoSize - StartOutputDebugInfoSize; 2223 } 2224 2225 void DWARFLinker::updateAccelKind(DWARFContext &Dwarf) { 2226 if (Options.TheAccelTableKind != AccelTableKind::Default) 2227 return; 2228 2229 auto &DwarfObj = Dwarf.getDWARFObj(); 2230 2231 if (!AtLeastOneDwarfAccelTable && 2232 (!DwarfObj.getAppleNamesSection().Data.empty() || 2233 !DwarfObj.getAppleTypesSection().Data.empty() || 2234 !DwarfObj.getAppleNamespacesSection().Data.empty() || 2235 !DwarfObj.getAppleObjCSection().Data.empty())) { 2236 AtLeastOneAppleAccelTable = true; 2237 } 2238 2239 if (!AtLeastOneDwarfAccelTable && !DwarfObj.getNamesSection().Data.empty()) { 2240 AtLeastOneDwarfAccelTable = true; 2241 } 2242 } 2243 2244 bool DWARFLinker::emitPaperTrailWarnings(const DWARFFile &File, 2245 OffsetsStringPool &StringPool) { 2246 2247 if (File.Warnings.empty()) 2248 return false; 2249 2250 DIE *CUDie = DIE::get(DIEAlloc, dwarf::DW_TAG_compile_unit); 2251 CUDie->setOffset(11); 2252 StringRef Producer; 2253 StringRef WarningHeader; 2254 2255 switch (DwarfLinkerClientID) { 2256 case DwarfLinkerClient::Dsymutil: 2257 Producer = StringPool.internString("dsymutil"); 2258 WarningHeader = "dsymutil_warning"; 2259 break; 2260 2261 default: 2262 Producer = StringPool.internString("dwarfopt"); 2263 WarningHeader = "dwarfopt_warning"; 2264 break; 2265 } 2266 2267 StringRef FileName = StringPool.internString(File.FileName); 2268 CUDie->addValue(DIEAlloc, dwarf::DW_AT_producer, dwarf::DW_FORM_strp, 2269 DIEInteger(StringPool.getStringOffset(Producer))); 2270 DIEBlock *String = new (DIEAlloc) DIEBlock(); 2271 DIEBlocks.push_back(String); 2272 for (auto &C : FileName) 2273 String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1, 2274 DIEInteger(C)); 2275 String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1, 2276 DIEInteger(0)); 2277 2278 CUDie->addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_string, String); 2279 for (const auto &Warning : File.Warnings) { 2280 DIE &ConstDie = CUDie->addChild(DIE::get(DIEAlloc, dwarf::DW_TAG_constant)); 2281 ConstDie.addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, 2282 DIEInteger(StringPool.getStringOffset(WarningHeader))); 2283 ConstDie.addValue(DIEAlloc, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 2284 DIEInteger(1)); 2285 ConstDie.addValue(DIEAlloc, dwarf::DW_AT_const_value, dwarf::DW_FORM_strp, 2286 DIEInteger(StringPool.getStringOffset(Warning))); 2287 } 2288 unsigned Size = 4 /* FORM_strp */ + FileName.size() + 1 + 2289 File.Warnings.size() * (4 + 1 + 4) + 1 /* End of children */; 2290 DIEAbbrev Abbrev = CUDie->generateAbbrev(); 2291 assignAbbrev(Abbrev); 2292 CUDie->setAbbrevNumber(Abbrev.getNumber()); 2293 Size += getULEB128Size(Abbrev.getNumber()); 2294 // Abbreviation ordering needed for classic compatibility. 2295 for (auto &Child : CUDie->children()) { 2296 Abbrev = Child.generateAbbrev(); 2297 assignAbbrev(Abbrev); 2298 Child.setAbbrevNumber(Abbrev.getNumber()); 2299 Size += getULEB128Size(Abbrev.getNumber()); 2300 } 2301 CUDie->setSize(Size); 2302 TheDwarfEmitter->emitPaperTrailWarningsDie(*CUDie); 2303 2304 return true; 2305 } 2306 2307 void DWARFLinker::copyInvariantDebugSection(DWARFContext &Dwarf) { 2308 if (!needToTranslateStrings()) 2309 TheDwarfEmitter->emitSectionContents( 2310 Dwarf.getDWARFObj().getLineSection().Data, "debug_line"); 2311 TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getLocSection().Data, 2312 "debug_loc"); 2313 TheDwarfEmitter->emitSectionContents( 2314 Dwarf.getDWARFObj().getRangesSection().Data, "debug_ranges"); 2315 TheDwarfEmitter->emitSectionContents( 2316 Dwarf.getDWARFObj().getFrameSection().Data, "debug_frame"); 2317 TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getArangesSection(), 2318 "debug_aranges"); 2319 } 2320 2321 void DWARFLinker::addObjectFile(DWARFFile &File) { 2322 ObjectContexts.emplace_back(LinkContext(File)); 2323 2324 if (ObjectContexts.back().File.Dwarf) 2325 updateAccelKind(*ObjectContexts.back().File.Dwarf); 2326 } 2327 2328 bool DWARFLinker::link() { 2329 assert(Options.NoOutput || TheDwarfEmitter); 2330 2331 // A unique ID that identifies each compile unit. 2332 unsigned UnitID = 0; 2333 2334 // First populate the data structure we need for each iteration of the 2335 // parallel loop. 2336 unsigned NumObjects = ObjectContexts.size(); 2337 2338 // This Dwarf string pool which is used for emission. It must be used 2339 // serially as the order of calling getStringOffset matters for 2340 // reproducibility. 2341 OffsetsStringPool OffsetsStringPool(StringsTranslator, true); 2342 2343 // ODR Contexts for the optimize. 2344 DeclContextTree ODRContexts; 2345 2346 // If we haven't decided on an accelerator table kind yet, we base ourselves 2347 // on the DWARF we have seen so far. At this point we haven't pulled in debug 2348 // information from modules yet, so it is technically possible that they 2349 // would affect the decision. However, as they're built with the same 2350 // compiler and flags, it is safe to assume that they will follow the 2351 // decision made here. 2352 if (Options.TheAccelTableKind == AccelTableKind::Default) { 2353 if (AtLeastOneDwarfAccelTable && !AtLeastOneAppleAccelTable) 2354 Options.TheAccelTableKind = AccelTableKind::Dwarf; 2355 else 2356 Options.TheAccelTableKind = AccelTableKind::Apple; 2357 } 2358 2359 for (LinkContext &OptContext : ObjectContexts) { 2360 if (Options.Verbose) { 2361 if (DwarfLinkerClientID == DwarfLinkerClient::Dsymutil) 2362 outs() << "DEBUG MAP OBJECT: " << OptContext.File.FileName << "\n"; 2363 else 2364 outs() << "OBJECT FILE: " << OptContext.File.FileName << "\n"; 2365 } 2366 2367 if (emitPaperTrailWarnings(OptContext.File, OffsetsStringPool)) 2368 continue; 2369 2370 if (!OptContext.File.Dwarf) 2371 continue; 2372 // Look for relocations that correspond to address map entries. 2373 2374 // there was findvalidrelocations previously ... probably we need to gather 2375 // info here 2376 if (LLVM_LIKELY(!Options.Update) && 2377 !OptContext.File.Addresses->hasValidRelocs()) { 2378 if (Options.Verbose) 2379 outs() << "No valid relocations found. Skipping.\n"; 2380 2381 // Set "Skip" flag as a signal to other loops that we should not 2382 // process this iteration. 2383 OptContext.Skip = true; 2384 continue; 2385 } 2386 2387 // Setup access to the debug info. 2388 if (!OptContext.File.Dwarf) 2389 continue; 2390 2391 // In a first phase, just read in the debug info and load all clang modules. 2392 OptContext.CompileUnits.reserve( 2393 OptContext.File.Dwarf->getNumCompileUnits()); 2394 2395 for (const auto &CU : OptContext.File.Dwarf->compile_units()) { 2396 updateDwarfVersion(CU->getVersion()); 2397 auto CUDie = CU->getUnitDIE(false); 2398 if (Options.Verbose) { 2399 outs() << "Input compilation unit:"; 2400 DIDumpOptions DumpOpts; 2401 DumpOpts.ChildRecurseDepth = 0; 2402 DumpOpts.Verbose = Options.Verbose; 2403 CUDie.dump(outs(), 0, DumpOpts); 2404 } 2405 if (CUDie && !LLVM_UNLIKELY(Options.Update)) 2406 registerModuleReference(CUDie, *CU, OptContext.File, OffsetsStringPool, 2407 ODRContexts, 0, UnitID, 2408 OptContext.File.Dwarf->isLittleEndian()); 2409 } 2410 } 2411 2412 // If we haven't seen any CUs, pick an arbitrary valid Dwarf version anyway. 2413 if (MaxDwarfVersion == 0) 2414 MaxDwarfVersion = 3; 2415 2416 // At this point we know how much data we have emitted. We use this value to 2417 // compare canonical DIE offsets in analyzeContextInfo to see if a definition 2418 // is already emitted, without being affected by canonical die offsets set 2419 // later. This prevents undeterminism when analyze and clone execute 2420 // concurrently, as clone set the canonical DIE offset and analyze reads it. 2421 const uint64_t ModulesEndOffset = 2422 Options.NoOutput ? 0 : TheDwarfEmitter->getDebugInfoSectionSize(); 2423 2424 // These variables manage the list of processed object files. 2425 // The mutex and condition variable are to ensure that this is thread safe. 2426 std::mutex ProcessedFilesMutex; 2427 std::condition_variable ProcessedFilesConditionVariable; 2428 BitVector ProcessedFiles(NumObjects, false); 2429 2430 // Analyzing the context info is particularly expensive so it is executed in 2431 // parallel with emitting the previous compile unit. 2432 auto AnalyzeLambda = [&](size_t I) { 2433 auto &Context = ObjectContexts[I]; 2434 2435 if (Context.Skip || !Context.File.Dwarf) 2436 return; 2437 2438 for (const auto &CU : Context.File.Dwarf->compile_units()) { 2439 updateDwarfVersion(CU->getVersion()); 2440 // The !registerModuleReference() condition effectively skips 2441 // over fully resolved skeleton units. This second pass of 2442 // registerModuleReferences doesn't do any new work, but it 2443 // will collect top-level errors, which are suppressed. Module 2444 // warnings were already displayed in the first iteration. 2445 bool Quiet = true; 2446 auto CUDie = CU->getUnitDIE(false); 2447 if (!CUDie || LLVM_UNLIKELY(Options.Update) || 2448 !registerModuleReference(CUDie, *CU, Context.File, OffsetsStringPool, 2449 ODRContexts, ModulesEndOffset, UnitID, 2450 Quiet)) { 2451 Context.CompileUnits.push_back(std::make_unique<CompileUnit>( 2452 *CU, UnitID++, !Options.NoODR && !Options.Update, "")); 2453 } 2454 } 2455 2456 // Now build the DIE parent links that we will use during the next phase. 2457 for (auto &CurrentUnit : Context.CompileUnits) { 2458 auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE(); 2459 if (!CUDie) 2460 continue; 2461 analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0, 2462 *CurrentUnit, &ODRContexts.getRoot(), ODRContexts, 2463 ModulesEndOffset, Options.ParseableSwiftInterfaces, 2464 [&](const Twine &Warning, const DWARFDie &DIE) { 2465 reportWarning(Warning, Context.File, &DIE); 2466 }); 2467 } 2468 }; 2469 2470 // For each object file map how many bytes were emitted. 2471 StringMap<DebugInfoSize> SizeByObject; 2472 2473 // And then the remaining work in serial again. 2474 // Note, although this loop runs in serial, it can run in parallel with 2475 // the analyzeContextInfo loop so long as we process files with indices >= 2476 // than those processed by analyzeContextInfo. 2477 auto CloneLambda = [&](size_t I) { 2478 auto &OptContext = ObjectContexts[I]; 2479 if (OptContext.Skip || !OptContext.File.Dwarf) 2480 return; 2481 2482 // Then mark all the DIEs that need to be present in the generated output 2483 // and collect some information about them. 2484 // Note that this loop can not be merged with the previous one because 2485 // cross-cu references require the ParentIdx to be setup for every CU in 2486 // the object file before calling this. 2487 if (LLVM_UNLIKELY(Options.Update)) { 2488 for (auto &CurrentUnit : OptContext.CompileUnits) 2489 CurrentUnit->markEverythingAsKept(); 2490 copyInvariantDebugSection(*OptContext.File.Dwarf); 2491 } else { 2492 for (auto &CurrentUnit : OptContext.CompileUnits) 2493 lookForDIEsToKeep(*OptContext.File.Addresses, 2494 OptContext.File.Addresses->getValidAddressRanges(), 2495 OptContext.CompileUnits, 2496 CurrentUnit->getOrigUnit().getUnitDIE(), 2497 OptContext.File, *CurrentUnit, 0); 2498 } 2499 2500 // The calls to applyValidRelocs inside cloneDIE will walk the reloc 2501 // array again (in the same way findValidRelocsInDebugInfo() did). We 2502 // need to reset the NextValidReloc index to the beginning. 2503 if (OptContext.File.Addresses->hasValidRelocs() || 2504 LLVM_UNLIKELY(Options.Update)) { 2505 SizeByObject[OptContext.File.FileName].Input = 2506 getDebugInfoSize(*OptContext.File.Dwarf); 2507 SizeByObject[OptContext.File.FileName].Output = 2508 DIECloner(*this, TheDwarfEmitter, OptContext.File, DIEAlloc, 2509 OptContext.CompileUnits, Options.Update) 2510 .cloneAllCompileUnits(*OptContext.File.Dwarf, OptContext.File, 2511 OffsetsStringPool, 2512 OptContext.File.Dwarf->isLittleEndian()); 2513 } 2514 if (!Options.NoOutput && !OptContext.CompileUnits.empty() && 2515 LLVM_LIKELY(!Options.Update)) 2516 patchFrameInfoForObject( 2517 OptContext.File, OptContext.File.Addresses->getValidAddressRanges(), 2518 *OptContext.File.Dwarf, 2519 OptContext.CompileUnits[0]->getOrigUnit().getAddressByteSize()); 2520 2521 // Clean-up before starting working on the next object. 2522 cleanupAuxiliarryData(OptContext); 2523 }; 2524 2525 auto EmitLambda = [&]() { 2526 // Emit everything that's global. 2527 if (!Options.NoOutput) { 2528 TheDwarfEmitter->emitAbbrevs(Abbreviations, MaxDwarfVersion); 2529 TheDwarfEmitter->emitStrings(OffsetsStringPool); 2530 switch (Options.TheAccelTableKind) { 2531 case AccelTableKind::Apple: 2532 TheDwarfEmitter->emitAppleNames(AppleNames); 2533 TheDwarfEmitter->emitAppleNamespaces(AppleNamespaces); 2534 TheDwarfEmitter->emitAppleTypes(AppleTypes); 2535 TheDwarfEmitter->emitAppleObjc(AppleObjc); 2536 break; 2537 case AccelTableKind::Dwarf: 2538 TheDwarfEmitter->emitDebugNames(DebugNames); 2539 break; 2540 case AccelTableKind::Default: 2541 llvm_unreachable("Default should have already been resolved."); 2542 break; 2543 } 2544 } 2545 }; 2546 2547 auto AnalyzeAll = [&]() { 2548 for (unsigned I = 0, E = NumObjects; I != E; ++I) { 2549 AnalyzeLambda(I); 2550 2551 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex); 2552 ProcessedFiles.set(I); 2553 ProcessedFilesConditionVariable.notify_one(); 2554 } 2555 }; 2556 2557 auto CloneAll = [&]() { 2558 for (unsigned I = 0, E = NumObjects; I != E; ++I) { 2559 { 2560 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex); 2561 if (!ProcessedFiles[I]) { 2562 ProcessedFilesConditionVariable.wait( 2563 LockGuard, [&]() { return ProcessedFiles[I]; }); 2564 } 2565 } 2566 2567 CloneLambda(I); 2568 } 2569 EmitLambda(); 2570 }; 2571 2572 // To limit memory usage in the single threaded case, analyze and clone are 2573 // run sequentially so the OptContext is freed after processing each object 2574 // in endDebugObject. 2575 if (Options.Threads == 1) { 2576 for (unsigned I = 0, E = NumObjects; I != E; ++I) { 2577 AnalyzeLambda(I); 2578 CloneLambda(I); 2579 } 2580 EmitLambda(); 2581 } else { 2582 ThreadPool Pool(hardware_concurrency(2)); 2583 Pool.async(AnalyzeAll); 2584 Pool.async(CloneAll); 2585 Pool.wait(); 2586 } 2587 2588 if (Options.Statistics) { 2589 // Create a vector sorted in descending order by output size. 2590 std::vector<std::pair<StringRef, DebugInfoSize>> Sorted; 2591 for (auto &E : SizeByObject) 2592 Sorted.emplace_back(E.first(), E.second); 2593 llvm::sort(Sorted, [](auto &LHS, auto &RHS) { 2594 return LHS.second.Output > RHS.second.Output; 2595 }); 2596 2597 auto ComputePercentange = [](int64_t Input, int64_t Output) -> float { 2598 const float Difference = Output - Input; 2599 const float Sum = Input + Output; 2600 if (Sum == 0) 2601 return 0; 2602 return (Difference / (Sum / 2)); 2603 }; 2604 2605 int64_t InputTotal = 0; 2606 int64_t OutputTotal = 0; 2607 const char *FormatStr = "{0,-45} {1,10}b {2,10}b {3,8:P}\n"; 2608 2609 // Print header. 2610 outs() << ".debug_info section size (in bytes)\n"; 2611 outs() << "----------------------------------------------------------------" 2612 "---------------\n"; 2613 outs() << "Filename Object " 2614 " dSYM Change\n"; 2615 outs() << "----------------------------------------------------------------" 2616 "---------------\n"; 2617 2618 // Print body. 2619 for (auto &E : Sorted) { 2620 InputTotal += E.second.Input; 2621 OutputTotal += E.second.Output; 2622 llvm::outs() << formatv( 2623 FormatStr, sys::path::filename(E.first).take_back(45), E.second.Input, 2624 E.second.Output, ComputePercentange(E.second.Input, E.second.Output)); 2625 } 2626 // Print total and footer. 2627 outs() << "----------------------------------------------------------------" 2628 "---------------\n"; 2629 llvm::outs() << formatv(FormatStr, "Total", InputTotal, OutputTotal, 2630 ComputePercentange(InputTotal, OutputTotal)); 2631 outs() << "----------------------------------------------------------------" 2632 "---------------\n\n"; 2633 } 2634 2635 return true; 2636 } 2637 2638 } // namespace llvm 2639