LLVM 24.0.0git
DWARFLinkerImpl.cpp
Go to the documentation of this file.
1//=== DWARFLinkerImpl.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 "DWARFLinkerImpl.h"
10#include "DependencyTracker.h"
16
17using namespace llvm;
18using namespace dwarf_linker;
19using namespace dwarf_linker::parallel;
20
28
30 DWARFFile &File, uint64_t ObjFileIdx,
32 uint64_t &ModuleUnitIdx,
33 std::atomic<size_t> &UniqueUnitID)
37
38 if (File.Dwarf) {
39 if (!File.Dwarf->compile_units().empty())
40 CompileUnits.reserve(File.Dwarf->getNumCompileUnits());
41
42 // Set context format&endianness based on the input file.
43 Format.Version = File.Dwarf->getMaxVersion();
44 Format.AddrSize = File.Dwarf->getCUAddrSize();
45 Endianness = File.Dwarf->isLittleEndian() ? llvm::endianness::little
46 : llvm::endianness::big;
47 }
48}
49
51 CompileUnitHandlerTy OnCUDieLoaded) {
52 ObjectContexts.emplace_back(std::make_unique<LinkContext>(
55
56 if (ObjectContexts.back()->InputDWARFFile.Dwarf) {
57 for (const std::unique_ptr<DWARFUnit> &CU :
58 ObjectContexts.back()->InputDWARFFile.Dwarf->compile_units()) {
59 DWARFDie CUDie = CU->getUnitDIE();
60
61 if (!CUDie)
62 continue;
63
64 OnCUDieLoaded(*CU);
65
66 // Register mofule reference.
67 if (!GlobalData.getOptions().UpdateIndexTablesOnly)
68 ObjectContexts.back()->registerModuleReference(CUDie, Loader,
69 OnCUDieLoaded);
70 }
71 }
72}
73
75 ObjectContexts.reserve(ObjFilesNum);
76}
77
79 // UniqueUnitID is initialized by the constructor and must not be reset
80 // here. addObjectFile() may have already handed out IDs to clang module
81 // CUs loaded from .pcm files, and the IDs handed out below must stay
82 // disjoint from those.
83
85 return Err;
86
87 dwarf::FormParams GlobalFormat = {GlobalData.getOptions().TargetDWARFVersion,
90
91 if (std::optional<std::reference_wrapper<const Triple>> CurTriple =
92 GlobalData.getTargetTriple()) {
93 GlobalEndianness = (*CurTriple).get().isLittleEndian()
96 }
97 std::optional<uint16_t> Language;
98
99 for (std::unique_ptr<LinkContext> &Context : ObjectContexts) {
100 if (Context->InputDWARFFile.Dwarf == nullptr) {
101 Context->setOutputFormat(Context->getFormParams(), GlobalEndianness);
102 continue;
103 }
104
105 if (GlobalData.getOptions().Verbose) {
106 outs() << "DEBUG MAP OBJECT: " << Context->InputDWARFFile.FileName
107 << "\n";
108
109 for (const std::unique_ptr<DWARFUnit> &OrigCU :
110 Context->InputDWARFFile.Dwarf->compile_units()) {
111 outs() << "Input compilation unit:";
112 DIDumpOptions DumpOpts;
113 DumpOpts.ChildRecurseDepth = 0;
114 DumpOpts.Verbose = GlobalData.getOptions().Verbose;
115 OrigCU->getUnitDIE().dump(outs(), 0, DumpOpts);
116 }
117 }
118
119 // Verify input DWARF if requested.
120 if (GlobalData.getOptions().VerifyInputDWARF)
121 verifyInput(Context->InputDWARFFile);
122
123 if (!GlobalData.getTargetTriple())
124 GlobalEndianness = Context->getEndianness();
125 GlobalFormat.AddrSize =
126 std::max(GlobalFormat.AddrSize, Context->getFormParams().AddrSize);
127
128 Context->setOutputFormat(Context->getFormParams(), GlobalEndianness);
129
130 // FIXME: move creation of CompileUnits into the addObjectFile.
131 // This would allow to not scan for context Language and Modules state
132 // twice. And then following handling might be removed.
133 for (const std::unique_ptr<DWARFUnit> &OrigCU :
134 Context->InputDWARFFile.Dwarf->compile_units()) {
135 DWARFDie UnitDie = OrigCU->getUnitDIE();
136
137 if (!Language) {
138 if (std::optional<uint64_t> LangVal = UnitDie.getLanguage())
139 if (isODRLanguage(*LangVal))
140 Language = static_cast<uint16_t>(*LangVal);
141 }
142 }
143
144 // Clang module units decide their ODR availability from their own
145 // language, so they have to be part of this scan as well. A module unit
146 // can be the only ODR unit of a link, and any unit which deduplicates
147 // types requires the artificial type unit to exist.
148 for (const std::unique_ptr<CompileUnit> &Module :
149 Context->ModulesCompileUnits) {
150 if (!Language) {
151 if (std::optional<uint16_t> LangVal = Module->getLanguage())
152 if (isODRLanguage(*LangVal))
153 Language = *LangVal;
154 }
155 }
156 }
157
158 if (GlobalFormat.AddrSize == 0) {
159 if (std::optional<std::reference_wrapper<const Triple>> TargetTriple =
160 GlobalData.getTargetTriple())
161 GlobalFormat.AddrSize = (*TargetTriple).get().isArch32Bit() ? 4 : 8;
162 else
163 GlobalFormat.AddrSize = 8;
164 }
165
166 CommonSections.setOutputFormat(GlobalFormat, GlobalEndianness);
167
168 if (!GlobalData.Options.NoODR && Language.has_value()) {
170 TGroup.spawn([&]() {
171 ArtificialTypeUnit = std::make_unique<TypeUnit>(
172 GlobalData, UniqueUnitID++, Language, GlobalFormat, GlobalEndianness);
173 });
174 }
175
176 // Set this process-global once. link() runs per architecture and dsymutil
177 // may run those links concurrently, so assigning it from each would be a
178 // data race; the thread count is the same for every architecture, so the
179 // first assignment suffices. Size the executor from that thread count rather
180 // than the per-architecture CU count, which is moot once it is shared.
181 static llvm::once_flag ParallelStrategyFlag;
182 llvm::call_once(ParallelStrategyFlag, [&] {
184 hardware_concurrency(GlobalData.getOptions().Threads);
185 });
186
187 // Link object files.
188 if (GlobalData.getOptions().Threads == 1) {
189 for (std::unique_ptr<LinkContext> &Context : ObjectContexts) {
190 // Link object file.
191 if (Error Err = Context->link(ArtificialTypeUnit.get()))
192 GlobalData.error(std::move(Err), Context->InputDWARFFile.FileName);
193 if (Error Err = Context->unloadInput())
194 GlobalData.error(std::move(Err), Context->InputDWARFFile.FileName);
195 }
196 } else {
197 assert(ThreadPool && "setThreadPool() must be called before link()");
199 for (std::unique_ptr<LinkContext> &Context : ObjectContexts)
200 Group.async([&]() {
201 // Link object file.
202 if (Error Err = Context->link(ArtificialTypeUnit.get()))
203 GlobalData.error(std::move(Err), Context->InputDWARFFile.FileName);
204 if (Error Err = Context->unloadInput())
205 GlobalData.error(std::move(Err), Context->InputDWARFFile.FileName);
206 });
207 }
208
209 // Merge staged parseable Swift interface entries into the shared map. Done
210 // serially so that the final map contents and any conflict warnings are
211 // deterministic.
212 if (DWARFLinkerBase::SwiftInterfacesMapTy *SwiftInterfaces =
213 GlobalData.Options.ParseableSwiftInterfaces) {
214 for (std::unique_ptr<LinkContext> &Context : ObjectContexts) {
215 for (std::unique_ptr<CompileUnit> &ModuleUnit :
216 Context->ModulesCompileUnits)
217 ModuleUnit->mergeSwiftInterfaces(*SwiftInterfaces);
218 for (std::unique_ptr<CompileUnit> &CU : Context->CompileUnits)
219 CU->mergeSwiftInterfaces(*SwiftInterfaces);
220 }
221 }
222
223 // Build the linker-wide CIE registry, then emit each context's
224 // .debug_frame in parallel. See CIERegistry for the ownership rules.
225 if (!GlobalData.getOptions().UpdateIndexTablesOnly) {
227 for (std::unique_ptr<LinkContext> &Context : ObjectContexts)
228 if (Context->FrameScan)
229 Context->registerCIEs(CIEs);
230
232 for (std::unique_ptr<LinkContext> &Context : ObjectContexts) {
233 if (!Context->FrameScan)
234 continue;
235 TGroup.spawn([&]() {
236 if (Error Err = Context->emitDebugFrame(CIEs))
237 GlobalData.error(std::move(Err), Context->InputDWARFFile.FileName);
238 });
239 }
240 }
241
242 if (ArtificialTypeUnit != nullptr && !ArtificialTypeUnit->getTypePool()
243 .getRoot()
244 ->getValue()
245 .load()
246 ->Children.empty()) {
247 if (GlobalData.getTargetTriple().has_value())
248 if (Error Err = ArtificialTypeUnit->finishCloningAndEmit(
249 (*GlobalData.getTargetTriple()).get()))
250 return Err;
251 }
252
253 // At this stage each compile units are cloned to their own set of debug
254 // sections. Now, update patches, assign offsets and assemble final file
255 // glueing debug tables from each compile unit.
257
258 return Error::success();
259}
260
262 assert(File.Dwarf);
263
264 std::string Buffer;
265 raw_string_ostream OS(Buffer);
266 DIDumpOptions DumpOpts;
267 if (!File.Dwarf->verify(OS, DumpOpts.noImplicitRecursion())) {
268 if (GlobalData.getOptions().InputVerificationHandler)
269 GlobalData.getOptions().InputVerificationHandler(File, OS.str());
270 }
271}
272
274 if (GlobalData.getOptions().TargetDWARFVersion == 0)
275 return createStringError(std::errc::invalid_argument,
276 "target DWARF version is not set");
277
278 if (GlobalData.getOptions().Verbose && GlobalData.getOptions().Threads != 1) {
279 GlobalData.Options.Threads = 1;
280 GlobalData.warn(
281 "set number of threads to 1 to make --verbose to work properly.", "");
282 }
283
284 // Do not do types deduplication in case --update.
285 if (GlobalData.getOptions().UpdateIndexTablesOnly &&
286 !GlobalData.Options.NoODR)
287 GlobalData.Options.NoODR = true;
288
289 return Error::success();
290}
291
292/// Resolve the relative path to a build artifact referenced by DWARF of \p File
293/// by applying DW_AT_comp_dir.
295 const DWARFFile &File) {
297 Buf, File.remapPath(dwarf::toStringRef(CU.find(dwarf::DW_AT_comp_dir))));
298}
299
300static uint64_t getDwoId(const DWARFDie &CUDie) {
301 auto DwoId = dwarf::toUnsigned(
302 CUDie.find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
303 if (DwoId)
304 return *DwoId;
305 return 0;
306}
307
308static std::string
310 const DWARFLinker::ObjectPrefixMapTy &ObjectPrefixMap) {
311 if (ObjectPrefixMap.empty())
312 return Path.str();
313
314 SmallString<256> p = Path;
315 for (const auto &Entry : ObjectPrefixMap)
316 if (llvm::sys::path::replace_path_prefix(p, Entry.first, Entry.second))
317 break;
318 return p.str().str();
319}
320
321static std::string getPCMFile(const DWARFDie &CUDie,
322 DWARFLinker::ObjectPrefixMapTy *ObjectPrefixMap,
323 const DWARFFile &File) {
324 std::string PCMFile = dwarf::toString(
325 CUDie.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
326
327 if (PCMFile.empty())
328 return PCMFile;
329
330 if (ObjectPrefixMap)
331 PCMFile = remapPath(PCMFile, *ObjectPrefixMap);
332
333 return File.remapPath(PCMFile);
334}
335
337 const DWARFDie &CUDie, std::string &PCMFile, unsigned Indent, bool Quiet) {
338 if (PCMFile.empty())
339 return std::make_pair(false, false);
340
341 // Clang module DWARF skeleton CUs abuse this for the path to the module.
342 uint64_t DwoId = getDwoId(CUDie);
343
344 std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
345 if (Name.empty()) {
346 if (!Quiet)
347 GlobalData.warn("anonymous module skeleton CU for " + PCMFile + ".",
348 InputDWARFFile.FileName);
349 return std::make_pair(true, true);
350 }
351
352 if (!Quiet && GlobalData.getOptions().Verbose) {
353 outs().indent(Indent);
354 outs() << "Found clang module reference " << PCMFile;
355 }
356
357 auto Cached = ClangModules.find(PCMFile);
358 if (Cached != ClangModules.end()) {
359 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
360 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
361 // ASTFileSignatures will change randomly when a module is rebuilt.
362 if (!Quiet && GlobalData.getOptions().Verbose && (Cached->second != DwoId))
363 GlobalData.warn(
364 Twine("hash mismatch: this object file was built against a "
365 "different version of the module ") +
366 PCMFile + ".",
367 InputDWARFFile.FileName);
368 if (!Quiet && GlobalData.getOptions().Verbose)
369 outs() << " [cached].\n";
370 return std::make_pair(true, true);
371 }
372
373 return std::make_pair(true, false);
374}
375
376/// If this compile unit is really a skeleton CU that points to a
377/// clang module, register it in ClangModules and return true.
378///
379/// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
380/// pointing to the module, and a DW_AT_gnu_dwo_id with the module
381/// hash.
383 const DWARFDie &CUDie, ObjFileLoaderTy Loader,
384 CompileUnitHandlerTy OnCUDieLoaded, unsigned Indent) {
385 std::string PCMFile = getPCMFile(
386 CUDie, GlobalData.getOptions().ObjectPrefixMap, InputDWARFFile);
387 std::pair<bool, bool> IsClangModuleRef =
388 isClangModuleRef(CUDie, PCMFile, Indent, false);
389
390 if (!IsClangModuleRef.first)
391 return false;
392
393 if (IsClangModuleRef.second)
394 return true;
395
396 if (GlobalData.getOptions().Verbose)
397 outs() << " ...\n";
398
399 // Cyclic dependencies are disallowed by Clang, but we still
400 // shouldn't run into an infinite loop, so mark it as processed now.
401 ClangModules.insert({PCMFile, getDwoId(CUDie)});
402
403 if (Error E =
404 loadClangModule(Loader, CUDie, PCMFile, OnCUDieLoaded, Indent + 2)) {
405 consumeError(std::move(E));
406 return false;
407 }
408 return true;
409}
410
412 ObjFileLoaderTy Loader, const DWARFDie &CUDie, const std::string &PCMFile,
413 CompileUnitHandlerTy OnCUDieLoaded, unsigned Indent) {
414
415 uint64_t DwoId = getDwoId(CUDie);
416 std::string ModuleName = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
417
418 /// Using a SmallString<0> because loadClangModule() is recursive.
419 SmallString<0> Path(GlobalData.getOptions().PrependPath);
420 if (sys::path::is_relative(PCMFile))
422 sys::path::append(Path, PCMFile);
423 // Don't use the cached binary holder because we have no thread-safety
424 // guarantee and the lifetime is limited.
425
426 if (Loader == nullptr) {
427 GlobalData.error("cann't load clang module: loader is not specified.",
428 InputDWARFFile.FileName);
429 return Error::success();
430 }
431
432 auto ErrOrObj = Loader(InputDWARFFile.FileName, Path);
433 if (!ErrOrObj)
434 return Error::success();
435
436 // The module was built by the same build as the object file referencing it,
437 // so the same prefix map applies.
438 if (!ErrOrObj->PrefixMap)
439 ErrOrObj->PrefixMap = InputDWARFFile.PrefixMap;
440
441 std::unique_ptr<CompileUnit> Unit;
442 for (const auto &CU : ErrOrObj->Dwarf->compile_units()) {
443 OnCUDieLoaded(*CU);
444 // Recursively get all modules imported by this one.
445 auto ChildCUDie = CU->getUnitDIE();
446 if (!ChildCUDie)
447 continue;
448 if (!registerModuleReference(ChildCUDie, Loader, OnCUDieLoaded, Indent)) {
449 if (Unit) {
450 std::string Err =
451 (PCMFile +
452 ": Clang modules are expected to have exactly 1 compile unit.\n");
453 GlobalData.error(Err, InputDWARFFile.FileName);
455 }
456 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
457 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
458 // ASTFileSignatures will change randomly when a module is rebuilt.
459 uint64_t PCMDwoId = getDwoId(ChildCUDie);
460 if (PCMDwoId != DwoId) {
461 if (GlobalData.getOptions().Verbose)
462 GlobalData.warn(
463 Twine("hash mismatch: this object file was built against a "
464 "different version of the module ") +
465 PCMFile + ".",
466 InputDWARFFile.FileName);
467 // Update the cache entry with the DwoId of the module loaded from disk.
468 ClangModules[PCMFile] = PCMDwoId;
469 }
470
471 // Empty modules units should not be cloned.
472 if (!ChildCUDie.hasChildren())
473 continue;
474
475 // Add this module.
476 Unit = std::make_unique<CompileUnit>(
477 GlobalData, *CU, UniqueUnitID.fetch_add(1), ModuleName, *ErrOrObj,
478 getUnitForOffset, CU->getFormParams(), getEndianness());
479 }
480 }
481
482 if (Unit) {
483 // Incrementing the shared counter needs no synchronization: reaching this
484 // point requires a loader, and only the serial pass over the object files
485 // supplies one.
486 if (Error E = Unit->setPriority(ModuleUnitObjFileIdx, ModuleUnitIdx++))
487 return E;
488
489 ModulesCompileUnits.emplace_back(std::move(Unit));
490 // Preload line table, as it can't be loaded asynchronously.
491 ModulesCompileUnits.back()->loadLineTable();
492 }
493
494 return Error::success();
495}
496
499 if (!InputDWARFFile.Dwarf)
500 return Error::success();
501
502 // Preload macro tables, as they can't be loaded asynchronously.
503 InputDWARFFile.Dwarf->getDebugMacinfo();
504 InputDWARFFile.Dwarf->getDebugMacro();
505
506 // Link modules compile units first.
507 parallelForEach(ModulesCompileUnits, [&](std::unique_ptr<CompileUnit> &Mod) {
508 // A module unit describes DIEs which no address reaches, so nothing marks
509 // it inter-connected and the inter-connected loops below, which iterate
510 // CompileUnits alone, would never advance it.
511 assert(!Mod->isInterconnectedCU() && "module unit is inter-connected");
513 });
514
515 // Check for live relocations. If there is no any live relocation then we
516 // can skip entire object file.
517 if (!GlobalData.getOptions().UpdateIndexTablesOnly &&
518 !InputDWARFFile.Addresses->hasValidRelocs()) {
519 if (GlobalData.getOptions().Verbose)
520 outs() << "No valid relocations found. Skipping.\n";
521 return Error::success();
522 }
523
525
526 // Create CompileUnit structures to keep information about source
527 // DWARFUnit`s, load line tables.
528 uint64_t LocalCUIdx = 0;
529 for (const auto &OrigCU : InputDWARFFile.Dwarf->compile_units()) {
530 // Load only unit DIE at this stage.
531 auto CUDie = OrigCU->getUnitDIE();
532 std::string PCMFile = getPCMFile(
533 CUDie, GlobalData.getOptions().ObjectPrefixMap, InputDWARFFile);
534
535 // The !isClangModuleRef condition effectively skips over fully resolved
536 // skeleton units.
537 if (!CUDie || GlobalData.getOptions().UpdateIndexTablesOnly ||
538 !isClangModuleRef(CUDie, PCMFile, 0, true).first) {
539 CompileUnits.emplace_back(std::make_unique<CompileUnit>(
540 GlobalData, *OrigCU, UniqueUnitID.fetch_add(1), "", InputDWARFFile,
541 getUnitForOffset, OrigCU->getFormParams(), getEndianness()));
542 if (llvm::Error E =
543 CompileUnits.back()->setPriority(ObjectFileIdx, LocalCUIdx++))
544 return E;
545
546 // Preload line table, as it can't be loaded asynchronously.
547 CompileUnits.back()->loadLineTable();
548 }
549 };
550
552
553 // Link self-sufficient compile units and discover inter-connected compile
554 // units.
555 parallelForEach(CompileUnits, [&](std::unique_ptr<CompileUnit> &CU) {
557 });
558
559 // Link all inter-connected units.
562
563 if (Error Err = finiteLoop([&]() -> Expected<bool> {
565
566 // Load inter-connected units and find their live roots.
567 parallelForEach(CompileUnits, [&](std::unique_ptr<CompileUnit> &CU) {
568 if (CU->isInterconnectedCU()) {
569 CU->maybeResetToLoadedStage();
572 }
573 });
574
575 // Do liveness analysis for inter-connected units.
576 parallelForEach(CompileUnits, [&](std::unique_ptr<CompileUnit> &CU) {
579 });
580
581 return HasNewInterconnectedCUs.load();
582 }))
583 return Err;
584
585 // Update dependencies.
586 if (Error Err = finiteLoop([&]() -> Expected<bool> {
588 parallelForEach(CompileUnits, [&](std::unique_ptr<CompileUnit> &CU) {
592 });
593 return HasNewGlobalDependency.load();
594 }))
595 return Err;
596 parallelForEach(CompileUnits, [&](std::unique_ptr<CompileUnit> &CU) {
597 if (CU->isInterconnectedCU() &&
600 });
601
602 // Assign type names.
603 parallelForEach(CompileUnits, [&](std::unique_ptr<CompileUnit> &CU) {
606 });
607
608 // Clone inter-connected units.
609 parallelForEach(CompileUnits, [&](std::unique_ptr<CompileUnit> &CU) {
612 });
613
614 // Update patches for inter-connected units.
615 parallelForEach(CompileUnits, [&](std::unique_ptr<CompileUnit> &CU) {
618 });
619
620 // Release data.
621 parallelForEach(CompileUnits, [&](std::unique_ptr<CompileUnit> &CU) {
624 });
625 }
626
627 // The input is unloaded next, while the units are only placed once all the
628 // inputs are linked.
629 for (std::unique_ptr<CompileUnit> &CU : CompileUnits)
630 if (CU->getStage() != CompileUnit::Stage::Skipped)
631 CU->saveRelocations();
632
633 if (GlobalData.getOptions().UpdateIndexTablesOnly) {
634 // Emit Invariant sections.
635
636 if (Error Err = emitInvariantSections())
637 return Err;
638 }
639
640 return Error::success();
641}
642
645 enum CompileUnit::Stage DoUntilStage) {
646 if (InterCUProcessingStarted != CU.isInterconnectedCU())
647 return;
648
649 if (Error Err = finiteLoop([&]() -> Expected<bool> {
650 if (CU.getStage() >= DoUntilStage)
651 return false;
652
653 switch (CU.getStage()) {
655 // Load input compilation unit DIEs.
656 // Analyze properties of DIEs.
657 if (!CU.loadInputDIEs()) {
658 // We do not need to do liveness analysis for invalid compilation
659 // unit.
661 } else {
662 CU.analyzeDWARFStructure();
663
664 // The registerModuleReference() condition effectively skips
665 // over fully resolved skeleton units. This second pass of
666 // registerModuleReferences doesn't do any new work, but it
667 // will collect top-level errors, which are suppressed. Module
668 // warnings were already displayed in the first iteration.
669 //
670 // Runs concurrently, so it must stay a no-op: it may only be
671 // entered when the serial pass in addObjectFile() has already
672 // populated the module map.
673 if (!GlobalData.getOptions().UpdateIndexTablesOnly &&
675 CU.getOrigUnit().getUnitDIE(), nullptr,
676 [](const DWARFUnit &) {}, 0))
678 else
680 }
681 } break;
682
684 CU.collectLiveRoots();
686 break;
687
689 // Mark all the DIEs that need to be present in the generated output.
690 // If ODR requested, build type names.
691 if (!CU.resolveDependenciesAndMarkLiveness(InterCUProcessingStarted,
694 "Flag indicating new inter-connections is not set");
695 return false;
696 }
697
699 } break;
700
703 if (CU.updateDependenciesCompleteness())
705 return false;
706 } else {
707 if (Error Err = finiteLoop([&]() -> Expected<bool> {
708 return CU.updateDependenciesCompleteness();
709 }))
710 return std::move(Err);
711
713 }
714 } break;
715
717#ifndef NDEBUG
718 CU.verifyDependencies();
719#endif
720
721 if (ArtificialTypeUnit) {
722 if (Error Err =
723 CU.assignTypeNames(ArtificialTypeUnit->getTypePool()))
724 return std::move(Err);
725 }
727 break;
728
730 // Clone input compile unit.
731 if (CU.isClangModule() ||
732 GlobalData.getOptions().UpdateIndexTablesOnly ||
733 CU.getContainingFile().Addresses->hasValidRelocs()) {
734 if (Error Err = CU.cloneAndEmit(GlobalData.getTargetTriple(),
736 return std::move(Err);
737 }
738
740 break;
741
743 // Update DIEs referencies.
744 CU.updateDieRefPatchesWithClonedOffsets();
745
746 // Later than cloning, so that the offsets are final, and no later,
747 // because a unit which got this far can no longer be skipped and have
748 // its section dropped from the output.
749 if (CU.isClangModule())
750 CU.noteModuleAnchors();
751
753 break;
754
756 // Cleanup resources.
757 CU.cleanupDataAfterClonning();
759 break;
760
762 assert(false);
763 break;
764
766 // Nothing to do.
767 break;
768 }
769
770 return true;
771 })) {
772 CU.error(std::move(Err));
773 CU.cleanupDataAfterClonning();
775 }
776}
777
779 if (!GlobalData.getTargetTriple().has_value())
780 return Error::success();
781
783 << InputDWARFFile.Dwarf->getDWARFObj().getLocSection().Data;
785 << InputDWARFFile.Dwarf->getDWARFObj().getLoclistsSection().Data;
787 << InputDWARFFile.Dwarf->getDWARFObj().getRangesSection().Data;
789 << InputDWARFFile.Dwarf->getDWARFObj().getRnglistsSection().Data;
791 << InputDWARFFile.Dwarf->getDWARFObj().getArangesSection();
793 << InputDWARFFile.Dwarf->getDWARFObj().getFrameSection().Data;
795 << InputDWARFFile.Dwarf->getDWARFObj().getAddrSection().Data;
796
797 return Error::success();
798}
799
801 if (GlobalData.getOptions().UpdateIndexTablesOnly)
802 return Error::success();
803 if (!GlobalData.getTargetTriple().has_value())
804 return Error::success();
805
806 if (InputDWARFFile.Dwarf == nullptr)
807 return Error::success();
808 if (CompileUnits.empty())
809 return Error::success();
810
811 const DWARFObject &InputDWARFObj = InputDWARFFile.Dwarf->getDWARFObj();
812
813 StringRef OrigFrameData = InputDWARFObj.getFrameSection().Data;
814 if (OrigFrameData.empty())
815 return Error::success();
816
817 auto Scan = std::make_unique<FrameScanResult>();
818 Scan->FrameData = OrigFrameData;
819 Scan->AddressSize = InputDWARFObj.getAddressSize();
820
821 RangesTy AllUnitsRanges;
822 for (std::unique_ptr<CompileUnit> &Unit : CompileUnits) {
823 for (auto CurRange : Unit->getFunctionRanges())
824 AllUnitsRanges.insert(CurRange.Range, CurRange.Value);
825 }
826
827 StringRef FrameBytes = Scan->FrameData;
828 DataExtractor Data(FrameBytes, InputDWARFObj.isLittleEndian());
829 uint64_t InputOffset = 0;
830 const unsigned SrcAddrSize = Scan->AddressSize;
831 // Width of the CIE_pointer field at the start of every FDE (and of the
832 // CIE_id sentinel at the start of every CIE) in DWARF32 .debug_frame.
833 constexpr unsigned CIEPointerSize = 4;
834
835 // CIEs defined in this input, keyed by their input offsets.
837 DenseSet<uint64_t> AddedCIEs;
838
839 while (Data.isValidOffset(InputOffset)) {
840 uint64_t EntryOffset = InputOffset;
841 uint32_t InitialLength = Data.getU32(&InputOffset);
842 if (InitialLength == 0xFFFFFFFF)
843 return createFileError(InputDWARFFile.FileName,
844 createStringError(std::errc::invalid_argument,
845 "Dwarf64 bits not supported"));
846
847 // Reject lengths that don't fit in the input section. substr() saturates
848 // silently, which would otherwise let a malformed length poison the
849 // CIE bytes used as the registry key.
850 if (InitialLength > FrameBytes.size() - InputOffset)
851 return createFileError(
852 InputDWARFFile.FileName,
853 createStringError(std::errc::invalid_argument,
854 "Truncated .debug_frame entry."));
855
856 uint32_t CIEId = Data.getU32(&InputOffset);
857 if (CIEId == 0xFFFFFFFF) {
858 // This is a CIE, store it.
859 StringRef CIEData = FrameBytes.substr(EntryOffset, InitialLength + 4);
860 LocalCIEs[EntryOffset] = CIEData;
861 // The -4 is to account for the CIEId we just read.
862 InputOffset += InitialLength - 4;
863 continue;
864 }
865
866 uint64_t Loc = Data.getUnsigned(&InputOffset, SrcAddrSize);
867
868 // Some compilers seem to emit frame info that doesn't start at
869 // the function entry point, thus we can't just lookup the address
870 // in the debug map. Use the AddressInfo's range map to see if the FDE
871 // describes something that we can relocate.
872 std::optional<AddressRangeValuePair> Range =
873 AllUnitsRanges.getRangeThatContains(Loc);
874 if (!Range) {
875 // The +4 is to account for the size of the InitialLength field itself.
876 InputOffset = EntryOffset + InitialLength + 4;
877 continue;
878 }
879
880 // This is an FDE, and we have a mapping.
881 StringRef CIEData = LocalCIEs.lookup(CIEId);
882 if (CIEData.empty())
883 return createFileError(
884 InputDWARFFile.FileName,
885 createStringError(std::errc::invalid_argument,
886 "Inconsistent debug_frame content. Dropping."));
887
888 // Reject FDEs whose length doesn't even cover the CIE_pointer and
889 // initial_location fields; otherwise the unsigned subtraction below
890 // would wrap and substr() would saturate to a giant garbage blob.
891 if (InitialLength < CIEPointerSize + SrcAddrSize)
892 return createFileError(InputDWARFFile.FileName,
893 createStringError(std::errc::invalid_argument,
894 "Truncated .debug_frame FDE."));
895
896 // Promote each CIE on first reference; CIEs no FDE references are
897 // dropped from the output.
898 if (AddedCIEs.insert(CIEId).second)
899 Scan->CIEs.push_back(CIEData);
900
901 unsigned FDERemainingBytes = InitialLength - (CIEPointerSize + SrcAddrSize);
902 Scan->FDEs.push_back({CIEData, Loc + Range->Value,
903 FrameBytes.substr(InputOffset, FDERemainingBytes)});
904 InputOffset += FDERemainingBytes;
905 }
906
907 FrameScan = std::move(Scan);
908 return Error::success();
909}
910
912 assert(FrameScan && "registerCIEs called without FrameScan");
913 SectionDescriptor &OutSection =
915
916 uint32_t NextLocalOffset = 0;
917 for (StringRef CIEBytes : FrameScan->CIEs) {
918 auto [It, Inserted] =
919 CIEs.try_emplace(CIEBytes, CIELocation{&OutSection, NextLocalOffset});
920 if (Inserted) {
921 FrameScan->OwnedCIEs.push_back(CIEBytes);
922 NextLocalOffset += static_cast<uint32_t>(CIEBytes.size());
923 }
924 }
925}
926
928 assert(FrameScan && "emitDebugFrame called without FrameScan");
929 SectionDescriptor &OutSection =
931
932 // Emit owned CIEs at the offsets registerCIEs reserved for them.
933 for (StringRef CIEBytes : FrameScan->OwnedCIEs)
934 OutSection.OS << CIEBytes;
935
936 const dwarf::FormParams FP = OutSection.getFormParams();
937 const unsigned SrcAddrSize = FrameScan->AddressSize;
938
939 for (const FrameScanResult::FDE &FDE : FrameScan->FDEs) {
940 auto It = CIEs.find(FDE.CIEBytes);
941 assert(It != CIEs.end() && "CIE missing from registry");
942 SectionDescriptor *CIEOwnerSection = It->second.OwnerSection;
943 const uint32_t CIELocalOffset = It->second.LocalOffset;
944
945 const uint64_t FDEPos = OutSection.OS.tell();
946 // Note: this guards against a single context's section exceeding the
947 // DWARF32 limit. It does NOT catch the post-glue overflow that would
948 // happen if the concatenated .debug_frame across all contexts pushes
949 // past 4 GB; that case slips through silently because StartOffset is
950 // not yet assigned. A post-glue check would belong in the patch
951 // resolver in OutputSections.cpp.
952 if (FDEPos > FP.getDwarfMaxOffset())
953 return createFileError(
954 InputDWARFFile.FileName,
955 createStringError(".debug_frame section offset "
956 "0x" +
957 Twine::utohexstr(FDEPos) + " exceeds the " +
958 dwarf::FormatString(FP.Format) + " limit"));
959
960 // CIE_pointer field follows the 4-byte initial_length.
961 OutSection.notePatch(DebugOffsetPatch{FDEPos + 4, CIEOwnerSection, true});
962
963 emitFDE(CIELocalOffset, SrcAddrSize, FDE.Address, FDE.Instructions,
964 OutSection);
965 }
966
967 FrameScan.reset();
968 return Error::success();
969}
970
972 // Scan the input's .debug_frame now, while the DWARFContext is still
973 // loaded, so the later (post-pool) emission pass can run against the
974 // scan result alone.
975 Error ScanErr = scanFrameData();
976 InputDWARFFile.unload();
977 return ScanErr;
978}
979
980/// Emit a FDE into the debug_frame section. \p FDEBytes
981/// contains the FDE data without the length, CIE offset and address
982/// which will be replaced with the parameter values.
984 uint32_t AddrSize, uint64_t Address,
985 StringRef FDEBytes,
986 SectionDescriptor &Section) {
987 Section.emitIntVal(FDEBytes.size() + 4 + AddrSize, 4);
988 Section.emitIntVal(CIEOffset, 4);
989 Section.emitIntVal(Address, AddrSize);
990 Section.OS.write(FDEBytes.data(), FDEBytes.size());
991}
992
994 if (!GlobalData.getTargetTriple().has_value())
995 return;
997
998 // Go through all object files, all compile units and assign
999 // offsets to them.
1000 assignOffsets();
1001
1002 forEachCompileUnit([&](CompileUnit *CU) { CU->reportUnitOffsets(); });
1003
1004 // Patch size/offsets fields according to the assigned CU offsets.
1006
1007 // Emit common sections and write debug tables from all object files/compile
1008 // units into the resulting file.
1010
1011 if (ArtificialTypeUnit != nullptr)
1012 ArtificialTypeUnit.reset();
1013
1014 // Write common debug sections into the resulting file.
1016
1017 // Cleanup data.
1019
1020 if (GlobalData.getOptions().Statistics)
1022}
1023
1025
1026 // For each object file map how many bytes were emitted.
1027 StringMap<DebugInfoSize> SizeByObject;
1028
1029 for (const std::unique_ptr<LinkContext> &Context : ObjectContexts) {
1030 uint64_t AllDebugInfoSectionsSize = 0;
1031
1032 for (std::unique_ptr<CompileUnit> &CU : Context->CompileUnits)
1033 if (std::optional<SectionDescriptor *> DebugInfo =
1034 CU->tryGetSectionDescriptor(DebugSectionKind::DebugInfo))
1035 AllDebugInfoSectionsSize += (*DebugInfo)->getContents().size();
1036
1037 auto &Size = SizeByObject[Context->InputDWARFFile.FileName];
1038 Size.Input = Context->OriginalDebugInfoSize;
1039 Size.Output = AllDebugInfoSectionsSize;
1040 }
1041
1042 // Create a vector sorted in descending order by output size.
1043 std::vector<std::pair<StringRef, DebugInfoSize>> Sorted;
1044 for (auto &E : SizeByObject)
1045 Sorted.emplace_back(E.first(), E.second);
1046 llvm::sort(Sorted, [](auto &LHS, auto &RHS) {
1047 return LHS.second.Output > RHS.second.Output;
1048 });
1049
1050 auto ComputePercentange = [](int64_t Input, int64_t Output) -> float {
1051 const float Difference = Output - Input;
1052 const float Sum = Input + Output;
1053 if (Sum == 0)
1054 return 0;
1055 return (Difference / (Sum / 2));
1056 };
1057
1058 int64_t InputTotal = 0;
1059 int64_t OutputTotal = 0;
1060 const char *FormatStr = "{0,-45} {1,10}b {2,10}b {3,8:P}\n";
1061
1062 // Print header.
1063 outs() << ".debug_info section size (in bytes)\n";
1064 outs() << "----------------------------------------------------------------"
1065 "---------------\n";
1066 outs() << "Filename Object "
1067 " dSYM Change\n";
1068 outs() << "----------------------------------------------------------------"
1069 "---------------\n";
1070
1071 // Print body.
1072 for (auto &E : Sorted) {
1073 InputTotal += E.second.Input;
1074 OutputTotal += E.second.Output;
1075 llvm::outs() << formatv(
1076 FormatStr, sys::path::filename(E.first).take_back(45), E.second.Input,
1077 E.second.Output, ComputePercentange(E.second.Input, E.second.Output));
1078 }
1079 // Print total and footer.
1080 outs() << "----------------------------------------------------------------"
1081 "---------------\n";
1082 llvm::outs() << formatv(FormatStr, "Total", InputTotal, OutputTotal,
1083 ComputePercentange(InputTotal, OutputTotal));
1084 outs() << "----------------------------------------------------------------"
1085 "---------------\n\n";
1086}
1087
1090 TGroup.spawn([&]() { assignOffsetsToStrings(); });
1091 TGroup.spawn([&]() { assignOffsetsToSections(); });
1092}
1093
1095 size_t CurDebugStrIndex = 1; // start from 1 to take into account zero entry.
1096 uint64_t CurDebugStrOffset =
1097 1; // start from 1 to take into account zero entry.
1098 size_t CurDebugLineStrIndex = 0;
1099 uint64_t CurDebugLineStrOffset = 0;
1100
1101 // Enumerates all strings, add them into the DwarfStringPoolEntry map,
1102 // assign offset and index to the string if it is not indexed yet.
1104 const StringEntry *String) {
1105 switch (Kind) {
1108 assert(Entry != nullptr);
1109
1110 if (!Entry->isIndexed()) {
1111 Entry->Offset = CurDebugStrOffset;
1112 CurDebugStrOffset += Entry->String.size() + 1;
1113 Entry->Index = CurDebugStrIndex++;
1114 }
1115 } break;
1119 assert(Entry != nullptr);
1120
1121 if (!Entry->isIndexed()) {
1122 Entry->Offset = CurDebugLineStrOffset;
1123 CurDebugLineStrOffset += Entry->String.size() + 1;
1124 Entry->Index = CurDebugLineStrIndex++;
1125 }
1126 } break;
1127 }
1128 });
1129}
1130
1132 std::array<uint64_t, SectionKindsNum> SectionSizesAccumulator = {0};
1133
1134 forEachObjectSectionsSet([&](OutputSections &UnitSections) {
1135 UnitSections.assignSectionsOffsetAndAccumulateSize(SectionSizesAccumulator);
1136 });
1137}
1138
1141 StringHandler) {
1142 // To save space we do not create any separate string table.
1143 // We use already allocated string patches and accelerator entries:
1144 // enumerate them in natural order and assign offsets.
1145 // ASSUMPTION: strings should be stored into .debug_str/.debug_line_str
1146 // sections in the same order as they were assigned offsets.
1148 CU->forEach([&](SectionDescriptor &OutSection) {
1149 OutSection.ListDebugStrPatch.forEach([&](DebugStrPatch &Patch) {
1150 StringHandler(StringDestinationKind::DebugStr, Patch.String);
1151 });
1152
1153 OutSection.ListDebugLineStrPatch.forEach([&](DebugLineStrPatch &Patch) {
1154 StringHandler(StringDestinationKind::DebugLineStr, Patch.String);
1155 });
1156 });
1157
1158 CU->forEachAcceleratorRecord([&](DwarfUnit::AccelInfo &Info) {
1159 StringHandler(DebugStr, Info.String);
1160 });
1161 });
1162
1163 if (ArtificialTypeUnit != nullptr) {
1164 ArtificialTypeUnit->forEach([&](SectionDescriptor &OutSection) {
1165 OutSection.ListDebugStrPatch.forEach([&](DebugStrPatch &Patch) {
1166 StringHandler(StringDestinationKind::DebugStr, Patch.String);
1167 });
1168
1169 OutSection.ListDebugLineStrPatch.forEach([&](DebugLineStrPatch &Patch) {
1170 StringHandler(StringDestinationKind::DebugLineStr, Patch.String);
1171 });
1172
1173 OutSection.ListDebugTypeStrPatch.forEach([&](DebugTypeStrPatch &Patch) {
1174 if (Patch.Die == nullptr)
1175 return;
1176
1177 TypeEntryBody *TypeEntry = Patch.TypeName->getValue().load();
1178 if (&TypeEntry->getFinalDie() != Patch.Die)
1179 return;
1180
1181 StringHandler(StringDestinationKind::DebugStr, Patch.String);
1182 });
1183
1184 OutSection.ListDebugTypeLineStrPatch.forEach(
1185 [&](DebugTypeLineStrPatch &Patch) {
1186 if (Patch.Die == nullptr)
1187 return;
1188
1189 TypeEntryBody *TypeEntry = Patch.TypeName->getValue().load();
1190 if (&TypeEntry->getFinalDie() != Patch.Die)
1191 return;
1192
1193 StringHandler(StringDestinationKind::DebugStr, Patch.String);
1194 });
1195 });
1196 }
1197}
1198
1200 function_ref<void(OutputSections &)> SectionsSetHandler) {
1201 // Handle artificial type unit first.
1202 if (ArtificialTypeUnit != nullptr)
1203 SectionsSetHandler(*ArtificialTypeUnit);
1204
1205 // Then all modules(before regular compilation units).
1206 for (const std::unique_ptr<LinkContext> &Context : ObjectContexts)
1207 for (std::unique_ptr<CompileUnit> &ModuleUnit :
1208 Context->ModulesCompileUnits)
1209 if (ModuleUnit->getStage() != CompileUnit::Stage::Skipped)
1210 SectionsSetHandler(*ModuleUnit);
1211
1212 // Finally all compilation units.
1213 for (const std::unique_ptr<LinkContext> &Context : ObjectContexts) {
1214 // Handle object file common sections.
1215 SectionsSetHandler(*Context);
1216
1217 // Handle compilation units.
1218 for (std::unique_ptr<CompileUnit> &CU : Context->CompileUnits)
1219 if (CU->getStage() != CompileUnit::Stage::Skipped)
1220 SectionsSetHandler(*CU);
1221 }
1222}
1223
1225 function_ref<void(DwarfUnit *CU)> UnitHandler) {
1226 if (ArtificialTypeUnit != nullptr)
1227 UnitHandler(ArtificialTypeUnit.get());
1228
1229 // Enumerate module units.
1230 for (const std::unique_ptr<LinkContext> &Context : ObjectContexts)
1231 for (std::unique_ptr<CompileUnit> &ModuleUnit :
1232 Context->ModulesCompileUnits)
1233 if (ModuleUnit->getStage() != CompileUnit::Stage::Skipped)
1234 UnitHandler(ModuleUnit.get());
1235
1236 // Enumerate compile units.
1237 for (const std::unique_ptr<LinkContext> &Context : ObjectContexts)
1238 for (std::unique_ptr<CompileUnit> &CU : Context->CompileUnits)
1239 if (CU->getStage() != CompileUnit::Stage::Skipped)
1240 UnitHandler(CU.get());
1241}
1242
1244 function_ref<void(CompileUnit *CU)> UnitHandler) {
1245 // Enumerate module units.
1246 for (const std::unique_ptr<LinkContext> &Context : ObjectContexts)
1247 for (std::unique_ptr<CompileUnit> &ModuleUnit :
1248 Context->ModulesCompileUnits)
1249 if (ModuleUnit->getStage() != CompileUnit::Stage::Skipped)
1250 UnitHandler(ModuleUnit.get());
1251
1252 // Enumerate compile units.
1253 for (const std::unique_ptr<LinkContext> &Context : ObjectContexts)
1254 for (std::unique_ptr<CompileUnit> &CU : Context->CompileUnits)
1255 if (CU->getStage() != CompileUnit::Stage::Skipped)
1256 UnitHandler(CU.get());
1257}
1258
1260 forEachObjectSectionsSet([&](OutputSections &SectionsSet) {
1261 SectionsSet.forEach([&](SectionDescriptor &OutSection) {
1262 SectionsSet.applyPatches(OutSection, DebugStrStrings, DebugLineStrStrings,
1263 ArtificialTypeUnit.get());
1264 });
1265 });
1266}
1267
1270
1271 // Create section descriptors ahead if they are not exist at the moment.
1272 // SectionDescriptors container is not thread safe. Thus we should be sure
1273 // that descriptors would not be created in following parallel tasks.
1274
1275 CommonSections.getOrCreateSectionDescriptor(DebugSectionKind::DebugStr);
1276 CommonSections.getOrCreateSectionDescriptor(DebugSectionKind::DebugLineStr);
1277
1278 if (llvm::is_contained(GlobalData.Options.AccelTables,
1280 CommonSections.getOrCreateSectionDescriptor(DebugSectionKind::AppleNames);
1281 CommonSections.getOrCreateSectionDescriptor(
1283 CommonSections.getOrCreateSectionDescriptor(DebugSectionKind::AppleObjC);
1284 CommonSections.getOrCreateSectionDescriptor(DebugSectionKind::AppleTypes);
1285 }
1286
1287 if (llvm::is_contained(GlobalData.Options.AccelTables,
1289 CommonSections.getOrCreateSectionDescriptor(DebugSectionKind::DebugNames);
1290
1291 // Emit .debug_str and .debug_line_str sections.
1292 TG.spawn([&]() { emitStringSections(); });
1293
1294 if (llvm::is_contained(GlobalData.Options.AccelTables,
1296 // Emit apple accelerator sections.
1297 TG.spawn([&]() {
1298 emitAppleAcceleratorSections((*GlobalData.getTargetTriple()).get());
1299 });
1300 }
1301
1302 if (llvm::is_contained(GlobalData.Options.AccelTables,
1304 // Emit .debug_names section.
1305 TG.spawn([&]() {
1306 emitDWARFv5DebugNamesSection((*GlobalData.getTargetTriple()).get());
1307 });
1308 }
1309
1310 // Write compile units to the output file.
1311 TG.spawn([&]() { writeCompileUnitsToTheOutput(); });
1312}
1313
1315 uint64_t DebugStrNextOffset = 0;
1316 uint64_t DebugLineStrNextOffset = 0;
1317
1318 // Emit zero length string. Accelerator tables does not work correctly
1319 // if the first string is not zero length string.
1320 CommonSections.getSectionDescriptor(DebugSectionKind::DebugStr)
1321 .emitInplaceString("");
1322 DebugStrNextOffset++;
1323
1325 [&](StringDestinationKind Kind, const StringEntry *String) {
1326 switch (Kind) {
1328 DwarfStringPoolEntryWithExtString *StringToEmit =
1329 DebugStrStrings.getExistingEntry(String);
1330 assert(StringToEmit->isIndexed());
1331
1332 // Strings may be repeated. Use accumulated DebugStrNextOffset
1333 // to understand whether corresponding string is already emitted.
1334 // Skip string if its offset less than accumulated offset.
1335 if (StringToEmit->Offset >= DebugStrNextOffset) {
1336 DebugStrNextOffset =
1337 StringToEmit->Offset + StringToEmit->String.size() + 1;
1338 // Emit the string itself.
1339 CommonSections.getSectionDescriptor(DebugSectionKind::DebugStr)
1340 .emitInplaceString(StringToEmit->String);
1341 }
1342 } break;
1344 DwarfStringPoolEntryWithExtString *StringToEmit =
1345 DebugLineStrStrings.getExistingEntry(String);
1346 assert(StringToEmit->isIndexed());
1347
1348 // Strings may be repeated. Use accumulated DebugLineStrStrings
1349 // to understand whether corresponding string is already emitted.
1350 // Skip string if its offset less than accumulated offset.
1351 if (StringToEmit->Offset >= DebugLineStrNextOffset) {
1352 DebugLineStrNextOffset =
1353 StringToEmit->Offset + StringToEmit->String.size() + 1;
1354 // Emit the string itself.
1356 .emitInplaceString(StringToEmit->String);
1357 }
1358 } break;
1359 }
1360 });
1361}
1362
1368
1370 CU->forEachAcceleratorRecord([&](const DwarfUnit::AccelInfo &Info) {
1371 uint64_t OutOffset = Info.OutOffset;
1372 switch (Info.Type) {
1374 llvm_unreachable("Unknown accelerator record");
1375 } break;
1377 AppleNamespaces.addName(
1378 *DebugStrStrings.getExistingEntry(Info.String),
1379 CU->getSectionDescriptor(DebugSectionKind::DebugInfo).StartOffset +
1380 OutOffset);
1381 } break;
1383 AppleNames.addName(
1384 *DebugStrStrings.getExistingEntry(Info.String),
1385 CU->getSectionDescriptor(DebugSectionKind::DebugInfo).StartOffset +
1386 OutOffset);
1387 } break;
1389 AppleObjC.addName(
1390 *DebugStrStrings.getExistingEntry(Info.String),
1391 CU->getSectionDescriptor(DebugSectionKind::DebugInfo).StartOffset +
1392 OutOffset);
1393 } break;
1395 AppleTypes.addName(
1396 *DebugStrStrings.getExistingEntry(Info.String),
1397 CU->getSectionDescriptor(DebugSectionKind::DebugInfo).StartOffset +
1398 OutOffset,
1399 Info.Tag,
1400 Info.ObjcClassImplementation ? dwarf::DW_FLAG_type_implementation
1401 : 0,
1402 Info.QualifiedNameHash);
1403 } break;
1404 }
1405 });
1406 });
1407
1408 {
1409 // FIXME: we use AsmPrinter to emit accelerator sections.
1410 // It might be beneficial to directly emit accelerator data
1411 // to the raw_svector_ostream.
1412 SectionDescriptor &OutSection =
1415 OutSection.OS);
1416 if (Error Err = Emitter.init(TargetTriple, "__DWARF")) {
1417 consumeError(std::move(Err));
1418 return;
1419 }
1420
1421 // Emit table.
1422 Emitter.emitAppleNamespaces(AppleNamespaces);
1423 Emitter.finish();
1424
1425 // Set start offset and size for output section.
1427 }
1428
1429 {
1430 // FIXME: we use AsmPrinter to emit accelerator sections.
1431 // It might be beneficial to directly emit accelerator data
1432 // to the raw_svector_ostream.
1433 SectionDescriptor &OutSection =
1434 CommonSections.getSectionDescriptor(DebugSectionKind::AppleNames);
1436 OutSection.OS);
1437 if (Error Err = Emitter.init(TargetTriple, "__DWARF")) {
1438 consumeError(std::move(Err));
1439 return;
1440 }
1441
1442 // Emit table.
1443 Emitter.emitAppleNames(AppleNames);
1444 Emitter.finish();
1445
1446 // Set start offset ans size for output section.
1448 }
1449
1450 {
1451 // FIXME: we use AsmPrinter to emit accelerator sections.
1452 // It might be beneficial to directly emit accelerator data
1453 // to the raw_svector_ostream.
1454 SectionDescriptor &OutSection =
1455 CommonSections.getSectionDescriptor(DebugSectionKind::AppleObjC);
1457 OutSection.OS);
1458 if (Error Err = Emitter.init(TargetTriple, "__DWARF")) {
1459 consumeError(std::move(Err));
1460 return;
1461 }
1462
1463 // Emit table.
1464 Emitter.emitAppleObjc(AppleObjC);
1465 Emitter.finish();
1466
1467 // Set start offset ans size for output section.
1469 }
1470
1471 {
1472 // FIXME: we use AsmPrinter to emit accelerator sections.
1473 // It might be beneficial to directly emit accelerator data
1474 // to the raw_svector_ostream.
1475 SectionDescriptor &OutSection =
1476 CommonSections.getSectionDescriptor(DebugSectionKind::AppleTypes);
1478 OutSection.OS);
1479 if (Error Err = Emitter.init(TargetTriple, "__DWARF")) {
1480 consumeError(std::move(Err));
1481 return;
1482 }
1483
1484 // Emit table.
1485 Emitter.emitAppleTypes(AppleTypes);
1486 Emitter.finish();
1487
1488 // Set start offset ans size for output section.
1490 }
1491}
1492
1494 std::unique_ptr<DWARF5AccelTable> DebugNames;
1495
1496 DebugNamesUnitsOffsets CompUnits;
1497 CompUnitIDToIdx CUidToIdx;
1498
1499 unsigned Id = 0;
1500
1502 bool HasRecords = false;
1503 CU->forEachAcceleratorRecord([&](const DwarfUnit::AccelInfo &Info) {
1504 if (DebugNames == nullptr)
1505 DebugNames = std::make_unique<DWARF5AccelTable>();
1506
1507 HasRecords = true;
1508 switch (Info.Type) {
1512 DebugNames->addName(*DebugStrStrings.getExistingEntry(Info.String),
1513 Info.OutOffset, Info.ParentOffset, Info.Tag,
1514 CU->getUniqueID(),
1515 CU->getTag() == dwarf::DW_TAG_type_unit);
1516 } break;
1517
1518 default:
1519 break; // Nothing to do.
1520 };
1521 });
1522
1523 if (HasRecords) {
1524 CompUnits.push_back(
1525 CU->getOrCreateSectionDescriptor(DebugSectionKind::DebugInfo)
1526 .StartOffset);
1527 CUidToIdx[CU->getUniqueID()] = Id++;
1528 }
1529 });
1530
1531 if (DebugNames != nullptr) {
1532 // FIXME: we use AsmPrinter to emit accelerator sections.
1533 // It might be beneficial to directly emit accelerator data
1534 // to the raw_svector_ostream.
1535 SectionDescriptor &OutSection =
1536 CommonSections.getSectionDescriptor(DebugSectionKind::DebugNames);
1538 OutSection.OS);
1539 if (Error Err = Emitter.init(TargetTriple, "__DWARF")) {
1540 consumeError(std::move(Err));
1541 return;
1542 }
1543
1544 // Emit table.
1545 Emitter.emitDebugNames(*DebugNames, CompUnits, CUidToIdx);
1546 Emitter.finish();
1547
1548 // Set start offset ans size for output section.
1550 }
1551}
1552
1554 GlobalData.getStringPool().clear();
1555 DebugStrStrings.clear();
1556 DebugLineStrStrings.clear();
1557}
1558
1560 // Enumerate all sections and store them into the final emitter.
1562 Sections.forEach([&](std::shared_ptr<SectionDescriptor> OutSection) {
1563 // Emit section content.
1564 SectionHandler(OutSection);
1565 });
1566 });
1567}
1568
1570 CommonSections.forEach([&](std::shared_ptr<SectionDescriptor> OutSection) {
1571 SectionHandler(OutSection);
1572 });
1573}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
dxil container DXContainer Global Emitter
static fatal_error_handler_t ErrorHandler
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
The Input class is used to parse a yaml document into in-memory structs and vectors.
This class holds an abstract representation of an Accelerator Table, consisting of a sequence of buck...
Definition AccelTable.h:203
std::optional< T > getRangeThatContains(uint64_t Addr) const
void insert(AddressRange Range, int64_t Value)
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
Definition DWARFDie.h:43
LLVM_ABI std::optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
Definition DWARFDie.cpp:335
LLVM_ABI std::optional< uint64_t > getLanguage() const
Returns the DW_LANG_ code for this DIE's DWARF unit, if it exists.
Definition DWARFDie.cpp:506
virtual bool isLittleEndian() const =0
virtual const DWARFSection & getFrameSection() const
Definition DWARFObject.h:44
virtual uint8_t getAddressSize() const
Definition DWARFObject.h:35
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
iterator end()
Definition StringMap.h:214
iterator find(StringRef Key)
Definition StringMap.h:227
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Definition StringMap.h:370
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:589
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
A group of tasks to be run on a thread pool.
Definition ThreadPool.h:269
auto async(Function &&F, Args &&...ArgList)
Calls ThreadPool::async() for this group.
Definition ThreadPool.h:280
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static Twine utohexstr(uint64_t Val)
Definition Twine.h:385
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
This class represents DWARF information for source file and it's address map.
Definition DWARFFile.h:27
std::map< std::string, std::string > ObjectPrefixMapTy
function_ref< void(const DWARFUnit &Unit)> CompileUnitHandlerTy
std::function< void( const Twine &Warning, StringRef Context, const DWARFDie *DIE)> MessageHandlerTy
@ Apple
.apple_names, .apple_namespaces, .apple_types, .apple_objc.
std::map< std::string, std::string > SwiftInterfacesMapTy
std::function< ErrorOr< DWARFFile & >( StringRef ContainerName, StringRef Path)> ObjFileLoaderTy
Stores all information related to a compile unit, be it in its original instance of the object file o...
Stage
The stages of new compile unit processing.
@ LiveRootsCollected
DIEs with a live address are found.
@ CreatedNotLoaded
Created, linked with input DWARF file.
@ PatchesUpdated
Offsets inside patch records are updated.
@ Cleaned
Resources(Input DWARF, Output DWARF tree) are released.
@ LivenessAnalysisDone
Input DWARF is analysed(DIEs pointing to the real code section and theDIEs they depend on are marked)...
@ UpdateDependenciesCompleteness
Check if dependencies have incompatible placement.
void forEachObjectSectionsSet(function_ref< void(OutputSections &SectionsSet)> SectionsSetHandler)
Enumerates sections for modules, invariant for object files, compile units.
void emitDWARFv5DebugNamesSection(const Triple &TargetTriple)
Emit .debug_names section.
static constexpr uint64_t ModuleUnitObjFileIdx
The object file index given to every clang module unit.
void writeCompileUnitsToTheOutput()
Enumerate all compile units and put their data into the output stream.
void forEachCompileUnit(function_ref< void(CompileUnit *CU)> UnitHandler)
Enumerates all comple units.
void assignOffsetsToStrings()
Enumerate all compile units and assign offsets to their strings.
void assignOffsets()
Enumerate all compile units and assign offsets to their sections and strings.
Error link() override
Link debug info for added files.
Error validateAndUpdateOptions()
Validate specified options.
void writeCommonSectionsToTheOutput()
Enumerate common sections and put their data into the output stream.
void assignOffsetsToSections()
Enumerate all compile units and assign offsets to their sections.
void printStatistic()
Print statistic for processed Debug Info.
void glueCompileUnitsAndWriteToTheOutput()
Take already linked compile units and glue them into single file.
void emitAppleAcceleratorSections(const Triple &TargetTriple)
Emit apple accelerator sections.
void verifyInput(const DWARFFile &File)
Verify input DWARF file.
void forEachCompileAndTypeUnit(function_ref< void(DwarfUnit *CU)> UnitHandler)
Enumerates all compile and type units.
DWARFLinkerImpl(MessageHandlerTy ErrorHandler, MessageHandlerTy WarningHandler)
void addObjectFile(DWARFFile &File, ObjFileLoaderTy Loader=nullptr, CompileUnitHandlerTy OnCUDieLoaded=[](const DWARFUnit &) {}) override
Add object file to be linked.
void cleanupDataAfterDWARFOutputIsWritten()
Cleanup data(string pools) after output sections are generated.
void forEachOutputString(function_ref< void(StringDestinationKind, const StringEntry *)> StringHandler)
Enumerates all strings.
static constexpr uint64_t FirstObjFileIdx
Object file indices follow the module units'.
void emitCommonSectionsAndWriteCompileUnitsToTheOutput()
Emit debug sections common for all input files.
void patchOffsetsAndSizes()
Enumerates all patches and update them with the correct values.
This class emits DWARF data to the output stream.
Base class for all Dwarf units(Compile unit/Type table unit).
This class keeps data and services common for the whole linking process.
This class keeps contents and offsets to the debug sections.
void applyPatches(SectionDescriptor &Section, StringEntryToDwarfStringPoolEntryMap &DebugStrStrings, StringEntryToDwarfStringPoolEntryMap &DebugLineStrStrings, TypeUnit *TypeUnitPtr)
Enumerate all sections, for each section apply all section patches.
OutputSections(LinkingGlobalData &GlobalData)
void forEach(function_ref< void(SectionDescriptor &)> Handler)
Enumerate all sections and call Handler for each.
llvm::endianness getEndianness() const
Endiannes for the sections.
SectionDescriptor & getOrCreateSectionDescriptor(DebugSectionKind SectionKind)
Returns descriptor for the specified section of SectionKind.
void assignSectionsOffsetAndAccumulateSize(std::array< uint64_t, SectionKindsNum > &SectionSizesAccumulator)
Enumerate all sections, for each section set current offset (kept by SectionSizesAccumulator),...
const SectionDescriptor & getSectionDescriptor(DebugSectionKind SectionKind) const
Returns descriptor for the specified section of SectionKind.
Keeps cloned data for the type DIE.
Definition TypePool.h:76
Type Unit is used to represent an artificial compilation unit which keeps all type information.
An efficient, type-erasing, non-owning reference to a callable.
LLVM_ABI void spawn(std::function< void()> f)
Definition Parallel.cpp:244
uint64_t tell() const
tell - Return the current offset with the file.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
ThreadPoolInterface * ThreadPool
Thread pool that links the object files, or null to use a private pool.
std::atomic< size_t > UniqueUnitID
Unique ID for compile unit.
SmallVector< std::unique_ptr< LinkContext > > ObjectContexts
Keeps all linking contexts.
StringEntryToDwarfStringPoolEntryMap DebugLineStrStrings
DwarfStringPoolEntries for .debug_line_str section.
SectionHandlerTy SectionHandler
Hanler for output sections.
std::unique_ptr< TypeUnit > ArtificialTypeUnit
Type unit.
StringEntryToDwarfStringPoolEntryMap DebugStrStrings
DwarfStringPoolEntries for .debug_str section.
uint64_t ModuleUnitIdx
Numbers the clang module units of the whole link, so that they form one priority sequence regardless ...
OutputSections CommonSections
Common sections.
StringMap< uint64_t > ClangModules
Mapping the PCM filename to the DwoId.
LLVM_ABI StringRef FormatString(DwarfFormat Format)
Definition Dwarf.cpp:1065
void setEstimatedObjfilesAmount(unsigned ObjFilesNum) override
Set estimated objects files amount, for preliminary data allocation.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isODRLanguage(uint16_t Language)
std::vector< std::variant< MCSymbol *, uint64_t > > DebugNamesUnitsOffsets
DenseMap< unsigned, unsigned > CompUnitIDToIdx
StringMapEntry< std::atomic< TypeEntryBody * > > TypeEntry
Definition TypePool.h:31
StringMapEntry< EmptyStringSetTag > StringEntry
StringEntry keeps data of the string: the length, external offset and a string body which is placed r...
Definition StringPool.h:23
Error finiteLoop(function_ref< Expected< bool >()> Iteration, size_t MaxCounter=100000)
This function calls Iteration() until it returns false.
Definition Utils.h:76
AddressRangesMap RangesTy
Mapped value in the address map is the offset to apply to the linked address.
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
@ DWARF32
Definition Dwarf.h:93
StringRef toStringRef(const std::optional< DWARFFormValue > &V, StringRef Default={})
Take an optional DWARFFormValue and try to extract a string value from it.
@ DW_FLAG_type_implementation
Definition Dwarf.h:1056
std::optional< uint64_t > toUnsigned(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an unsigned constant.
LLVM_ABI ThreadPoolStrategy strategy
Definition Parallel.cpp:27
LLVM_ABI bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
Definition Path.cpp:716
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
LLVM_ABI bool replace_path_prefix(SmallVectorImpl< char > &Path, StringRef OldPrefix, StringRef NewPrefix, Style style=Style::native)
Replace matching path prefix with another path.
Definition Path.cpp:529
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
This is an optimization pass for GlobalISel generic memory operations.
ThreadPoolStrategy hardware_concurrency(unsigned ThreadCount=0)
Returns a default thread strategy where all available hardware resources are to be used,...
Definition Threading.h:190
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1415
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
static std::string getPCMFile(const DWARFDie &CUDie, const DWARFLinkerBase::ObjectPrefixMapTy *ObjectPrefixMap, const DWARFFile &File)
static std::string remapPath(StringRef Path, const DWARFLinkerBase::ObjectPrefixMapTy &ObjectPrefixMap)
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
static uint64_t getDwoId(const DWARFDie &CUDie)
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
void call_once(once_flag &flag, Function &&F, Args &&... ArgList)
Execute the function specified as a parameter once.
Definition Threading.h:86
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
static void resolveRelativeObjectPath(SmallVectorImpl< char > &Buf, DWARFDie CU, const DWARFFile &File)
Resolve the relative path to a build artifact referenced by DWARF of File by applying DW_AT_comp_dir.
void parallelForEach(IterTy Begin, IterTy End, FuncTy Fn)
Definition Parallel.h:209
endianness
Definition bit.h:71
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
Container for dump options that control which debug information will be dumped.
Definition DIContext.h:197
DIDumpOptions noImplicitRecursion() const
Return the options with RecurseDepth set to 0 unless explicitly required.
Definition DIContext.h:238
unsigned ChildRecurseDepth
Definition DIContext.h:199
DwarfStringPoolEntry with string keeping externally.
A helper struct providing information about the byte size of DW_FORM values that vary in size dependi...
Definition Dwarf.h:1221
Section + local offset of a .debug_frame CIE that has been (or will be) emitted by some LinkContext.
uint64_t getInputDebugInfoSize() const
Computes the total size of the debug info.
bool InterCUProcessingStarted
Flag indicating that all inter-connected units are loaded and the dwarf linking process for these uni...
bool registerModuleReference(const DWARFDie &CUDie, ObjFileLoaderTy Loader, CompileUnitHandlerTy OnCUDieLoaded, unsigned Indent=0)
If this compile unit is really a skeleton CU that points to a clang module, register it in ClangModul...
Error loadClangModule(ObjFileLoaderTy Loader, const DWARFDie &CUDie, const std::string &PCMFile, CompileUnitHandlerTy OnCUDieLoaded, unsigned Indent=0)
Recursively add the debug info in this clang module .pcm file (and all the modules imported by it in ...
LinkContext(LinkingGlobalData &GlobalData, DWARFFile &File, uint64_t ObjFileIdx, StringMap< uint64_t > &ClangModules, uint64_t &ModuleUnitIdx, std::atomic< size_t > &UniqueUnitID)
Error scanFrameData()
Parse this context's input .debug_frame into FrameScan.
uint64_t OriginalDebugInfoSize
Size of Debug info before optimizing.
std::pair< bool, bool > isClangModuleRef(const DWARFDie &CUDie, std::string &PCMFile, unsigned Indent, bool Quiet)
Check whether specified CUDie is a Clang module reference.
void emitFDE(uint32_t CIEOffset, uint32_t AddrSize, uint64_t Address, StringRef FDEBytes, SectionDescriptor &Section)
Emit FDE record.
UnitListTy CompileUnits
Set of Compilation Units(may be accessed asynchroniously for reading).
void linkSingleCompileUnit(CompileUnit &CU, TypeUnit *ArtificialTypeUnit, enum CompileUnit::Stage DoUntilStage=CompileUnit::Stage::Cleaned)
Link specified compile unit until specified stage.
UnitListTy ModulesCompileUnits
Set of Compile Units for modules.
void registerCIEs(CIERegistry &CIEs)
Register this context's CIEs with the linker-wide registry.
std::atomic< bool > HasNewInterconnectedCUs
Flag indicating that new inter-connected compilation units were discovered.
Error emitDebugFrame(const CIERegistry &CIEs)
Emit this context's .debug_frame section.
std::atomic< size_t > & UniqueUnitID
Counter for compile units ID.
Error link(TypeUnit *ArtificialTypeUnit)
Link compile units for this context.
StringMap< CIELocation > CIERegistry
Linker-wide registry for .debug_frame CIEs.
Error unloadInput()
Unload the input DWARFContext after scanning the input .debug_frame into FrameScan.
uint64_t ObjectFileIdx
Index of this object file in the link order (used for deterministic type DIE allocation).
std::function< CompileUnit *(uint64_t)> getUnitForOffset
This structure is used to update strings offsets into .debug_line_str.
This structure is used to update strings offsets into .debug_str.
This structure keeps fields which would be used for creating accelerator table.
dwarf::FormParams getFormParams() const
Returns FormParams used by section.
This structure is used to keep data of the concrete section.
raw_svector_ostream OS
Stream which stores data to the Contents.
void setSizesForSectionCreatedByAsmPrinter()
Some sections are emitted using AsmPrinter.
The llvm::once_flag structure.
Definition Threading.h:67