1//=== DWARFLinkerCompileUnit.cpp ------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "DWARFLinkerCompileUnit.h"
10#include "AcceleratorRecordsSaver.h"
11#include "DIEAttributeCloner.h"
12#include "DIEGenerator.h"
13#include "DependencyTracker.h"
14#include "SyntheticTypeNameBuilder.h"
15#include "llvm/DWARFLinker/Utils.h"
16#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
17#include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h"
18#include "llvm/Support/FileSystem.h"
19#include "llvm/Support/FormatVariadic.h"
20#include "llvm/Support/Path.h"
21#include <utility>
22
23using namespace llvm;
24using namespace dwarf_linker;
25using namespace dwarf_linker::parallel;
26
27CompileUnit::CompileUnit(LinkingGlobalData &GlobalData, unsigned ID,
28 StringRef ClangModuleName, DWARFFile &File,
29 OffsetToUnitTy UnitFromOffset,
30 dwarf::FormParams Format, llvm::endianness Endianess)
31 : DwarfUnit(GlobalData, ID, ClangModuleName), File(File),
32 getUnitFromOffset(UnitFromOffset), Stage(Stage::CreatedNotLoaded),
33 AcceleratorRecords(&GlobalData.getAllocator()) {
34 UnitName = File.FileName;
35 setOutputFormat(Format, Endianness: Endianess);
36 getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugInfo);
37}
38
39CompileUnit::CompileUnit(LinkingGlobalData &GlobalData, DWARFUnit &OrigUnit,
40 unsigned ID, StringRef ClangModuleName,
41 DWARFFile &File, OffsetToUnitTy UnitFromOffset,
42 dwarf::FormParams Format, llvm::endianness Endianess)
43 : DwarfUnit(GlobalData, ID, ClangModuleName), File(File),
44 OrigUnit(&OrigUnit), getUnitFromOffset(UnitFromOffset),
45 Stage(Stage::CreatedNotLoaded),
46 AcceleratorRecords(&GlobalData.getAllocator()) {
47 setOutputFormat(Format, Endianness: Endianess);
48 getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugInfo);
49
50 DWARFDie CUDie = OrigUnit.getUnitDIE();
51 if (!CUDie)
52 return;
53
54 Language = CUDie.getLanguage();
55
56 if (!GlobalData.getOptions().NoODR && Language.has_value() &&
57 isODRLanguage(Language: *Language))
58 NoODR = false;
59
60 if (const char *CUName = CUDie.getName(Kind: DINameKind::ShortName))
61 UnitName = CUName;
62 else
63 UnitName = File.FileName;
64 SysRoot = dwarf::toStringRef(V: CUDie.find(Attr: dwarf::DW_AT_LLVM_sysroot)).str();
65}
66
67void CompileUnit::loadLineTable() {
68 LineTablePtr = File.Dwarf->getLineTableForUnit(U: &getOrigUnit());
69}
70
71void CompileUnit::maybeResetToLoadedStage() {
72 // Nothing to reset if stage is less than "Loaded".
73 if (getStage() < Stage::Loaded)
74 return;
75
76 // Note: We need to do erasing for "LiveRootsCollected" stage because
77 // if live analysys failed then we will have "LiveRootsCollected" stage
78 // with marking from "LivenessAnalysisDone" stage partially
79 // done. That marking should be cleared.
80
81 for (DIEInfo &Info : DieInfoArray)
82 Info.unsetFlagsWhichSetDuringLiveAnalysis();
83
84 LowPc = std::nullopt;
85 HighPc = 0;
86 Labels.clear();
87 Ranges.clear();
88 Dependencies.reset(p: nullptr);
89
90 if (getStage() < Stage::Cloned) {
91 setStage(Stage::Loaded);
92 return;
93 }
94
95 AcceleratorRecords.erase();
96 AbbreviationsSet.clear();
97 Abbreviations.clear();
98 OutUnitDIE = nullptr;
99 DebugAddrIndexMap.clear();
100 DebugStringIndexMap.clear();
101 StmtSeqListAttributes.clear();
102
103 llvm::fill(Range&: OutDieOffsetArray, Value: 0);
104 llvm::fill(Range&: TypeEntries, Value: nullptr);
105 eraseSections();
106
107 setStage(Stage::CreatedNotLoaded);
108}
109
110bool CompileUnit::loadInputDIEs() {
111 DWARFDie InputUnitDIE = getUnitDIE(ExtractUnitDIEOnly: false);
112 if (!InputUnitDIE)
113 return false;
114
115 // load input dies, resize Info structures array.
116 DieInfoArray.resize(N: getOrigUnit().getNumDIEs());
117 OutDieOffsetArray.resize(N: getOrigUnit().getNumDIEs(), NV: 0);
118 if (!NoODR)
119 TypeEntries.resize(N: getOrigUnit().getNumDIEs());
120 return true;
121}
122
123void CompileUnit::analyzeDWARFStructureRec(const DWARFDebugInfoEntry *DieEntry,
124 bool IsODRUnavailableFunctionScope) {
125 CompileUnit::DIEInfo &DieInfo = getDIEInfo(Entry: DieEntry);
126
127 for (const DWARFDebugInfoEntry *CurChild = getFirstChildEntry(Die: DieEntry);
128 CurChild && CurChild->getAbbreviationDeclarationPtr();
129 CurChild = getSiblingEntry(Die: CurChild)) {
130 CompileUnit::DIEInfo &ChildInfo = getDIEInfo(Entry: CurChild);
131 bool ChildIsODRUnavailableFunctionScope = IsODRUnavailableFunctionScope;
132
133 if (DieInfo.getIsInMouduleScope())
134 ChildInfo.setIsInMouduleScope();
135
136 if (DieInfo.getIsInFunctionScope())
137 ChildInfo.setIsInFunctionScope();
138
139 if (DieInfo.getIsInAnonNamespaceScope())
140 ChildInfo.setIsInAnonNamespaceScope();
141
142 switch (CurChild->getTag()) {
143 case dwarf::DW_TAG_module:
144 ChildInfo.setIsInMouduleScope();
145 if (DieEntry->getTag() == dwarf::DW_TAG_compile_unit &&
146 dwarf::toString(V: find(Die: CurChild, Attrs: dwarf::DW_AT_name), Default: "") !=
147 getClangModuleName())
148 analyzeImportedModule(DieEntry: CurChild);
149 break;
150 case dwarf::DW_TAG_subprogram:
151 ChildInfo.setIsInFunctionScope();
152 if (!ChildIsODRUnavailableFunctionScope &&
153 !ChildInfo.getIsInMouduleScope()) {
154 if (find(Die: CurChild,
155 Attrs: {dwarf::DW_AT_abstract_origin, dwarf::DW_AT_specification}))
156 ChildIsODRUnavailableFunctionScope = true;
157 }
158 break;
159 case dwarf::DW_TAG_namespace: {
160 UnitEntryPairTy NamespaceEntry = {this, CurChild};
161
162 if (find(Die: CurChild, Attrs: dwarf::DW_AT_extension))
163 NamespaceEntry = NamespaceEntry.getNamespaceOrigin();
164
165 if (!NamespaceEntry.CU->find(Die: NamespaceEntry.DieEntry, Attrs: dwarf::DW_AT_name))
166 ChildInfo.setIsInAnonNamespaceScope();
167 } break;
168 default:
169 break;
170 }
171
172 if (!isClangModule() && !getGlobalData().getOptions().UpdateIndexTablesOnly)
173 ChildInfo.setTrackLiveness();
174
175 if ((!ChildInfo.getIsInAnonNamespaceScope() &&
176 !ChildIsODRUnavailableFunctionScope && !NoODR))
177 ChildInfo.setODRAvailable();
178
179 if (CurChild->hasChildren())
180 analyzeDWARFStructureRec(DieEntry: CurChild, IsODRUnavailableFunctionScope: ChildIsODRUnavailableFunctionScope);
181 }
182}
183
184StringEntry *CompileUnit::getFileName(unsigned FileIdx,
185 StringPool &GlobalStrings) {
186 if (LineTablePtr) {
187 if (LineTablePtr->hasFileAtIndex(FileIndex: FileIdx)) {
188 // Cache the resolved paths based on the index in the line table,
189 // because calling realpath is expensive.
190 ResolvedPathsMap::const_iterator It = ResolvedFullPaths.find(Val: FileIdx);
191 if (It == ResolvedFullPaths.end()) {
192 std::string OrigFileName;
193 bool FoundFileName = LineTablePtr->getFileNameByIndex(
194 FileIndex: FileIdx, CompDir: getOrigUnit().getCompilationDir(),
195 Kind: DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
196 Result&: OrigFileName);
197 (void)FoundFileName;
198 assert(FoundFileName && "Must get file name from line table");
199
200 // Second level of caching, this time based on the file's parent
201 // path.
202 StringRef FileName = sys::path::filename(path: OrigFileName);
203 StringRef ParentPath = sys::path::parent_path(path: OrigFileName);
204
205 // If the ParentPath has not yet been resolved, resolve and cache it for
206 // future look-ups.
207 StringMap<StringEntry *>::iterator ParentIt =
208 ResolvedParentPaths.find(Key: ParentPath);
209 if (ParentIt == ResolvedParentPaths.end()) {
210 SmallString<256> RealPath;
211 sys::fs::real_path(path: ParentPath, output&: RealPath);
212 ParentIt =
213 ResolvedParentPaths
214 .insert(KV: {ParentPath, GlobalStrings.insert(NewValue: RealPath).first})
215 .first;
216 }
217
218 // Join the file name again with the resolved path.
219 SmallString<256> ResolvedPath(ParentIt->second->first());
220 sys::path::append(path&: ResolvedPath, a: FileName);
221
222 It = ResolvedFullPaths
223 .insert(KV: std::make_pair(
224 x&: FileIdx, y: GlobalStrings.insert(NewValue: ResolvedPath).first))
225 .first;
226 }
227
228 return It->second;
229 }
230 }
231
232 return nullptr;
233}
234
235llvm::Error CompileUnit::setPriority(uint64_t ObjFileIdx, uint64_t LocalIdx) {
236 if (ObjFileIdx > std::numeric_limits<uint32_t>::max())
237 return llvm::createStringError(Fmt: "cannot compute priority when number of "
238 "object files exceeds UINT32_MAX");
239 if (LocalIdx > std::numeric_limits<uint32_t>::max())
240 return llvm::createStringError(Fmt: "cannot compute priority when number of "
241 "local index exceeds UINT32_MAX");
242
243 Priority = (ObjFileIdx << 32) | LocalIdx;
244 return llvm::Error::success();
245}
246
247void CompileUnit::cleanupDataAfterClonning() {
248 AbbreviationsSet.clear();
249 ResolvedFullPaths.shrink_and_clear();
250 ResolvedParentPaths.clear();
251 FileNames.shrink_and_clear();
252 DieInfoArray = SmallVector<DIEInfo>();
253 OutDieOffsetArray = SmallVector<uint64_t>();
254 TypeEntries = SmallVector<TypeEntry *>();
255 Dependencies.reset(p: nullptr);
256 StmtSeqListAttributes.clear();
257 getOrigUnit().clear();
258}
259
260bool CompileUnit::getModulePath(const DWARFDebugInfoEntry *DieEntry,
261 SmallVectorImpl<char> &Path) {
262 assert(DieEntry->getTag() == dwarf::DW_TAG_module);
263
264 SmallVector<StringRef, 4> Names;
265 for (const DWARFDebugInfoEntry *CurEntry = DieEntry;
266 CurEntry && CurEntry->getTag() == dwarf::DW_TAG_module;
267 CurEntry = getParent(Die: CurEntry).getDebugInfoEntry()) {
268 StringRef Name = dwarf::toStringRef(V: find(Die: CurEntry, Attrs: dwarf::DW_AT_name));
269 if (Name.empty())
270 return false;
271 Names.push_back(Elt: Name);
272 }
273
274 for (StringRef Name : reverse(C&: Names)) {
275 Path.append(in_start: Name.begin(), in_end: Name.end());
276 Path.push_back(Elt: '\0');
277 }
278
279 return true;
280}
281
282void CompileUnit::noteModuleAnchors() {
283 const DWARFDebugInfoEntry *UnitEntry = getUnitDIE().getDebugInfoEntry();
284 assert(UnitEntry && "unit reached cloning without loaded DIEs");
285
286 // Find the root, ignoring the skeletons for the imported module.
287 const DWARFDebugInfoEntry *Root = nullptr;
288 for (const DWARFDebugInfoEntry *CurChild = getFirstChildEntry(Die: UnitEntry);
289 CurChild && CurChild->getAbbreviationDeclarationPtr();
290 CurChild = getSiblingEntry(Die: CurChild)) {
291 if (CurChild->getTag() == dwarf::DW_TAG_module &&
292 dwarf::toStringRef(V: find(Die: CurChild, Attrs: dwarf::DW_AT_name)) ==
293 getClangModuleName()) {
294 Root = CurChild;
295 break;
296 }
297 }
298 if (!Root)
299 return;
300
301 SmallString<128> Path;
302
303 // Submodules nest inside the module which declares them, so following the
304 // DW_TAG_module chain down from the root visits every module this unit
305 // describes, without walking the types they contain.
306 SmallVector<const DWARFDebugInfoEntry *, 4> WorkList = {Root};
307 while (!WorkList.empty()) {
308 const DWARFDebugInfoEntry *DieEntry = WorkList.pop_back_val();
309
310 for (const DWARFDebugInfoEntry *CurChild = getFirstChildEntry(Die: DieEntry);
311 CurChild && CurChild->getAbbreviationDeclarationPtr();
312 CurChild = getSiblingEntry(Die: CurChild))
313 if (CurChild->getTag() == dwarf::DW_TAG_module)
314 WorkList.push_back(Elt: CurChild);
315
316 Path.clear();
317 if (!getModulePath(DieEntry, Path))
318 continue;
319
320 ModuleAnchor Anchor;
321 Anchor.Priority = getPriority();
322 if (getDIEInfo(Entry: DieEntry).needToPlaceInTypeTable())
323 Anchor.TypeName = getDieTypeEntry(InputDieEntry: DieEntry);
324 if (!Anchor.TypeName) {
325 // Don't create a dangling reference to a DIE without a type entry or
326 // output offset.
327 uint64_t OutOffset = getDieOutOffset(InputDieEntry: DieEntry);
328 if (!OutOffset)
329 continue;
330 Anchor.Section = &getSectionDescriptor(SectionKind: DebugSectionKind::DebugInfo);
331 Anchor.LocalOffset = OutOffset;
332 }
333
334 getGlobalData().getModulePool().set(Path, Location: Anchor);
335 }
336}
337
338/// Collect references to parseable Swift interfaces in imported
339/// DW_TAG_module blocks.
340void CompileUnit::analyzeImportedModule(const DWARFDebugInfoEntry *DieEntry) {
341 if (!Language || Language != dwarf::DW_LANG_Swift)
342 return;
343
344 if (!GlobalData.getOptions().ParseableSwiftInterfaces)
345 return;
346
347 StringRef Path =
348 dwarf::toStringRef(V: find(Die: DieEntry, Attrs: dwarf::DW_AT_LLVM_include_path));
349 if (!Path.ends_with(Suffix: ".swiftinterface"))
350 return;
351 // Undo prefix mapping before comparing against the SDK and toolchain.
352 std::string RemappedPath = File.remapPath(Path);
353 Path = RemappedPath;
354 // Don't track interfaces that are part of the SDK.
355 StringRef SysRoot =
356 dwarf::toStringRef(V: find(Die: DieEntry, Attrs: dwarf::DW_AT_LLVM_sysroot));
357 if (SysRoot.empty())
358 SysRoot = getSysRoot();
359 std::string RemappedSysRoot = File.remapPath(Path: SysRoot);
360 SysRoot = RemappedSysRoot;
361 if (!SysRoot.empty() && Path.starts_with(Prefix: SysRoot))
362 return;
363 // Don't track interfaces that are part of the toolchain.
364 // For example: Swift, _Concurrency, ...
365 StringRef DeveloperDir = guessDeveloperDir(SysRoot);
366 if (!DeveloperDir.empty() && Path.starts_with(Prefix: DeveloperDir))
367 return;
368 if (isInToolchainDir(Path))
369 return;
370 if (std::optional<DWARFFormValue> Val = find(Die: DieEntry, Attrs: dwarf::DW_AT_name)) {
371 Expected<const char *> Name = Val->getAsCString();
372 if (!Name) {
373 warn(Warning: Name.takeError());
374 return;
375 }
376
377 // The prepend path is applied later when copying.
378 SmallString<128> ResolvedPath;
379 if (!isPathAbsoluteOnWindowsOrPosix(Path))
380 ResolvedPath = File.remapPath(
381 Path: dwarf::toStringRef(V: getUnitDIE().find(Attr: dwarf::DW_AT_comp_dir)));
382 sys::path::append(path&: ResolvedPath, a: Path);
383
384 // Stage the entry. It will be merged into the shared
385 // ParseableSwiftInterfaces map after the parallel analysis phase so that
386 // the final contents and any conflict warnings are deterministic.
387 PendingSwiftInterfaces.emplace_back(Args&: *Name, Args&: ResolvedPath);
388 }
389}
390
391void CompileUnit::mergeSwiftInterfaces(
392 DWARFLinkerBase::SwiftInterfacesMapTy &Map) {
393 for (auto &Pending : PendingSwiftInterfaces) {
394 auto &Entry = Map[Pending.ModuleName];
395 if (!Entry.empty() && Entry != Pending.ResolvedPath)
396 warn(Warning: Twine("conflicting parseable interfaces for Swift Module ") +
397 Pending.ModuleName + ": " + Entry + " and " + Pending.ResolvedPath +
398 ".");
399 Entry = Pending.ResolvedPath;
400 }
401 PendingSwiftInterfaces.clear();
402}
403
404Error CompileUnit::assignTypeNames(TypePool &TypePoolRef) {
405 if (!getUnitDIE().isValid())
406 return Error::success();
407
408 SyntheticTypeNameBuilder NameBuilder(TypePoolRef);
409 return assignTypeNamesRec(DieEntry: getDebugInfoEntry(Index: 0), NameBuilder);
410}
411
412Error CompileUnit::assignTypeNamesRec(const DWARFDebugInfoEntry *DieEntry,
413 SyntheticTypeNameBuilder &NameBuilder) {
414 OrderedChildrenIndexAssigner ChildrenIndexAssigner(*this, DieEntry);
415 for (const DWARFDebugInfoEntry *CurChild = getFirstChildEntry(Die: DieEntry);
416 CurChild && CurChild->getAbbreviationDeclarationPtr();
417 CurChild = getSiblingEntry(Die: CurChild)) {
418 CompileUnit::DIEInfo &ChildInfo = getDIEInfo(Entry: CurChild);
419 if (!ChildInfo.needToPlaceInTypeTable())
420 continue;
421
422 assert(ChildInfo.getODRAvailable());
423 if (Error Err = NameBuilder.assignName(
424 InputUnitEntryPair: {this, CurChild},
425 ChildIndex: ChildrenIndexAssigner.getChildIndex(CU&: *this, ChildDieEntry: CurChild)))
426 return Err;
427
428 if (Error Err = assignTypeNamesRec(DieEntry: CurChild, NameBuilder))
429 return Err;
430 }
431
432 return Error::success();
433}
434
435void CompileUnit::updateDieRefPatchesWithClonedOffsets() {
436 if (std::optional<SectionDescriptor *> DebugInfoSection =
437 tryGetSectionDescriptor(SectionKind: DebugSectionKind::DebugInfo)) {
438
439 (*DebugInfoSection)
440 ->ListDebugDieRefPatch.forEach(Handler: [&](DebugDieRefPatch &Patch) {
441 /// Replace stored DIE indexes with DIE output offsets.
442 Patch.RefDieIdxOrClonedOffset =
443 Patch.RefCU.getPointer()->getDieOutOffset(
444 Idx: Patch.RefDieIdxOrClonedOffset);
445 });
446
447 (*DebugInfoSection)
448 ->ListDebugULEB128DieRefPatch.forEach(
449 Handler: [&](DebugULEB128DieRefPatch &Patch) {
450 /// Replace stored DIE indexes with DIE output offsets.
451 Patch.RefDieIdxOrClonedOffset =
452 Patch.RefCU.getPointer()->getDieOutOffset(
453 Idx: Patch.RefDieIdxOrClonedOffset);
454 });
455
456 (*DebugInfoSection)
457 ->ListDebugDieModuleRefPatch.forEach(
458 Handler: [&](DebugDieModuleRefPatch &Patch) {
459 /// Replace stored DIE indexes with DIE output offsets.
460 Patch.RefDieIdxOrClonedOffset =
461 Patch.RefCU.getPointer()->getDieOutOffset(
462 Idx: Patch.RefDieIdxOrClonedOffset);
463 });
464 }
465
466 if (std::optional<SectionDescriptor *> DebugLocSection =
467 tryGetSectionDescriptor(SectionKind: DebugSectionKind::DebugLoc)) {
468 (*DebugLocSection)
469 ->ListDebugULEB128DieRefPatch.forEach(
470 Handler: [](DebugULEB128DieRefPatch &Patch) {
471 /// Replace stored DIE indexes with DIE output offsets.
472 Patch.RefDieIdxOrClonedOffset =
473 Patch.RefCU.getPointer()->getDieOutOffset(
474 Idx: Patch.RefDieIdxOrClonedOffset);
475 });
476 }
477
478 if (std::optional<SectionDescriptor *> DebugLocListsSection =
479 tryGetSectionDescriptor(SectionKind: DebugSectionKind::DebugLocLists)) {
480 (*DebugLocListsSection)
481 ->ListDebugULEB128DieRefPatch.forEach(
482 Handler: [](DebugULEB128DieRefPatch &Patch) {
483 /// Replace stored DIE indexes with DIE output offsets.
484 Patch.RefDieIdxOrClonedOffset =
485 Patch.RefCU.getPointer()->getDieOutOffset(
486 Idx: Patch.RefDieIdxOrClonedOffset);
487 });
488 }
489}
490
491std::optional<UnitEntryPairTy> CompileUnit::resolveDIEReference(
492 const DWARFFormValue &RefValue,
493 ResolveInterCUReferencesMode CanResolveInterCUReferences) {
494 CompileUnit *RefCU;
495 uint64_t RefDIEOffset;
496 if (std::optional<uint64_t> Offset = RefValue.getAsRelativeReference()) {
497 RefCU = this;
498 RefDIEOffset = RefValue.getUnit()->getOffset() + *Offset;
499 } else if (Offset = RefValue.getAsDebugInfoReference(); Offset) {
500 RefCU = getUnitFromOffset(*Offset);
501 RefDIEOffset = *Offset;
502 } else {
503 return std::nullopt;
504 }
505
506 if (RefCU == this) {
507 // Referenced DIE is in current compile unit.
508 if (std::optional<uint32_t> RefDieIdx =
509 getDIEIndexForOffset(Offset: RefDIEOffset)) {
510 const DWARFDebugInfoEntry *RefEntry = getDebugInfoEntry(Index: *RefDieIdx);
511 // In a file with broken references, an attribute might point to a
512 // NULL DIE. Treat that as a resolution failure so callers can warn.
513 if (RefEntry && RefEntry->getAbbreviationDeclarationPtr())
514 return UnitEntryPairTy{this, RefEntry};
515 }
516 } else if (RefCU && CanResolveInterCUReferences) {
517 // Referenced DIE is in other compile unit.
518
519 // Check whether DIEs are loaded for that compile unit.
520 enum Stage ReferredCUStage = RefCU->getStage();
521 if (ReferredCUStage < Stage::Loaded || ReferredCUStage > Stage::Cloned)
522 return UnitEntryPairTy{RefCU, nullptr};
523
524 if (std::optional<uint32_t> RefDieIdx =
525 RefCU->getDIEIndexForOffset(Offset: RefDIEOffset)) {
526 const DWARFDebugInfoEntry *RefEntry =
527 RefCU->getDebugInfoEntry(Index: *RefDieIdx);
528 if (RefEntry && RefEntry->getAbbreviationDeclarationPtr())
529 return UnitEntryPairTy{RefCU, RefEntry};
530 }
531 } else {
532 return UnitEntryPairTy{RefCU, nullptr};
533 }
534 return std::nullopt;
535}
536
537std::optional<UnitEntryPairTy> CompileUnit::resolveDIEReference(
538 const DWARFDebugInfoEntry *DieEntry, dwarf::Attribute Attr,
539 ResolveInterCUReferencesMode CanResolveInterCUReferences) {
540 if (std::optional<DWARFFormValue> AttrVal = find(Die: DieEntry, Attrs: Attr))
541 return resolveDIEReference(RefValue: *AttrVal, CanResolveInterCUReferences);
542
543 return std::nullopt;
544}
545
546void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
547 int64_t PcOffset) {
548 std::lock_guard<std::mutex> Guard(RangesMutex);
549
550 Ranges.insert(Range: {FuncLowPc, FuncHighPc}, Value: PcOffset);
551 if (LowPc)
552 LowPc = std::min(a: *LowPc, b: FuncLowPc + PcOffset);
553 else
554 LowPc = FuncLowPc + PcOffset;
555 this->HighPc = std::max(a: HighPc, b: FuncHighPc + PcOffset);
556}
557
558void CompileUnit::addLabelLowPc(uint64_t LabelLowPc, int64_t PcOffset) {
559 std::lock_guard<std::mutex> Guard(LabelsMutex);
560 Labels.insert(KV: {LabelLowPc, PcOffset});
561}
562
563Error CompileUnit::cloneAndEmitDebugLocations() {
564 if (getGlobalData().getOptions().UpdateIndexTablesOnly)
565 return Error::success();
566
567 if (getOrigUnit().getVersion() < 5) {
568 emitLocations(LocationSectionKind: DebugSectionKind::DebugLoc);
569 return Error::success();
570 }
571
572 emitLocations(LocationSectionKind: DebugSectionKind::DebugLocLists);
573 return Error::success();
574}
575
576void CompileUnit::emitLocations(DebugSectionKind LocationSectionKind) {
577 SectionDescriptor &DebugInfoSection =
578 getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugInfo);
579
580 if (!DebugInfoSection.ListDebugLocPatch.empty()) {
581 SectionDescriptor &OutLocationSection =
582 getOrCreateSectionDescriptor(SectionKind: LocationSectionKind);
583 DWARFUnit &OrigUnit = getOrigUnit();
584
585 uint64_t OffsetAfterUnitLength = emitLocListHeader(OutLocationSection);
586
587 DebugInfoSection.ListDebugLocPatch.forEach(Handler: [&](DebugLocPatch &Patch) {
588 // Get location expressions vector corresponding to the current
589 // attribute from the source DWARF.
590 uint64_t InputDebugLocSectionOffset = DebugInfoSection.getIntVal(
591 PatchOffset: Patch.PatchOffset,
592 Size: DebugInfoSection.getFormParams().getDwarfOffsetByteSize());
593 Expected<DWARFLocationExpressionsVector> OriginalLocations =
594 OrigUnit.findLoclistFromOffset(Offset: InputDebugLocSectionOffset);
595
596 if (!OriginalLocations) {
597 warn(Warning: OriginalLocations.takeError());
598 return;
599 }
600
601 LinkedLocationExpressionsVector LinkedLocationExpressions;
602 for (DWARFLocationExpression &CurExpression : *OriginalLocations) {
603 LinkedLocationExpressionsWithOffsetPatches LinkedExpression;
604
605 if (CurExpression.Range) {
606 // Relocate address range.
607 LinkedExpression.Expression.Range = {
608 CurExpression.Range->LowPC + Patch.AddrAdjustmentValue,
609 CurExpression.Range->HighPC + Patch.AddrAdjustmentValue};
610 }
611
612 DataExtractor Data(CurExpression.Expr, OrigUnit.isLittleEndian());
613
614 DWARFExpression InputExpression(Data, OrigUnit.getAddressByteSize(),
615 OrigUnit.getFormParams().Format);
616 cloneDieAttrExpression(InputExpression,
617 OutputExpression&: LinkedExpression.Expression.Expr,
618 Section&: OutLocationSection, VarAddressAdjustment: Patch.AddrAdjustmentValue,
619 PatchesOffsets&: LinkedExpression.Patches);
620
621 LinkedLocationExpressions.push_back(Elt: {LinkedExpression});
622 }
623
624 // Emit locations list table fragment corresponding to the CurLocAttr.
625 DebugInfoSection.apply(PatchOffset: Patch.PatchOffset, AttrForm: dwarf::DW_FORM_sec_offset,
626 Val: OutLocationSection.OS.tell());
627 emitLocListFragment(LinkedLocationExpression: LinkedLocationExpressions, OutLocationSection);
628 });
629
630 if (OffsetAfterUnitLength > 0) {
631 assert(OffsetAfterUnitLength -
632 OutLocationSection.getFormParams().getDwarfOffsetByteSize() <
633 OffsetAfterUnitLength);
634 OutLocationSection.apply(
635 PatchOffset: OffsetAfterUnitLength -
636 OutLocationSection.getFormParams().getDwarfOffsetByteSize(),
637 AttrForm: dwarf::DW_FORM_sec_offset,
638 Val: OutLocationSection.OS.tell() - OffsetAfterUnitLength);
639 }
640 }
641}
642
643/// Emit debug locations(.debug_loc, .debug_loclists) header.
644uint64_t CompileUnit::emitLocListHeader(SectionDescriptor &OutLocationSection) {
645 if (getOrigUnit().getVersion() < 5)
646 return 0;
647
648 // unit_length.
649 OutLocationSection.emitUnitLength(Length: 0xBADDEF);
650 uint64_t OffsetAfterUnitLength = OutLocationSection.OS.tell();
651
652 // Version.
653 OutLocationSection.emitIntVal(Val: 5, Size: 2);
654
655 // Address size.
656 OutLocationSection.emitIntVal(Val: OutLocationSection.getFormParams().AddrSize, Size: 1);
657
658 // Seg_size
659 OutLocationSection.emitIntVal(Val: 0, Size: 1);
660
661 // Offset entry count
662 OutLocationSection.emitIntVal(Val: 0, Size: 4);
663
664 return OffsetAfterUnitLength;
665}
666
667/// Emit debug locations(.debug_loc, .debug_loclists) fragment.
668uint64_t CompileUnit::emitLocListFragment(
669 const LinkedLocationExpressionsVector &LinkedLocationExpression,
670 SectionDescriptor &OutLocationSection) {
671 uint64_t OffsetBeforeLocationExpression = 0;
672
673 if (getOrigUnit().getVersion() < 5) {
674 uint64_t BaseAddress = 0;
675 if (std::optional<uint64_t> LowPC = getLowPc())
676 BaseAddress = *LowPC;
677
678 for (const LinkedLocationExpressionsWithOffsetPatches &LocExpression :
679 LinkedLocationExpression) {
680 if (LocExpression.Expression.Range) {
681 OutLocationSection.emitIntVal(
682 Val: LocExpression.Expression.Range->LowPC - BaseAddress,
683 Size: OutLocationSection.getFormParams().AddrSize);
684 OutLocationSection.emitIntVal(
685 Val: LocExpression.Expression.Range->HighPC - BaseAddress,
686 Size: OutLocationSection.getFormParams().AddrSize);
687 }
688
689 OutLocationSection.emitIntVal(Val: LocExpression.Expression.Expr.size(), Size: 2);
690 OffsetBeforeLocationExpression = OutLocationSection.OS.tell();
691 for (uint64_t *OffsetPtr : LocExpression.Patches)
692 *OffsetPtr += OffsetBeforeLocationExpression;
693
694 OutLocationSection.OS
695 << StringRef((const char *)LocExpression.Expression.Expr.data(),
696 LocExpression.Expression.Expr.size());
697 }
698
699 // Emit the terminator entry.
700 OutLocationSection.emitIntVal(Val: 0,
701 Size: OutLocationSection.getFormParams().AddrSize);
702 OutLocationSection.emitIntVal(Val: 0,
703 Size: OutLocationSection.getFormParams().AddrSize);
704 return OffsetBeforeLocationExpression;
705 }
706
707 std::optional<uint64_t> BaseAddress;
708 for (const LinkedLocationExpressionsWithOffsetPatches &LocExpression :
709 LinkedLocationExpression) {
710 if (LocExpression.Expression.Range) {
711 // Check whether base address is set. If it is not set yet
712 // then set current base address and emit base address selection entry.
713 if (!BaseAddress) {
714 BaseAddress = LocExpression.Expression.Range->LowPC;
715
716 // Emit base address.
717 OutLocationSection.emitIntVal(Val: dwarf::DW_LLE_base_addressx, Size: 1);
718 encodeULEB128(Value: DebugAddrIndexMap.getValueIndex(Value: *BaseAddress),
719 OS&: OutLocationSection.OS);
720 }
721
722 // Emit type of entry.
723 OutLocationSection.emitIntVal(Val: dwarf::DW_LLE_offset_pair, Size: 1);
724
725 // Emit start offset relative to base address.
726 encodeULEB128(Value: LocExpression.Expression.Range->LowPC - *BaseAddress,
727 OS&: OutLocationSection.OS);
728
729 // Emit end offset relative to base address.
730 encodeULEB128(Value: LocExpression.Expression.Range->HighPC - *BaseAddress,
731 OS&: OutLocationSection.OS);
732 } else
733 // Emit type of entry.
734 OutLocationSection.emitIntVal(Val: dwarf::DW_LLE_default_location, Size: 1);
735
736 encodeULEB128(Value: LocExpression.Expression.Expr.size(), OS&: OutLocationSection.OS);
737 OffsetBeforeLocationExpression = OutLocationSection.OS.tell();
738 for (uint64_t *OffsetPtr : LocExpression.Patches)
739 *OffsetPtr += OffsetBeforeLocationExpression;
740
741 OutLocationSection.OS << StringRef(
742 (const char *)LocExpression.Expression.Expr.data(),
743 LocExpression.Expression.Expr.size());
744 }
745
746 // Emit the terminator entry.
747 OutLocationSection.emitIntVal(Val: dwarf::DW_LLE_end_of_list, Size: 1);
748 return OffsetBeforeLocationExpression;
749}
750
751Error CompileUnit::emitDebugAddrSection() {
752 if (GlobalData.getOptions().UpdateIndexTablesOnly)
753 return Error::success();
754
755 if (getVersion() < 5)
756 return Error::success();
757
758 // Every cloned unit root has DW_AT_addr_base, so emit the table even when it
759 // is empty.
760 SectionDescriptor &OutAddrSection =
761 getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugAddr);
762
763 // Emit section header.
764
765 // Emit length.
766 OutAddrSection.emitUnitLength(Length: 0xBADDEF);
767 uint64_t OffsetAfterSectionLength = OutAddrSection.OS.tell();
768
769 // Emit version.
770 OutAddrSection.emitIntVal(Val: 5, Size: 2);
771
772 // Emit address size.
773 OutAddrSection.emitIntVal(Val: getFormParams().AddrSize, Size: 1);
774
775 // Emit segment size.
776 OutAddrSection.emitIntVal(Val: 0, Size: 1);
777
778 // Emit addresses.
779 for (uint64_t AddrValue : DebugAddrIndexMap.getValues())
780 OutAddrSection.emitIntVal(Val: AddrValue, Size: getFormParams().AddrSize);
781
782 // Patch section length.
783 OutAddrSection.apply(
784 PatchOffset: OffsetAfterSectionLength -
785 OutAddrSection.getFormParams().getDwarfOffsetByteSize(),
786 AttrForm: dwarf::DW_FORM_sec_offset,
787 Val: OutAddrSection.OS.tell() - OffsetAfterSectionLength);
788
789 return Error::success();
790}
791
792Error CompileUnit::cloneAndEmitRanges() {
793 if (getGlobalData().getOptions().UpdateIndexTablesOnly)
794 return Error::success();
795
796 // Build set of linked address ranges for unit function ranges.
797 AddressRanges LinkedFunctionRanges;
798 for (const AddressRangeValuePair &Range : getFunctionRanges())
799 LinkedFunctionRanges.insert(
800 Range: {Range.Range.start() + Range.Value, Range.Range.end() + Range.Value});
801
802 emitAranges(LinkedFunctionRanges);
803
804 if (getOrigUnit().getVersion() < 5) {
805 cloneAndEmitRangeList(RngSectionKind: DebugSectionKind::DebugRange, LinkedFunctionRanges);
806 return Error::success();
807 }
808
809 cloneAndEmitRangeList(RngSectionKind: DebugSectionKind::DebugRngLists, LinkedFunctionRanges);
810 return Error::success();
811}
812
813void CompileUnit::cloneAndEmitRangeList(DebugSectionKind RngSectionKind,
814 AddressRanges &LinkedFunctionRanges) {
815 SectionDescriptor &DebugInfoSection =
816 getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugInfo);
817 SectionDescriptor &OutRangeSection =
818 getOrCreateSectionDescriptor(SectionKind: RngSectionKind);
819
820 if (!DebugInfoSection.ListDebugRangePatch.empty()) {
821 std::optional<AddressRangeValuePair> CachedRange;
822 uint64_t OffsetAfterUnitLength = emitRangeListHeader(OutRangeSection);
823
824 DebugRangePatch *CompileUnitRangePtr = nullptr;
825 DebugInfoSection.ListDebugRangePatch.forEach(Handler: [&](DebugRangePatch &Patch) {
826 if (Patch.IsCompileUnitRanges) {
827 CompileUnitRangePtr = &Patch;
828 } else {
829 // Get ranges from the source DWARF corresponding to the current
830 // attribute.
831 AddressRanges LinkedRanges;
832 uint64_t InputDebugRangesSectionOffset = DebugInfoSection.getIntVal(
833 PatchOffset: Patch.PatchOffset,
834 Size: DebugInfoSection.getFormParams().getDwarfOffsetByteSize());
835 if (Expected<DWARFAddressRangesVector> InputRanges =
836 getOrigUnit().findRnglistFromOffset(
837 Offset: InputDebugRangesSectionOffset)) {
838 // Apply relocation adjustment.
839 for (const auto &Range : *InputRanges) {
840 if (!CachedRange || !CachedRange->Range.contains(Addr: Range.LowPC))
841 CachedRange =
842 getFunctionRanges().getRangeThatContains(Addr: Range.LowPC);
843
844 // All range entries should lie in the function range.
845 if (!CachedRange) {
846 warn(Warning: "inconsistent range data.");
847 continue;
848 }
849
850 // Store range for emiting.
851 LinkedRanges.insert(Range: {Range.LowPC + CachedRange->Value,
852 Range.HighPC + CachedRange->Value});
853 }
854 } else {
855 llvm::consumeError(Err: InputRanges.takeError());
856 warn(Warning: "invalid range list ignored.");
857 }
858
859 // Emit linked ranges.
860 DebugInfoSection.apply(PatchOffset: Patch.PatchOffset, AttrForm: dwarf::DW_FORM_sec_offset,
861 Val: OutRangeSection.OS.tell());
862 emitRangeListFragment(LinkedRanges, OutRangeSection);
863 }
864 });
865
866 if (CompileUnitRangePtr != nullptr) {
867 // Emit compile unit ranges last to be binary compatible with classic
868 // dsymutil.
869 DebugInfoSection.apply(PatchOffset: CompileUnitRangePtr->PatchOffset,
870 AttrForm: dwarf::DW_FORM_sec_offset,
871 Val: OutRangeSection.OS.tell());
872 emitRangeListFragment(LinkedRanges: LinkedFunctionRanges, OutRangeSection);
873 }
874
875 if (OffsetAfterUnitLength > 0) {
876 assert(OffsetAfterUnitLength -
877 OutRangeSection.getFormParams().getDwarfOffsetByteSize() <
878 OffsetAfterUnitLength);
879 OutRangeSection.apply(
880 PatchOffset: OffsetAfterUnitLength -
881 OutRangeSection.getFormParams().getDwarfOffsetByteSize(),
882 AttrForm: dwarf::DW_FORM_sec_offset,
883 Val: OutRangeSection.OS.tell() - OffsetAfterUnitLength);
884 }
885 }
886}
887
888uint64_t CompileUnit::emitRangeListHeader(SectionDescriptor &OutRangeSection) {
889 if (OutRangeSection.getFormParams().Version < 5)
890 return 0;
891
892 // unit_length.
893 OutRangeSection.emitUnitLength(Length: 0xBADDEF);
894 uint64_t OffsetAfterUnitLength = OutRangeSection.OS.tell();
895
896 // Version.
897 OutRangeSection.emitIntVal(Val: 5, Size: 2);
898
899 // Address size.
900 OutRangeSection.emitIntVal(Val: OutRangeSection.getFormParams().AddrSize, Size: 1);
901
902 // Seg_size
903 OutRangeSection.emitIntVal(Val: 0, Size: 1);
904
905 // Offset entry count
906 OutRangeSection.emitIntVal(Val: 0, Size: 4);
907
908 return OffsetAfterUnitLength;
909}
910
911void CompileUnit::emitRangeListFragment(const AddressRanges &LinkedRanges,
912 SectionDescriptor &OutRangeSection) {
913 if (OutRangeSection.getFormParams().Version < 5) {
914 // Emit ranges.
915 uint64_t BaseAddress = 0;
916 if (std::optional<uint64_t> LowPC = getLowPc())
917 BaseAddress = *LowPC;
918
919 for (const AddressRange &Range : LinkedRanges) {
920 OutRangeSection.emitIntVal(Val: Range.start() - BaseAddress,
921 Size: OutRangeSection.getFormParams().AddrSize);
922 OutRangeSection.emitIntVal(Val: Range.end() - BaseAddress,
923 Size: OutRangeSection.getFormParams().AddrSize);
924 }
925
926 // Add the terminator entry.
927 OutRangeSection.emitIntVal(Val: 0, Size: OutRangeSection.getFormParams().AddrSize);
928 OutRangeSection.emitIntVal(Val: 0, Size: OutRangeSection.getFormParams().AddrSize);
929 return;
930 }
931
932 std::optional<uint64_t> BaseAddress;
933 for (const AddressRange &Range : LinkedRanges) {
934 if (!BaseAddress) {
935 BaseAddress = Range.start();
936
937 // Emit base address.
938 OutRangeSection.emitIntVal(Val: dwarf::DW_RLE_base_addressx, Size: 1);
939 encodeULEB128(Value: getDebugAddrIndex(Addr: *BaseAddress), OS&: OutRangeSection.OS);
940 }
941
942 // Emit type of entry.
943 OutRangeSection.emitIntVal(Val: dwarf::DW_RLE_offset_pair, Size: 1);
944
945 // Emit start offset relative to base address.
946 encodeULEB128(Value: Range.start() - *BaseAddress, OS&: OutRangeSection.OS);
947
948 // Emit end offset relative to base address.
949 encodeULEB128(Value: Range.end() - *BaseAddress, OS&: OutRangeSection.OS);
950 }
951
952 // Emit the terminator entry.
953 OutRangeSection.emitIntVal(Val: dwarf::DW_RLE_end_of_list, Size: 1);
954}
955
956void CompileUnit::emitAranges(AddressRanges &LinkedFunctionRanges) {
957 if (LinkedFunctionRanges.empty())
958 return;
959
960 SectionDescriptor &DebugInfoSection =
961 getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugInfo);
962 SectionDescriptor &OutArangesSection =
963 getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugARanges);
964
965 // Emit Header.
966 unsigned HeaderSize =
967 sizeof(int32_t) + // Size of contents (w/o this field
968 sizeof(int16_t) + // DWARF ARange version number
969 sizeof(int32_t) + // Offset of CU in the .debug_info section
970 sizeof(int8_t) + // Pointer Size (in bytes)
971 sizeof(int8_t); // Segment Size (in bytes)
972
973 unsigned TupleSize = OutArangesSection.getFormParams().AddrSize * 2;
974 unsigned Padding = offsetToAlignment(Value: HeaderSize, Alignment: Align(TupleSize));
975
976 OutArangesSection.emitOffset(Val: 0xBADDEF); // Aranges length
977 uint64_t OffsetAfterArangesLengthField = OutArangesSection.OS.tell();
978
979 OutArangesSection.emitIntVal(Val: dwarf::DW_ARANGES_VERSION, Size: 2); // Version number
980 OutArangesSection.notePatch(
981 Patch: DebugOffsetPatch{OutArangesSection.OS.tell(), &DebugInfoSection});
982 OutArangesSection.emitOffset(Val: 0xBADDEF); // Corresponding unit's offset
983 OutArangesSection.emitIntVal(Val: OutArangesSection.getFormParams().AddrSize,
984 Size: 1); // Address size
985 OutArangesSection.emitIntVal(Val: 0, Size: 1); // Segment size
986
987 for (size_t Idx = 0; Idx < Padding; Idx++)
988 OutArangesSection.emitIntVal(Val: 0, Size: 1); // Padding
989
990 // Emit linked ranges.
991 for (const AddressRange &Range : LinkedFunctionRanges) {
992 OutArangesSection.emitIntVal(Val: Range.start(),
993 Size: OutArangesSection.getFormParams().AddrSize);
994 OutArangesSection.emitIntVal(Val: Range.end() - Range.start(),
995 Size: OutArangesSection.getFormParams().AddrSize);
996 }
997
998 // Emit terminator.
999 OutArangesSection.emitIntVal(Val: 0, Size: OutArangesSection.getFormParams().AddrSize);
1000 OutArangesSection.emitIntVal(Val: 0, Size: OutArangesSection.getFormParams().AddrSize);
1001
1002 uint64_t OffsetAfterArangesEnd = OutArangesSection.OS.tell();
1003
1004 // Update Aranges lentgh.
1005 OutArangesSection.apply(
1006 PatchOffset: OffsetAfterArangesLengthField -
1007 OutArangesSection.getFormParams().getDwarfOffsetByteSize(),
1008 AttrForm: dwarf::DW_FORM_sec_offset,
1009 Val: OffsetAfterArangesEnd - OffsetAfterArangesLengthField);
1010}
1011
1012Error CompileUnit::cloneAndEmitDebugMacro() {
1013 if (getOutUnitDIE() == nullptr)
1014 return Error::success();
1015
1016 DWARFUnit &OrigUnit = getOrigUnit();
1017 DWARFDie OrigUnitDie = OrigUnit.getUnitDIE();
1018
1019 // Check for .debug_macro table.
1020 if (std::optional<uint64_t> MacroAttr =
1021 dwarf::toSectionOffset(V: OrigUnitDie.find(Attr: dwarf::DW_AT_macros))) {
1022 if (const DWARFDebugMacro *Table =
1023 getContainingFile().Dwarf->getDebugMacro()) {
1024 emitMacroTableImpl(MacroTable: Table, OffsetToMacroTable: *MacroAttr, hasDWARFv5Header: true);
1025 }
1026 }
1027
1028 // Check for .debug_macinfo table.
1029 if (std::optional<uint64_t> MacroAttr =
1030 dwarf::toSectionOffset(V: OrigUnitDie.find(Attr: dwarf::DW_AT_macro_info))) {
1031 if (const DWARFDebugMacro *Table =
1032 getContainingFile().Dwarf->getDebugMacinfo()) {
1033 emitMacroTableImpl(MacroTable: Table, OffsetToMacroTable: *MacroAttr, hasDWARFv5Header: false);
1034 }
1035 }
1036
1037 return Error::success();
1038}
1039
1040void CompileUnit::emitMacroTableImpl(const DWARFDebugMacro *MacroTable,
1041 uint64_t OffsetToMacroTable,
1042 bool hasDWARFv5Header) {
1043 SectionDescriptor &OutSection =
1044 hasDWARFv5Header
1045 ? getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugMacro)
1046 : getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugMacinfo);
1047
1048 bool DefAttributeIsReported = false;
1049 bool UndefAttributeIsReported = false;
1050 bool ImportAttributeIsReported = false;
1051
1052 for (const DWARFDebugMacro::MacroList &List : MacroTable->MacroLists) {
1053 if (OffsetToMacroTable == List.Offset) {
1054 // Write DWARFv5 header.
1055 if (hasDWARFv5Header) {
1056 // Write header version.
1057 OutSection.emitIntVal(Val: List.Header.Version, Size: sizeof(List.Header.Version));
1058
1059 uint8_t Flags = List.Header.Flags;
1060
1061 // Check for OPCODE_OPERANDS_TABLE.
1062 if (Flags &
1063 DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE) {
1064 Flags &=
1065 ~DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE;
1066 warn(Warning: "opcode_operands_table is not supported yet.");
1067 }
1068
1069 // Check for DEBUG_LINE_OFFSET.
1070 std::optional<uint64_t> StmtListOffset;
1071 if (Flags & DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET) {
1072 // Get offset to the line table from the cloned compile unit.
1073 for (auto &V : getOutUnitDIE()->values()) {
1074 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
1075 StmtListOffset = V.getDIEInteger().getValue();
1076 break;
1077 }
1078 }
1079
1080 if (!StmtListOffset) {
1081 Flags &= ~DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET;
1082 warn(Warning: "couldn`t find line table for macro table.");
1083 }
1084 }
1085
1086 // Write flags.
1087 OutSection.emitIntVal(Val: Flags, Size: sizeof(Flags));
1088
1089 // Write offset to line table.
1090 if (StmtListOffset) {
1091 OutSection.notePatch(Patch: DebugOffsetPatch{
1092 OutSection.OS.tell(),
1093 &getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugLine)});
1094 // TODO: check that List.Header.getOffsetByteSize() and
1095 // DebugOffsetPatch agree on size.
1096 OutSection.emitIntVal(Val: 0xBADDEF, Size: List.Header.getOffsetByteSize());
1097 }
1098 }
1099
1100 // Write macro entries.
1101 for (const DWARFDebugMacro::Entry &MacroEntry : List.Macros) {
1102 if (MacroEntry.Type == 0) {
1103 encodeULEB128(Value: MacroEntry.Type, OS&: OutSection.OS);
1104 continue;
1105 }
1106
1107 uint8_t MacroType = MacroEntry.Type;
1108 switch (MacroType) {
1109 default: {
1110 bool HasVendorSpecificExtension =
1111 (!hasDWARFv5Header &&
1112 MacroType == dwarf::DW_MACINFO_vendor_ext) ||
1113 (hasDWARFv5Header && (MacroType >= dwarf::DW_MACRO_lo_user &&
1114 MacroType <= dwarf::DW_MACRO_hi_user));
1115
1116 if (HasVendorSpecificExtension) {
1117 // Write macinfo type.
1118 OutSection.emitIntVal(Val: MacroType, Size: 1);
1119
1120 // Write vendor extension constant.
1121 encodeULEB128(Value: MacroEntry.ExtConstant, OS&: OutSection.OS);
1122
1123 // Write vendor extension string.
1124 OutSection.emitString(StringForm: dwarf::DW_FORM_string, StringVal: MacroEntry.ExtStr);
1125 } else
1126 warn(Warning: "unknown macro type. skip.");
1127 } break;
1128 // debug_macro and debug_macinfo share some common encodings.
1129 // DW_MACRO_define == DW_MACINFO_define
1130 // DW_MACRO_undef == DW_MACINFO_undef
1131 // DW_MACRO_start_file == DW_MACINFO_start_file
1132 // DW_MACRO_end_file == DW_MACINFO_end_file
1133 // For readibility/uniformity we are using DW_MACRO_*.
1134 case dwarf::DW_MACRO_define:
1135 case dwarf::DW_MACRO_undef: {
1136 // Write macinfo type.
1137 OutSection.emitIntVal(Val: MacroType, Size: 1);
1138
1139 // Write source line.
1140 encodeULEB128(Value: MacroEntry.Line, OS&: OutSection.OS);
1141
1142 // Write macro string.
1143 OutSection.emitString(StringForm: dwarf::DW_FORM_string, StringVal: MacroEntry.MacroStr);
1144 } break;
1145 case dwarf::DW_MACRO_define_strp:
1146 case dwarf::DW_MACRO_undef_strp:
1147 case dwarf::DW_MACRO_define_strx:
1148 case dwarf::DW_MACRO_undef_strx: {
1149 // DW_MACRO_*_strx forms are not supported currently.
1150 // Convert to *_strp.
1151 switch (MacroType) {
1152 case dwarf::DW_MACRO_define_strx: {
1153 MacroType = dwarf::DW_MACRO_define_strp;
1154 if (!DefAttributeIsReported) {
1155 warn(Warning: "DW_MACRO_define_strx unsupported yet. Convert to "
1156 "DW_MACRO_define_strp.");
1157 DefAttributeIsReported = true;
1158 }
1159 } break;
1160 case dwarf::DW_MACRO_undef_strx: {
1161 MacroType = dwarf::DW_MACRO_undef_strp;
1162 if (!UndefAttributeIsReported) {
1163 warn(Warning: "DW_MACRO_undef_strx unsupported yet. Convert to "
1164 "DW_MACRO_undef_strp.");
1165 UndefAttributeIsReported = true;
1166 }
1167 } break;
1168 default:
1169 // Nothing to do.
1170 break;
1171 }
1172
1173 // Write macinfo type.
1174 OutSection.emitIntVal(Val: MacroType, Size: 1);
1175
1176 // Write source line.
1177 encodeULEB128(Value: MacroEntry.Line, OS&: OutSection.OS);
1178
1179 // Write macro string.
1180 OutSection.emitString(StringForm: dwarf::DW_FORM_strp, StringVal: MacroEntry.MacroStr);
1181 break;
1182 }
1183 case dwarf::DW_MACRO_start_file: {
1184 // Write macinfo type.
1185 OutSection.emitIntVal(Val: MacroType, Size: 1);
1186 // Write source line.
1187 encodeULEB128(Value: MacroEntry.Line, OS&: OutSection.OS);
1188 // Write source file id.
1189 encodeULEB128(Value: MacroEntry.File, OS&: OutSection.OS);
1190 } break;
1191 case dwarf::DW_MACRO_end_file: {
1192 // Write macinfo type.
1193 OutSection.emitIntVal(Val: MacroType, Size: 1);
1194 } break;
1195 case dwarf::DW_MACRO_import:
1196 case dwarf::DW_MACRO_import_sup: {
1197 if (!ImportAttributeIsReported) {
1198 warn(Warning: "DW_MACRO_import and DW_MACRO_import_sup are unsupported "
1199 "yet. remove.");
1200 ImportAttributeIsReported = true;
1201 }
1202 } break;
1203 }
1204 }
1205
1206 return;
1207 }
1208 }
1209}
1210
1211void CompileUnit::cloneDieAttrExpression(
1212 const DWARFExpression &InputExpression,
1213 SmallVectorImpl<uint8_t> &OutputExpression, SectionDescriptor &Section,
1214 std::optional<int64_t> VarAddressAdjustment,
1215 OffsetsPtrVector &PatchesOffsets) {
1216 using Encoding = DWARFExpression::Operation::Encoding;
1217
1218 DWARFUnit &OrigUnit = getOrigUnit();
1219 uint8_t OrigAddressByteSize = OrigUnit.getAddressByteSize();
1220
1221 uint64_t OpOffset = 0;
1222 for (auto &Op : InputExpression) {
1223 if (Op.isError()) {
1224 // The operation could not be decoded, so neither it nor anything after
1225 // it can be located. Its end offset is the offset it started at, so the
1226 // slice copied below would be empty and the rest of the expression
1227 // would be silently dropped. Preserve the remaining bytes instead.
1228 warn(Warning: "cannot decode a DW_OP, copying the rest of the expression "
1229 "unmodified.");
1230 StringRef Bytes = InputExpression.getData().substr(Start: OpOffset);
1231 OutputExpression.append(in_start: Bytes.begin(), in_end: Bytes.end());
1232 return;
1233 }
1234 auto Desc = Op.getDescription();
1235 // DW_OP_const_type is variable-length and has 3
1236 // operands. Thus far we only support 2.
1237 if ((Desc.Op.size() == 2 && Desc.Op[0] == Encoding::BaseTypeRef) ||
1238 (Desc.Op.size() == 2 && Desc.Op[1] == Encoding::BaseTypeRef &&
1239 Desc.Op[0] != Encoding::Size1))
1240 warn(Warning: "unsupported DW_OP encoding.");
1241
1242 if ((Desc.Op.size() == 1 && Desc.Op[0] == Encoding::BaseTypeRef) ||
1243 (Desc.Op.size() == 2 && Desc.Op[1] == Encoding::BaseTypeRef &&
1244 Desc.Op[0] == Encoding::Size1)) {
1245 // This code assumes that the other non-typeref operand fits into 1 byte.
1246 assert(OpOffset < Op.getEndOffset());
1247 uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
1248 assert(ULEBsize <= 16);
1249
1250 // Copy over the operation.
1251 assert(!Op.getSubCode() && "SubOps not yet supported");
1252 OutputExpression.push_back(Elt: Op.getCode());
1253 uint64_t RefOffset;
1254 if (Desc.Op.size() == 1) {
1255 RefOffset = Op.getRawOperand(Idx: 0);
1256 } else {
1257 OutputExpression.push_back(Elt: Op.getRawOperand(Idx: 0));
1258 RefOffset = Op.getRawOperand(Idx: 1);
1259 }
1260 uint8_t ULEB[16];
1261 uint32_t Offset = 0;
1262 unsigned RealSize = 0;
1263 // Look up the base type. For DW_OP_convert, the operand may be 0 to
1264 // instead indicate the generic type. The same holds for
1265 // DW_OP_reinterpret, which is currently not supported.
1266 if (RefOffset > 0 || Op.getCode() != dwarf::DW_OP_convert) {
1267 RefOffset += OrigUnit.getOffset();
1268 uint32_t RefDieIdx = 0;
1269 if (std::optional<uint32_t> Idx =
1270 OrigUnit.getDIEIndexForOffset(Offset: RefOffset))
1271 RefDieIdx = *Idx;
1272
1273 // Use fixed size for ULEB128 data, since we need to update that size
1274 // later with the proper offsets. Use 5 for DWARF32, 9 for DWARF64.
1275 ULEBsize = getFormParams().getDwarfOffsetByteSize() + 1;
1276
1277 RealSize = encodeULEB128(Value: 0xBADDEF, p: ULEB, PadTo: ULEBsize);
1278
1279 Section.notePatchWithOffsetUpdate(
1280 Patch: DebugULEB128DieRefPatch(OutputExpression.size(), this, this,
1281 RefDieIdx),
1282 PatchesOffsetsList&: PatchesOffsets);
1283 } else
1284 RealSize = encodeULEB128(Value: Offset, p: ULEB, PadTo: ULEBsize);
1285
1286 if (RealSize > ULEBsize) {
1287 // Emit the generic type as a fallback.
1288 RealSize = encodeULEB128(Value: 0, p: ULEB, PadTo: ULEBsize);
1289 warn(Warning: "base type ref doesn't fit.");
1290 }
1291 assert(RealSize == ULEBsize && "padding failed");
1292 ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
1293 OutputExpression.append(in_start: ULEBbytes.begin(), in_end: ULEBbytes.end());
1294 } else if (!getGlobalData().getOptions().UpdateIndexTablesOnly &&
1295 Op.getCode() == dwarf::DW_OP_addrx) {
1296 if (std::optional<object::SectionedAddress> SA =
1297 OrigUnit.getAddrOffsetSectionItem(Index: Op.getRawOperand(Idx: 0))) {
1298 // DWARFLinker does not use addrx forms since it generates relocated
1299 // addresses. Replace DW_OP_addrx with DW_OP_addr here.
1300 // Argument of DW_OP_addrx should be relocated here as it is not
1301 // processed by applyValidRelocs.
1302 OutputExpression.push_back(Elt: dwarf::DW_OP_addr);
1303 uint64_t LinkedAddress =
1304 SA->Address +
1305 getContainingFile()
1306 .Addresses->getAddrIndexRelocAdjustment(U&: OrigUnit, Op, Verbose: false)
1307 .value_or(u: VarAddressAdjustment.value_or(u: 0));
1308 if (getEndianness() != llvm::endianness::native)
1309 sys::swapByteOrder(Value&: LinkedAddress);
1310 ArrayRef<uint8_t> AddressBytes(
1311 reinterpret_cast<const uint8_t *>(&LinkedAddress),
1312 OrigAddressByteSize);
1313 OutputExpression.append(in_start: AddressBytes.begin(), in_end: AddressBytes.end());
1314 } else
1315 warn(Warning: "cann't read DW_OP_addrx operand.");
1316 } else if (!getGlobalData().getOptions().UpdateIndexTablesOnly &&
1317 Op.getCode() == dwarf::DW_OP_constx) {
1318 if (std::optional<object::SectionedAddress> SA =
1319 OrigUnit.getAddrOffsetSectionItem(Index: Op.getRawOperand(Idx: 0))) {
1320 // DWARFLinker does not use constx forms since it generates relocated
1321 // addresses. Replace DW_OP_constx with DW_OP_const[*]u here.
1322 // Argument of DW_OP_constx should be relocated here as it is not
1323 // processed by applyValidRelocs.
1324 std::optional<uint8_t> OutOperandKind;
1325 switch (OrigAddressByteSize) {
1326 case 2:
1327 OutOperandKind = dwarf::DW_OP_const2u;
1328 break;
1329 case 4:
1330 OutOperandKind = dwarf::DW_OP_const4u;
1331 break;
1332 case 8:
1333 OutOperandKind = dwarf::DW_OP_const8u;
1334 break;
1335 default:
1336 warn(
1337 Warning: formatv(Fmt: ("unsupported address size: {0}."), Vals&: OrigAddressByteSize));
1338 break;
1339 }
1340
1341 if (OutOperandKind) {
1342 OutputExpression.push_back(Elt: *OutOperandKind);
1343 uint64_t LinkedAddress =
1344 SA->Address +
1345 getContainingFile()
1346 .Addresses->getAddrIndexRelocAdjustment(U&: OrigUnit, Op, Verbose: false)
1347 .value_or(u: VarAddressAdjustment.value_or(u: 0));
1348 if (getEndianness() != llvm::endianness::native)
1349 sys::swapByteOrder(Value&: LinkedAddress);
1350 ArrayRef<uint8_t> AddressBytes(
1351 reinterpret_cast<const uint8_t *>(&LinkedAddress),
1352 OrigAddressByteSize);
1353 OutputExpression.append(in_start: AddressBytes.begin(), in_end: AddressBytes.end());
1354 }
1355 } else
1356 warn(Warning: "cann't read DW_OP_constx operand.");
1357 } else {
1358 // Copy over everything else unmodified.
1359 StringRef Bytes =
1360 InputExpression.getData().slice(Start: OpOffset, End: Op.getEndOffset());
1361 OutputExpression.append(in_start: Bytes.begin(), in_end: Bytes.end());
1362 }
1363 OpOffset = Op.getEndOffset();
1364 }
1365}
1366
1367Error CompileUnit::cloneAndEmit(
1368 std::optional<std::reference_wrapper<const Triple>> TargetTriple,
1369 TypeUnit *ArtificialTypeUnit) {
1370 BumpPtrAllocator Allocator;
1371
1372 DWARFDie OrigUnitDIE = getOrigUnit().getUnitDIE();
1373 if (!OrigUnitDIE.isValid())
1374 return Error::success();
1375
1376 TypeEntry *RootEntry = nullptr;
1377 if (ArtificialTypeUnit)
1378 RootEntry = ArtificialTypeUnit->getTypePool().getRoot();
1379
1380 // Clone input DIE entry recursively.
1381 std::pair<DIE *, TypeEntry *> OutCUDie = cloneDIE(
1382 InputDieEntry: OrigUnitDIE.getDebugInfoEntry(), ClonedParentTypeDIE: RootEntry, OutOffset: getDebugInfoHeaderSize(),
1383 FuncAddressAdjustment: std::nullopt, VarAddressAdjustment: std::nullopt, Allocator, ArtificialTypeUnit);
1384 setOutUnitDIE(OutCUDie.first);
1385
1386 if (!TargetTriple.has_value() || (OutCUDie.first == nullptr))
1387 return Error::success();
1388
1389 if (Error Err = cloneAndEmitLineTable(TargetTriple: (*TargetTriple).get()))
1390 return Err;
1391
1392 if (Error Err = cloneAndEmitDebugMacro())
1393 return Err;
1394
1395 getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugInfo);
1396 if (Error Err = emitDebugInfo(TargetTriple: (*TargetTriple).get()))
1397 return Err;
1398
1399 // ASSUMPTION: .debug_info section should already be emitted at this point.
1400 // cloneAndEmitRanges & cloneAndEmitDebugLocations use .debug_info section
1401 // data.
1402
1403 if (Error Err = cloneAndEmitRanges())
1404 return Err;
1405
1406 if (Error Err = cloneAndEmitDebugLocations())
1407 return Err;
1408
1409 if (Error Err = emitDebugAddrSection())
1410 return Err;
1411
1412 // Generate Pub accelerator tables.
1413 if (llvm::is_contained(Range: GlobalData.getOptions().AccelTables,
1414 Element: DWARFLinker::AccelTableKind::Pub))
1415 emitPubAccelerators();
1416
1417 if (Error Err = emitDebugStringOffsetSection())
1418 return Err;
1419
1420 return emitAbbreviations();
1421}
1422
1423std::pair<DIE *, TypeEntry *> CompileUnit::cloneDIE(
1424 const DWARFDebugInfoEntry *InputDieEntry, TypeEntry *ClonedParentTypeDIE,
1425 uint64_t OutOffset, std::optional<int64_t> FuncAddressAdjustment,
1426 std::optional<int64_t> VarAddressAdjustment, BumpPtrAllocator &Allocator,
1427 TypeUnit *ArtificialTypeUnit, uint32_t SiblingOrdinal) {
1428 uint32_t InputDieIdx = getDIEIndex(Die: InputDieEntry);
1429 CompileUnit::DIEInfo &Info = getDIEInfo(Idx: InputDieIdx);
1430
1431 bool NeedToClonePlainDIE = Info.needToKeepInPlainDwarf();
1432 bool NeedToCloneTypeDIE =
1433 (InputDieEntry->getTag() != dwarf::DW_TAG_compile_unit) &&
1434 Info.needToPlaceInTypeTable();
1435 std::pair<DIE *, TypeEntry *> ClonedDIE;
1436
1437 DIEGenerator PlainDIEGenerator(Allocator, *this);
1438
1439 if (NeedToClonePlainDIE)
1440 // Create a cloned DIE which would be placed into the cloned version
1441 // of input compile unit.
1442 ClonedDIE.first = createPlainDIEandCloneAttributes(
1443 InputDieEntry, PlainDIEGenerator, OutOffset, FuncAddressAdjustment,
1444 VarAddressAdjustment);
1445 if (NeedToCloneTypeDIE) {
1446 // Create a cloned DIE which would be placed into the artificial type
1447 // unit.
1448 assert(ArtificialTypeUnit != nullptr);
1449 DIEGenerator TypeDIEGenerator(
1450 ArtificialTypeUnit->getTypePool().getThreadLocalAllocator(), *this);
1451
1452 ClonedDIE.second = createTypeDIEandCloneAttributes(
1453 InputDieEntry, TypeDIEGenerator, ClonedParentTypeDIE,
1454 ArtificialTypeUnit, SiblingOrdinal);
1455 }
1456 TypeEntry *TypeParentForChild =
1457 ClonedDIE.second ? ClonedDIE.second : ClonedParentTypeDIE;
1458
1459 bool HasPlainChildrenToClone =
1460 (ClonedDIE.first && Info.getKeepPlainChildren());
1461
1462 bool HasTypeChildrenToClone =
1463 ((ClonedDIE.second ||
1464 InputDieEntry->getTag() == dwarf::DW_TAG_compile_unit) &&
1465 Info.getKeepTypeChildren());
1466
1467 // Recursively clone children.
1468 if (HasPlainChildrenToClone || HasTypeChildrenToClone) {
1469 uint32_t ChildOrdinal = 0;
1470 for (const DWARFDebugInfoEntry *CurChild =
1471 getFirstChildEntry(Die: InputDieEntry);
1472 CurChild && CurChild->getAbbreviationDeclarationPtr();
1473 CurChild = getSiblingEntry(Die: CurChild), ++ChildOrdinal) {
1474 std::pair<DIE *, TypeEntry *> ClonedChild = cloneDIE(
1475 InputDieEntry: CurChild, ClonedParentTypeDIE: TypeParentForChild, OutOffset, FuncAddressAdjustment,
1476 VarAddressAdjustment, Allocator, ArtificialTypeUnit, SiblingOrdinal: ChildOrdinal);
1477
1478 if (ClonedChild.first) {
1479 OutOffset =
1480 ClonedChild.first->getOffset() + ClonedChild.first->getSize();
1481 PlainDIEGenerator.addChild(Child: ClonedChild.first);
1482 }
1483 }
1484 assert(ClonedDIE.first == nullptr ||
1485 HasPlainChildrenToClone == ClonedDIE.first->hasChildren());
1486
1487 // Account for the end of children marker.
1488 if (HasPlainChildrenToClone)
1489 OutOffset += sizeof(int8_t);
1490 }
1491
1492 // Update our size.
1493 if (ClonedDIE.first != nullptr)
1494 ClonedDIE.first->setSize(OutOffset - ClonedDIE.first->getOffset());
1495
1496 return ClonedDIE;
1497}
1498
1499DIE *CompileUnit::createPlainDIEandCloneAttributes(
1500 const DWARFDebugInfoEntry *InputDieEntry, DIEGenerator &PlainDIEGenerator,
1501 uint64_t &OutOffset, std::optional<int64_t> &FuncAddressAdjustment,
1502 std::optional<int64_t> &VarAddressAdjustment) {
1503 uint32_t InputDieIdx = getDIEIndex(Die: InputDieEntry);
1504 CompileUnit::DIEInfo &Info = getDIEInfo(Idx: InputDieIdx);
1505 DIE *ClonedDIE = nullptr;
1506 bool HasLocationExpressionAddress = false;
1507 if (InputDieEntry->getTag() == dwarf::DW_TAG_subprogram) {
1508 // Get relocation adjustment value for the current function.
1509 FuncAddressAdjustment =
1510 getContainingFile().Addresses->getSubprogramRelocAdjustment(
1511 DIE: getDIE(Die: InputDieEntry), Verbose: false);
1512 } else if (InputDieEntry->getTag() == dwarf::DW_TAG_label) {
1513 // Get relocation adjustment value for the current label.
1514 std::optional<uint64_t> lowPC =
1515 dwarf::toAddress(V: find(Die: InputDieEntry, Attrs: dwarf::DW_AT_low_pc));
1516 if (lowPC) {
1517 LabelMapTy::iterator It = Labels.find(Val: *lowPC);
1518 if (It != Labels.end())
1519 FuncAddressAdjustment = It->second;
1520 }
1521 } else if (InputDieEntry->getTag() == dwarf::DW_TAG_variable) {
1522 // Get relocation adjustment value for the current variable.
1523 std::pair<bool, std::optional<int64_t>> LocExprAddrAndRelocAdjustment =
1524 getContainingFile().Addresses->getVariableRelocAdjustment(
1525 DIE: getDIE(Die: InputDieEntry), Verbose: false);
1526
1527 HasLocationExpressionAddress = LocExprAddrAndRelocAdjustment.first;
1528 if (LocExprAddrAndRelocAdjustment.first &&
1529 LocExprAddrAndRelocAdjustment.second)
1530 VarAddressAdjustment = *LocExprAddrAndRelocAdjustment.second;
1531 }
1532
1533 ClonedDIE = PlainDIEGenerator.createDIE(DieTag: InputDieEntry->getTag(), OutOffset);
1534
1535 // Offset to the DIE would be used after output DIE tree is deleted.
1536 // Thus we need to remember DIE offset separately.
1537 rememberDieOutOffset(Idx: InputDieIdx, Offset: OutOffset);
1538
1539 // Clone Attributes.
1540 DIEAttributeCloner AttributesCloner(ClonedDIE, *this, this, InputDieEntry,
1541 PlainDIEGenerator, FuncAddressAdjustment,
1542 VarAddressAdjustment,
1543 HasLocationExpressionAddress);
1544 AttributesCloner.clone();
1545
1546 // Remember accelerator info.
1547 AcceleratorRecordsSaver AccelRecordsSaver(getGlobalData(), *this, this);
1548 AccelRecordsSaver.save(InputDieEntry, OutDIE: ClonedDIE, AttrInfo&: AttributesCloner.AttrInfo,
1549 TypeEntry: nullptr);
1550
1551 OutOffset =
1552 AttributesCloner.finalizeAbbreviations(HasChildrenToClone: Info.getKeepPlainChildren());
1553
1554 return ClonedDIE;
1555}
1556
1557/// Allocates output DIE for the specified \p TypeDescriptor.
1558DIE *CompileUnit::allocateTypeDie(TypeEntryBody *TypeDescriptor,
1559 DIEGenerator &TypeDIEGenerator,
1560 dwarf::Tag DieTag, bool IsDeclaration,
1561 bool IsParentDeclaration) {
1562 uint64_t Priority = getPriority();
1563
1564 // Lock-free pre-checks: skip the lock (and downstream cloning) when this CU
1565 // has no chance of winning the type slot.
1566 if (!IsDeclaration && !IsParentDeclaration) {
1567 // DiePriority only ever decreases, so a relaxed read that is <= our
1568 // priority means we definitely cannot win.
1569 if (Priority >= TypeDescriptor->DiePriority.load(m: std::memory_order_relaxed))
1570 return nullptr;
1571 } else {
1572 // Once a definition exists the declaration slot is dead.
1573 if (TypeDescriptor->Die.load(m: std::memory_order_relaxed))
1574 return nullptr;
1575 }
1576
1577 while (TypeDescriptor->Lock.test_and_set(m: std::memory_order_acquire))
1578 ; // spin
1579
1580 DIE *Result = nullptr;
1581
1582 if (!IsDeclaration && !IsParentDeclaration) {
1583 // Definition: lowest priority wins.
1584 if (Priority <
1585 TypeDescriptor->DiePriority.load(m: std::memory_order_relaxed)) {
1586 TypeDescriptor->DiePriority.store(i: Priority, m: std::memory_order_relaxed);
1587 Result = TypeDIEGenerator.createDIE(DieTag, OutOffset: 0);
1588 TypeDescriptor->Die.store(p: Result, m: std::memory_order_relaxed);
1589 }
1590 } else if (!TypeDescriptor->Die.load(m: std::memory_order_relaxed)) {
1591 // Declaration (no definition exists yet).
1592 // Prefer declarations whose parent is a definition (better context);
1593 // break ties by CU priority (lower wins).
1594 bool WorseParent =
1595 IsParentDeclaration && !TypeDescriptor->DeclarationParentIsDeclaration;
1596 bool BetterParent =
1597 !IsParentDeclaration && TypeDescriptor->DeclarationParentIsDeclaration;
1598 if (!WorseParent &&
1599 (BetterParent || Priority < TypeDescriptor->DeclarationDiePriority)) {
1600 TypeDescriptor->DeclarationDiePriority = Priority;
1601 TypeDescriptor->DeclarationParentIsDeclaration = IsParentDeclaration;
1602 Result = TypeDIEGenerator.createDIE(DieTag, OutOffset: 0);
1603 TypeDescriptor->DeclarationDie.store(p: Result, m: std::memory_order_relaxed);
1604 }
1605 }
1606
1607 TypeDescriptor->Lock.clear(m: std::memory_order_release);
1608 return Result;
1609}
1610
1611TypeEntry *CompileUnit::createTypeDIEandCloneAttributes(
1612 const DWARFDebugInfoEntry *InputDieEntry, DIEGenerator &TypeDIEGenerator,
1613 TypeEntry *ClonedParentTypeDIE, TypeUnit *ArtificialTypeUnit,
1614 uint32_t SiblingOrdinal) {
1615 assert(ArtificialTypeUnit != nullptr);
1616 uint32_t InputDieIdx = getDIEIndex(Die: InputDieEntry);
1617
1618 TypeEntry *Entry = getDieTypeEntry(Idx: InputDieIdx);
1619 assert(Entry != nullptr);
1620 assert(ClonedParentTypeDIE != nullptr);
1621 TypeEntryBody *EntryBody =
1622 ArtificialTypeUnit->getTypePool().getOrCreateTypeEntryBody(
1623 Entry, ParentEntry: ClonedParentTypeDIE);
1624 assert(EntryBody);
1625
1626 // Min-merge this child's ordinal in its parent's child list so children of
1627 // record-like types (class/struct/union/interface) sort in source order.
1628 // Min across CUs because Clang appends template instantiations lazily, so
1629 // positions vary between CUs.
1630 if (std::optional<uint32_t> ParentIdx = InputDieEntry->getParentIdx()) {
1631 dwarf::Tag ParentTag = getDebugInfoEntry(Index: *ParentIdx)->getTag();
1632 if (ParentTag == dwarf::DW_TAG_structure_type ||
1633 ParentTag == dwarf::DW_TAG_class_type ||
1634 ParentTag == dwarf::DW_TAG_union_type ||
1635 ParentTag == dwarf::DW_TAG_interface_type) {
1636 uint32_t Prev = EntryBody->SortKey.load(m: std::memory_order_relaxed);
1637 while (SiblingOrdinal < Prev &&
1638 !EntryBody->SortKey.compare_exchange_weak(
1639 i1&: Prev, i2: SiblingOrdinal, m1: std::memory_order_relaxed,
1640 m2: std::memory_order_relaxed))
1641 ;
1642 }
1643 }
1644
1645 bool IsDeclaration =
1646 dwarf::toUnsigned(V: find(Die: InputDieEntry, Attrs: dwarf::DW_AT_declaration), Default: 0);
1647
1648 bool ParentIsDeclaration = false;
1649 if (std::optional<uint32_t> ParentIdx = InputDieEntry->getParentIdx())
1650 ParentIsDeclaration =
1651 dwarf::toUnsigned(V: find(DieIdx: *ParentIdx, Attrs: dwarf::DW_AT_declaration), Default: 0);
1652
1653 DIE *OutDIE =
1654 allocateTypeDie(TypeDescriptor: EntryBody, TypeDIEGenerator, DieTag: InputDieEntry->getTag(),
1655 IsDeclaration, IsParentDeclaration: ParentIsDeclaration);
1656
1657 if (OutDIE != nullptr) {
1658 assert(ArtificialTypeUnit != nullptr);
1659 ArtificialTypeUnit->getSectionDescriptor(SectionKind: DebugSectionKind::DebugInfo);
1660
1661 DIEAttributeCloner AttributesCloner(OutDIE, *this, ArtificialTypeUnit,
1662 InputDieEntry, TypeDIEGenerator,
1663 std::nullopt, std::nullopt, false);
1664 AttributesCloner.clone();
1665
1666 // Remember accelerator info.
1667 AcceleratorRecordsSaver AccelRecordsSaver(getGlobalData(), *this,
1668 ArtificialTypeUnit);
1669 AccelRecordsSaver.save(InputDieEntry, OutDIE, AttrInfo&: AttributesCloner.AttrInfo,
1670 TypeEntry: Entry);
1671
1672 // if AttributesCloner.getOutOffset() == 0 then we need to add
1673 // 1 to avoid assertion for zero size. We will subtract it back later.
1674 OutDIE->setSize(AttributesCloner.getOutOffset() + 1);
1675 }
1676
1677 return Entry;
1678}
1679
1680Error CompileUnit::cloneAndEmitLineTable(const Triple &TargetTriple) {
1681 const DWARFDebugLine::LineTable *InputLineTable =
1682 getContainingFile().Dwarf->getLineTableForUnit(U: &getOrigUnit());
1683 if (InputLineTable == nullptr) {
1684 if (getOrigUnit().getUnitDIE().find(Attr: dwarf::DW_AT_stmt_list))
1685 warn(Warning: "cann't load line table.");
1686 return Error::success();
1687 }
1688
1689 DWARFDebugLine::LineTable OutLineTable;
1690
1691 // Set Line Table header.
1692 OutLineTable.Prologue = InputLineTable->Prologue;
1693 OutLineTable.Prologue.FormParams.AddrSize = getFormParams().AddrSize;
1694
1695 // Set Line Table Rows.
1696 if (getGlobalData().getOptions().UpdateIndexTablesOnly) {
1697 OutLineTable.Rows = InputLineTable->Rows;
1698 // If all the line table contains is a DW_LNE_end_sequence, clear the line
1699 // table rows, it will be inserted again in the DWARFStreamer.
1700 if (OutLineTable.Rows.size() == 1 && OutLineTable.Rows[0].EndSequence)
1701 OutLineTable.Rows.clear();
1702
1703 OutLineTable.Sequences = InputLineTable->Sequences;
1704 return emitDebugLine(TargetTriple, OutLineTable);
1705 }
1706
1707 SmallVector<uint64_t> OrigRowIndices;
1708 filterLineTableRows(InputLineTable: *InputLineTable, NewRows&: OutLineTable.Rows, NewRowIndices&: OrigRowIndices);
1709
1710 if (StmtSeqListAttributes.empty())
1711 return emitDebugLine(TargetTriple, OutLineTable);
1712
1713 // When DW_AT_LLVM_stmt_sequence attributes on this CU need their values
1714 // rewritten to point at the correct output sequence, have the emitter
1715 // record, for every row that originated from an input row, the byte
1716 // offset of the DW_LNE_set_address that opens the sequence containing
1717 // that row. Keying the map on the input row index (rather than on an
1718 // output address) avoids collisions when two input sequences would
1719 // relocate to the same output address — e.g. ICF folding two functions
1720 // from the same CU to a single output range.
1721 //
1722 // The patching below MUST run before emitDebugInfo() serializes the
1723 // DIE bytes and before OutputSections::applyPatches() runs for this
1724 // unit's .debug_info — it writes a local offset into the DIEValue that
1725 // the serializer then emits, and a DebugOffsetPatch (registered at DIE
1726 // cloning time) later adds the CU's .debug_line start offset to reach
1727 // the final absolute value.
1728 DenseMap<uint64_t, uint64_t> RowIndexToSeqStartOffset;
1729 if (Error Err = emitDebugLine(TargetTriple, OutLineTable, OrigRowIndices,
1730 RowIndexToSeqStartOffset: &RowIndexToSeqStartOffset))
1731 return Err;
1732
1733 DenseMap<uint64_t, uint64_t> SeqOffsetToFirstRowIndex =
1734 buildStmtSeqOffsetToFirstRowIndex(InputLineTable: *InputLineTable);
1735 patchStmtSeqAttributes(SeqOffsetToFirstRowIndex, RowIndexToSeqStartOffset);
1736 return Error::success();
1737}
1738
1739void CompileUnit::filterLineTableRows(
1740 const DWARFDebugLine::LineTable &InputLineTable,
1741 std::vector<DWARFDebugLine::Row> &NewRows,
1742 SmallVectorImpl<uint64_t> &NewRowIndices) {
1743 NewRows.reserve(n: InputLineTable.Rows.size());
1744 NewRowIndices.reserve(N: InputLineTable.Rows.size());
1745
1746 // Current sequence of rows being extracted, before being inserted
1747 // in NewRows. Kept in lockstep with SeqIndices, which stores the
1748 // originating input row index (or InvalidRowIndex for manufactured
1749 // end-of-range rows).
1750 std::vector<DWARFDebugLine::Row> Seq;
1751 SmallVector<uint64_t> SeqIndices;
1752 constexpr uint64_t InvalidRowIndex = std::numeric_limits<uint64_t>::max();
1753
1754 const auto &FunctionRanges = getFunctionRanges();
1755 std::optional<AddressRangeValuePair> CurrRange;
1756
1757 // FIXME: This logic is meant to generate exactly the same output as
1758 // Darwin's classic dsymutil. There is a nicer way to implement this
1759 // by simply putting all the relocated line info in NewRows and simply
1760 // sorting NewRows before passing it to emitLineTableForUnit. This
1761 // should be correct as sequences for a function should stay
1762 // together in the sorted output. There are a few corner cases that
1763 // look suspicious though, and that required to implement the logic
1764 // this way. Revisit that once initial validation is finished.
1765
1766 // Iterate over the object file line info and extract the sequences
1767 // that correspond to linked functions.
1768 for (auto [InputRowIdx, InputRow] : llvm::enumerate(First: InputLineTable.Rows)) {
1769 DWARFDebugLine::Row Row = InputRow;
1770 // Check whether we stepped out of the range. The range is
1771 // half-open, but consider accept the end address of the range if
1772 // it is marked as end_sequence in the input (because in that
1773 // case, the relocation offset is accurate and that entry won't
1774 // serve as the start of another function).
1775 if (!CurrRange || !CurrRange->Range.contains(Addr: Row.Address.Address)) {
1776 // We just stepped out of a known range. Insert a end_sequence
1777 // corresponding to the end of the range.
1778 uint64_t StopAddress =
1779 CurrRange ? CurrRange->Range.end() + CurrRange->Value : -1ULL;
1780 CurrRange = FunctionRanges.getRangeThatContains(Addr: Row.Address.Address);
1781 if (StopAddress != -1ULL && !Seq.empty()) {
1782 // Insert end sequence row with the computed end address, but
1783 // the same line as the previous one. This row is synthesised
1784 // and has no input counterpart, so tag it with
1785 // InvalidRowIndex.
1786 auto NextLine = Seq.back();
1787 NextLine.Address.Address = StopAddress;
1788 NextLine.EndSequence = 1;
1789 NextLine.PrologueEnd = 0;
1790 NextLine.BasicBlock = 0;
1791 NextLine.EpilogueBegin = 0;
1792 Seq.push_back(x: NextLine);
1793 SeqIndices.push_back(Elt: InvalidRowIndex);
1794 insertLineSequence(Seq, SeqIndices, Rows&: NewRows, RowIndices&: NewRowIndices);
1795 }
1796
1797 if (!CurrRange)
1798 continue;
1799 }
1800
1801 // Ignore empty sequences.
1802 if (Row.EndSequence && Seq.empty())
1803 continue;
1804
1805 // Relocate row address and add it to the current sequence.
1806 Row.Address.Address += CurrRange->Value;
1807 Seq.emplace_back(args&: Row);
1808 SeqIndices.push_back(Elt: InputRowIdx);
1809
1810 if (Row.EndSequence)
1811 insertLineSequence(Seq, SeqIndices, Rows&: NewRows, RowIndices&: NewRowIndices);
1812 }
1813}
1814
1815void CompileUnit::patchStmtSeqAttributes(
1816 const DenseMap<uint64_t, uint64_t> &SeqOffsetToFirstRowIndex,
1817 const DenseMap<uint64_t, uint64_t> &RowIndexToSeqStartOffset) {
1818 const uint64_t InvalidOffset = getFormParams().getDwarfMaxOffset();
1819
1820 for (const CompileUnit::StmtSeqPatch &Patch : StmtSeqListAttributes) {
1821 uint64_t NewStmtSeq = InvalidOffset;
1822 auto RowIt = SeqOffsetToFirstRowIndex.find(Val: Patch.InputStmtSeqOffset);
1823 if (RowIt != SeqOffsetToFirstRowIndex.end()) {
1824 auto OffIt = RowIndexToSeqStartOffset.find(Val: RowIt->second);
1825 if (OffIt != RowIndexToSeqStartOffset.end())
1826 NewStmtSeq = OffIt->second;
1827 }
1828 // When resolution fails, the InvalidOffset sentinel must survive the
1829 // combination-time section-offset fixup. The patch applier preserves
1830 // InvalidOffset as-is so consumers see a clean invalid marker rather
1831 // than StartOffset - 1.
1832 *Patch.Value = DIEValue(Patch.Value->getAttribute(), Patch.Value->getForm(),
1833 DIEInteger(NewStmtSeq));
1834 }
1835}
1836
1837DenseMap<uint64_t, uint64_t> CompileUnit::buildStmtSeqOffsetToFirstRowIndex(
1838 const DWARFDebugLine::LineTable &InputLineTable) const {
1839 // Collect this CU's stmt-sequence attribute values (input offsets),
1840 // sorted ascending and deduplicated.
1841 SmallVector<uint64_t> StmtAttrs;
1842 StmtAttrs.reserve(N: StmtSeqListAttributes.size());
1843 for (const StmtSeqPatch &Patch : StmtSeqListAttributes)
1844 StmtAttrs.push_back(Elt: Patch.InputStmtSeqOffset);
1845 llvm::sort(C&: StmtAttrs);
1846 StmtAttrs.erase(CS: llvm::unique(R&: StmtAttrs), CE: StmtAttrs.end());
1847
1848 DenseMap<uint64_t, uint64_t> Result;
1849 dwarf_linker::buildStmtSeqOffsetToFirstRowIndex(LT: InputLineTable, SortedStmtSeqOffsets: StmtAttrs,
1850 SeqOffToFirstRow&: Result);
1851 return Result;
1852}
1853
1854void CompileUnit::insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
1855 SmallVectorImpl<uint64_t> &SeqIndices,
1856 std::vector<DWARFDebugLine::Row> &Rows,
1857 SmallVectorImpl<uint64_t> &RowIndices) {
1858 assert(Seq.size() == SeqIndices.size() &&
1859 "Seq and SeqIndices must be kept in lockstep");
1860 assert(Rows.size() == RowIndices.size() &&
1861 "Rows and RowIndices must be kept in lockstep");
1862 if (Seq.empty())
1863 return;
1864
1865 auto ClearSeq = [&] {
1866 Seq.clear();
1867 SeqIndices.clear();
1868 };
1869
1870 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
1871 llvm::append_range(C&: Rows, R&: Seq);
1872 llvm::append_range(C&: RowIndices, R&: SeqIndices);
1873 ClearSeq();
1874 return;
1875 }
1876
1877 object::SectionedAddress Front = Seq.front().Address;
1878 auto InsertPoint = partition_point(
1879 Range&: Rows, P: [=](const DWARFDebugLine::Row &O) { return O.Address < Front; });
1880 size_t InsertIdx = std::distance(first: Rows.begin(), last: InsertPoint);
1881
1882 // FIXME: this only removes the unneeded end_sequence if the
1883 // sequences have been inserted in order. Using a global sort like
1884 // described in cloneAndEmitLineTable() and delaying the end_sequene
1885 // elimination to DebugLineEmitter::emit() we can get rid of all of them.
1886 if (InsertPoint != Rows.end() && InsertPoint->Address == Front &&
1887 InsertPoint->EndSequence) {
1888 *InsertPoint = Seq.front();
1889 RowIndices[InsertIdx] = SeqIndices.front();
1890 Rows.insert(position: InsertPoint + 1, first: Seq.begin() + 1, last: Seq.end());
1891 RowIndices.insert(I: RowIndices.begin() + InsertIdx + 1,
1892 From: SeqIndices.begin() + 1, To: SeqIndices.end());
1893 } else {
1894 Rows.insert(position: InsertPoint, first: Seq.begin(), last: Seq.end());
1895 RowIndices.insert(I: RowIndices.begin() + InsertIdx, From: SeqIndices.begin(),
1896 To: SeqIndices.end());
1897 }
1898
1899 ClearSeq();
1900}
1901
1902#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1903LLVM_DUMP_METHOD void CompileUnit::DIEInfo::dump() {
1904 llvm::errs() << "{";
1905 llvm::errs() << " Placement: ";
1906 switch (getPlacement()) {
1907 case NotSet:
1908 llvm::errs() << "NotSet";
1909 break;
1910 case TypeTable:
1911 llvm::errs() << "TypeTable";
1912 break;
1913 case PlainDwarf:
1914 llvm::errs() << "PlainDwarf";
1915 break;
1916 case Both:
1917 llvm::errs() << "Both";
1918 break;
1919 }
1920
1921 llvm::errs() << " Keep: " << getKeep();
1922 llvm::errs() << " KeepPlainChildren: " << getKeepPlainChildren();
1923 llvm::errs() << " KeepTypeChildren: " << getKeepTypeChildren();
1924 llvm::errs() << " IsInMouduleScope: " << getIsInMouduleScope();
1925 llvm::errs() << " IsInFunctionScope: " << getIsInFunctionScope();
1926 llvm::errs() << " IsInAnonNamespaceScope: " << getIsInAnonNamespaceScope();
1927 llvm::errs() << " ODRAvailable: " << getODRAvailable();
1928 llvm::errs() << " TrackLiveness: " << getTrackLiveness();
1929 llvm::errs() << "}\n";
1930}
1931#endif // if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1932
1933std::optional<std::pair<StringRef, StringRef>>
1934CompileUnit::getDirAndFilenameFromLineTable(
1935 const DWARFFormValue &FileIdxValue) {
1936 uint64_t FileIdx;
1937 if (std::optional<uint64_t> Val = FileIdxValue.getAsUnsignedConstant())
1938 FileIdx = *Val;
1939 else if (std::optional<int64_t> Val = FileIdxValue.getAsSignedConstant())
1940 FileIdx = *Val;
1941 else if (std::optional<uint64_t> Val = FileIdxValue.getAsSectionOffset())
1942 FileIdx = *Val;
1943 else
1944 return std::nullopt;
1945
1946 return getDirAndFilenameFromLineTable(FileIdx);
1947}
1948
1949std::optional<std::pair<StringRef, StringRef>>
1950CompileUnit::getDirAndFilenameFromLineTable(uint64_t FileIdx) {
1951 std::lock_guard<std::mutex> Guard(FileNamesMutex);
1952 FileNamesCache::iterator FileData = FileNames.find(Val: FileIdx);
1953 if (FileData != FileNames.end())
1954 return {{StringRef(FileData->second->first),
1955 StringRef(FileData->second->second)}};
1956
1957 if (const DWARFDebugLine::LineTable *LineTable =
1958 getOrigUnit().getContext().getLineTableForUnit(U: &getOrigUnit())) {
1959 if (LineTable->hasFileAtIndex(FileIndex: FileIdx)) {
1960
1961 const llvm::DWARFDebugLine::FileNameEntry &Entry =
1962 LineTable->Prologue.getFileNameEntry(Index: FileIdx);
1963
1964 Expected<const char *> Name = Entry.Name.getAsCString();
1965 if (!Name) {
1966 warn(Warning: Name.takeError());
1967 return std::nullopt;
1968 }
1969
1970 std::string FileName = *Name;
1971 if (isPathAbsoluteOnWindowsOrPosix(Path: FileName)) {
1972 FileName = File.remapPath(Path: FileName);
1973 FileNamesCache::iterator FileData =
1974 FileNames
1975 .insert(KV: {FileIdx,
1976 std::make_unique<std::pair<std::string, std::string>>(
1977 args: std::string(""), args: std::move(FileName))})
1978 .first;
1979 return {{StringRef(FileData->second->first),
1980 StringRef(FileData->second->second)}};
1981 }
1982
1983 SmallString<256> FilePath;
1984 StringRef IncludeDir;
1985 // Be defensive about the contents of Entry.
1986 if (getVersion() >= 5) {
1987 // DirIdx 0 is the compilation directory, so don't include it for
1988 // relative names.
1989 if ((Entry.DirIdx != 0) &&
1990 Entry.DirIdx < LineTable->Prologue.IncludeDirectories.size()) {
1991 Expected<const char *> DirName =
1992 LineTable->Prologue.IncludeDirectories[Entry.DirIdx]
1993 .getAsCString();
1994 if (DirName)
1995 IncludeDir = *DirName;
1996 else {
1997 warn(Warning: DirName.takeError());
1998 return std::nullopt;
1999 }
2000 }
2001 } else {
2002 if (0 < Entry.DirIdx &&
2003 Entry.DirIdx <= LineTable->Prologue.IncludeDirectories.size()) {
2004 Expected<const char *> DirName =
2005 LineTable->Prologue.IncludeDirectories[Entry.DirIdx - 1]
2006 .getAsCString();
2007 if (DirName)
2008 IncludeDir = *DirName;
2009 else {
2010 warn(Warning: DirName.takeError());
2011 return std::nullopt;
2012 }
2013 }
2014 }
2015
2016 StringRef CompDir = getOrigUnit().getCompilationDir();
2017
2018 if (!CompDir.empty() && !isPathAbsoluteOnWindowsOrPosix(Path: IncludeDir)) {
2019 sys::path::append(path&: FilePath, style: sys::path::Style::native, a: CompDir);
2020 }
2021
2022 sys::path::append(path&: FilePath, style: sys::path::Style::native, a: IncludeDir);
2023
2024 FileNamesCache::iterator FileData =
2025 FileNames
2026 .insert(KV: {FileIdx,
2027 std::make_unique<std::pair<std::string, std::string>>(
2028 args: File.remapPath(Path: FilePath), args: std::move(FileName))})
2029 .first;
2030 return {{StringRef(FileData->second->first),
2031 StringRef(FileData->second->second)}};
2032 }
2033 }
2034
2035 return std::nullopt;
2036}
2037
2038#define MAX_REFERENCIES_DEPTH 1000
2039UnitEntryPairTy UnitEntryPairTy::getNamespaceOrigin() {
2040 UnitEntryPairTy CUDiePair(*this);
2041 std::optional<UnitEntryPairTy> RefDiePair;
2042 int refDepth = 0;
2043 do {
2044 RefDiePair = CUDiePair.CU->resolveDIEReference(
2045 DieEntry: CUDiePair.DieEntry, Attr: dwarf::DW_AT_extension,
2046 CanResolveInterCUReferences: ResolveInterCUReferencesMode::Resolve);
2047 if (!RefDiePair || !RefDiePair->DieEntry)
2048 return CUDiePair;
2049
2050 CUDiePair = *RefDiePair;
2051 } while (refDepth++ < MAX_REFERENCIES_DEPTH);
2052
2053 return CUDiePair;
2054}
2055
2056std::optional<UnitEntryPairTy> UnitEntryPairTy::getParent() {
2057 if (std::optional<uint32_t> ParentIdx = DieEntry->getParentIdx())
2058 return UnitEntryPairTy{CU, CU->getDebugInfoEntry(Index: *ParentIdx)};
2059
2060 return std::nullopt;
2061}
2062
2063CompileUnit::OutputUnitVariantPtr::OutputUnitVariantPtr(CompileUnit *U)
2064 : Ptr(U) {
2065 assert(U != nullptr);
2066}
2067
2068CompileUnit::OutputUnitVariantPtr::OutputUnitVariantPtr(TypeUnit *U) : Ptr(U) {
2069 assert(U != nullptr);
2070}
2071
2072DwarfUnit *CompileUnit::OutputUnitVariantPtr::operator->() {
2073 if (isCompileUnit())
2074 return getAsCompileUnit();
2075 else
2076 return getAsTypeUnit();
2077}
2078
2079bool CompileUnit::OutputUnitVariantPtr::isCompileUnit() {
2080 return isa<CompileUnit *>(Val: Ptr);
2081}
2082
2083bool CompileUnit::OutputUnitVariantPtr::isTypeUnit() {
2084 return isa<TypeUnit *>(Val: Ptr);
2085}
2086
2087CompileUnit *CompileUnit::OutputUnitVariantPtr::getAsCompileUnit() {
2088 return cast<CompileUnit *>(Val&: Ptr);
2089}
2090
2091TypeUnit *CompileUnit::OutputUnitVariantPtr::getAsTypeUnit() {
2092 return cast<TypeUnit *>(Val&: Ptr);
2093}
2094
2095void CompileUnit::collectLiveRoots() {
2096 if (!Dependencies)
2097 Dependencies.reset(p: new DependencyTracker(*this));
2098
2099 Dependencies->collectLiveRoots();
2100}
2101
2102bool CompileUnit::resolveDependenciesAndMarkLiveness(
2103 bool InterCUProcessingStarted, std::atomic<bool> &HasNewInterconnectedCUs) {
2104 assert(Dependencies.get());
2105
2106 return Dependencies->resolveDependenciesAndMarkLiveness(
2107 InterCUProcessingStarted, HasNewInterconnectedCUs);
2108}
2109
2110bool CompileUnit::updateDependenciesCompleteness() {
2111 assert(Dependencies.get());
2112
2113 return Dependencies->updateDependenciesCompleteness();
2114}
2115
2116void CompileUnit::verifyDependencies() {
2117 assert(Dependencies.get());
2118
2119 Dependencies->verifyKeepChain();
2120}
2121
2122ArrayRef<dwarf::Attribute> dwarf_linker::parallel::getODRAttributes() {
2123 static dwarf::Attribute ODRAttributes[] = {
2124 dwarf::DW_AT_type, dwarf::DW_AT_specification,
2125 dwarf::DW_AT_abstract_origin, dwarf::DW_AT_import,
2126 dwarf::DW_AT_LLVM_alloc_type};
2127
2128 return ODRAttributes;
2129}
2130