LLVM  14.0.0git
DIPrinter.cpp
Go to the documentation of this file.
1 //===- lib/DebugInfo/Symbolize/DIPrinter.cpp ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the DIPrinter class, which is responsible for printing
10 // structures defined in DebugInfo/DIContext.h
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "llvm/ADT/StringRef.h"
17 #include "llvm/Support/ErrorOr.h"
18 #include "llvm/Support/Format.h"
21 #include "llvm/Support/Path.h"
23 #include <algorithm>
24 #include <cmath>
25 #include <cstddef>
26 #include <cstdint>
27 #include <memory>
28 #include <string>
29 
30 namespace llvm {
31 namespace symbolize {
32 
33 class SourceCode {
34  std::unique_ptr<MemoryBuffer> MemBuf;
35 
36  const Optional<StringRef> load(StringRef FileName,
37  const Optional<StringRef> &EmbeddedSource) {
38  if (Lines <= 0)
39  return None;
40 
41  if (EmbeddedSource)
42  return EmbeddedSource;
43  else {
45  MemoryBuffer::getFile(FileName);
46  if (!BufOrErr)
47  return None;
48  MemBuf = std::move(*BufOrErr);
49  return MemBuf->getBuffer();
50  }
51  }
52 
53  const Optional<StringRef> pruneSource(const Optional<StringRef> &Source) {
54  if (!Source)
55  return None;
56  size_t FirstLinePos = StringRef::npos, Pos = 0;
57  for (int64_t L = 1; L <= LastLine; ++L, ++Pos) {
58  if (L == FirstLine)
59  FirstLinePos = Pos;
60  Pos = Source->find('\n', Pos);
61  if (Pos == StringRef::npos)
62  break;
63  }
64  if (FirstLinePos == StringRef::npos)
65  return None;
66  return Source->substr(FirstLinePos, (Pos == StringRef::npos)
68  : Pos - FirstLinePos);
69  }
70 
71 public:
72  const int64_t Line;
73  const int Lines;
74  const int64_t FirstLine;
75  const int64_t LastLine;
77 
79  StringRef FileName, int64_t Line, int Lines,
80  const Optional<StringRef> &EmbeddedSource = Optional<StringRef>(None))
81  : Line(Line), Lines(Lines),
82  FirstLine(std::max(static_cast<int64_t>(1), Line - Lines / 2)),
83  LastLine(FirstLine + Lines - 1),
84  PrunedSource(pruneSource(load(FileName, EmbeddedSource))) {}
85 
86  void format(raw_ostream &OS) {
87  if (!PrunedSource)
88  return;
89  size_t MaxLineNumberWidth = std::ceil(std::log10(LastLine));
90  int64_t L = FirstLine;
91  for (size_t Pos = 0; Pos < PrunedSource->size(); ++L) {
92  size_t PosEnd = PrunedSource->find('\n', Pos);
93  StringRef String = PrunedSource->substr(
94  Pos, (PosEnd == StringRef::npos) ? StringRef::npos : (PosEnd - Pos));
95  if (String.endswith("\r"))
96  String = String.drop_back(1);
97  OS << format_decimal(L, MaxLineNumberWidth);
98  if (L == Line)
99  OS << " >: ";
100  else
101  OS << " : ";
102  OS << String << '\n';
103  if (PosEnd == StringRef::npos)
104  break;
105  Pos = PosEnd + 1;
106  }
107  }
108 };
109 
110 void PlainPrinterBase::printHeader(uint64_t Address) {
111  if (Config.PrintAddress) {
112  OS << "0x";
113  OS.write_hex(Address);
114  StringRef Delimiter = Config.Pretty ? ": " : "\n";
115  OS << Delimiter;
116  }
117 }
118 
119 // Prints source code around in the FileName the Line.
122 }
123 
124 void PlainPrinterBase::printFunctionName(StringRef FunctionName, bool Inlined) {
125  if (Config.PrintFunctions) {
126  if (FunctionName == DILineInfo::BadString)
127  FunctionName = DILineInfo::Addr2LineBadString;
128  StringRef Delimiter = Config.Pretty ? " at " : "\n";
129  StringRef Prefix = (Config.Pretty && Inlined) ? " (inlined by) " : "";
130  OS << Prefix << FunctionName << Delimiter;
131  }
132 }
133 
134 void LLVMPrinter::printSimpleLocation(StringRef Filename,
135  const DILineInfo &Info) {
136  OS << Filename << ':' << Info.Line << ':' << Info.Column << '\n';
137  printContext(
138  SourceCode(Filename, Info.Line, Config.SourceContextLines, Info.Source));
139 }
140 
141 void GNUPrinter::printSimpleLocation(StringRef Filename,
142  const DILineInfo &Info) {
143  OS << Filename << ':' << Info.Line;
144  if (Info.Discriminator)
145  OS << " (discriminator " << Info.Discriminator << ')';
146  OS << '\n';
147  printContext(
148  SourceCode(Filename, Info.Line, Config.SourceContextLines, Info.Source));
149 }
150 
152  const DILineInfo &Info) {
153  OS << " Filename: " << Filename << '\n';
154  if (Info.StartLine) {
155  OS << " Function start filename: " << Info.StartFileName << '\n';
156  OS << " Function start line: " << Info.StartLine << '\n';
157  }
159  OS << " Line: " << Info.Line << '\n';
160  OS << " Column: " << Info.Column << '\n';
161  if (Info.Discriminator)
162  OS << " Discriminator: " << Info.Discriminator << '\n';
163 }
164 
165 void LLVMPrinter::printStartAddress(const DILineInfo &Info) {
166  if (Info.StartAddress) {
167  OS << " Function start address: 0x";
168  OS.write_hex(*Info.StartAddress);
169  OS << '\n';
170  }
171 }
172 
173 void LLVMPrinter::printFooter() { OS << '\n'; }
174 
175 void PlainPrinterBase::print(const DILineInfo &Info, bool Inlined) {
176  printFunctionName(Info.FunctionName, Inlined);
177  StringRef Filename = Info.FileName;
178  if (Filename == DILineInfo::BadString)
180  if (Config.Verbose)
181  printVerbose(Filename, Info);
182  else
183  printSimpleLocation(Filename, Info);
184 }
185 
187  printHeader(*Request.Address);
188  print(Info, false);
189  printFooter();
190 }
191 
193  const DIInliningInfo &Info) {
194  printHeader(*Request.Address);
195  uint32_t FramesNum = Info.getNumberOfFrames();
196  if (FramesNum == 0)
197  print(DILineInfo(), false);
198  else
199  for (uint32_t I = 0; I < FramesNum; ++I)
200  print(Info.getFrame(I), I > 0);
201  printFooter();
202 }
203 
204 void PlainPrinterBase::print(const Request &Request, const DIGlobal &Global) {
205  printHeader(*Request.Address);
206  StringRef Name = Global.Name;
209  OS << Name << "\n";
210  OS << Global.Start << " " << Global.Size << "\n";
211  printFooter();
212 }
213 
215  const std::vector<DILocal> &Locals) {
216  printHeader(*Request.Address);
217  if (Locals.empty())
219  else
220  for (const DILocal &L : Locals) {
221  if (L.FunctionName.empty())
223  else
224  OS << L.FunctionName;
225  OS << '\n';
226 
227  if (L.Name.empty())
229  else
230  OS << L.Name;
231  OS << '\n';
232 
233  if (L.DeclFile.empty())
235  else
236  OS << L.DeclFile;
237 
238  OS << ':' << L.DeclLine << '\n';
239 
240  if (L.FrameOffset)
241  OS << *L.FrameOffset;
242  else
244  OS << ' ';
245 
246  if (L.Size)
247  OS << *L.Size;
248  else
250  OS << ' ';
251 
252  if (L.TagOffset)
253  OS << *L.TagOffset;
254  else
256  OS << '\n';
257  }
258  printFooter();
259 }
260 
262  StringRef Command) {
263  OS << Command << '\n';
264 }
265 
267  const ErrorInfoBase &ErrorInfo,
268  StringRef ErrorBanner) {
269  ES << ErrorBanner;
270  ErrorInfo.log(ES);
271  ES << '\n';
272  // Print an empty struct too.
273  return true;
274 }
275 
276 static std::string toHex(uint64_t V) {
277  return ("0x" + Twine::utohexstr(V)).str();
278 }
279 
280 static json::Object toJSON(const Request &Request, StringRef ErrorMsg = "") {
281  json::Object Json({{"ModuleName", Request.ModuleName.str()}});
282  if (Request.Address)
283  Json["Address"] = toHex(*Request.Address);
284  if (!ErrorMsg.empty())
285  Json["Error"] = json::Object({{"Message", ErrorMsg.str()}});
286  return Json;
287 }
288 
290  DIInliningInfo InliningInfo;
291  InliningInfo.addFrame(Info);
292  print(Request, InliningInfo);
293 }
294 
296  json::Array Array;
297  for (uint32_t I = 0, N = Info.getNumberOfFrames(); I < N; ++I) {
298  const DILineInfo &LineInfo = Info.getFrame(I);
300  {{"FunctionName", LineInfo.FunctionName != DILineInfo::BadString
301  ? LineInfo.FunctionName
302  : ""},
303  {"StartFileName", LineInfo.StartFileName != DILineInfo::BadString
304  ? LineInfo.StartFileName
305  : ""},
306  {"StartLine", LineInfo.StartLine},
307  {"StartAddress",
308  LineInfo.StartAddress ? toHex(*LineInfo.StartAddress) : ""},
309  {"FileName",
310  LineInfo.FileName != DILineInfo::BadString ? LineInfo.FileName : ""},
311  {"Line", LineInfo.Line},
312  {"Column", LineInfo.Column},
313  {"Discriminator", LineInfo.Discriminator}});
314  SourceCode SourceCode(LineInfo.FileName, LineInfo.Line,
315  Config.SourceContextLines, LineInfo.Source);
316  std::string FormattedSource;
317  raw_string_ostream Stream(FormattedSource);
318  SourceCode.format(Stream);
319  if (!FormattedSource.empty())
320  Object["Source"] = std::move(FormattedSource);
321  Array.push_back(std::move(Object));
322  }
323  json::Object Json = toJSON(Request);
324  Json["Symbol"] = std::move(Array);
325  if (ObjectList)
326  ObjectList->push_back(std::move(Json));
327  else
328  printJSON(std::move(Json));
329 }
330 
331 void JSONPrinter::print(const Request &Request, const DIGlobal &Global) {
333  {{"Name", Global.Name != DILineInfo::BadString ? Global.Name : ""},
334  {"Start", toHex(Global.Start)},
335  {"Size", toHex(Global.Size)}});
336  json::Object Json = toJSON(Request);
337  Json["Data"] = std::move(Data);
338  if (ObjectList)
339  ObjectList->push_back(std::move(Json));
340  else
341  printJSON(std::move(Json));
342 }
343 
345  const std::vector<DILocal> &Locals) {
346  json::Array Frame;
347  for (const DILocal &Local : Locals) {
348  json::Object FrameObject(
349  {{"FunctionName", Local.FunctionName},
350  {"Name", Local.Name},
351  {"DeclFile", Local.DeclFile},
352  {"DeclLine", int64_t(Local.DeclLine)},
353  {"Size", Local.Size ? toHex(*Local.Size) : ""},
354  {"TagOffset", Local.TagOffset ? toHex(*Local.TagOffset) : ""}});
355  if (Local.FrameOffset)
356  FrameObject["FrameOffset"] = *Local.FrameOffset;
357  Frame.push_back(std::move(FrameObject));
358  }
359  json::Object Json = toJSON(Request);
360  Json["Frame"] = std::move(Frame);
361  if (ObjectList)
362  ObjectList->push_back(std::move(Json));
363  else
364  printJSON(std::move(Json));
365 }
366 
368  StringRef Command) {
370  StringError("unable to parse arguments: " + Command,
371  std::make_error_code(std::errc::invalid_argument)),
372  "");
373 }
374 
376  const ErrorInfoBase &ErrorInfo,
377  StringRef ErrorBanner) {
379  if (ObjectList)
380  ObjectList->push_back(std::move(Json));
381  else
382  printJSON(std::move(Json));
383  return false;
384 }
385 
387  assert(!ObjectList);
388  ObjectList = std::make_unique<json::Array>();
389 }
390 
392  assert(ObjectList);
393  printJSON(std::move(*ObjectList));
394  ObjectList.reset();
395 }
396 
397 } // end namespace symbolize
398 } // end namespace llvm
MemoryBuffer.h
llvm::ErrorInfoBase::log
virtual void log(raw_ostream &OS) const =0
Print an error message to an output stream.
llvm::DILineInfo::Source
Optional< StringRef > Source
Definition: DIContext.h:39
llvm::symbolize::SourceCode::FirstLine
const int64_t FirstLine
Definition: DIPrinter.cpp:74
llvm
---------------------— PointerInfo ------------------------------------—
Definition: AllocatorList.h:23
llvm::symbolize::PlainPrinterBase::printInvalidCommand
void printInvalidCommand(const Request &Request, StringRef Command) override
Definition: DIPrinter.cpp:261
llvm::symbolize::PlainPrinterBase::printContext
void printContext(SourceCode SourceCode)
Definition: DIPrinter.cpp:120
llvm::symbolize::SourceCode::LastLine
const int64_t LastLine
Definition: DIPrinter.cpp:75
llvm::symbolize::SourceCode::SourceCode
SourceCode(StringRef FileName, int64_t Line, int Lines, const Optional< StringRef > &EmbeddedSource=Optional< StringRef >(None))
Definition: DIPrinter.cpp:78
ceil
We have fiadd patterns now but the followings have the same cost and complexity We need a way to specify the later is more profitable def def The FP stackifier should handle simple permutates to reduce number of shuffle e g ceil
Definition: README-FPStack.txt:54
llvm::cl::Prefix
@ Prefix
Definition: CommandLine.h:164
llvm::DIInliningInfo
A format-neutral container for inlined code description.
Definition: DIContext.h:87
StringRef.h
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:625
llvm::symbolize::JSONPrinter::listBegin
void listBegin() override
Definition: DIPrinter.cpp:386
llvm::StringRef::npos
static constexpr size_t npos
Definition: StringRef.h:60
llvm::symbolize::PlainPrinterBase::Config
PrinterConfig Config
Definition: DIPrinter.h:74
Path.h
llvm::DILineInfo::BadString
static constexpr const char *const BadString
Definition: DIContext.h:33
llvm::format_decimal
FormattedNumber format_decimal(int64_t N, unsigned Width)
format_decimal - Output N as a right justified, fixed-width decimal.
Definition: Format.h:211
llvm::symbolize::PlainPrinterBase::OS
raw_ostream & OS
Definition: DIPrinter.h:72
llvm::symbolize::PlainPrinterBase::print
void print(const DILineInfo &Info, bool Inlined)
Definition: DIPrinter.cpp:175
llvm::Optional
Definition: APInt.h:33
llvm::symbolize::PlainPrinterBase::printFooter
virtual void printFooter()
Definition: DIPrinter.h:83
llvm::symbolize::JSONPrinter::print
void print(const Request &Request, const DILineInfo &Info) override
Definition: DIPrinter.cpp:289
Format.h
llvm::symbolize::toJSON
static json::Object toJSON(const Request &Request, StringRef ErrorMsg="")
Definition: DIPrinter.cpp:280
llvm::json::Array::push_back
void push_back(const Value &E)
Definition: JSON.h:190
llvm::Data
@ Data
Definition: SIMachineScheduler.h:55
llvm::DILineInfo::FunctionName
std::string FunctionName
Definition: DIContext.h:37
llvm::symbolize::Request::Address
Optional< uint64_t > Address
Definition: DIPrinter.h:37
llvm::DILineInfo::Addr2LineBadString
static constexpr const char *const Addr2LineBadString
Definition: DIContext.h:35
llvm::DILineInfo::Column
uint32_t Column
Definition: DIContext.h:41
llvm::MemoryBuffer::getFile
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Definition: MemoryBuffer.cpp:246
llvm::symbolize::PrinterConfig::PrintAddress
bool PrintAddress
Definition: DIPrinter.h:63
llvm::symbolize::PlainPrinterBase::printStartAddress
virtual void printStartAddress(const DILineInfo &Info)
Definition: DIPrinter.h:82
llvm::DIInliningInfo::addFrame
void addFrame(const DILineInfo &Frame)
Definition: DIContext.h:105
llvm::symbolize::JSONPrinter::printInvalidCommand
void printInvalidCommand(const Request &Request, StringRef Command) override
Definition: DIPrinter.cpp:367
llvm::json::Array
An Array is a JSON array, which contains heterogeneous JSON values.
Definition: JSON.h:156
LineIterator.h
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
llvm::DILineInfo::StartLine
uint32_t StartLine
Definition: DIContext.h:42
Info
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
llvm::symbolize::PrinterConfig::PrintFunctions
bool PrintFunctions
Definition: DIPrinter.h:64
llvm::symbolize::Request::ModuleName
StringRef ModuleName
Definition: DIPrinter.h:36
llvm::StringRef::str
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:245
llvm::None
const NoneType None
Definition: None.h:23
llvm::ErrorInfoBase
Base class for error info classes.
Definition: Error.h:48
llvm::ErrorInfoBase::message
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:56
llvm::symbolize::PrinterConfig::SourceContextLines
int SourceContextLines
Definition: DIPrinter.h:67
llvm::OutputFileType::Object
@ Object
llvm::DILineInfo::Line
uint32_t Line
Definition: DIContext.h:40
llvm::Twine::utohexstr
static Twine utohexstr(const uint64_t &Val)
Definition: Twine.h:408
uint64_t
llvm::symbolize::toHex
static std::string toHex(uint64_t V)
Definition: DIPrinter.cpp:276
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
ErrorOr.h
I
#define I(x, y, z)
Definition: MD5.cpp:59
llvm::symbolize::PrinterConfig::Verbose
bool Verbose
Definition: DIPrinter.h:66
llvm::DILineInfo
A format-neutral container for source line information.
Definition: DIContext.h:31
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::DILineInfo::Discriminator
uint32_t Discriminator
Definition: DIContext.h:46
llvm::StringError
This class wraps a string in an Error.
Definition: Error.h:1208
llvm::ErrorInfo
Base class for user error types.
Definition: Error.h:349
llvm::Sched::Source
@ Source
Definition: TargetLowering.h:100
DIPrinter.h
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
uint32_t
llvm::symbolize::PrinterConfig::Pretty
bool Pretty
Definition: DIPrinter.h:65
llvm::make_error_code
std::error_code make_error_code(BitcodeError E)
Definition: BitcodeReader.h:270
DIContext.h
llvm::GraphProgram::Name
Name
Definition: GraphWriter.h:52
std
Definition: BitVector.h:838
llvm::DIGlobal
Container for description of a global variable.
Definition: DIContext.h:111
llvm::symbolize::PlainPrinterBase::printVerbose
void printVerbose(StringRef Filename, const DILineInfo &Info)
Definition: DIPrinter.cpp:151
llvm::DILocal
Definition: DIContext.h:119
llvm::symbolize::Request
Definition: DIPrinter.h:35
llvm::symbolize::PlainPrinterBase::printSimpleLocation
virtual void printSimpleLocation(StringRef Filename, const DILineInfo &Info)=0
llvm::DILineInfo::StartAddress
Optional< uint64_t > StartAddress
Definition: DIContext.h:43
llvm::symbolize::JSONPrinter::listEnd
void listEnd() override
Definition: DIPrinter.cpp:391
llvm::symbolize::SourceCode
Definition: DIPrinter.cpp:33
llvm::symbolize::PlainPrinterBase::ES
raw_ostream & ES
Definition: DIPrinter.h:73
llvm::symbolize::SourceCode::format
void format(raw_ostream &OS)
Definition: DIPrinter.cpp:86
llvm::DILineInfo::FileName
std::string FileName
Definition: DIContext.h:36
llvm::symbolize::PlainPrinterBase::printError
bool printError(const Request &Request, const ErrorInfoBase &ErrorInfo, StringRef ErrorBanner) override
Definition: DIPrinter.cpp:266
N
#define N
llvm::ErrorOr
Represents either an error or a value T.
Definition: ErrorOr.h:56
llvm::max
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:340
llvm::symbolize::JSONPrinter::printError
bool printError(const Request &Request, const ErrorInfoBase &ErrorInfo, StringRef ErrorBanner) override
Definition: DIPrinter.cpp:375
llvm::symbolize::SourceCode::Lines
const int Lines
Definition: DIPrinter.cpp:73
raw_ostream.h
llvm::json::Object
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition: JSON.h:90
llvm::symbolize::SourceCode::Line
const int64_t Line
Definition: DIPrinter.cpp:72
llvm::symbolize::SourceCode::PrunedSource
const Optional< StringRef > PrunedSource
Definition: DIPrinter.cpp:76
llvm::symbolize::PlainPrinterBase::printFunctionName
void printFunctionName(StringRef FunctionName, bool Inlined)
Definition: DIPrinter.cpp:124
llvm::raw_ostream::write_hex
raw_ostream & write_hex(unsigned long long N)
Output N in hexadecimal, without any prefix or padding.
Definition: raw_ostream.cpp:140
llvm::DILineInfo::StartFileName
std::string StartFileName
Definition: DIContext.h:38