xray-graph.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. //===-- xray-graph.cpp: XRay Function Call Graph Renderer -----------------===//
  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. // Generate a DOT file to represent the function call graph encountered in
  10. // the trace.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "xray-graph.h"
  14. #include "xray-registry.h"
  15. #include "llvm/Support/ErrorHandling.h"
  16. #include "llvm/XRay/InstrumentationMap.h"
  17. #include "llvm/XRay/Trace.h"
  18. using namespace llvm;
  19. using namespace llvm::xray;
  20. // Setup llvm-xray graph subcommand and its options.
  21. static cl::SubCommand GraphC("graph", "Generate function-call graph");
  22. static cl::opt<std::string> GraphInput(cl::Positional,
  23. cl::desc("<xray log file>"),
  24. cl::Required, cl::sub(GraphC));
  25. static cl::opt<bool>
  26. GraphKeepGoing("keep-going", cl::desc("Keep going on errors encountered"),
  27. cl::sub(GraphC), cl::init(false));
  28. static cl::alias GraphKeepGoing2("k", cl::aliasopt(GraphKeepGoing),
  29. cl::desc("Alias for -keep-going"),
  30. cl::sub(GraphC));
  31. static cl::opt<std::string>
  32. GraphOutput("output", cl::value_desc("Output file"), cl::init("-"),
  33. cl::desc("output file; use '-' for stdout"), cl::sub(GraphC));
  34. static cl::alias GraphOutput2("o", cl::aliasopt(GraphOutput),
  35. cl::desc("Alias for -output"), cl::sub(GraphC));
  36. static cl::opt<std::string>
  37. GraphInstrMap("instr_map",
  38. cl::desc("binary with the instrumrntation map, or "
  39. "a separate instrumentation map"),
  40. cl::value_desc("binary with xray_instr_map"), cl::sub(GraphC),
  41. cl::init(""));
  42. static cl::alias GraphInstrMap2("m", cl::aliasopt(GraphInstrMap),
  43. cl::desc("alias for -instr_map"),
  44. cl::sub(GraphC));
  45. static cl::opt<bool> GraphDeduceSiblingCalls(
  46. "deduce-sibling-calls",
  47. cl::desc("Deduce sibling calls when unrolling function call stacks"),
  48. cl::sub(GraphC), cl::init(false));
  49. static cl::alias
  50. GraphDeduceSiblingCalls2("d", cl::aliasopt(GraphDeduceSiblingCalls),
  51. cl::desc("Alias for -deduce-sibling-calls"),
  52. cl::sub(GraphC));
  53. static cl::opt<GraphRenderer::StatType>
  54. GraphEdgeLabel("edge-label",
  55. cl::desc("Output graphs with edges labeled with this field"),
  56. cl::value_desc("field"), cl::sub(GraphC),
  57. cl::init(GraphRenderer::StatType::NONE),
  58. cl::values(clEnumValN(GraphRenderer::StatType::NONE, "none",
  59. "Do not label Edges"),
  60. clEnumValN(GraphRenderer::StatType::COUNT,
  61. "count", "function call counts"),
  62. clEnumValN(GraphRenderer::StatType::MIN, "min",
  63. "minimum function durations"),
  64. clEnumValN(GraphRenderer::StatType::MED, "med",
  65. "median function durations"),
  66. clEnumValN(GraphRenderer::StatType::PCT90, "90p",
  67. "90th percentile durations"),
  68. clEnumValN(GraphRenderer::StatType::PCT99, "99p",
  69. "99th percentile durations"),
  70. clEnumValN(GraphRenderer::StatType::MAX, "max",
  71. "maximum function durations"),
  72. clEnumValN(GraphRenderer::StatType::SUM, "sum",
  73. "sum of call durations")));
  74. static cl::alias GraphEdgeLabel2("e", cl::aliasopt(GraphEdgeLabel),
  75. cl::desc("Alias for -edge-label"),
  76. cl::sub(GraphC));
  77. static cl::opt<GraphRenderer::StatType> GraphVertexLabel(
  78. "vertex-label",
  79. cl::desc("Output graphs with vertices labeled with this field"),
  80. cl::value_desc("field"), cl::sub(GraphC),
  81. cl::init(GraphRenderer::StatType::NONE),
  82. cl::values(clEnumValN(GraphRenderer::StatType::NONE, "none",
  83. "Do not label Vertices"),
  84. clEnumValN(GraphRenderer::StatType::COUNT, "count",
  85. "function call counts"),
  86. clEnumValN(GraphRenderer::StatType::MIN, "min",
  87. "minimum function durations"),
  88. clEnumValN(GraphRenderer::StatType::MED, "med",
  89. "median function durations"),
  90. clEnumValN(GraphRenderer::StatType::PCT90, "90p",
  91. "90th percentile durations"),
  92. clEnumValN(GraphRenderer::StatType::PCT99, "99p",
  93. "99th percentile durations"),
  94. clEnumValN(GraphRenderer::StatType::MAX, "max",
  95. "maximum function durations"),
  96. clEnumValN(GraphRenderer::StatType::SUM, "sum",
  97. "sum of call durations")));
  98. static cl::alias GraphVertexLabel2("v", cl::aliasopt(GraphVertexLabel),
  99. cl::desc("Alias for -edge-label"),
  100. cl::sub(GraphC));
  101. static cl::opt<GraphRenderer::StatType> GraphEdgeColorType(
  102. "color-edges",
  103. cl::desc("Output graphs with edge colors determined by this field"),
  104. cl::value_desc("field"), cl::sub(GraphC),
  105. cl::init(GraphRenderer::StatType::NONE),
  106. cl::values(clEnumValN(GraphRenderer::StatType::NONE, "none",
  107. "Do not color Edges"),
  108. clEnumValN(GraphRenderer::StatType::COUNT, "count",
  109. "function call counts"),
  110. clEnumValN(GraphRenderer::StatType::MIN, "min",
  111. "minimum function durations"),
  112. clEnumValN(GraphRenderer::StatType::MED, "med",
  113. "median function durations"),
  114. clEnumValN(GraphRenderer::StatType::PCT90, "90p",
  115. "90th percentile durations"),
  116. clEnumValN(GraphRenderer::StatType::PCT99, "99p",
  117. "99th percentile durations"),
  118. clEnumValN(GraphRenderer::StatType::MAX, "max",
  119. "maximum function durations"),
  120. clEnumValN(GraphRenderer::StatType::SUM, "sum",
  121. "sum of call durations")));
  122. static cl::alias GraphEdgeColorType2("c", cl::aliasopt(GraphEdgeColorType),
  123. cl::desc("Alias for -color-edges"),
  124. cl::sub(GraphC));
  125. static cl::opt<GraphRenderer::StatType> GraphVertexColorType(
  126. "color-vertices",
  127. cl::desc("Output graphs with vertex colors determined by this field"),
  128. cl::value_desc("field"), cl::sub(GraphC),
  129. cl::init(GraphRenderer::StatType::NONE),
  130. cl::values(clEnumValN(GraphRenderer::StatType::NONE, "none",
  131. "Do not color vertices"),
  132. clEnumValN(GraphRenderer::StatType::COUNT, "count",
  133. "function call counts"),
  134. clEnumValN(GraphRenderer::StatType::MIN, "min",
  135. "minimum function durations"),
  136. clEnumValN(GraphRenderer::StatType::MED, "med",
  137. "median function durations"),
  138. clEnumValN(GraphRenderer::StatType::PCT90, "90p",
  139. "90th percentile durations"),
  140. clEnumValN(GraphRenderer::StatType::PCT99, "99p",
  141. "99th percentile durations"),
  142. clEnumValN(GraphRenderer::StatType::MAX, "max",
  143. "maximum function durations"),
  144. clEnumValN(GraphRenderer::StatType::SUM, "sum",
  145. "sum of call durations")));
  146. static cl::alias GraphVertexColorType2("b", cl::aliasopt(GraphVertexColorType),
  147. cl::desc("Alias for -edge-label"),
  148. cl::sub(GraphC));
  149. template <class T> T diff(T L, T R) { return std::max(L, R) - std::min(L, R); }
  150. // Updates the statistics for a GraphRenderer::TimeStat
  151. static void updateStat(GraphRenderer::TimeStat &S, int64_t L) {
  152. S.Count++;
  153. if (S.Min > L || S.Min == 0)
  154. S.Min = L;
  155. if (S.Max < L)
  156. S.Max = L;
  157. S.Sum += L;
  158. }
  159. // Evaluates an XRay record and performs accounting on it.
  160. //
  161. // If the record is an ENTER record it pushes the FuncID and TSC onto a
  162. // structure representing the call stack for that function.
  163. // If the record is an EXIT record it checks computes computes the ammount of
  164. // time the function took to complete and then stores that information in an
  165. // edge of the graph. If there is no matching ENTER record the function tries
  166. // to recover by assuming that there were EXIT records which were missed, for
  167. // example caused by tail call elimination and if the option is enabled then
  168. // then tries to recover from this.
  169. //
  170. // This funciton will also error if the records are out of order, as the trace
  171. // is expected to be sorted.
  172. //
  173. // The graph generated has an immaginary root for functions called by no-one at
  174. // FuncId 0.
  175. //
  176. // FIXME: Refactor this and account subcommand to reduce code duplication.
  177. Error GraphRenderer::accountRecord(const XRayRecord &Record) {
  178. using std::make_error_code;
  179. using std::errc;
  180. if (CurrentMaxTSC == 0)
  181. CurrentMaxTSC = Record.TSC;
  182. if (Record.TSC < CurrentMaxTSC)
  183. return make_error<StringError>("Records not in order",
  184. make_error_code(errc::invalid_argument));
  185. auto &ThreadStack = PerThreadFunctionStack[Record.TId];
  186. switch (Record.Type) {
  187. case RecordTypes::ENTER:
  188. case RecordTypes::ENTER_ARG: {
  189. if (Record.FuncId != 0 && G.count(Record.FuncId) == 0)
  190. G[Record.FuncId].SymbolName = FuncIdHelper.SymbolOrNumber(Record.FuncId);
  191. ThreadStack.push_back({Record.FuncId, Record.TSC});
  192. break;
  193. }
  194. case RecordTypes::EXIT:
  195. case RecordTypes::TAIL_EXIT: {
  196. // FIXME: Refactor this and the account subcommand to reduce code
  197. // duplication
  198. if (ThreadStack.size() == 0 || ThreadStack.back().FuncId != Record.FuncId) {
  199. if (!DeduceSiblingCalls)
  200. return make_error<StringError>("No matching ENTRY record",
  201. make_error_code(errc::invalid_argument));
  202. auto Parent = std::find_if(
  203. ThreadStack.rbegin(), ThreadStack.rend(),
  204. [&](const FunctionAttr &A) { return A.FuncId == Record.FuncId; });
  205. if (Parent == ThreadStack.rend())
  206. return make_error<StringError>(
  207. "No matching Entry record in stack",
  208. make_error_code(errc::invalid_argument)); // There is no matching
  209. // Function for this exit.
  210. while (ThreadStack.back().FuncId != Record.FuncId) {
  211. TimestampT D = diff(ThreadStack.back().TSC, Record.TSC);
  212. VertexIdentifier TopFuncId = ThreadStack.back().FuncId;
  213. ThreadStack.pop_back();
  214. assert(ThreadStack.size() != 0);
  215. EdgeIdentifier EI(ThreadStack.back().FuncId, TopFuncId);
  216. auto &EA = G[EI];
  217. EA.Timings.push_back(D);
  218. updateStat(EA.S, D);
  219. updateStat(G[TopFuncId].S, D);
  220. }
  221. }
  222. uint64_t D = diff(ThreadStack.back().TSC, Record.TSC);
  223. ThreadStack.pop_back();
  224. VertexIdentifier VI = ThreadStack.empty() ? 0 : ThreadStack.back().FuncId;
  225. EdgeIdentifier EI(VI, Record.FuncId);
  226. auto &EA = G[EI];
  227. EA.Timings.push_back(D);
  228. updateStat(EA.S, D);
  229. updateStat(G[Record.FuncId].S, D);
  230. break;
  231. }
  232. case RecordTypes::CUSTOM_EVENT:
  233. case RecordTypes::TYPED_EVENT:
  234. // TODO: Support custom and typed events in the graph processing?
  235. break;
  236. }
  237. return Error::success();
  238. }
  239. template <typename U>
  240. void GraphRenderer::getStats(U begin, U end, GraphRenderer::TimeStat &S) {
  241. if (begin == end) return;
  242. std::ptrdiff_t MedianOff = S.Count / 2;
  243. std::nth_element(begin, begin + MedianOff, end);
  244. S.Median = *(begin + MedianOff);
  245. std::ptrdiff_t Pct90Off = (S.Count * 9) / 10;
  246. std::nth_element(begin, begin + Pct90Off, end);
  247. S.Pct90 = *(begin + Pct90Off);
  248. std::ptrdiff_t Pct99Off = (S.Count * 99) / 100;
  249. std::nth_element(begin, begin + Pct99Off, end);
  250. S.Pct99 = *(begin + Pct99Off);
  251. }
  252. void GraphRenderer::updateMaxStats(const GraphRenderer::TimeStat &S,
  253. GraphRenderer::TimeStat &M) {
  254. M.Count = std::max(M.Count, S.Count);
  255. M.Min = std::max(M.Min, S.Min);
  256. M.Median = std::max(M.Median, S.Median);
  257. M.Pct90 = std::max(M.Pct90, S.Pct90);
  258. M.Pct99 = std::max(M.Pct99, S.Pct99);
  259. M.Max = std::max(M.Max, S.Max);
  260. M.Sum = std::max(M.Sum, S.Sum);
  261. }
  262. void GraphRenderer::calculateEdgeStatistics() {
  263. assert(!G.edges().empty());
  264. for (auto &E : G.edges()) {
  265. auto &A = E.second;
  266. assert(!A.Timings.empty());
  267. getStats(A.Timings.begin(), A.Timings.end(), A.S);
  268. updateMaxStats(A.S, G.GraphEdgeMax);
  269. }
  270. }
  271. void GraphRenderer::calculateVertexStatistics() {
  272. std::vector<uint64_t> TempTimings;
  273. for (auto &V : G.vertices()) {
  274. if (V.first != 0) {
  275. for (auto &E : G.inEdges(V.first)) {
  276. auto &A = E.second;
  277. TempTimings.insert(TempTimings.end(), A.Timings.begin(),
  278. A.Timings.end());
  279. }
  280. getStats(TempTimings.begin(), TempTimings.end(), G[V.first].S);
  281. updateMaxStats(G[V.first].S, G.GraphVertexMax);
  282. TempTimings.clear();
  283. }
  284. }
  285. }
  286. // A Helper function for normalizeStatistics which normalises a single
  287. // TimeStat element.
  288. static void normalizeTimeStat(GraphRenderer::TimeStat &S,
  289. double CycleFrequency) {
  290. int64_t OldCount = S.Count;
  291. S = S / CycleFrequency;
  292. S.Count = OldCount;
  293. }
  294. // Normalises the statistics in the graph for a given TSC frequency.
  295. void GraphRenderer::normalizeStatistics(double CycleFrequency) {
  296. for (auto &E : G.edges()) {
  297. auto &S = E.second.S;
  298. normalizeTimeStat(S, CycleFrequency);
  299. }
  300. for (auto &V : G.vertices()) {
  301. auto &S = V.second.S;
  302. normalizeTimeStat(S, CycleFrequency);
  303. }
  304. normalizeTimeStat(G.GraphEdgeMax, CycleFrequency);
  305. normalizeTimeStat(G.GraphVertexMax, CycleFrequency);
  306. }
  307. // Returns a string containing the value of statistic field T
  308. std::string
  309. GraphRenderer::TimeStat::getString(GraphRenderer::StatType T) const {
  310. std::string St;
  311. raw_string_ostream S{St};
  312. double TimeStat::*DoubleStatPtrs[] = {&TimeStat::Min, &TimeStat::Median,
  313. &TimeStat::Pct90, &TimeStat::Pct99,
  314. &TimeStat::Max, &TimeStat::Sum};
  315. switch (T) {
  316. case GraphRenderer::StatType::NONE:
  317. break;
  318. case GraphRenderer::StatType::COUNT:
  319. S << Count;
  320. break;
  321. default:
  322. S << (*this).*
  323. DoubleStatPtrs[static_cast<int>(T) -
  324. static_cast<int>(GraphRenderer::StatType::MIN)];
  325. break;
  326. }
  327. return S.str();
  328. }
  329. // Returns the quotient between the property T of this and another TimeStat as
  330. // a double
  331. double GraphRenderer::TimeStat::getDouble(StatType T) const {
  332. double retval = 0;
  333. double TimeStat::*DoubleStatPtrs[] = {&TimeStat::Min, &TimeStat::Median,
  334. &TimeStat::Pct90, &TimeStat::Pct99,
  335. &TimeStat::Max, &TimeStat::Sum};
  336. switch (T) {
  337. case GraphRenderer::StatType::NONE:
  338. retval = 0.0;
  339. break;
  340. case GraphRenderer::StatType::COUNT:
  341. retval = static_cast<double>(Count);
  342. break;
  343. default:
  344. retval =
  345. (*this).*DoubleStatPtrs[static_cast<int>(T) -
  346. static_cast<int>(GraphRenderer::StatType::MIN)];
  347. break;
  348. }
  349. return retval;
  350. }
  351. // Outputs a DOT format version of the Graph embedded in the GraphRenderer
  352. // object on OS. It does this in the expected way by itterating
  353. // through all edges then vertices and then outputting them and their
  354. // annotations.
  355. //
  356. // FIXME: output more information, better presented.
  357. void GraphRenderer::exportGraphAsDOT(raw_ostream &OS, StatType ET, StatType EC,
  358. StatType VT, StatType VC) {
  359. OS << "digraph xray {\n";
  360. if (VT != StatType::NONE)
  361. OS << "node [shape=record];\n";
  362. for (const auto &E : G.edges()) {
  363. const auto &S = E.second.S;
  364. OS << "F" << E.first.first << " -> "
  365. << "F" << E.first.second << " [label=\"" << S.getString(ET) << "\"";
  366. if (EC != StatType::NONE)
  367. OS << " color=\""
  368. << CHelper.getColorString(
  369. std::sqrt(S.getDouble(EC) / G.GraphEdgeMax.getDouble(EC)))
  370. << "\"";
  371. OS << "];\n";
  372. }
  373. for (const auto &V : G.vertices()) {
  374. const auto &VA = V.second;
  375. if (V.first == 0)
  376. continue;
  377. OS << "F" << V.first << " [label=\"" << (VT != StatType::NONE ? "{" : "")
  378. << (VA.SymbolName.size() > 40 ? VA.SymbolName.substr(0, 40) + "..."
  379. : VA.SymbolName);
  380. if (VT != StatType::NONE)
  381. OS << "|" << VA.S.getString(VT) << "}\"";
  382. else
  383. OS << "\"";
  384. if (VC != StatType::NONE)
  385. OS << " color=\""
  386. << CHelper.getColorString(
  387. std::sqrt(VA.S.getDouble(VC) / G.GraphVertexMax.getDouble(VC)))
  388. << "\"";
  389. OS << "];\n";
  390. }
  391. OS << "}\n";
  392. }
  393. Expected<GraphRenderer> GraphRenderer::Factory::getGraphRenderer() {
  394. InstrumentationMap Map;
  395. if (!GraphInstrMap.empty()) {
  396. auto InstrumentationMapOrError = loadInstrumentationMap(GraphInstrMap);
  397. if (!InstrumentationMapOrError)
  398. return joinErrors(
  399. make_error<StringError>(
  400. Twine("Cannot open instrumentation map '") + GraphInstrMap + "'",
  401. std::make_error_code(std::errc::invalid_argument)),
  402. InstrumentationMapOrError.takeError());
  403. Map = std::move(*InstrumentationMapOrError);
  404. }
  405. const auto &FunctionAddresses = Map.getFunctionAddresses();
  406. symbolize::LLVMSymbolizer Symbolizer;
  407. const auto &Header = Trace.getFileHeader();
  408. llvm::xray::FuncIdConversionHelper FuncIdHelper(InstrMap, Symbolizer,
  409. FunctionAddresses);
  410. xray::GraphRenderer GR(FuncIdHelper, DeduceSiblingCalls);
  411. for (const auto &Record : Trace) {
  412. auto E = GR.accountRecord(Record);
  413. if (!E)
  414. continue;
  415. for (const auto &ThreadStack : GR.getPerThreadFunctionStack()) {
  416. errs() << "Thread ID: " << ThreadStack.first << "\n";
  417. auto Level = ThreadStack.second.size();
  418. for (const auto &Entry : llvm::reverse(ThreadStack.second))
  419. errs() << "#" << Level-- << "\t"
  420. << FuncIdHelper.SymbolOrNumber(Entry.FuncId) << '\n';
  421. }
  422. if (!GraphKeepGoing)
  423. return joinErrors(make_error<StringError>(
  424. "Error encountered generating the call graph.",
  425. std::make_error_code(std::errc::invalid_argument)),
  426. std::move(E));
  427. handleAllErrors(std::move(E),
  428. [&](const ErrorInfoBase &E) { E.log(errs()); });
  429. }
  430. GR.G.GraphEdgeMax = {};
  431. GR.G.GraphVertexMax = {};
  432. GR.calculateEdgeStatistics();
  433. GR.calculateVertexStatistics();
  434. if (Header.CycleFrequency)
  435. GR.normalizeStatistics(Header.CycleFrequency);
  436. return GR;
  437. }
  438. // Here we register and implement the llvm-xray graph subcommand.
  439. // The bulk of this code reads in the options, opens the required files, uses
  440. // those files to create a context for analysing the xray trace, then there is a
  441. // short loop which actually analyses the trace, generates the graph and then
  442. // outputs it as a DOT.
  443. //
  444. // FIXME: include additional filtering and annalysis passes to provide more
  445. // specific useful information.
  446. static CommandRegistration Unused(&GraphC, []() -> Error {
  447. GraphRenderer::Factory F;
  448. F.KeepGoing = GraphKeepGoing;
  449. F.DeduceSiblingCalls = GraphDeduceSiblingCalls;
  450. F.InstrMap = GraphInstrMap;
  451. auto TraceOrErr = loadTraceFile(GraphInput, true);
  452. if (!TraceOrErr)
  453. return make_error<StringError>(
  454. Twine("Failed loading input file '") + GraphInput + "'",
  455. make_error_code(llvm::errc::invalid_argument));
  456. F.Trace = std::move(*TraceOrErr);
  457. auto GROrError = F.getGraphRenderer();
  458. if (!GROrError)
  459. return GROrError.takeError();
  460. auto &GR = *GROrError;
  461. std::error_code EC;
  462. raw_fd_ostream OS(GraphOutput, EC, sys::fs::OpenFlags::OF_Text);
  463. if (EC)
  464. return make_error<StringError>(
  465. Twine("Cannot open file '") + GraphOutput + "' for writing.", EC);
  466. GR.exportGraphAsDOT(OS, GraphEdgeLabel, GraphEdgeColorType, GraphVertexLabel,
  467. GraphVertexColorType);
  468. return Error::success();
  469. });