LLVM 18.0.0git
DWARFLinkerImpl.h
Go to the documentation of this file.
1//===- DWARFLinkerImpl.h ----------------------------------------*- C++ -*-===//
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#ifndef LLVM_LIB_DWARFLINKERPARALLEL_DWARFLINKERIMPL_H
10#define LLVM_LIB_DWARFLINKERPARALLEL_DWARFLINKERIMPL_H
11
12#include "DWARFEmitterImpl.h"
19
20namespace llvm {
21namespace dwarflinker_parallel {
22
23/// This class links debug info.
25public:
27 MessageHandlerTy WarningHandler,
28 TranslatorFuncTy StringsTranslator)
31 GlobalData.setTranslator(StringsTranslator);
33 GlobalData.setWarningHandler(WarningHandler);
34 }
35
36 /// Create debug info emitter.
37 Error createEmitter(const Triple &TheTriple, OutputFileType FileType,
38 raw_pwrite_stream &OutFile) override;
39
40 ExtraDwarfEmitter *getEmitter() override;
41
42 /// Add object file to be linked. Pre-load compile unit die. Call
43 /// \p OnCUDieLoaded for each compile unit die. If specified \p File
44 /// has reference to the Clang module then such module would be
45 /// pre-loaded by \p Loader for !Update case.
46 ///
47 /// \pre NoODR, Update options should be set before call to addObjectFile.
48 void addObjectFile(
49 DWARFFile &File, ObjFileLoaderTy Loader = nullptr,
50
51 CompileUnitHandlerTy OnCUDieLoaded = [](const DWARFUnit &) {}) override;
52
53 /// Link debug info for added files.
54 Error link() override;
55
56 /// \defgroup Methods setting various linking options:
57 ///
58 /// @{
59 ///
60
61 /// Allows to generate log of linking process to the standard output.
62 void setVerbosity(bool Verbose) override {
64 }
65
66 /// Print statistics to standard output.
67 void setStatistics(bool Statistics) override {
68 GlobalData.Options.Statistics = Statistics;
69 }
70
71 /// Verify the input DWARF.
72 void setVerifyInputDWARF(bool Verify) override {
74 }
75
76 /// Do not unique types according to ODR.
77 void setNoODR(bool) override {
78 // FIXME: set option when ODR mode will be supported.
79 // getOptions().NoODR = NoODR;
81 }
82
83 /// Update index tables only(do not modify rest of DWARF).
84 void setUpdateIndexTablesOnly(bool UpdateIndexTablesOnly) override {
85 GlobalData.Options.UpdateIndexTablesOnly = UpdateIndexTablesOnly;
86 }
87
88 /// Allow generating valid, but non-deterministic output.
89 void
90 setAllowNonDeterministicOutput(bool AllowNonDeterministicOutput) override {
92 AllowNonDeterministicOutput;
93 }
94
95 /// Set to keep the enclosing function for a static variable.
96 void setKeepFunctionForStatic(bool KeepFunctionForStatic) override {
97 GlobalData.Options.KeepFunctionForStatic = KeepFunctionForStatic;
98 }
99
100 /// Use specified number of threads for parallel files linking.
101 void setNumThreads(unsigned NumThreads) override {
102 GlobalData.Options.Threads = NumThreads;
103 }
104
105 /// Add kind of accelerator tables to be generated.
106 void addAccelTableKind(AccelTableKind Kind) override {
109 }
110
111 /// Set prepend path for clang modules.
112 void setPrependPath(const std::string &Ppath) override {
114 }
115
116 /// Set estimated objects files amount, for preliminary data allocation.
117 void setEstimatedObjfilesAmount(unsigned ObjFilesNum) override {
118 ObjectContexts.reserve(ObjFilesNum);
119 }
120
121 /// Set verification handler which would be used to report verification
122 /// errors.
123 void
126 }
127
128 /// Set map for Swift interfaces.
131 }
132
133 /// Set prefix map for objects.
136 }
137
138 /// Set target DWARF version.
139 Error setTargetDWARFVersion(uint16_t TargetDWARFVersion) override {
140 if ((TargetDWARFVersion < 1) || (TargetDWARFVersion > 5))
141 return createStringError(std::errc::invalid_argument,
142 "unsupported DWARF version: %d",
143 TargetDWARFVersion);
144
145 GlobalData.Options.TargetDWARFVersion = TargetDWARFVersion;
146 return Error::success();
147 }
148 /// @}
149
150protected:
151 /// Verify input DWARF file.
152 void verifyInput(const DWARFFile &File);
153
154 /// Validate specified options.
156
157 /// Take already linked compile units and glue them into single file.
159
160 /// Hold the input and output of the debug info size in bytes.
164 };
165
166 friend class DependencyTracker;
167 /// Keeps track of data associated with one object during linking.
168 /// i.e. source file descriptor, compilation units, output data
169 /// for compilation units common tables.
170 struct LinkContext : public OutputSections {
172
173 /// Keep information for referenced clang module: already loaded DWARF info
174 /// of the clang module and a CompileUnit of the module.
176 RefModuleUnit(DWARFFile &File, std::unique_ptr<CompileUnit> Unit)
177 : File(File), Unit(std::move(Unit)) {}
179 : File(Other.File), Unit(std::move(Other.Unit)) {}
180 RefModuleUnit(const RefModuleUnit &) = delete;
181
183 std::unique_ptr<CompileUnit> Unit;
184 };
186
187 /// Object file descriptor.
189
190 /// Set of Compilation Units(may be accessed asynchroniously for reading).
192
193 /// Set of Compile Units for modules.
195
196 /// Size of Debug info before optimizing.
198
199 /// Flag indicating that all inter-connected units are loaded
200 /// and the dwarf linking process for these units is started.
202
204
205 std::optional<Triple> TargetTriple;
206
207 /// Flag indicating that new inter-connected compilation units were
208 /// discovered. It is used for restarting units processing
209 /// if new inter-connected units were found.
210 std::atomic<bool> HasNewInterconnectedCUs = {false};
211
212 /// Counter for compile units ID.
213 std::atomic<size_t> &UniqueUnitID;
214
217 std::atomic<size_t> &UniqueUnitID,
218 std::optional<Triple> TargetTriple)
222
223 if (File.Dwarf) {
224 if (!File.Dwarf->compile_units().empty())
225 CompileUnits.reserve(File.Dwarf->getNumCompileUnits());
226
227 // Set context format&endianness based on the input file.
228 Format.Version = File.Dwarf->getMaxVersion();
229 Format.AddrSize = File.Dwarf->getCUAddrSize();
230 Endianness = File.Dwarf->isLittleEndian() ? support::endianness::little
231 : support::endianness::big;
232 }
233 }
234
235 /// Check whether specified \p CUDie is a Clang module reference.
236 /// if \p Quiet is false then display error messages.
237 /// \return first == true if CUDie is a Clang module reference.
238 /// second == true if module is already loaded.
239 std::pair<bool, bool> isClangModuleRef(const DWARFDie &CUDie,
240 std::string &PCMFile,
241 unsigned Indent, bool Quiet);
242
243 /// If this compile unit is really a skeleton CU that points to a
244 /// clang module, register it in ClangModules and return true.
245 ///
246 /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
247 /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
248 /// hash.
249 bool registerModuleReference(const DWARFDie &CUDie, ObjFileLoaderTy Loader,
250 CompileUnitHandlerTy OnCUDieLoaded,
251 unsigned Indent = 0);
252
253 /// Recursively add the debug info in this clang module .pcm
254 /// file (and all the modules imported by it in a bottom-up fashion)
255 /// to ModuleUnits.
256 Error loadClangModule(ObjFileLoaderTy Loader, const DWARFDie &CUDie,
257 const std::string &PCMFile,
258 CompileUnitHandlerTy OnCUDieLoaded,
259 unsigned Indent = 0);
260
261 /// Add Compile Unit corresponding to the module.
263 ModulesCompileUnits.emplace_back(std::move(Unit));
264 }
265
266 /// Computes the total size of the debug info.
268 uint64_t Size = 0;
269
270 if (InputDWARFFile.Dwarf == nullptr)
271 return Size;
272
273 for (auto &Unit : InputDWARFFile.Dwarf->compile_units())
274 Size += Unit->getLength();
275
276 return Size;
277 }
278
279 /// Link compile units for this context.
280 Error link();
281
282 /// Link specified compile unit until specified stage.
286
287 /// Emit invariant sections.
289
290 /// Clone and emit .debug_frame.
292
293 /// Emit FDE record.
294 void emitFDE(uint32_t CIEOffset, uint32_t AddrSize, uint64_t Address,
295 StringRef FDEBytes, SectionDescriptor &Section);
296
298 [&](uint64_t Offset) -> CompileUnit * {
299 auto CU = llvm::upper_bound(
301 [](uint64_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
302 return LHS < RHS->getOrigUnit().getNextUnitOffset();
303 });
304
305 return CU != CompileUnits.end() ? CU->get() : nullptr;
306 };
307 };
308
309 /// Enumerate all compile units and assign offsets to their sections and
310 /// strings.
311 void assignOffsets();
312
313 /// Enumerate all compile units and assign offsets to their sections.
315
316 /// Enumerate all compile units and assign offsets to their strings.
318
319 /// Enumerates specified string patches, assigns offset and index.
320 template <typename PatchTy>
322 ArrayList<PatchTy> &Section, size_t &IndexAccumulator,
323 uint64_t &OffsetAccumulator,
324 StringEntryToDwarfStringPoolEntryMap &StringsForEmission);
325
326 /// Print statistic for processed Debug Info.
327 void printStatistic();
328
329 /// Enumerates sections for modules, invariant for object files, compile
330 /// units.
332 function_ref<void(OutputSections &SectionsSet)> SectionsSetHandler);
333
334 /// Enumerates all patches and update them with the correct values.
336
337 /// Emit debug sections common for all input files.
338 void emitCommonSections();
339
340 /// Cleanup data(string pools) after output sections are generated.
342
343 /// Enumerate all compile units and put their data into the output stream.
345
346 template <typename PatchTy>
347 void emitStringsImpl(ArrayList<PatchTy> &StringPatches,
349 uint64_t &NextOffset, SectionDescriptor &OutSection);
350
351 /// \defgroup Data members accessed asinchroniously.
352 ///
353 /// @{
354
355 /// Unique ID for compile unit.
356 std::atomic<size_t> UniqueUnitID;
357
358 /// Mapping the PCM filename to the DwoId.
361 /// @}
362
363 /// \defgroup Data members accessed sequentially.
364 ///
365 /// @{
366 /// DwarfStringPoolEntries for .debug_str section.
368
369 /// DwarfStringPoolEntries for .debug_line_str section.
371
372 /// Keeps all linking contexts.
374
375 /// Common sections.
377
378 /// The emitter of final dwarf file.
379 std::unique_ptr<DwarfEmitterImpl> TheDwarfEmitter;
380
381 /// Overall compile units number.
383
384 /// Data global for the whole linking process.
386 /// @}
387};
388
389} // end namespace dwarflinker_parallel
390} // end namespace llvm
391
392#endif // LLVM_LIB_DWARFLINKERPARALLEL_DWARFLINKERIMPL_H
This file contains support for writing accelerator tables.
uint64_t Size
static fatal_error_handler_t ErrorHandler
ppc ctr loops PowerPC CTR Loops Verify
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Value * RHS
Value * LHS
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
Definition: DWARFDie.h:42
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:941
void reserve(size_type N)
Definition: SmallVector.h:667
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:112
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
This class is a simple list of T structures.
Definition: ArrayList.h:21
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.
@ Cleaned
Resources(Input DWARF, Output DWARF tree) are released.
This class represents DWARF information for source file and it's address map.
Definition: DWARFFile.h:26
std::unique_ptr< DWARFContext > Dwarf
Source DWARF information.
Definition: DWARFFile.h:38
void writeDWARFToTheOutput()
Enumerate all compile units and put their data into the output stream.
void glueCompileUnitsAndWriteToTheOutput()
Take already linked compile units and glue them into single file.
void verifyInput(const DWARFFile &File)
Verify input DWARF file.
void emitCommonSections()
Emit debug sections common for all input files.
void cleanupDataAfterOutputSectionsAreGenerated()
Cleanup data(string pools) after output sections are generated.
void addObjectFile(DWARFFile &File, ObjFileLoaderTy Loader=nullptr, CompileUnitHandlerTy OnCUDieLoaded=[](const DWARFUnit &) {}) override
Add object file to be linked.
void printStatistic()
Print statistic for processed Debug Info.
void emitStringsImpl(ArrayList< PatchTy > &StringPatches, const StringEntryToDwarfStringPoolEntryMap &Strings, uint64_t &NextOffset, SectionDescriptor &OutSection)
void forEachObjectSectionsSet(function_ref< void(OutputSections &SectionsSet)> SectionsSetHandler)
Enumerates sections for modules, invariant for object files, compile units.
Error createEmitter(const Triple &TheTriple, OutputFileType FileType, raw_pwrite_stream &OutFile) override
Create debug info emitter.
void assignOffsetsToStringsImpl(ArrayList< PatchTy > &Section, size_t &IndexAccumulator, uint64_t &OffsetAccumulator, StringEntryToDwarfStringPoolEntryMap &StringsForEmission)
Enumerates specified string patches, assigns offset and index.
ExtraDwarfEmitter * getEmitter() override
Returns previously created dwarf emitter. May be nullptr.
Error link() override
Link debug info for added files.
void assignOffsetsToSections()
Enumerate all compile units and assign offsets to their sections.
Error validateAndUpdateOptions()
Validate specified options.
DWARFLinkerImpl(MessageHandlerTy ErrorHandler, MessageHandlerTy WarningHandler, TranslatorFuncTy StringsTranslator)
void assignOffsets()
Enumerate all compile units and assign offsets to their sections and strings.
void patchOffsetsAndSizes()
Enumerates all patches and update them with the correct values.
void assignOffsetsToStrings()
Enumerate all compile units and assign offsets to their strings.
std::function< void(const DWARFFile &File, llvm::StringRef Output)> InputVerificationHandlerTy
Definition: DWARFLinker.h:137
std::map< std::string, std::string > SwiftInterfacesMapTy
Definition: DWARFLinker.h:141
std::function< ErrorOr< DWARFFile & >(StringRef ContainerName, StringRef Path)> ObjFileLoaderTy
Definition: DWARFLinker.h:136
std::function< void(const Twine &Warning, StringRef Context, const DWARFDie *DIE)> MessageHandlerTy
Definition: DWARFLinker.h:134
std::map< std::string, std::string > ObjectPrefixMapTy
Definition: DWARFLinker.h:138
std::function< StringRef(StringRef)> TranslatorFuncTy
Definition: DWARFLinker.h:140
function_ref< void(const DWARFUnit &Unit)> CompileUnitHandlerTy
Definition: DWARFLinker.h:139
This class discovers DIEs dependencies and marks "live" DIEs.
ExtraDwarfEmitter allows adding extra data to the DWARFLinker output.
Definition: DWARFLinker.h:93
This class keeps data and services common for the whole linking process.
void setWarningHandler(MessageHandlerTy Handler)
Set warning handler.
const DWARFLinkerOptions & getOptions() const
Returns linking options.
void setTranslator(TranslatorFuncTy Translator)
Set translation function.
void setErrorHandler(MessageHandlerTy Handler)
Set error handler.
This class keeps contents and offsets to the debug sections.
support::endianness Endianness
Endiannes for sections.
dwarf::FormParams Format
Format for sections.
This class creates a DwarfStringPoolEntry for the corresponding StringEntry.
An efficient, type-erasing, non-owning reference to a callable.
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:428
std::atomic< size_t > UniqueUnitID
Unique ID for compile unit.
OutputSections CommonSections
Common sections.
std::unique_ptr< DwarfEmitterImpl > TheDwarfEmitter
The emitter of final dwarf file.
uint64_t OverallNumberOfCU
Overall compile units number.
StringEntryToDwarfStringPoolEntryMap DebugLineStrStrings
DwarfStringPoolEntries for .debug_line_str section.
SmallVector< std::unique_ptr< LinkContext > > ObjectContexts
Keeps all linking contexts.
LinkingGlobalData GlobalData
Data global for the whole linking process.
StringEntryToDwarfStringPoolEntryMap DebugStrStrings
StringMap< uint64_t > ClangModules
Mapping the PCM filename to the DwoId.
void setNoODR(bool) override
Do not unique types according to ODR.
void setEstimatedObjfilesAmount(unsigned ObjFilesNum) override
Set estimated objects files amount, for preliminary data allocation.
void setSwiftInterfacesMap(SwiftInterfacesMapTy *Map) override
Set map for Swift interfaces.
void setUpdateIndexTablesOnly(bool UpdateIndexTablesOnly) override
Update index tables only(do not modify rest of DWARF).
void setVerifyInputDWARF(bool Verify) override
Verify the input DWARF.
void setInputVerificationHandler(InputVerificationHandlerTy Handler) override
Set verification handler which would be used to report verification errors.
void setVerbosity(bool Verbose) override
Allows to generate log of linking process to the standard output.
void setAllowNonDeterministicOutput(bool AllowNonDeterministicOutput) override
Allow generating valid, but non-deterministic output.
void addAccelTableKind(AccelTableKind Kind) override
Add kind of accelerator tables to be generated.
void setStatistics(bool Statistics) override
Print statistics to standard output.
void setNumThreads(unsigned NumThreads) override
Use specified number of threads for parallel files linking.
void setPrependPath(const std::string &Ppath) override
Set prepend path for clang modules.
void setKeepFunctionForStatic(bool KeepFunctionForStatic) override
Set to keep the enclosing function for a static variable.
void setObjectPrefixMap(ObjectPrefixMapTy *Map) override
Set prefix map for objects.
Error setTargetDWARFVersion(uint16_t TargetDWARFVersion) override
Set target DWARF version.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:440
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1959
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1244
AccelTableKind
The kind of accelerator tables we should emit.
Definition: DwarfDebug.h:339
@ Other
Any other memory.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1854
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1884
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
Hold the input and output of the debug info size in bytes.
Keep information for referenced clang module: already loaded DWARF info of the clang module and a Com...
RefModuleUnit(DWARFFile &File, std::unique_ptr< CompileUnit > Unit)
Keeps track of data associated with one object during linking.
UnitListTy CompileUnits
Set of Compilation Units(may be accessed asynchroniously for reading).
Error link()
Link compile units for this context.
ModuleUnitListTy ModulesCompileUnits
Set of Compile Units for modules.
void emitFDE(uint32_t CIEOffset, uint32_t AddrSize, uint64_t Address, StringRef FDEBytes, SectionDescriptor &Section)
Emit FDE record.
LinkContext(LinkingGlobalData &GlobalData, DWARFFile &File, StringMap< uint64_t > &ClangModules, std::atomic< size_t > &UniqueUnitID, std::optional< Triple > TargetTriple)
bool InterCUProcessingStarted
Flag indicating that all inter-connected units are loaded and the dwarf linking process for these uni...
uint64_t getInputDebugInfoSize() const
Computes the total size of the debug info.
Error cloneAndEmitDebugFrame()
Clone and emit .debug_frame.
void addModulesCompileUnit(RefModuleUnit &&Unit)
Add Compile Unit corresponding to the module.
std::atomic< size_t > & UniqueUnitID
Counter for compile units ID.
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 ...
void linkSingleCompileUnit(CompileUnit &CU, enum CompileUnit::Stage DoUntilStage=CompileUnit::Stage::Cleaned)
Link specified compile unit until specified stage.
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...
uint64_t OriginalDebugInfoSize
Size of Debug info before optimizing.
std::atomic< bool > HasNewInterconnectedCUs
Flag indicating that new inter-connected compilation units were discovered.
std::function< CompileUnit *(uint64_t)> getUnitForOffset
std::pair< bool, bool > isClangModuleRef(const DWARFDie &CUDie, std::string &PCMFile, unsigned Indent, bool Quiet)
Check whether specified CUDie is a Clang module reference.
uint16_t TargetDWARFVersion
DWARF version for the output.
std::string PrependPath
Prepend path for the clang modules.
bool Verbose
Generate processing log to the standard output.
bool KeepFunctionForStatic
Whether we want a static variable to force us to keep its enclosing function.
SmallVector< DWARFLinker::AccelTableKind, 1 > AccelTables
The accelerator table kinds.
bool AllowNonDeterministicOutput
Allow to generate valid, but non deterministic output.
bool NoODR
Do not unique types according to ODR.
DWARFLinker::InputVerificationHandlerTy InputVerificationHandler
input verification handler(it might be called asynchronously).
DWARFLinker::SwiftInterfacesMapTy * ParseableSwiftInterfaces
A list of all .swiftinterface files referenced by the debug info, mapping Module name to path on disk...
DWARFLinker::ObjectPrefixMapTy * ObjectPrefixMap
A list of remappings to apply to file paths.
This structure is used to keep data of the concrete section.