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