1//===-- SourcePrinter.cpp - source interleaving utilities ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the LiveElementPrinter and SourcePrinter classes to
10// keep track of DWARF info as the current address is updated, and print out the
11// source file line and variable or inlined function liveness as needed.
12//
13//===----------------------------------------------------------------------===//
14
15#include "SourcePrinter.h"
16#include "llvm-objdump.h"
17#include "llvm/ADT/SmallString.h"
18#include "llvm/DebugInfo/DWARF/DWARFExpressionPrinter.h"
19#include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h"
20#include "llvm/Demangle/Demangle.h"
21#include "llvm/Support/FileSystem.h"
22#include "llvm/Support/FormatVariadic.h"
23#include "llvm/Support/Path.h"
24
25#define DEBUG_TYPE "objdump"
26
27namespace llvm {
28namespace objdump {
29
30static bool sourceFileExists(StringRef Path) {
31 if (sys::fs::exists(Path) && !sys::fs::is_directory(Path))
32 return true;
33
34 return false;
35}
36
37static void normalizeSourcePath(SmallVectorImpl<char> &Path) {
38 sys::path::native(path&: Path);
39 sys::path::remove_dots(path&: Path, /*remove_dot_dot=*/true);
40}
41
42static std::optional<std::string> trySourcePath(StringRef Path) {
43 SmallString<256> Normalized(Path);
44 normalizeSourcePath(Path&: Normalized);
45 if (sourceFileExists(Path: Normalized))
46 return std::string(Normalized);
47 return std::nullopt;
48}
49
50static std::optional<std::string>
51searchSourceWithDirs(StringRef FileName, ArrayRef<StringRef> SearchDirs,
52 bool TryLiteralFirst) {
53 if (TryLiteralFirst)
54 if (auto Path = trySourcePath(Path: FileName))
55 return Path;
56
57 StringRef PathSuffix = sys::path::relative_path(path: FileName);
58 StringRef BaseName = sys::path::filename(path: FileName);
59 for (StringRef Dir : SearchDirs) {
60 SmallString<256> Candidate(Dir);
61 sys::path::append(path&: Candidate, a: PathSuffix);
62 if (auto Path = trySourcePath(Path: Candidate))
63 return Path;
64 }
65 for (StringRef Dir : SearchDirs) {
66 SmallString<256> Candidate(Dir);
67 sys::path::append(path&: Candidate, a: BaseName);
68 if (auto Path = trySourcePath(Path: Candidate))
69 return Path;
70 }
71 return std::nullopt;
72}
73
74static std::optional<std::string>
75findSourceFilePath(StringRef FileName, ArrayRef<StringRef> SearchDirs) {
76 if (FileName.empty() || FileName == DILineInfo::BadString)
77 return std::nullopt;
78
79 if (sys::path::is_absolute_gnu(path: FileName))
80 return searchSourceWithDirs(FileName, SearchDirs, /*TryLiteralFirst=*/true);
81 return searchSourceWithDirs(FileName, SearchDirs, /*TryLiteralFirst=*/false);
82}
83
84static std::string applySubstitutePaths(StringRef FileName) {
85 if (SubstitutePaths.empty())
86 return FileName.str();
87
88 StringRef BaseName = sys::path::filename(path: FileName);
89 SmallString<256> Directory(sys::path::parent_path(path: FileName));
90 normalizeSourcePath(Path&: Directory);
91
92 for (const auto &[From, To] : SubstitutePaths) {
93 SmallString<256> FromPath(From);
94 normalizeSourcePath(Path&: FromPath);
95 StringRef Dir = Directory;
96 if (!Dir.starts_with(Prefix: FromPath))
97 continue;
98 if (Dir.size() > FromPath.size() &&
99 !sys::path::is_separator(value: Dir[FromPath.size()]))
100 continue;
101
102 SmallString<256> NewDir(To);
103 StringRef Suffix = Dir.substr(Start: FromPath.size());
104 while (!Suffix.empty() && sys::path::is_separator(value: Suffix.front()))
105 Suffix = Suffix.drop_front();
106 if (!Suffix.empty())
107 sys::path::append(path&: NewDir, a: Suffix);
108 normalizeSourcePath(Path&: NewDir);
109
110 if (NewDir.empty())
111 return BaseName.str();
112 SmallString<256> Result(NewDir);
113 sys::path::append(path&: Result, a: BaseName);
114 normalizeSourcePath(Path&: Result);
115 return std::string(Result);
116 }
117
118 return FileName.str();
119}
120
121bool InlinedFunction::liveAtAddress(object::SectionedAddress Addr) const {
122 if (!Range.valid())
123 return false;
124
125 return Range.LowPC <= Addr.Address && Range.HighPC > Addr.Address;
126}
127
128void InlinedFunction::print(raw_ostream &OS, const MCRegisterInfo &MRI) const {
129 const char *MangledCallerName = FuncDie.getName(Kind: DINameKind::LinkageName);
130 if (!MangledCallerName)
131 return;
132
133 if (Demangle)
134 OS << "inlined into " << demangle(MangledName: MangledCallerName);
135 else
136 OS << "inlined into " << MangledCallerName;
137}
138
139void InlinedFunction::dump(raw_ostream &OS) const {
140 OS << Name << " @ " << Range << ": ";
141}
142
143void InlinedFunction::printElementLine(raw_ostream &OS,
144 object::SectionedAddress Addr,
145 bool IsEnd) const {
146 uint32_t CallFile, CallLine, CallColumn, CallDiscriminator;
147 InlinedFuncDie.getCallerFrame(CallFile, CallLine, CallColumn,
148 CallDiscriminator);
149 const DWARFDebugLine::LineTable *LineTable =
150 Unit->getContext().getLineTableForUnit(U: Unit);
151 std::string FileName;
152 if (!LineTable->hasFileAtIndex(FileIndex: CallFile))
153 return;
154 if (!LineTable->getFileNameByIndex(
155 FileIndex: CallFile, CompDir: Unit->getCompilationDir(),
156 Kind: DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Result&: FileName))
157 return;
158
159 if (FileName.empty())
160 return;
161
162 const char *MangledCallerName = FuncDie.getName(Kind: DINameKind::LinkageName);
163 if (!MangledCallerName)
164 return;
165
166 std::string CallerName = MangledCallerName;
167 std::string CalleeName = Name;
168 if (Demangle) {
169 CallerName = demangle(MangledName: MangledCallerName);
170 CalleeName = demangle(MangledName: Name);
171 }
172
173 OS << "; " << FileName << ":" << CallLine << ":" << CallColumn << ": ";
174 if (IsEnd)
175 OS << "end of ";
176 OS << CalleeName << " inlined into " << CallerName << "\n";
177}
178
179bool LiveVariable::liveAtAddress(object::SectionedAddress Addr) const {
180 if (LocExpr.Range == std::nullopt)
181 return false;
182 return LocExpr.Range->SectionIndex == Addr.SectionIndex &&
183 LocExpr.Range->LowPC <= Addr.Address &&
184 LocExpr.Range->HighPC > Addr.Address;
185}
186
187void LiveVariable::print(raw_ostream &OS, const MCRegisterInfo &MRI) const {
188 DataExtractor Data(LocExpr.Expr, Unit->getContext().isLittleEndian());
189 DWARFExpression Expression(Data, Unit->getAddressByteSize());
190
191 auto GetRegName = [&MRI](uint64_t DwarfRegNum, bool IsEH) -> StringRef {
192 if (std::optional<MCRegister> LLVMRegNum =
193 MRI.getLLVMRegNum(RegNum: DwarfRegNum, isEH: IsEH))
194 if (const char *RegName = MRI.getName(RegNo: *LLVMRegNum))
195 return StringRef(RegName);
196 return {};
197 };
198
199 printDwarfExpressionCompact(E: &Expression, OS, GetNameForDWARFReg: GetRegName);
200}
201
202void LiveVariable::dump(raw_ostream &OS) const {
203 OS << Name << " @ " << LocExpr.Range << ": ";
204}
205
206void LiveElementPrinter::addInlinedFunction(DWARFDie FuncDie,
207 DWARFDie InlinedFuncDie) {
208 uint64_t FuncLowPC, FuncHighPC, SectionIndex;
209 if (!InlinedFuncDie.getLowAndHighPC(LowPC&: FuncLowPC, HighPC&: FuncHighPC, SectionIndex))
210 return;
211
212 DWARFUnit *U = InlinedFuncDie.getDwarfUnit();
213 const char *InlinedFuncName = InlinedFuncDie.getName(Kind: DINameKind::LinkageName);
214 DWARFAddressRange Range{FuncLowPC, FuncHighPC, SectionIndex};
215 // Add the new element to the main vector.
216 LiveElements.emplace_back(args: std::make_unique<InlinedFunction>(
217 args&: InlinedFuncName, args&: U, args&: FuncDie, args&: InlinedFuncDie, args&: Range));
218
219 LiveElement *LE = LiveElements.back().get();
220 // Map the element's low address (LowPC) to its pointer for fast range start
221 // lookup.
222 LiveElementsByAddress[FuncLowPC].push_back(x: LE);
223 // Map the element's high address (HighPC) to its pointer for fast range end
224 // lookup.
225 LiveElementsByEndAddress[FuncHighPC].push_back(x: LE);
226 // Map the pointer to its DWARF discovery index for deterministic
227 // ordering.
228 ElementPtrToIndex[LE] = LiveElements.size() - 1;
229}
230
231/// Registers the most recently added LiveVariable into all data structures.
232void LiveElementPrinter::registerNewVariable() {
233 assert(
234 !LiveElements.empty() &&
235 "registerNewVariable called before element was added to LiveElements.");
236 LiveVariable *CurrentVar =
237 static_cast<LiveVariable *>(LiveElements.back().get());
238 assert(ElementPtrToIndex.count(CurrentVar) == 0 &&
239 "Element already registered!");
240
241 // Map from a LiveElement pointer to its index in the LiveElements.
242 ElementPtrToIndex[CurrentVar] = LiveElements.size() - 1;
243
244 if (const std::optional<DWARFAddressRange> &Range =
245 CurrentVar->getLocExpr().Range) {
246 // Add the variable to address-based maps.
247 LiveElementsByAddress[Range->LowPC].push_back(x: CurrentVar);
248 LiveElementsByEndAddress[Range->HighPC].push_back(x: CurrentVar);
249 }
250}
251
252void LiveElementPrinter::addVariable(DWARFDie FuncDie, DWARFDie VarDie) {
253 uint64_t FuncLowPC, FuncHighPC, SectionIndex;
254 FuncDie.getLowAndHighPC(LowPC&: FuncLowPC, HighPC&: FuncHighPC, SectionIndex);
255 const char *VarName = VarDie.getName(Kind: DINameKind::ShortName);
256 DWARFUnit *U = VarDie.getDwarfUnit();
257
258 Expected<DWARFLocationExpressionsVector> Locs =
259 VarDie.getLocations(Attr: dwarf::DW_AT_location);
260 if (!Locs) {
261 // If the variable doesn't have any locations, just ignore it. We don't
262 // report an error or warning here as that could be noisy on optimised
263 // code.
264 consumeError(Err: Locs.takeError());
265 return;
266 }
267
268 for (const DWARFLocationExpression &LocExpr : *Locs) {
269 if (LocExpr.Range) {
270 LiveElements.emplace_back(
271 args: std::make_unique<LiveVariable>(args: LocExpr, args&: VarName, args&: U, args&: FuncDie));
272 } else {
273 // If the LocExpr does not have an associated range, it is valid for
274 // the whole of the function.
275 // TODO: technically it is not valid for any range covered by another
276 // LocExpr, does that happen in reality?
277 DWARFLocationExpression WholeFuncExpr{
278 .Range: DWARFAddressRange(FuncLowPC, FuncHighPC, SectionIndex), .Expr: LocExpr.Expr};
279 LiveElements.emplace_back(
280 args: std::make_unique<LiveVariable>(args&: WholeFuncExpr, args&: VarName, args&: U, args&: FuncDie));
281 }
282
283 // Register the new variable with all data structures.
284 registerNewVariable();
285 }
286}
287
288void LiveElementPrinter::addFunction(DWARFDie D) {
289 for (const DWARFDie &Child : D.children()) {
290 if (DbgVariables != DFDisabled &&
291 (Child.getTag() == dwarf::DW_TAG_variable ||
292 Child.getTag() == dwarf::DW_TAG_formal_parameter)) {
293 addVariable(FuncDie: D, VarDie: Child);
294 } else if (DbgInlinedFunctions != DFDisabled &&
295 Child.getTag() == dwarf::DW_TAG_inlined_subroutine) {
296 addInlinedFunction(FuncDie: D, InlinedFuncDie: Child);
297 addFunction(D: Child);
298 } else
299 addFunction(D: Child);
300 }
301}
302
303// Get the column number (in characters) at which the first live element
304// line should be printed.
305unsigned LiveElementPrinter::getIndentLevel() const {
306 return DbgIndent + getInstStartColumn(STI);
307}
308
309// Indent to the first live-range column to the right of the currently
310// printed line, and return the index of that column.
311// TODO: formatted_raw_ostream uses "column" to mean a number of characters
312// since the last \n, and we use it to mean the number of slots in which we
313// put live element lines. Pick a less overloaded word.
314unsigned LiveElementPrinter::moveToFirstVarColumn(formatted_raw_ostream &OS) {
315 // Logical column number: column zero is the first column we print in, each
316 // logical column is 2 physical columns wide.
317 unsigned FirstUnprintedLogicalColumn =
318 std::max(a: (int)(OS.getColumn() - getIndentLevel() + 1) / 2, b: 0);
319 // Physical column number: the actual column number in characters, with
320 // zero being the left-most side of the screen.
321 unsigned FirstUnprintedPhysicalColumn =
322 getIndentLevel() + FirstUnprintedLogicalColumn * 2;
323
324 if (FirstUnprintedPhysicalColumn > OS.getColumn())
325 OS.PadToColumn(NewCol: FirstUnprintedPhysicalColumn);
326
327 return FirstUnprintedLogicalColumn;
328}
329
330unsigned LiveElementPrinter::getOrCreateColumn(unsigned ElementIdx) {
331 // Check if the element already has an assigned column.
332 auto it = ElementToColumn.find(Val: ElementIdx);
333 if (it != ElementToColumn.end())
334 return it->second;
335
336 unsigned ColIdx;
337 if (!FreeCols.empty()) {
338 // Get the smallest available index from the set.
339 ColIdx = *FreeCols.begin();
340 // Remove the index from the set.
341 FreeCols.erase(position: FreeCols.begin());
342 } else {
343 // No free columns, so create a new one.
344 ColIdx = ActiveCols.size();
345 ActiveCols.emplace_back();
346 }
347
348 // Assign the element to the column and update the map.
349 ElementToColumn[ElementIdx] = ColIdx;
350 ActiveCols[ColIdx].ElementIdx = ElementIdx;
351 return ColIdx;
352}
353
354void LiveElementPrinter::freeColumn(unsigned ColIdx) {
355 unsigned ElementIdx = ActiveCols[ColIdx].ElementIdx;
356
357 // Clear the column's data.
358 ActiveCols[ColIdx].clear();
359
360 // Remove the element's entry from the map and add the column to the free
361 // list.
362 ElementToColumn.erase(Val: ElementIdx);
363 FreeCols.insert(x: ColIdx);
364}
365
366std::vector<unsigned>
367LiveElementPrinter::getSortedActiveElementIndices() const {
368 // Get all element indices that currently have an assigned column.
369 std::vector<unsigned> Indices;
370 for (const auto &Pair : ElementToColumn)
371 Indices.push_back(x: Pair.first);
372
373 // Sort by the DWARF discovery order.
374 llvm::stable_sort(Range&: Indices);
375 return Indices;
376}
377
378void LiveElementPrinter::dump() const {
379 for (const std::unique_ptr<LiveElement> &LE : LiveElements) {
380 LE->dump(OS&: dbgs());
381 LE->print(OS&: dbgs(), MRI);
382 dbgs() << "\n";
383 }
384}
385
386void LiveElementPrinter::addCompileUnit(DWARFDie D) {
387 if (D.getTag() == dwarf::DW_TAG_subprogram)
388 addFunction(D);
389 else
390 for (const DWARFDie &Child : D.children())
391 addFunction(D: Child);
392}
393
394/// Update to match the state of the instruction between ThisAddr and
395/// NextAddr. In the common case, any live range active at ThisAddr is
396/// live-in to the instruction, and any live range active at NextAddr is
397/// live-out of the instruction. If IncludeDefinedVars is false, then live
398/// ranges starting at NextAddr will be ignored.
399void LiveElementPrinter::update(object::SectionedAddress ThisAddr,
400 object::SectionedAddress NextAddr,
401 bool IncludeDefinedVars) {
402 // Exit early if only printing function limits.
403 if (DbgInlinedFunctions == DFLimitsOnly)
404 return;
405
406 // Free columns identified in the previous cycle.
407 for (unsigned ColIdx : ColumnsToFreeNextCycle)
408 freeColumn(ColIdx);
409 ColumnsToFreeNextCycle.clear();
410
411 // Update status of active columns and collect those to free next cycle.
412 for (unsigned ColIdx = 0, End = ActiveCols.size(); ColIdx < End; ++ColIdx) {
413 if (!ActiveCols[ColIdx].isActive())
414 continue;
415
416 const std::unique_ptr<LiveElement> &LE =
417 LiveElements[ActiveCols[ColIdx].ElementIdx];
418 ActiveCols[ColIdx].LiveIn = LE->liveAtAddress(Addr: ThisAddr);
419 ActiveCols[ColIdx].LiveOut = LE->liveAtAddress(Addr: NextAddr);
420
421 LLVM_DEBUG({
422 std::string Name = Demangle ? demangle(LE->getName()) : LE->getName();
423 dbgs() << "pass 1, " << ThisAddr.Address << "-" << NextAddr.Address
424 << ", " << Name << ", Col " << ColIdx
425 << ": LiveIn=" << ActiveCols[ColIdx].LiveIn
426 << ", LiveOut=" << ActiveCols[ColIdx].LiveOut << "\n";
427 });
428
429 // If element is fully dead, deactivate column immediately.
430 if (!ActiveCols[ColIdx].LiveIn && !ActiveCols[ColIdx].LiveOut) {
431 ActiveCols[ColIdx].ElementIdx = Column::NullElementIdx;
432 continue;
433 }
434
435 // Mark for cleanup in the next cycle if range ends here.
436 if (ActiveCols[ColIdx].LiveIn && !ActiveCols[ColIdx].LiveOut)
437 ColumnsToFreeNextCycle.push_back(x: ColIdx);
438 }
439
440 // Next, look for variables which don't already have a column, but which
441 // are now live (those starting at ThisAddr or NextAddr).
442 if (IncludeDefinedVars) {
443 // Collect all elements starting at ThisAddr and NextAddr.
444 std::vector<std::pair<unsigned, LiveElement *>> NewLiveElements;
445 auto CollectNewElements = [&](const auto &It) {
446 if (It == LiveElementsByAddress.end())
447 return;
448
449 const std::vector<LiveElement *> &ElementList = It->second;
450 for (LiveElement *LE : ElementList) {
451 auto IndexIt = ElementPtrToIndex.find(Val: LE);
452 assert(IndexIt != ElementPtrToIndex.end() &&
453 "LiveElement in address map but missing from index map!");
454
455 // Get the element index for sorting and column management.
456 unsigned ElementIdx = IndexIt->second;
457 // Skip elements that already have a column.
458 if (ElementToColumn.count(Val: ElementIdx))
459 continue;
460
461 bool LiveIn = LE->liveAtAddress(Addr: ThisAddr);
462 bool LiveOut = LE->liveAtAddress(Addr: NextAddr);
463 if (!LiveIn && !LiveOut)
464 continue;
465
466 NewLiveElements.emplace_back(args&: ElementIdx, args&: LE);
467 }
468 };
469
470 // Collect elements starting at ThisAddr.
471 CollectNewElements(LiveElementsByAddress.find(Key: ThisAddr.Address));
472 // Collect elements starting at NextAddr (the address immediately
473 // following the instruction).
474 CollectNewElements(LiveElementsByAddress.find(Key: NextAddr.Address));
475 // Sort elements by DWARF discovery order for deterministic column
476 // assignment.
477 llvm::stable_sort(Range&: NewLiveElements, C: [](const auto &A, const auto &B) {
478 return A.first < B.first;
479 });
480
481 // Assign columns in deterministic order.
482 for (const auto &ElementPair : NewLiveElements) {
483 unsigned ElementIdx = ElementPair.first;
484 // Skip if element was already added from the first range.
485 if (ElementToColumn.count(Val: ElementIdx))
486 continue;
487
488 LiveElement *LE = ElementPair.second;
489 bool LiveIn = LE->liveAtAddress(Addr: ThisAddr);
490 bool LiveOut = LE->liveAtAddress(Addr: NextAddr);
491
492 // Assign or create a column.
493 unsigned ColIdx = getOrCreateColumn(ElementIdx);
494 LLVM_DEBUG({
495 std::string Name = Demangle ? demangle(LE->getName()) : LE->getName();
496 dbgs() << "pass 2, " << ThisAddr.Address << "-" << NextAddr.Address
497 << ", " << Name << ", Col " << ColIdx << ": LiveIn=" << LiveIn
498 << ", LiveOut=" << LiveOut << "\n";
499 });
500
501 ActiveCols[ColIdx].LiveIn = LiveIn;
502 ActiveCols[ColIdx].LiveOut = LiveOut;
503 ActiveCols[ColIdx].MustDrawLabel = true;
504
505 // Mark for cleanup next cycle if range ends here.
506 if (ActiveCols[ColIdx].LiveIn && !ActiveCols[ColIdx].LiveOut)
507 ColumnsToFreeNextCycle.push_back(x: ColIdx);
508 }
509 }
510}
511
512enum class LineChar {
513 RangeStart,
514 RangeMid,
515 RangeEnd,
516 LabelVert,
517 LabelCornerNew,
518 LabelCornerActive,
519 LabelHoriz,
520};
521const char *LiveElementPrinter::getLineChar(LineChar C) const {
522 bool IsASCII = DbgVariables == DFASCII || DbgInlinedFunctions == DFASCII;
523 switch (C) {
524 case LineChar::RangeStart:
525 return IsASCII ? "^" : (const char *)u8"\u2548";
526 case LineChar::RangeMid:
527 return IsASCII ? "|" : (const char *)u8"\u2503";
528 case LineChar::RangeEnd:
529 return IsASCII ? "v" : (const char *)u8"\u253b";
530 case LineChar::LabelVert:
531 return IsASCII ? "|" : (const char *)u8"\u2502";
532 case LineChar::LabelCornerNew:
533 return IsASCII ? "/" : (const char *)u8"\u250c";
534 case LineChar::LabelCornerActive:
535 return IsASCII ? "|" : (const char *)u8"\u2520";
536 case LineChar::LabelHoriz:
537 return IsASCII ? "-" : (const char *)u8"\u2500";
538 }
539 llvm_unreachable("Unhandled LineChar enum");
540}
541
542/// Print live ranges to the right of an existing line. This assumes the
543/// line is not an instruction, so doesn't start or end any live ranges, so
544/// we only need to print active ranges or empty columns. If AfterInst is
545/// true, this is being printed after the last instruction fed to update(),
546/// otherwise this is being printed before it.
547void LiveElementPrinter::printAfterOtherLine(formatted_raw_ostream &OS,
548 bool AfterInst) {
549 if (ActiveCols.size()) {
550 unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS);
551 for (size_t ColIdx = FirstUnprintedColumn, End = ActiveCols.size();
552 ColIdx < End; ++ColIdx) {
553 if (ActiveCols[ColIdx].isActive()) {
554 if ((AfterInst && ActiveCols[ColIdx].LiveOut) ||
555 (!AfterInst && ActiveCols[ColIdx].LiveIn))
556 OS << getLineChar(C: LineChar::RangeMid);
557 else if (!AfterInst && ActiveCols[ColIdx].LiveOut)
558 OS << getLineChar(C: LineChar::LabelVert);
559 else
560 OS << " ";
561 }
562 OS << " ";
563 }
564 }
565 OS << "\n";
566}
567
568/// Print any live element range info needed to the right of a
569/// non-instruction line of disassembly. This is where we print the element
570/// names and expressions, with thin line-drawing characters connecting them
571/// to the live range which starts at the next instruction. If MustPrint is
572/// true, we have to print at least one line (with the continuation of any
573/// already-active live ranges) because something has already been printed
574/// earlier on this line.
575void LiveElementPrinter::printBetweenInsts(formatted_raw_ostream &OS,
576 bool MustPrint) {
577 bool PrintedSomething = false;
578 // Get all active elements, sorted by discovery order.
579 std::vector<unsigned> SortedElementIndices = getSortedActiveElementIndices();
580 // The outer loop iterates over the deterministic DWARF discovery order.
581 for (unsigned ElementIdx : SortedElementIndices) {
582 // Look up the physical column index (ColIdx) assigned to this
583 // element. We use .at() because we are certain the element is active.
584 unsigned ColIdx = ElementToColumn.at(Val: ElementIdx);
585 if (ActiveCols[ColIdx].isActive() && ActiveCols[ColIdx].MustDrawLabel) {
586 // First we need to print the live range markers for any active
587 // columns to the left of this one.
588 OS.PadToColumn(NewCol: getIndentLevel());
589 for (unsigned ColIdx2 = 0; ColIdx2 < ColIdx; ++ColIdx2) {
590 if (ActiveCols[ColIdx2].isActive()) {
591 if (ActiveCols[ColIdx2].MustDrawLabel && !ActiveCols[ColIdx2].LiveIn)
592 OS << getLineChar(C: LineChar::LabelVert) << " ";
593 else
594 OS << getLineChar(C: LineChar::RangeMid) << " ";
595 } else
596 OS << " ";
597 }
598
599 const std::unique_ptr<LiveElement> &LE = LiveElements[ElementIdx];
600 // Then print the variable name and location of the new live range,
601 // with box drawing characters joining it to the live range line.
602 OS << getLineChar(C: ActiveCols[ColIdx].LiveIn ? LineChar::LabelCornerActive
603 : LineChar::LabelCornerNew)
604 << getLineChar(C: LineChar::LabelHoriz) << " ";
605
606 std::string Name = Demangle ? demangle(MangledName: LE->getName()) : LE->getName();
607 WithColor(OS, raw_ostream::GREEN) << Name;
608 OS << " = ";
609 {
610 WithColor ExprColor(OS, raw_ostream::CYAN);
611 LE->print(OS, MRI);
612 }
613
614 // If there are any columns to the right of the expression we just
615 // printed, then continue their live range lines.
616 unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS);
617 for (unsigned ColIdx2 = FirstUnprintedColumn, End = ActiveCols.size();
618 ColIdx2 < End; ++ColIdx2) {
619 if (ActiveCols[ColIdx2].isActive() && ActiveCols[ColIdx2].LiveIn)
620 OS << getLineChar(C: LineChar::RangeMid) << " ";
621 else
622 OS << " ";
623 }
624
625 OS << "\n";
626 PrintedSomething = true;
627 }
628 }
629
630 for (unsigned ColIdx = 0, End = ActiveCols.size(); ColIdx < End; ++ColIdx)
631 if (ActiveCols[ColIdx].isActive())
632 ActiveCols[ColIdx].MustDrawLabel = false;
633
634 // If we must print something (because we printed a line/column number),
635 // but don't have any new variables to print, then print a line which
636 // just continues any existing live ranges.
637 if (MustPrint && !PrintedSomething)
638 printAfterOtherLine(OS, AfterInst: false);
639}
640
641/// Print the live element ranges to the right of a disassembled instruction.
642void LiveElementPrinter::printAfterInst(formatted_raw_ostream &OS) {
643 if (!ActiveCols.size())
644 return;
645 unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS);
646 for (unsigned ColIdx = FirstUnprintedColumn, End = ActiveCols.size();
647 ColIdx < End; ++ColIdx) {
648 if (!ActiveCols[ColIdx].isActive())
649 OS << " ";
650 else if (ActiveCols[ColIdx].LiveIn && ActiveCols[ColIdx].LiveOut)
651 OS << getLineChar(C: LineChar::RangeMid) << " ";
652 else if (ActiveCols[ColIdx].LiveOut)
653 OS << getLineChar(C: LineChar::RangeStart) << " ";
654 else if (ActiveCols[ColIdx].LiveIn)
655 OS << getLineChar(C: LineChar::RangeEnd) << " ";
656 else
657 llvm_unreachable("var must be live in or out!");
658 }
659}
660
661void LiveElementPrinter::printBoundaryLine(formatted_raw_ostream &OS,
662 object::SectionedAddress Addr,
663 bool IsEnd) {
664 // Only print the start/end line for inlined functions if DFLimitsOnly is
665 // enabled.
666 if (DbgInlinedFunctions != DFLimitsOnly)
667 return;
668
669 // Select the appropriate map based on whether we are checking the start
670 // (LowPC) or end (HighPC) address.
671 const auto &AddressMap =
672 IsEnd ? LiveElementsByEndAddress : LiveElementsByAddress;
673
674 // Use the map to find all elements that start/end at the given address.
675 std::vector<unsigned> ElementIndices;
676 auto It = AddressMap.find(Key: Addr.Address);
677 if (It != AddressMap.end()) {
678 for (LiveElement *LE : It->second) {
679 // Look up the element index from the pointer.
680 auto IndexIt = ElementPtrToIndex.find(Val: LE);
681 assert(IndexIt != ElementPtrToIndex.end() &&
682 "LiveElement found in address map but missing index!");
683 ElementIndices.push_back(x: IndexIt->second);
684 }
685 }
686
687 // Sort the indices to ensure deterministic output order (by DWARF discovery
688 // order).
689 llvm::stable_sort(Range&: ElementIndices);
690
691 for (unsigned ElementIdx : ElementIndices) {
692 LiveElement *LE = LiveElements[ElementIdx].get();
693 LE->printElementLine(OS, Address: Addr, IsEnd);
694 }
695}
696
697bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
698 std::unique_ptr<MemoryBuffer> Buffer;
699 if (LineInfo.Source) {
700 Buffer = MemoryBuffer::getMemBuffer(InputData: *LineInfo.Source);
701 } else {
702 std::string PathToOpen = LineInfo.FileName;
703 if (!SourceDirs.empty()) {
704 SmallVector<StringRef, 8> SearchDirs;
705 for (const std::string &Dir : SourceDirs)
706 SearchDirs.push_back(Elt: Dir);
707 if (std::optional<std::string> Resolved =
708 findSourceFilePath(FileName: LineInfo.FileName, SearchDirs))
709 PathToOpen = std::move(*Resolved);
710 }
711
712 auto BufferOrError = MemoryBuffer::getFile(Filename: PathToOpen, /*IsText=*/true);
713 if (!BufferOrError) {
714 if (MissingSources.insert(key: LineInfo.FileName).second)
715 reportWarning(Message: "failed to find source " + LineInfo.FileName,
716 File: Obj->getFileName());
717 return false;
718 }
719 Buffer = std::move(*BufferOrError);
720 }
721 // Chomp the file to get lines
722 const char *BufferStart = Buffer->getBufferStart(),
723 *BufferEnd = Buffer->getBufferEnd();
724 std::vector<StringRef> &Lines = LineCache[LineInfo.FileName];
725 const char *Start = BufferStart;
726 for (const char *I = BufferStart; I != BufferEnd; ++I)
727 if (*I == '\n') {
728 Lines.emplace_back(args&: Start, args: I - Start - (BufferStart < I && I[-1] == '\r'));
729 Start = I + 1;
730 }
731 if (Start < BufferEnd)
732 Lines.emplace_back(args&: Start, args: BufferEnd - Start);
733 SourceCache[LineInfo.FileName] = std::move(Buffer);
734 return true;
735}
736
737void SourcePrinter::printSourceLine(formatted_raw_ostream &OS,
738 object::SectionedAddress Address,
739 StringRef ObjectFilename,
740 LiveElementPrinter &LEP,
741 StringRef Delimiter) {
742 if (!Symbolizer)
743 return;
744
745 DILineInfo LineInfo = DILineInfo();
746 Expected<DILineInfo> ExpectedLineInfo =
747 Symbolizer->symbolizeCode(Obj: *Obj, ModuleOffset: Address);
748 if (ExpectedLineInfo) {
749 LineInfo = *ExpectedLineInfo;
750 } else if (!WarnedInvalidDebugInfo) {
751 WarnedInvalidDebugInfo = true;
752 // TODO Untested.
753 reportWarning(Message: "failed to parse debug information: " +
754 toString(E: ExpectedLineInfo.takeError()),
755 File: ObjectFilename);
756 }
757 if (!objdump::SubstitutePaths.empty())
758 LineInfo.FileName = applySubstitutePaths(FileName: LineInfo.FileName);
759
760 if (!objdump::Prefix.empty() &&
761 sys::path::is_absolute_gnu(path: LineInfo.FileName)) {
762 // FileName has at least one character since is_absolute_gnu is false for
763 // an empty string.
764 assert(!LineInfo.FileName.empty());
765 if (PrefixStrip > 0) {
766 uint32_t Level = 0;
767 auto StrippedNameStart = LineInfo.FileName.begin();
768
769 // Path.h iterator skips extra separators. Therefore it cannot be used
770 // here to keep compatibility with GNU Objdump.
771 for (auto Pos = StrippedNameStart + 1, End = LineInfo.FileName.end();
772 Pos != End && Level < PrefixStrip; ++Pos) {
773 if (sys::path::is_separator(value: *Pos)) {
774 StrippedNameStart = Pos;
775 ++Level;
776 }
777 }
778
779 LineInfo.FileName =
780 std::string(StrippedNameStart, LineInfo.FileName.end());
781 }
782
783 SmallString<128> FilePath;
784 sys::path::append(path&: FilePath, a: Prefix, b: LineInfo.FileName);
785
786 LineInfo.FileName = std::string(FilePath);
787 }
788
789 if (PrintLines)
790 printLines(OS, Address, LineInfo, Delimiter, LEP);
791 if (PrintSource)
792 printSources(OS, LineInfo, ObjectFilename, Delimiter, LEP);
793 OldLineInfo = std::move(LineInfo);
794}
795
796void SourcePrinter::printLines(formatted_raw_ostream &OS,
797 object::SectionedAddress Address,
798 const DILineInfo &LineInfo, StringRef Delimiter,
799 LiveElementPrinter &LEP) {
800 bool PrintFunctionName = LineInfo.FunctionName != DILineInfo::BadString &&
801 LineInfo.FunctionName != OldLineInfo.FunctionName;
802 if (PrintFunctionName) {
803 OS << Delimiter << LineInfo.FunctionName;
804 // If demangling is successful, FunctionName will end with "()". Print it
805 // only if demangling did not run or was unsuccessful.
806 if (!StringRef(LineInfo.FunctionName).ends_with(Suffix: "()"))
807 OS << "()";
808 OS << ":\n";
809 }
810 if (LineInfo.FileName != DILineInfo::BadString && LineInfo.Line != 0 &&
811 (OldLineInfo.Line != LineInfo.Line ||
812 OldLineInfo.FileName != LineInfo.FileName || PrintFunctionName)) {
813 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line;
814 LEP.printBetweenInsts(OS, MustPrint: true);
815 }
816}
817
818// Get the source line text for LineInfo:
819// - use LineInfo::LineSource if available;
820// - use LineCache if LineInfo::Source otherwise.
821StringRef SourcePrinter::getLine(const DILineInfo &LineInfo,
822 StringRef ObjectFilename) {
823 if (LineInfo.LineSource)
824 return LineInfo.LineSource.value();
825
826 if (SourceCache.find(Key: LineInfo.FileName) == SourceCache.end())
827 if (!cacheSource(LineInfo))
828 return {};
829
830 auto LineBuffer = LineCache.find(Key: LineInfo.FileName);
831 if (LineBuffer == LineCache.end())
832 return {};
833
834 if (LineInfo.Line > LineBuffer->second.size()) {
835 reportWarning(
836 Message: formatv(Fmt: "debug info line number {0} exceeds the number of lines in {1}",
837 Vals: LineInfo.Line, Vals: LineInfo.FileName),
838 File: ObjectFilename);
839 return {};
840 }
841
842 // Vector begins at 0, line numbers are non-zero
843 return LineBuffer->second[LineInfo.Line - 1];
844}
845
846void SourcePrinter::printSources(formatted_raw_ostream &OS,
847 const DILineInfo &LineInfo,
848 StringRef ObjectFilename, StringRef Delimiter,
849 LiveElementPrinter &LEP) {
850 if (LineInfo.FileName == DILineInfo::BadString || LineInfo.Line == 0 ||
851 (OldLineInfo.Line == LineInfo.Line &&
852 OldLineInfo.FileName == LineInfo.FileName))
853 return;
854
855 StringRef Line = getLine(LineInfo, ObjectFilename);
856 if (!Line.empty()) {
857 OS << Delimiter << Line;
858 LEP.printBetweenInsts(OS, MustPrint: true);
859 }
860}
861
862SourcePrinter::SourcePrinter(const object::ObjectFile *Obj,
863 StringRef DefaultArch)
864 : Obj(Obj) {
865 symbolize::LLVMSymbolizer::Options SymbolizerOpts;
866 SymbolizerOpts.PrintFunctions =
867 DILineInfoSpecifier::FunctionNameKind::LinkageName;
868 SymbolizerOpts.Demangle = Demangle;
869 SymbolizerOpts.DefaultArch = std::string(DefaultArch);
870 Symbolizer.reset(p: new symbolize::LLVMSymbolizer(SymbolizerOpts));
871}
872
873} // namespace objdump
874} // namespace llvm
875