xref: /llvm-project/llvm/lib/ExecutionEngine/Orc/DebugUtils.cpp (revision 38a8760b99b7036ce5133574007a7ab7e5ea9d9c)
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 
9 #include "llvm/ExecutionEngine/Orc/DebugUtils.h"
10 
11 #include "llvm/ExecutionEngine/Orc/Core.h"
12 #include "llvm/Support/CommandLine.h"
13 #include "llvm/Support/Debug.h"
14 #include "llvm/Support/FileSystem.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/Support/Path.h"
18 #include "llvm/Support/raw_ostream.h"
19 
20 #define DEBUG_TYPE "orc"
21 
22 using namespace llvm;
23 
24 namespace {
25 
26 #ifndef NDEBUG
27 
28 cl::opt<bool> PrintHidden("debug-orc-print-hidden", cl::init(true),
29                           cl::desc("debug print hidden symbols defined by "
30                                    "materialization units"),
31                           cl::Hidden);
32 
33 cl::opt<bool> PrintCallable("debug-orc-print-callable", cl::init(true),
34                             cl::desc("debug print callable symbols defined by "
35                                      "materialization units"),
36                             cl::Hidden);
37 
38 cl::opt<bool> PrintData("debug-orc-print-data", cl::init(true),
39                         cl::desc("debug print data symbols defined by "
40                                  "materialization units"),
41                         cl::Hidden);
42 
43 #endif // NDEBUG
44 
45 // SetPrinter predicate that prints every element.
46 template <typename T> struct PrintAll {
47   bool operator()(const T &E) { return true; }
48 };
49 
50 bool anyPrintSymbolOptionSet() {
51 #ifndef NDEBUG
52   return PrintHidden || PrintCallable || PrintData;
53 #else
54   return false;
55 #endif // NDEBUG
56 }
57 
58 bool 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.
80 template <typename Sequence,
81           typename Pred = PrintAll<typename Sequence::value_type>>
82 class SequencePrinter {
83 public:
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 
103 private:
104   const Sequence &S;
105   char OpenSeq;
106   char CloseSeq;
107   mutable Pred ShouldPrint;
108 };
109 
110 template <typename Sequence, typename Pred>
111 SequencePrinter<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.
117 template <typename Sequence, typename Pred>
118 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
119                               const SequencePrinter<Sequence, Pred> &Printer) {
120   Printer.printTo(OS);
121   return OS;
122 }
123 
124 struct PrintSymbolFlagsMapElemsMatchingCLOpts {
125   bool operator()(const orc::SymbolFlagsMap::value_type &KV) {
126     return flagsMatchCLOpts(KV.second);
127   }
128 };
129 
130 struct PrintSymbolMapElemsMatchingCLOpts {
131   bool operator()(const orc::SymbolMap::value_type &KV) {
132     return flagsMatchCLOpts(KV.second.getFlags());
133   }
134 };
135 
136 } // end anonymous namespace
137 
138 namespace llvm {
139 namespace orc {
140 
141 raw_ostream &operator<<(raw_ostream &OS, const SymbolStringPtr &Sym) {
142   return OS << *Sym;
143 }
144 
145 raw_ostream &operator<<(raw_ostream &OS, const SymbolNameSet &Symbols) {
146   return OS << printSequence(Symbols, '{', '}', PrintAll<SymbolStringPtr>());
147 }
148 
149 raw_ostream &operator<<(raw_ostream &OS, const SymbolNameVector &Symbols) {
150   return OS << printSequence(Symbols, '[', ']', PrintAll<SymbolStringPtr>());
151 }
152 
153 raw_ostream &operator<<(raw_ostream &OS, const JITSymbolFlags &Flags) {
154   if (Flags.hasError())
155     OS << "[*ERROR*]";
156   if (Flags.isCallable())
157     OS << "[Callable]";
158   else
159     OS << "[Data]";
160   if (Flags.isWeak())
161     OS << "[Weak]";
162   else if (Flags.isCommon())
163     OS << "[Common]";
164 
165   if (!Flags.isExported())
166     OS << "[Hidden]";
167 
168   return OS;
169 }
170 
171 raw_ostream &operator<<(raw_ostream &OS, const JITEvaluatedSymbol &Sym) {
172   return OS << format("0x%016" PRIx64, Sym.getAddress()) << " "
173             << Sym.getFlags();
174 }
175 
176 raw_ostream &operator<<(raw_ostream &OS, const SymbolFlagsMap::value_type &KV) {
177   return OS << "(\"" << KV.first << "\", " << KV.second << ")";
178 }
179 
180 raw_ostream &operator<<(raw_ostream &OS, const SymbolMap::value_type &KV) {
181   return OS << "(\"" << KV.first << "\": " << KV.second << ")";
182 }
183 
184 raw_ostream &operator<<(raw_ostream &OS, const SymbolFlagsMap &SymbolFlags) {
185   return OS << printSequence(SymbolFlags, '{', '}',
186                              PrintSymbolFlagsMapElemsMatchingCLOpts());
187 }
188 
189 raw_ostream &operator<<(raw_ostream &OS, const SymbolMap &Symbols) {
190   return OS << printSequence(Symbols, '{', '}',
191                              PrintSymbolMapElemsMatchingCLOpts());
192 }
193 
194 raw_ostream &operator<<(raw_ostream &OS,
195                         const SymbolDependenceMap::value_type &KV) {
196   return OS << "(" << KV.first->getName() << ", " << KV.second << ")";
197 }
198 
199 raw_ostream &operator<<(raw_ostream &OS, const SymbolDependenceMap &Deps) {
200   return OS << printSequence(Deps, '{', '}',
201                              PrintAll<SymbolDependenceMap::value_type>());
202 }
203 
204 raw_ostream &operator<<(raw_ostream &OS, const MaterializationUnit &MU) {
205   OS << "MU@" << &MU << " (\"" << MU.getName() << "\"";
206   if (anyPrintSymbolOptionSet())
207     OS << ", " << MU.getSymbols();
208   return OS << ")";
209 }
210 
211 raw_ostream &operator<<(raw_ostream &OS, const LookupKind &K) {
212   switch (K) {
213   case LookupKind::Static:
214     return OS << "Static";
215   case LookupKind::DLSym:
216     return OS << "DLSym";
217   }
218   llvm_unreachable("Invalid lookup kind");
219 }
220 
221 raw_ostream &operator<<(raw_ostream &OS,
222                         const JITDylibLookupFlags &JDLookupFlags) {
223   switch (JDLookupFlags) {
224   case JITDylibLookupFlags::MatchExportedSymbolsOnly:
225     return OS << "MatchExportedSymbolsOnly";
226   case JITDylibLookupFlags::MatchAllSymbols:
227     return OS << "MatchAllSymbols";
228   }
229   llvm_unreachable("Invalid JITDylib lookup flags");
230 }
231 
232 raw_ostream &operator<<(raw_ostream &OS, const SymbolLookupFlags &LookupFlags) {
233   switch (LookupFlags) {
234   case SymbolLookupFlags::RequiredSymbol:
235     return OS << "RequiredSymbol";
236   case SymbolLookupFlags::WeaklyReferencedSymbol:
237     return OS << "WeaklyReferencedSymbol";
238   }
239   llvm_unreachable("Invalid symbol lookup flags");
240 }
241 
242 raw_ostream &operator<<(raw_ostream &OS,
243                         const SymbolLookupSet::value_type &KV) {
244   return OS << "(" << KV.first << ", " << KV.second << ")";
245 }
246 
247 raw_ostream &operator<<(raw_ostream &OS, const SymbolLookupSet &LookupSet) {
248   return OS << printSequence(LookupSet, '{', '}',
249                              PrintAll<SymbolLookupSet::value_type>());
250 }
251 
252 raw_ostream &operator<<(raw_ostream &OS,
253                         const JITDylibSearchOrder &SearchOrder) {
254   OS << "[";
255   if (!SearchOrder.empty()) {
256     assert(SearchOrder.front().first &&
257            "JITDylibList entries must not be null");
258     OS << " (\"" << SearchOrder.front().first->getName() << "\", "
259        << SearchOrder.begin()->second << ")";
260     for (auto &KV :
261          make_range(std::next(SearchOrder.begin(), 1), SearchOrder.end())) {
262       assert(KV.first && "JITDylibList entries must not be null");
263       OS << ", (\"" << KV.first->getName() << "\", " << KV.second << ")";
264     }
265   }
266   OS << " ]";
267   return OS;
268 }
269 
270 raw_ostream &operator<<(raw_ostream &OS, const SymbolAliasMap &Aliases) {
271   OS << "{";
272   for (auto &KV : Aliases)
273     OS << " " << *KV.first << ": " << KV.second.Aliasee << " "
274        << KV.second.AliasFlags;
275   OS << " }";
276   return OS;
277 }
278 
279 raw_ostream &operator<<(raw_ostream &OS, const SymbolState &S) {
280   switch (S) {
281   case SymbolState::Invalid:
282     return OS << "Invalid";
283   case SymbolState::NeverSearched:
284     return OS << "Never-Searched";
285   case SymbolState::Materializing:
286     return OS << "Materializing";
287   case SymbolState::Resolved:
288     return OS << "Resolved";
289   case SymbolState::Emitted:
290     return OS << "Emitted";
291   case SymbolState::Ready:
292     return OS << "Ready";
293   }
294   llvm_unreachable("Invalid state");
295 }
296 
297 DumpObjects::DumpObjects(std::string DumpDir, std::string IdentifierOverride)
298     : DumpDir(std::move(DumpDir)),
299       IdentifierOverride(std::move(IdentifierOverride)) {
300 
301   /// Discard any trailing separators.
302   while (!this->DumpDir.empty() &&
303          sys::path::is_separator(this->DumpDir.back()))
304     this->DumpDir.pop_back();
305 }
306 
307 Expected<std::unique_ptr<MemoryBuffer>>
308 DumpObjects::operator()(std::unique_ptr<MemoryBuffer> Obj) {
309   size_t Idx = 1;
310 
311   std::string DumpPathStem;
312   raw_string_ostream(DumpPathStem)
313       << DumpDir << (DumpDir.empty() ? "" : "/") << getBufferIdentifier(*Obj);
314 
315   std::string DumpPath = DumpPathStem + ".o";
316   while (sys::fs::exists(DumpPath)) {
317     DumpPath.clear();
318     raw_string_ostream(DumpPath) << DumpPathStem << "." << (++Idx) << ".o";
319   }
320 
321   LLVM_DEBUG({
322     dbgs() << "Dumping object buffer [ " << (const void *)Obj->getBufferStart()
323            << " -- " << (const void *)(Obj->getBufferEnd() - 1) << " ] to "
324            << DumpPath << "\n";
325   });
326 
327   std::error_code EC;
328   raw_fd_ostream DumpStream(DumpPath, EC);
329   if (EC)
330     return errorCodeToError(EC);
331   DumpStream.write(Obj->getBufferStart(), Obj->getBufferSize());
332 
333   return std::move(Obj);
334 }
335 
336 StringRef DumpObjects::getBufferIdentifier(MemoryBuffer &B) {
337   if (!IdentifierOverride.empty())
338     return IdentifierOverride;
339   StringRef Identifier = B.getBufferIdentifier();
340   Identifier.consume_back(".o");
341   return Identifier;
342 }
343 
344 } // End namespace orc.
345 } // End namespace llvm.
346