]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-xray/xray-account.cc
MFV: r325668
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / llvm-xray / xray-account.cc
1 //===- xray-account.h - XRay Function Call Accounting ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements basic function call accounting from an XRay trace.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include <algorithm>
15 #include <cassert>
16 #include <numeric>
17 #include <system_error>
18 #include <utility>
19
20 #include "xray-account.h"
21 #include "xray-registry.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/FormatVariadic.h"
24 #include "llvm/XRay/InstrumentationMap.h"
25 #include "llvm/XRay/Trace.h"
26
27 using namespace llvm;
28 using namespace llvm::xray;
29
30 static cl::SubCommand Account("account", "Function call accounting");
31 static cl::opt<std::string> AccountInput(cl::Positional,
32                                          cl::desc("<xray log file>"),
33                                          cl::Required, cl::sub(Account));
34 static cl::opt<bool>
35     AccountKeepGoing("keep-going", cl::desc("Keep going on errors encountered"),
36                      cl::sub(Account), cl::init(false));
37 static cl::alias AccountKeepGoing2("k", cl::aliasopt(AccountKeepGoing),
38                                    cl::desc("Alias for -keep_going"),
39                                    cl::sub(Account));
40 static cl::opt<bool> AccountDeduceSiblingCalls(
41     "deduce-sibling-calls",
42     cl::desc("Deduce sibling calls when unrolling function call stacks"),
43     cl::sub(Account), cl::init(false));
44 static cl::alias
45     AccountDeduceSiblingCalls2("d", cl::aliasopt(AccountDeduceSiblingCalls),
46                                cl::desc("Alias for -deduce_sibling_calls"),
47                                cl::sub(Account));
48 static cl::opt<std::string>
49     AccountOutput("output", cl::value_desc("output file"), cl::init("-"),
50                   cl::desc("output file; use '-' for stdout"),
51                   cl::sub(Account));
52 static cl::alias AccountOutput2("o", cl::aliasopt(AccountOutput),
53                                 cl::desc("Alias for -output"),
54                                 cl::sub(Account));
55 enum class AccountOutputFormats { TEXT, CSV };
56 static cl::opt<AccountOutputFormats>
57     AccountOutputFormat("format", cl::desc("output format"),
58                         cl::values(clEnumValN(AccountOutputFormats::TEXT,
59                                               "text", "report stats in text"),
60                                    clEnumValN(AccountOutputFormats::CSV, "csv",
61                                               "report stats in csv")),
62                         cl::sub(Account));
63 static cl::alias AccountOutputFormat2("f", cl::desc("Alias of -format"),
64                                       cl::aliasopt(AccountOutputFormat),
65                                       cl::sub(Account));
66
67 enum class SortField {
68   FUNCID,
69   COUNT,
70   MIN,
71   MED,
72   PCT90,
73   PCT99,
74   MAX,
75   SUM,
76   FUNC,
77 };
78
79 static cl::opt<SortField> AccountSortOutput(
80     "sort", cl::desc("sort output by this field"), cl::value_desc("field"),
81     cl::sub(Account), cl::init(SortField::FUNCID),
82     cl::values(clEnumValN(SortField::FUNCID, "funcid", "function id"),
83                clEnumValN(SortField::COUNT, "count", "funciton call counts"),
84                clEnumValN(SortField::MIN, "min", "minimum function durations"),
85                clEnumValN(SortField::MED, "med", "median function durations"),
86                clEnumValN(SortField::PCT90, "90p", "90th percentile durations"),
87                clEnumValN(SortField::PCT99, "99p", "99th percentile durations"),
88                clEnumValN(SortField::MAX, "max", "maximum function durations"),
89                clEnumValN(SortField::SUM, "sum", "sum of call durations"),
90                clEnumValN(SortField::FUNC, "func", "function names")));
91 static cl::alias AccountSortOutput2("s", cl::aliasopt(AccountSortOutput),
92                                     cl::desc("Alias for -sort"),
93                                     cl::sub(Account));
94
95 enum class SortDirection {
96   ASCENDING,
97   DESCENDING,
98 };
99 static cl::opt<SortDirection> AccountSortOrder(
100     "sortorder", cl::desc("sort ordering"), cl::init(SortDirection::ASCENDING),
101     cl::values(clEnumValN(SortDirection::ASCENDING, "asc", "ascending"),
102                clEnumValN(SortDirection::DESCENDING, "dsc", "descending")),
103     cl::sub(Account));
104 static cl::alias AccountSortOrder2("r", cl::aliasopt(AccountSortOrder),
105                                    cl::desc("Alias for -sortorder"),
106                                    cl::sub(Account));
107
108 static cl::opt<int> AccountTop("top", cl::desc("only show the top N results"),
109                                cl::value_desc("N"), cl::sub(Account),
110                                cl::init(-1));
111 static cl::alias AccountTop2("p", cl::desc("Alias for -top"),
112                              cl::aliasopt(AccountTop), cl::sub(Account));
113
114 static cl::opt<std::string>
115     AccountInstrMap("instr_map",
116                     cl::desc("binary with the instrumentation map, or "
117                              "a separate instrumentation map"),
118                     cl::value_desc("binary with xray_instr_map"),
119                     cl::sub(Account), cl::init(""));
120 static cl::alias AccountInstrMap2("m", cl::aliasopt(AccountInstrMap),
121                                   cl::desc("Alias for -instr_map"),
122                                   cl::sub(Account));
123
124 namespace {
125
126 template <class T, class U> void setMinMax(std::pair<T, T> &MM, U &&V) {
127   if (MM.first == 0 || MM.second == 0)
128     MM = std::make_pair(std::forward<U>(V), std::forward<U>(V));
129   else
130     MM = std::make_pair(std::min(MM.first, V), std::max(MM.second, V));
131 }
132
133 template <class T> T diff(T L, T R) { return std::max(L, R) - std::min(L, R); }
134
135 } // namespace
136
137 bool LatencyAccountant::accountRecord(const XRayRecord &Record) {
138   setMinMax(PerThreadMinMaxTSC[Record.TId], Record.TSC);
139   setMinMax(PerCPUMinMaxTSC[Record.CPU], Record.TSC);
140
141   if (CurrentMaxTSC == 0)
142     CurrentMaxTSC = Record.TSC;
143
144   if (Record.TSC < CurrentMaxTSC)
145     return false;
146
147   auto &ThreadStack = PerThreadFunctionStack[Record.TId];
148   switch (Record.Type) {
149   case RecordTypes::ENTER: {
150     // Function Enter
151     ThreadStack.emplace_back(Record.FuncId, Record.TSC);
152     break;
153   }
154   case RecordTypes::EXIT: {
155     // Function Exit
156     if (ThreadStack.back().first == Record.FuncId) {
157       const auto &Top = ThreadStack.back();
158       recordLatency(Top.first, diff(Top.second, Record.TSC));
159       ThreadStack.pop_back();
160       break;
161     }
162
163     if (!DeduceSiblingCalls)
164       return false;
165
166     // Look for the parent up the stack.
167     auto Parent =
168         std::find_if(ThreadStack.rbegin(), ThreadStack.rend(),
169                      [&](const std::pair<const int32_t, uint64_t> &E) {
170                        return E.first == Record.FuncId;
171                      });
172     if (Parent == ThreadStack.rend())
173       return false;
174
175     // Account time for this apparently sibling call exit up the stack.
176     // Considering the following case:
177     //
178     //   f()
179     //    g()
180     //      h()
181     //
182     // We might only ever see the following entries:
183     //
184     //   -> f()
185     //   -> g()
186     //   -> h()
187     //   <- h()
188     //   <- f()
189     //
190     // Now we don't see the exit to g() because some older version of the XRay
191     // runtime wasn't instrumenting tail exits. If we don't deduce tail calls,
192     // we may potentially never account time for g() -- and this code would have
193     // already bailed out, because `<- f()` doesn't match the current "top" of
194     // stack where we're waiting for the exit to `g()` instead. This is not
195     // ideal and brittle -- so instead we provide a potentially inaccurate
196     // accounting of g() instead, computing it from the exit of f().
197     //
198     // While it might be better that we account the time between `-> g()` and
199     // `-> h()` as the proper accounting of time for g() here, this introduces
200     // complexity to do correctly (need to backtrack, etc.).
201     //
202     // FIXME: Potentially implement the more complex deduction algorithm?
203     auto I = std::next(Parent).base();
204     for (auto &E : make_range(I, ThreadStack.end())) {
205       recordLatency(E.first, diff(E.second, Record.TSC));
206     }
207     ThreadStack.erase(I, ThreadStack.end());
208     break;
209   }
210   }
211
212   return true;
213 }
214
215 namespace {
216
217 // We consolidate the data into a struct which we can output in various forms.
218 struct ResultRow {
219   uint64_t Count;
220   double Min;
221   double Median;
222   double Pct90;
223   double Pct99;
224   double Max;
225   double Sum;
226   std::string DebugInfo;
227   std::string Function;
228 };
229
230 ResultRow getStats(std::vector<uint64_t> &Timings) {
231   assert(!Timings.empty());
232   ResultRow R;
233   R.Sum = std::accumulate(Timings.begin(), Timings.end(), 0.0);
234   auto MinMax = std::minmax_element(Timings.begin(), Timings.end());
235   R.Min = *MinMax.first;
236   R.Max = *MinMax.second;
237   auto MedianOff = Timings.size() / 2;
238   std::nth_element(Timings.begin(), Timings.begin() + MedianOff, Timings.end());
239   R.Median = Timings[MedianOff];
240   auto Pct90Off = std::floor(Timings.size() * 0.9);
241   std::nth_element(Timings.begin(), Timings.begin() + Pct90Off, Timings.end());
242   R.Pct90 = Timings[Pct90Off];
243   auto Pct99Off = std::floor(Timings.size() * 0.99);
244   std::nth_element(Timings.begin(), Timings.begin() + Pct90Off, Timings.end());
245   R.Pct99 = Timings[Pct99Off];
246   R.Count = Timings.size();
247   return R;
248 }
249
250 } // namespace
251
252 template <class F>
253 void LatencyAccountant::exportStats(const XRayFileHeader &Header, F Fn) const {
254   using TupleType = std::tuple<int32_t, uint64_t, ResultRow>;
255   std::vector<TupleType> Results;
256   Results.reserve(FunctionLatencies.size());
257   for (auto FT : FunctionLatencies) {
258     const auto &FuncId = FT.first;
259     auto &Timings = FT.second;
260     Results.emplace_back(FuncId, Timings.size(), getStats(Timings));
261     auto &Row = std::get<2>(Results.back());
262     if (Header.CycleFrequency) {
263       double CycleFrequency = Header.CycleFrequency;
264       Row.Min /= CycleFrequency;
265       Row.Median /= CycleFrequency;
266       Row.Pct90 /= CycleFrequency;
267       Row.Pct99 /= CycleFrequency;
268       Row.Max /= CycleFrequency;
269       Row.Sum /= CycleFrequency;
270     }
271
272     Row.Function = FuncIdHelper.SymbolOrNumber(FuncId);
273     Row.DebugInfo = FuncIdHelper.FileLineAndColumn(FuncId);
274   }
275
276   // Sort the data according to user-provided flags.
277   switch (AccountSortOutput) {
278   case SortField::FUNCID:
279     std::sort(Results.begin(), Results.end(),
280               [](const TupleType &L, const TupleType &R) {
281                 if (AccountSortOrder == SortDirection::ASCENDING)
282                   return std::get<0>(L) < std::get<0>(R);
283                 if (AccountSortOrder == SortDirection::DESCENDING)
284                   return std::get<0>(L) > std::get<0>(R);
285                 llvm_unreachable("Unknown sort direction");
286               });
287     break;
288   case SortField::COUNT:
289     std::sort(Results.begin(), Results.end(),
290               [](const TupleType &L, const TupleType &R) {
291                 if (AccountSortOrder == SortDirection::ASCENDING)
292                   return std::get<1>(L) < std::get<1>(R);
293                 if (AccountSortOrder == SortDirection::DESCENDING)
294                   return std::get<1>(L) > std::get<1>(R);
295                 llvm_unreachable("Unknown sort direction");
296               });
297     break;
298   default:
299     // Here we need to look into the ResultRow for the rest of the data that
300     // we want to sort by.
301     std::sort(Results.begin(), Results.end(),
302               [&](const TupleType &L, const TupleType &R) {
303                 auto &LR = std::get<2>(L);
304                 auto &RR = std::get<2>(R);
305                 switch (AccountSortOutput) {
306                 case SortField::COUNT:
307                   if (AccountSortOrder == SortDirection::ASCENDING)
308                     return LR.Count < RR.Count;
309                   if (AccountSortOrder == SortDirection::DESCENDING)
310                     return LR.Count > RR.Count;
311                   llvm_unreachable("Unknown sort direction");
312                 case SortField::MIN:
313                   if (AccountSortOrder == SortDirection::ASCENDING)
314                     return LR.Min < RR.Min;
315                   if (AccountSortOrder == SortDirection::DESCENDING)
316                     return LR.Min > RR.Min;
317                   llvm_unreachable("Unknown sort direction");
318                 case SortField::MED:
319                   if (AccountSortOrder == SortDirection::ASCENDING)
320                     return LR.Median < RR.Median;
321                   if (AccountSortOrder == SortDirection::DESCENDING)
322                     return LR.Median > RR.Median;
323                   llvm_unreachable("Unknown sort direction");
324                 case SortField::PCT90:
325                   if (AccountSortOrder == SortDirection::ASCENDING)
326                     return LR.Pct90 < RR.Pct90;
327                   if (AccountSortOrder == SortDirection::DESCENDING)
328                     return LR.Pct90 > RR.Pct90;
329                   llvm_unreachable("Unknown sort direction");
330                 case SortField::PCT99:
331                   if (AccountSortOrder == SortDirection::ASCENDING)
332                     return LR.Pct99 < RR.Pct99;
333                   if (AccountSortOrder == SortDirection::DESCENDING)
334                     return LR.Pct99 > RR.Pct99;
335                   llvm_unreachable("Unknown sort direction");
336                 case SortField::MAX:
337                   if (AccountSortOrder == SortDirection::ASCENDING)
338                     return LR.Max < RR.Max;
339                   if (AccountSortOrder == SortDirection::DESCENDING)
340                     return LR.Max > RR.Max;
341                   llvm_unreachable("Unknown sort direction");
342                 case SortField::SUM:
343                   if (AccountSortOrder == SortDirection::ASCENDING)
344                     return LR.Sum < RR.Sum;
345                   if (AccountSortOrder == SortDirection::DESCENDING)
346                     return LR.Sum > RR.Sum;
347                   llvm_unreachable("Unknown sort direction");
348                 default:
349                   llvm_unreachable("Unsupported sort order");
350                 }
351               });
352     break;
353   }
354
355   if (AccountTop > 0)
356     Results.erase(Results.begin() + AccountTop.getValue(), Results.end());
357
358   for (const auto &R : Results)
359     Fn(std::get<0>(R), std::get<1>(R), std::get<2>(R));
360 }
361
362 void LatencyAccountant::exportStatsAsText(raw_ostream &OS,
363                                           const XRayFileHeader &Header) const {
364   OS << "Functions with latencies: " << FunctionLatencies.size() << "\n";
365
366   // We spend some effort to make the text output more readable, so we do the
367   // following formatting decisions for each of the fields:
368   //
369   //   - funcid: 32-bit, but we can determine the largest number and be
370   //   between
371   //     a minimum of 5 characters, up to 9 characters, right aligned.
372   //   - count:  64-bit, but we can determine the largest number and be
373   //   between
374   //     a minimum of 5 characters, up to 9 characters, right aligned.
375   //   - min, median, 90pct, 99pct, max: double precision, but we want to keep
376   //     the values in seconds, with microsecond precision (0.000'001), so we
377   //     have at most 6 significant digits, with the whole number part to be
378   //     at
379   //     least 1 character. For readability we'll right-align, with full 9
380   //     characters each.
381   //   - debug info, function name: we format this as a concatenation of the
382   //     debug info and the function name.
383   //
384   static constexpr char StatsHeaderFormat[] =
385       "{0,+9} {1,+10} [{2,+9}, {3,+9}, {4,+9}, {5,+9}, {6,+9}] {7,+9}";
386   static constexpr char StatsFormat[] =
387       R"({0,+9} {1,+10} [{2,+9:f6}, {3,+9:f6}, {4,+9:f6}, {5,+9:f6}, {6,+9:f6}] {7,+9:f6})";
388   OS << llvm::formatv(StatsHeaderFormat, "funcid", "count", "min", "med", "90p",
389                       "99p", "max", "sum")
390      << llvm::formatv("  {0,-12}\n", "function");
391   exportStats(Header, [&](int32_t FuncId, size_t Count, const ResultRow &Row) {
392     OS << llvm::formatv(StatsFormat, FuncId, Count, Row.Min, Row.Median,
393                         Row.Pct90, Row.Pct99, Row.Max, Row.Sum)
394        << "  " << Row.DebugInfo << ": " << Row.Function << "\n";
395   });
396 }
397
398 void LatencyAccountant::exportStatsAsCSV(raw_ostream &OS,
399                                          const XRayFileHeader &Header) const {
400   OS << "funcid,count,min,median,90%ile,99%ile,max,sum,debug,function\n";
401   exportStats(Header, [&](int32_t FuncId, size_t Count, const ResultRow &Row) {
402     OS << FuncId << ',' << Count << ',' << Row.Min << ',' << Row.Median << ','
403        << Row.Pct90 << ',' << Row.Pct99 << ',' << Row.Max << "," << Row.Sum
404        << ",\"" << Row.DebugInfo << "\",\"" << Row.Function << "\"\n";
405   });
406 }
407
408 using namespace llvm::xray;
409
410 static CommandRegistration Unused(&Account, []() -> Error {
411   InstrumentationMap Map;
412   if (!AccountInstrMap.empty()) {
413     auto InstrumentationMapOrError = loadInstrumentationMap(AccountInstrMap);
414     if (!InstrumentationMapOrError)
415       return joinErrors(make_error<StringError>(
416                             Twine("Cannot open instrumentation map '") +
417                                 AccountInstrMap + "'",
418                             std::make_error_code(std::errc::invalid_argument)),
419                         InstrumentationMapOrError.takeError());
420     Map = std::move(*InstrumentationMapOrError);
421   }
422
423   std::error_code EC;
424   raw_fd_ostream OS(AccountOutput, EC, sys::fs::OpenFlags::F_Text);
425   if (EC)
426     return make_error<StringError>(
427         Twine("Cannot open file '") + AccountOutput + "' for writing.", EC);
428
429   const auto &FunctionAddresses = Map.getFunctionAddresses();
430   symbolize::LLVMSymbolizer::Options Opts(
431       symbolize::FunctionNameKind::LinkageName, true, true, false, "");
432   symbolize::LLVMSymbolizer Symbolizer(Opts);
433   llvm::xray::FuncIdConversionHelper FuncIdHelper(AccountInstrMap, Symbolizer,
434                                                   FunctionAddresses);
435   xray::LatencyAccountant FCA(FuncIdHelper, AccountDeduceSiblingCalls);
436   auto TraceOrErr = loadTraceFile(AccountInput);
437   if (!TraceOrErr)
438     return joinErrors(
439         make_error<StringError>(
440             Twine("Failed loading input file '") + AccountInput + "'",
441             std::make_error_code(std::errc::executable_format_error)),
442         TraceOrErr.takeError());
443
444   auto &T = *TraceOrErr;
445   for (const auto &Record : T) {
446     if (FCA.accountRecord(Record))
447       continue;
448     for (const auto &ThreadStack : FCA.getPerThreadFunctionStack()) {
449       errs() << "Thread ID: " << ThreadStack.first << "\n";
450       auto Level = ThreadStack.second.size();
451       for (const auto &Entry : llvm::reverse(ThreadStack.second))
452         errs() << "#" << Level-- << "\t"
453                << FuncIdHelper.SymbolOrNumber(Entry.first) << '\n';
454     }
455     if (!AccountKeepGoing)
456       return make_error<StringError>(
457           Twine("Failed accounting function calls in file '") + AccountInput +
458               "'.",
459           std::make_error_code(std::errc::executable_format_error));
460   }
461   switch (AccountOutputFormat) {
462   case AccountOutputFormats::TEXT:
463     FCA.exportStatsAsText(OS, T.getFileHeader());
464     break;
465   case AccountOutputFormats::CSV:
466     FCA.exportStatsAsCSV(OS, T.getFileHeader());
467     break;
468   }
469
470   return Error::success();
471 });