LLVM 24.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"
18#include "llvm/Support/Format.h"
21#include <algorithm>
22#include <cstddef>
23#include <cstdint>
24#include <memory>
25#include <string>
26
27namespace llvm {
28namespace symbolize {
29
31 std::unique_ptr<MemoryBuffer> MemBuf;
32
33 std::optional<StringRef>
34 load(StringRef FileName, const std::optional<StringRef> &EmbeddedSource) {
35 if (Lines <= 0)
36 return std::nullopt;
37
38 if (EmbeddedSource)
39 return EmbeddedSource;
40 else {
42 MemoryBuffer::getFile(FileName);
43 if (!BufOrErr)
44 return std::nullopt;
45 MemBuf = std::move(*BufOrErr);
46 return MemBuf->getBuffer();
47 }
48 }
49
50 std::optional<StringRef> pruneSource(const std::optional<StringRef> &Source) {
51 if (!Source)
52 return std::nullopt;
53 size_t FirstLinePos = StringRef::npos, Pos = 0;
54 for (int64_t L = 1; L <= LastLine; ++L, ++Pos) {
55 if (L == FirstLine)
56 FirstLinePos = Pos;
57 Pos = Source->find('\n', Pos);
58 if (Pos == StringRef::npos)
59 break;
60 }
61 if (FirstLinePos == StringRef::npos)
62 return std::nullopt;
63 return Source->substr(FirstLinePos, (Pos == StringRef::npos)
65 : Pos - FirstLinePos);
66 }
67
68public:
69 const int64_t Line;
70 const int Lines;
71 const int64_t FirstLine;
72 const int64_t LastLine;
73 const std::optional<StringRef> PrunedSource;
74
75 SourceCode(StringRef FileName, int64_t Line, int Lines,
76 const std::optional<StringRef> &EmbeddedSource =
77 std::optional<StringRef>())
78 : Line(Line), Lines(Lines),
79 FirstLine(std::max(static_cast<int64_t>(1), Line - Lines / 2)),
81 PrunedSource(pruneSource(load(FileName, EmbeddedSource))) {}
82
83 void format(raw_ostream &OS) {
84 if (!PrunedSource)
85 return;
86 size_t MaxLineNumberWidth = NumDigitsBase10(LastLine);
87 int64_t L = FirstLine;
88 for (size_t Pos = 0; Pos < PrunedSource->size(); ++L) {
89 size_t PosEnd = PrunedSource->find('\n', Pos);
91 Pos, (PosEnd == StringRef::npos) ? StringRef::npos : (PosEnd - Pos));
92 if (String.ends_with("\r"))
93 String = String.drop_back(1);
94 OS << format_decimal(L, MaxLineNumberWidth);
95 if (L == Line)
96 OS << " >: ";
97 else
98 OS << " : ";
99 OS << String << '\n';
100 if (PosEnd == StringRef::npos)
101 break;
102 Pos = PosEnd + 1;
103 }
104 }
105};
106
107void PlainPrinterBase::printHeader(std::optional<uint64_t> Address) {
108 if (Address.has_value() && Config.PrintAddress) {
109 OS << "0x";
111 StringRef Delimiter = Config.Pretty ? ": " : "\n";
112 OS << Delimiter;
113 }
114}
115
116// Prints source code around in the FileName the Line.
120
121void PlainPrinterBase::printFunctionName(StringRef FunctionName, bool Inlined) {
122 if (Config.PrintFunctions) {
123 if (FunctionName == DILineInfo::BadString)
124 FunctionName = DILineInfo::Addr2LineBadString;
125 StringRef Delimiter = Config.Pretty ? " at " : "\n";
126 StringRef Prefix = (Config.Pretty && Inlined) ? " (inlined by) " : "";
127 OS << Prefix << FunctionName << Delimiter;
128 }
129}
130
131void LLVMPrinter::printSimpleLocation(StringRef Filename,
132 const DILineInfo &Info) {
133 OS << Filename << ':' << Info.Line << ':' << Info.Column;
134 if (Info.IsApproximateLine)
135 OS << " " << Info.ApproxString;
136 OS << "\n";
138 SourceCode(Filename, Info.Line, Config.SourceContextLines, Info.Source));
139}
140
141void GNUPrinter::printSimpleLocation(StringRef Filename,
142 const DILineInfo &Info) {
143 OS << Filename << ':' << Info.Line;
144 if (Info.IsApproximateLine)
145 OS << " " << Info.ApproxString;
146 if (Info.Discriminator)
147 OS << " (discriminator " << Info.Discriminator << ')';
148 OS << '\n';
150 SourceCode(Filename, Info.Line, Config.SourceContextLines, Info.Source));
151}
152
154 const DILineInfo &Info) {
155 OS << " Filename: " << Filename << '\n';
156 if (Info.StartLine) {
157 OS << " Function start filename: " << Info.StartFileName << '\n';
158 OS << " Function start line: " << Info.StartLine << '\n';
159 }
160 printStartAddress(Info);
161 OS << " Line: " << Info.Line << '\n';
162 OS << " Column: " << Info.Column << '\n';
163 if (Info.Discriminator)
164 OS << " Discriminator: " << Info.Discriminator << '\n';
165 if (Info.IsApproximateLine)
166 OS << " Approximate: true" << '\n';
167}
168
169void LLVMPrinter::printStartAddress(const DILineInfo &Info) {
170 if (Info.StartAddress) {
171 OS << " Function start address: 0x";
172 OS.write_hex(*Info.StartAddress);
173 OS << '\n';
174 }
175}
176
177void LLVMPrinter::printFooter() { OS << '\n'; }
178
179void PlainPrinterBase::print(const DILineInfo &Info, bool Inlined) {
180 printFunctionName(Info.FunctionName, Inlined);
181 StringRef Filename = Info.FileName;
184 if (Config.Verbose)
185 printVerbose(Filename, Info);
186 else
188}
189
191 printHeader(Request.Address);
192 print(Info, false);
193 printFooter();
194}
195
197 const DIInliningInfo &Info) {
198 printHeader(*Request.Address);
199 uint32_t FramesNum = Info.getNumberOfFrames();
200 if (FramesNum == 0)
201 print(DILineInfo(), false);
202 else
203 for (uint32_t I = 0; I < FramesNum; ++I)
204 print(Info.getFrame(I), I > 0);
205 printFooter();
206}
207
209 printHeader(*Request.Address);
210 StringRef Name = Global.Name;
211 if (Name == DILineInfo::BadString)
213 OS << Name << "\n";
214 OS << Global.Start << " " << Global.Size << "\n";
215 if (Global.DeclFile.empty())
216 OS << "??:?\n";
217 else
218 OS << Global.DeclFile << ":" << Global.DeclLine << "\n";
219 printFooter();
220}
221
223 const std::vector<DILocal> &Locals) {
224 printHeader(*Request.Address);
225 if (Locals.empty())
227 else
228 for (const DILocal &L : Locals) {
229 if (L.FunctionName.empty())
231 else
232 OS << L.FunctionName;
233 OS << '\n';
234
235 if (L.Name.empty())
237 else
238 OS << L.Name;
239 OS << '\n';
240
241 if (L.DeclFile.empty())
243 else
244 OS << L.DeclFile;
245
246 OS << ':' << L.DeclLine << '\n';
247
248 if (L.FrameOffset)
249 OS << *L.FrameOffset;
250 else
252 OS << ' ';
253
254 if (L.Size)
255 OS << *L.Size;
256 else
258 OS << ' ';
259
260 if (L.TagOffset)
261 OS << *L.TagOffset;
262 else
264 OS << '\n';
265 }
266 printFooter();
267}
268
270 const std::vector<DILineInfo> &Locations) {
271 if (Locations.empty()) {
273 } else {
274 for (const DILineInfo &L : Locations)
275 print(L, false);
276 printFooter();
277 }
278}
279
281 const ErrorInfoBase &ErrorInfo) {
283 // Print an empty struct too.
284 return true;
285}
286
287static std::string toHex(uint64_t V) {
288 return ("0x" + Twine::utohexstr(V)).str();
289}
290
291static json::Object toJSON(const Request &Request, StringRef ErrorMsg = "") {
292 json::Object Json({{"ModuleName", Request.ModuleName.str()}});
293 if (!Request.Symbol.empty())
294 Json["SymName"] = Request.Symbol.str();
295 if (Request.Address)
296 Json["Address"] = toHex(*Request.Address);
297 if (!ErrorMsg.empty())
298 Json["Error"] = json::Object({{"Message", ErrorMsg.str()}});
299 return Json;
300}
301
302static json::Object toJSON(const DILineInfo &LineInfo) {
304 {{"FunctionName", LineInfo.FunctionName != DILineInfo::BadString
305 ? LineInfo.FunctionName
306 : ""},
307 {"StartFileName", LineInfo.StartFileName != DILineInfo::BadString
308 ? LineInfo.StartFileName
309 : ""},
310 {"StartLine", LineInfo.StartLine},
311 {"StartAddress",
312 LineInfo.StartAddress ? toHex(*LineInfo.StartAddress) : ""},
313 {"FileName",
314 LineInfo.FileName != DILineInfo::BadString ? LineInfo.FileName : ""},
315 {"Line", LineInfo.Line},
316 {"Column", LineInfo.Column},
317 {"Discriminator", LineInfo.Discriminator}});
318 if (LineInfo.IsApproximateLine)
319 Obj.insert({"Approximate", LineInfo.IsApproximateLine});
320 return Obj;
321}
322
323void JSONPrinter::print(const Request &Request, const DILineInfo &Info) {
324 DIInliningInfo InliningInfo;
325 InliningInfo.addFrame(Info);
326 print(Request, InliningInfo);
327}
328
330 json::Array Array;
331 for (uint32_t I = 0, N = Info.getNumberOfFrames(); I < N; ++I) {
332 const DILineInfo &LineInfo = Info.getFrame(I);
333 json::Object Object = toJSON(LineInfo);
334 SourceCode SourceCode(LineInfo.FileName, LineInfo.Line,
335 Config.SourceContextLines, LineInfo.Source);
336 std::string FormattedSource;
337 raw_string_ostream Stream(FormattedSource);
338 SourceCode.format(Stream);
339 if (!FormattedSource.empty())
340 Object["Source"] = std::move(FormattedSource);
341 Array.push_back(std::move(Object));
342 }
344 Json["Symbol"] = std::move(Array);
345 if (ObjectList)
346 ObjectList->push_back(std::move(Json));
347 else
348 printJSON(std::move(Json));
349}
350
353 {{"Name", Global.Name != DILineInfo::BadString ? Global.Name : ""},
354 {"Start", toHex(Global.Start)},
355 {"Size", toHex(Global.Size)}});
357 Json["Data"] = std::move(Data);
358 if (ObjectList)
359 ObjectList->push_back(std::move(Json));
360 else
361 printJSON(std::move(Json));
362}
363
365 const std::vector<DILocal> &Locals) {
366 json::Array Frame;
367 for (const DILocal &Local : Locals) {
368 json::Object FrameObject(
369 {{"FunctionName", Local.FunctionName},
370 {"Name", Local.Name},
371 {"DeclFile", Local.DeclFile},
372 {"DeclLine", int64_t(Local.DeclLine)},
373 {"Size", Local.Size ? toHex(*Local.Size) : ""},
374 {"TagOffset", Local.TagOffset ? toHex(*Local.TagOffset) : ""}});
375 if (Local.FrameOffset)
376 FrameObject["FrameOffset"] = *Local.FrameOffset;
377 Frame.push_back(std::move(FrameObject));
378 }
380 Json["Frame"] = std::move(Frame);
381 if (ObjectList)
382 ObjectList->push_back(std::move(Json));
383 else
384 printJSON(std::move(Json));
385}
386
388 const std::vector<DILineInfo> &Locations) {
389 json::Array Definitions;
390 for (const DILineInfo &L : Locations)
391 Definitions.push_back(toJSON(L));
393 Json["Loc"] = std::move(Definitions);
394 if (ObjectList)
395 ObjectList->push_back(std::move(Json));
396 else
397 printJSON(std::move(Json));
398}
399
401 const ErrorInfoBase &ErrorInfo) {
403 if (ObjectList)
404 ObjectList->push_back(std::move(Json));
405 else
406 printJSON(std::move(Json));
407 return false;
408}
409
411 assert(!ObjectList);
412 ObjectList = std::make_unique<json::Array>();
413}
414
416 assert(ObjectList);
417 printJSON(std::move(*ObjectList));
418 ObjectList.reset();
419}
420
421} // end namespace symbolize
422} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Mark last scratch load
Provides ErrorOr<T> smart pointer.
#define I(x, y, z)
Definition MD5.cpp:57
static constexpr StringLiteral Filename
A format-neutral container for inlined code description.
Definition DIContext.h:94
void addFrame(const DILineInfo &Frame)
Definition DIContext.h:114
Base class for error info classes.
Definition Error.h:44
virtual std::string message() const
Return the error message as a string.
Definition Error.h:52
Base class for user error types.
Definition Error.h:354
Represents either an error or a value T.
Definition ErrorOr.h:56
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
static Twine utohexstr(uint64_t Val)
Definition Twine.h:385
An Array is a JSON array, which contains heterogeneous JSON values.
Definition JSON.h:166
void push_back(const Value &E)
Definition JSON.h:548
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition JSON.h:98
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & write_hex(unsigned long long N)
Output N in hexadecimal, without any prefix or padding.
A raw_ostream that writes to an std::string.
void print(const Request &Request, const DILineInfo &Info) override
bool printError(const Request &Request, const ErrorInfoBase &ErrorInfo) override
void printContext(SourceCode SourceCode)
virtual void printStartAddress(const DILineInfo &Info)
Definition DIPrinter.h:83
bool printError(const Request &Request, const ErrorInfoBase &ErrorInfo) override
virtual void printSimpleLocation(StringRef Filename, const DILineInfo &Info)=0
void printVerbose(StringRef Filename, const DILineInfo &Info)
void printFunctionName(StringRef FunctionName, bool Inlined)
void print(const DILineInfo &Info, bool Inlined)
const std::optional< StringRef > PrunedSource
Definition DIPrinter.cpp:73
void format(raw_ostream &OS)
Definition DIPrinter.cpp:83
SourceCode(StringRef FileName, int64_t Line, int Lines, const std::optional< StringRef > &EmbeddedSource=std::optional< StringRef >())
Definition DIPrinter.cpp:75
static std::string toHex(uint64_t V)
static json::Object toJSON(const Request &Request, StringRef ErrorMsg="")
This is an optimization pass for GlobalISel generic memory operations.
FormattedNumber format_decimal(int64_t N, unsigned Width)
format_decimal - Output N as a right justified, fixed-width decimal.
Definition Format.h:189
LLVM_ABI int NumDigitsBase10(uint64_t X)
Returns the number of digits in the given integer.
@ Global
Append to llvm.global_dtors.
constexpr NextUseDistance max(NextUseDistance A, NextUseDistance B)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
Container for description of a global variable.
Definition DIContext.h:120
A format-neutral container for source line information.
Definition DIContext.h:32
static constexpr const char *const BadString
Definition DIContext.h:35
static constexpr const char *const Addr2LineBadString
Definition DIContext.h:37
std::optional< uint64_t > Address
Definition DIPrinter.h:37