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