LLVM 19.0.0git
DebugUtils.cpp
Go to the documentation of this file.
1//===---------- DebugUtils.cpp - Utilities for debugging ORC JITs ---------===//
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
10
13#include "llvm/Support/Debug.h"
15#include "llvm/Support/Format.h"
17#include "llvm/Support/Path.h"
19
20#define DEBUG_TYPE "orc"
21
22using namespace llvm;
23
24namespace {
25
26#ifndef NDEBUG
27
28cl::opt<bool> PrintHidden("debug-orc-print-hidden", cl::init(true),
29 cl::desc("debug print hidden symbols defined by "
30 "materialization units"),
32
33cl::opt<bool> PrintCallable("debug-orc-print-callable", cl::init(true),
34 cl::desc("debug print callable symbols defined by "
35 "materialization units"),
37
38cl::opt<bool> PrintData("debug-orc-print-data", cl::init(true),
39 cl::desc("debug print data symbols defined by "
40 "materialization units"),
42
43#endif // NDEBUG
44
45// SetPrinter predicate that prints every element.
46template <typename T> struct PrintAll {
47 bool operator()(const T &E) { return true; }
48};
49
50bool anyPrintSymbolOptionSet() {
51#ifndef NDEBUG
52 return PrintHidden || PrintCallable || PrintData;
53#else
54 return false;
55#endif // NDEBUG
56}
57
58bool flagsMatchCLOpts(const JITSymbolFlags &Flags) {
59#ifndef NDEBUG
60 // Bail out early if this is a hidden symbol and we're not printing hiddens.
61 if (!PrintHidden && !Flags.isExported())
62 return false;
63
64 // Return true if this is callable and we're printing callables.
65 if (PrintCallable && Flags.isCallable())
66 return true;
67
68 // Return true if this is data and we're printing data.
69 if (PrintData && !Flags.isCallable())
70 return true;
71
72 // otherwise return false.
73 return false;
74#else
75 return false;
76#endif // NDEBUG
77}
78
79// Prints a sequence of items, filtered by an user-supplied predicate.
80template <typename Sequence,
81 typename Pred = PrintAll<typename Sequence::value_type>>
82class SequencePrinter {
83public:
84 SequencePrinter(const Sequence &S, char OpenSeq, char CloseSeq,
85 Pred ShouldPrint = Pred())
86 : S(S), OpenSeq(OpenSeq), CloseSeq(CloseSeq),
87 ShouldPrint(std::move(ShouldPrint)) {}
88
89 void printTo(llvm::raw_ostream &OS) const {
90 bool PrintComma = false;
91 OS << OpenSeq;
92 for (auto &E : S) {
93 if (ShouldPrint(E)) {
94 if (PrintComma)
95 OS << ',';
96 OS << ' ' << E;
97 PrintComma = true;
98 }
99 }
100 OS << ' ' << CloseSeq;
101 }
102
103private:
104 const Sequence &S;
105 char OpenSeq;
106 char CloseSeq;
107 mutable Pred ShouldPrint;
108};
109
110template <typename Sequence, typename Pred>
111SequencePrinter<Sequence, Pred> printSequence(const Sequence &S, char OpenSeq,
112 char CloseSeq, Pred P = Pred()) {
113 return SequencePrinter<Sequence, Pred>(S, OpenSeq, CloseSeq, std::move(P));
114}
115
116// Render a SequencePrinter by delegating to its printTo method.
117template <typename Sequence, typename Pred>
119 const SequencePrinter<Sequence, Pred> &Printer) {
120 Printer.printTo(OS);
121 return OS;
122}
123
124struct PrintSymbolFlagsMapElemsMatchingCLOpts {
125 bool operator()(const orc::SymbolFlagsMap::value_type &KV) {
126 return flagsMatchCLOpts(KV.second);
127 }
128};
129
130struct PrintSymbolMapElemsMatchingCLOpts {
131 bool operator()(const orc::SymbolMap::value_type &KV) {
132 return flagsMatchCLOpts(KV.second.getFlags());
133 }
134};
135
136} // end anonymous namespace
137
138namespace llvm {
139namespace orc {
140
142 return OS << *Sym;
143}
144
146 return OS << *Sym;
147}
148
150 return OS << printSequence(Symbols, '{', '}', PrintAll<SymbolStringPtr>());
151}
152
154 return OS << printSequence(Symbols, '[', ']', PrintAll<SymbolStringPtr>());
155}
156
158 return OS << printSequence(Symbols, '[', ']', PrintAll<SymbolStringPtr>());
159}
160
162 if (Flags.hasError())
163 OS << "[*ERROR*]";
164 if (Flags.isCallable())
165 OS << "[Callable]";
166 else
167 OS << "[Data]";
168 if (Flags.isWeak())
169 OS << "[Weak]";
170 else if (Flags.isCommon())
171 OS << "[Common]";
172
173 if (!Flags.isExported())
174 OS << "[Hidden]";
175
176 return OS;
177}
178
180 return OS << Sym.getAddress() << " " << Sym.getFlags();
181}
182
184 return OS << "(\"" << KV.first << "\", " << KV.second << ")";
185}
186
188 return OS << "(\"" << KV.first << "\": " << KV.second << ")";
189}
190
192 return OS << printSequence(SymbolFlags, '{', '}',
193 PrintSymbolFlagsMapElemsMatchingCLOpts());
194}
195
197 return OS << printSequence(Symbols, '{', '}',
198 PrintSymbolMapElemsMatchingCLOpts());
199}
200
203 return OS << "(" << KV.first->getName() << ", " << KV.second << ")";
204}
205
207 return OS << printSequence(Deps, '{', '}',
208 PrintAll<SymbolDependenceMap::value_type>());
209}
210
212 OS << "MU@" << &MU << " (\"" << MU.getName() << "\"";
213 if (anyPrintSymbolOptionSet())
214 OS << ", " << MU.getSymbols();
215 return OS << ")";
216}
217
219 switch (K) {
221 return OS << "Static";
223 return OS << "DLSym";
224 }
225 llvm_unreachable("Invalid lookup kind");
226}
227
229 const JITDylibLookupFlags &JDLookupFlags) {
230 switch (JDLookupFlags) {
232 return OS << "MatchExportedSymbolsOnly";
234 return OS << "MatchAllSymbols";
235 }
236 llvm_unreachable("Invalid JITDylib lookup flags");
237}
238
240 switch (LookupFlags) {
242 return OS << "RequiredSymbol";
244 return OS << "WeaklyReferencedSymbol";
245 }
246 llvm_unreachable("Invalid symbol lookup flags");
247}
248
250 const SymbolLookupSet::value_type &KV) {
251 return OS << "(" << KV.first << ", " << KV.second << ")";
252}
253
255 return OS << printSequence(LookupSet, '{', '}',
256 PrintAll<SymbolLookupSet::value_type>());
257}
258
260 const JITDylibSearchOrder &SearchOrder) {
261 OS << "[";
262 if (!SearchOrder.empty()) {
263 assert(SearchOrder.front().first &&
264 "JITDylibList entries must not be null");
265 OS << " (\"" << SearchOrder.front().first->getName() << "\", "
266 << SearchOrder.begin()->second << ")";
267 for (auto &KV : llvm::drop_begin(SearchOrder)) {
268 assert(KV.first && "JITDylibList entries must not be null");
269 OS << ", (\"" << KV.first->getName() << "\", " << KV.second << ")";
270 }
271 }
272 OS << " ]";
273 return OS;
274}
275
277 OS << "{";
278 for (auto &KV : Aliases)
279 OS << " " << *KV.first << ": " << KV.second.Aliasee << " "
280 << KV.second.AliasFlags;
281 OS << " }";
282 return OS;
283}
284
286 switch (S) {
288 return OS << "Invalid";
290 return OS << "Never-Searched";
292 return OS << "Materializing";
294 return OS << "Resolved";
296 return OS << "Emitted";
298 return OS << "Ready";
299 }
300 llvm_unreachable("Invalid state");
301}
302
304 std::lock_guard<std::mutex> Lock(SSP.PoolMutex);
306 for (auto &KV : SSP.Pool)
307 Vec.emplace_back(KV.first(), KV.second);
308 llvm::sort(Vec, less_first());
309 for (auto &[K, V] : Vec)
310 OS << K << ": " << V << "\n";
311 return OS;
312}
313
314DumpObjects::DumpObjects(std::string DumpDir, std::string IdentifierOverride)
315 : DumpDir(std::move(DumpDir)),
316 IdentifierOverride(std::move(IdentifierOverride)) {
317
318 /// Discard any trailing separators.
319 while (!this->DumpDir.empty() &&
320 sys::path::is_separator(this->DumpDir.back()))
321 this->DumpDir.pop_back();
322}
323
325DumpObjects::operator()(std::unique_ptr<MemoryBuffer> Obj) {
326 size_t Idx = 1;
327
328 std::string DumpPathStem;
329 raw_string_ostream(DumpPathStem)
330 << DumpDir << (DumpDir.empty() ? "" : "/") << getBufferIdentifier(*Obj);
331
332 std::string DumpPath = DumpPathStem + ".o";
333 while (sys::fs::exists(DumpPath)) {
334 DumpPath.clear();
335 raw_string_ostream(DumpPath) << DumpPathStem << "." << (++Idx) << ".o";
336 }
337
338 LLVM_DEBUG({
339 dbgs() << "Dumping object buffer [ " << (const void *)Obj->getBufferStart()
340 << " -- " << (const void *)(Obj->getBufferEnd() - 1) << " ] to "
341 << DumpPath << "\n";
342 });
343
344 std::error_code EC;
345 raw_fd_ostream DumpStream(DumpPath, EC);
346 if (EC)
347 return errorCodeToError(EC);
348 DumpStream.write(Obj->getBufferStart(), Obj->getBufferSize());
349
350 return std::move(Obj);
351}
352
353StringRef DumpObjects::getBufferIdentifier(MemoryBuffer &B) {
354 if (!IdentifierOverride.empty())
355 return IdentifierOverride;
356 StringRef Identifier = B.getBufferIdentifier();
357 Identifier.consume_back(".o");
358 return Identifier;
359}
360
361} // End namespace orc.
362} // End namespace llvm.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
dxil pretty DXIL Metadata Pretty Printer
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
BucketT value_type
Definition: DenseMap.h:69
Tagged union holding either a T or a Error.
Definition: Error.h:474
Flags for symbols in the JIT.
Definition: JITSymbol.h:74
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:51
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Expected< std::unique_ptr< MemoryBuffer > > operator()(std::unique_ptr< MemoryBuffer > Obj)
Dumps the given buffer to disk.
Definition: DebugUtils.cpp:325
DumpObjects(std::string DumpDir="", std::string IdentifierOverride="")
Construct a DumpObjects transform that will dump objects to disk.
Definition: DebugUtils.cpp:314
Represents a defining location for a JIT symbol.
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
Definition: Core.h:693
virtual StringRef getName() const =0
Return the name of this materialization unit.
const SymbolFlagsMap & getSymbols() const
Return the set of symbols that this source provides.
Definition: Core.h:723
Non-owning SymbolStringPool entry pointer.
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:183
std::pair< SymbolStringPtr, SymbolLookupFlags > value_type
Definition: Core.h:185
String pool for symbol names used by the JIT.
Pointer to a pooled string representing a symbol name.
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:470
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & write(unsigned char C)
const char * getBufferStart() const
Return the beginning of the current stream buffer, or 0 if the stream is unbuffered.
Definition: raw_ostream.h:403
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:660
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
Definition: Core.h:162
SymbolLookupFlags
Lookup flags that apply to each symbol in a lookup.
Definition: Core.h:145
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition: Core.h:135
LookupKind
Describes the kind of lookup being performed.
Definition: Core.h:157
std::vector< SymbolStringPtr > SymbolNameVector
A vector of symbol names.
Definition: Core.h:117
SymbolState
Represents the state that a symbol has reached during materialization.
Definition: Core.h:859
@ Materializing
Added to the symbol table, never queried.
@ NeverSearched
No symbol should be in this state.
@ Ready
Emitted to memory, but waiting on transitive dependencies.
@ Emitted
Assigned address, still materializing.
@ Resolved
Queried, materialization begun.
raw_ostream & operator<<(raw_ostream &OS, const SymbolStringPtr &Sym)
Render a SymbolStringPtr.
Definition: DebugUtils.cpp:141
bool exists(const basic_file_status &status)
Does file exist?
Definition: Path.cpp:1078
bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition: Path.cpp:602
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1656
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:293
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1858
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:103
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
Function object to check whether the first component of a container supported by std::get (like std::...
Definition: STLExtras.h:1459