blob: a682dbe53e3bd80516a45be81cd135af8ab1b794 [file] [log] [blame]
Dean Michael Berrisf4f861b2018-05-02 00:43:17 +00001//===- xray-converter.cpp: XRay Trace Conversion --------------------------===//
Dean Michael Berris6e1f0662017-01-10 02:38:11 +00002//
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// Implements the trace conversion functions.
11//
12//===----------------------------------------------------------------------===//
13#include "xray-converter.h"
14
Keith Wyssed2657e2017-11-07 00:28:28 +000015#include "trie-node.h"
Dean Michael Berris6e1f0662017-01-10 02:38:11 +000016#include "xray-registry.h"
17#include "llvm/DebugInfo/Symbolize/Symbolize.h"
18#include "llvm/Support/EndianStream.h"
19#include "llvm/Support/FileSystem.h"
Keith Wyssed2657e2017-11-07 00:28:28 +000020#include "llvm/Support/FormatVariadic.h"
Pavel Labath8a1006b2017-01-16 16:38:23 +000021#include "llvm/Support/ScopedPrinter.h"
Dean Michael Berris6e1f0662017-01-10 02:38:11 +000022#include "llvm/Support/YAMLTraits.h"
23#include "llvm/Support/raw_ostream.h"
Dean Michael Berris93789c82017-02-01 00:05:29 +000024#include "llvm/XRay/InstrumentationMap.h"
Dean Michael Berris14cdbca2017-01-11 06:39:09 +000025#include "llvm/XRay/Trace.h"
26#include "llvm/XRay/YAMLXRayRecord.h"
Dean Michael Berris6e1f0662017-01-10 02:38:11 +000027
28using namespace llvm;
29using namespace xray;
30
31// llvm-xray convert
32// ----------------------------------------------------------------------------
33static cl::SubCommand Convert("convert", "Trace Format Conversion");
34static cl::opt<std::string> ConvertInput(cl::Positional,
35 cl::desc("<xray log file>"),
36 cl::Required, cl::sub(Convert));
Keith Wyssed2657e2017-11-07 00:28:28 +000037enum class ConvertFormats { BINARY, YAML, CHROME_TRACE_EVENT };
Dean Michael Berris6e1f0662017-01-10 02:38:11 +000038static cl::opt<ConvertFormats> ConvertOutputFormat(
39 "output-format", cl::desc("output format"),
40 cl::values(clEnumValN(ConvertFormats::BINARY, "raw", "output in binary"),
Keith Wyssed2657e2017-11-07 00:28:28 +000041 clEnumValN(ConvertFormats::YAML, "yaml", "output in yaml"),
42 clEnumValN(ConvertFormats::CHROME_TRACE_EVENT, "trace_event",
43 "Output in chrome's trace event format. "
44 "May be visualized with the Catapult trace viewer.")),
Dean Michael Berris6e1f0662017-01-10 02:38:11 +000045 cl::sub(Convert));
46static cl::alias ConvertOutputFormat2("f", cl::aliasopt(ConvertOutputFormat),
47 cl::desc("Alias for -output-format"),
48 cl::sub(Convert));
49static cl::opt<std::string>
50 ConvertOutput("output", cl::value_desc("output file"), cl::init("-"),
51 cl::desc("output file; use '-' for stdout"),
52 cl::sub(Convert));
53static cl::alias ConvertOutput2("o", cl::aliasopt(ConvertOutput),
54 cl::desc("Alias for -output"),
55 cl::sub(Convert));
56
57static cl::opt<bool>
58 ConvertSymbolize("symbolize",
59 cl::desc("symbolize function ids from the input log"),
60 cl::init(false), cl::sub(Convert));
61static cl::alias ConvertSymbolize2("y", cl::aliasopt(ConvertSymbolize),
62 cl::desc("Alias for -symbolize"),
63 cl::sub(Convert));
64
65static cl::opt<std::string>
66 ConvertInstrMap("instr_map",
67 cl::desc("binary with the instrumentation map, or "
68 "a separate instrumentation map"),
69 cl::value_desc("binary with xray_instr_map"),
70 cl::sub(Convert), cl::init(""));
71static cl::alias ConvertInstrMap2("m", cl::aliasopt(ConvertInstrMap),
72 cl::desc("Alias for -instr_map"),
73 cl::sub(Convert));
74static cl::opt<bool> ConvertSortInput(
75 "sort",
76 cl::desc("determines whether to sort input log records by timestamp"),
77 cl::sub(Convert), cl::init(true));
78static cl::alias ConvertSortInput2("s", cl::aliasopt(ConvertSortInput),
79 cl::desc("Alias for -sort"),
80 cl::sub(Convert));
Dean Michael Berris6e1f0662017-01-10 02:38:11 +000081
Dean Michael Berris6e1f0662017-01-10 02:38:11 +000082using llvm::yaml::Output;
83
Dean Michael Berris14cdbca2017-01-11 06:39:09 +000084void TraceConverter::exportAsYAML(const Trace &Records, raw_ostream &OS) {
Dean Michael Berris6e1f0662017-01-10 02:38:11 +000085 YAMLXRayTrace Trace;
86 const auto &FH = Records.getFileHeader();
87 Trace.Header = {FH.Version, FH.Type, FH.ConstantTSC, FH.NonstopTSC,
88 FH.CycleFrequency};
89 Trace.Records.reserve(Records.size());
90 for (const auto &R : Records) {
91 Trace.Records.push_back({R.RecordType, R.CPU, R.Type, R.FuncId,
92 Symbolize ? FuncIdHelper.SymbolOrNumber(R.FuncId)
Pavel Labath8a1006b2017-01-16 16:38:23 +000093 : llvm::to_string(R.FuncId),
Dean Michael Berrisb92b0b82018-11-06 08:51:37 +000094 R.TSC, R.TId, R.PId, R.CallArgs, R.Data});
Dean Michael Berris6e1f0662017-01-10 02:38:11 +000095 }
Dimitry Andric193dc0b2017-02-14 22:49:49 +000096 Output Out(OS, nullptr, 0);
Dean Michael Berrisb92b0b82018-11-06 08:51:37 +000097 Out.setWriteDefaultValues(false);
Dean Michael Berris6e1f0662017-01-10 02:38:11 +000098 Out << Trace;
99}
100
Dean Michael Berris14cdbca2017-01-11 06:39:09 +0000101void TraceConverter::exportAsRAWv1(const Trace &Records, raw_ostream &OS) {
Dean Michael Berris6e1f0662017-01-10 02:38:11 +0000102 // First write out the file header, in the correct endian-appropriate format
103 // (XRay assumes currently little endian).
Peter Collingbournea68d4cc2018-05-18 19:46:24 +0000104 support::endian::Writer Writer(OS, support::endianness::little);
Dean Michael Berris6e1f0662017-01-10 02:38:11 +0000105 const auto &FH = Records.getFileHeader();
106 Writer.write(FH.Version);
107 Writer.write(FH.Type);
108 uint32_t Bitfield{0};
109 if (FH.ConstantTSC)
110 Bitfield |= 1uL;
111 if (FH.NonstopTSC)
112 Bitfield |= 1uL << 1;
113 Writer.write(Bitfield);
114 Writer.write(FH.CycleFrequency);
115
116 // There's 16 bytes of padding at the end of the file header.
117 static constexpr uint32_t Padding4B = 0;
118 Writer.write(Padding4B);
119 Writer.write(Padding4B);
120 Writer.write(Padding4B);
121 Writer.write(Padding4B);
122
123 // Then write out the rest of the records, still in an endian-appropriate
124 // format.
125 for (const auto &R : Records) {
Dean Michael Berris6e1f0662017-01-10 02:38:11 +0000126 switch (R.Type) {
127 case RecordTypes::ENTER:
Martin Pelikan62b26112017-09-27 04:48:03 +0000128 case RecordTypes::ENTER_ARG:
Dean Michael Berrisb92b0b82018-11-06 08:51:37 +0000129 Writer.write(R.RecordType);
130 Writer.write(static_cast<uint8_t>(R.CPU));
Dean Michael Berris6e1f0662017-01-10 02:38:11 +0000131 Writer.write(uint8_t{0});
132 break;
133 case RecordTypes::EXIT:
Dean Michael Berrisb92b0b82018-11-06 08:51:37 +0000134 Writer.write(R.RecordType);
135 Writer.write(static_cast<uint8_t>(R.CPU));
Dean Michael Berris6e1f0662017-01-10 02:38:11 +0000136 Writer.write(uint8_t{1});
137 break;
Dean Michael Berrisd6aeff82017-09-18 06:08:46 +0000138 case RecordTypes::TAIL_EXIT:
Dean Michael Berrisb92b0b82018-11-06 08:51:37 +0000139 Writer.write(R.RecordType);
140 Writer.write(static_cast<uint8_t>(R.CPU));
Dean Michael Berrisd6aeff82017-09-18 06:08:46 +0000141 Writer.write(uint8_t{2});
142 break;
Dean Michael Berrisb92b0b82018-11-06 08:51:37 +0000143 case RecordTypes::CUSTOM_EVENT:
144 case RecordTypes::TYPED_EVENT:
145 // Skip custom and typed event records for v1 logs.
146 continue;
Dean Michael Berris6e1f0662017-01-10 02:38:11 +0000147 }
148 Writer.write(R.FuncId);
149 Writer.write(R.TSC);
150 Writer.write(R.TId);
Dean Michael Berris93177462018-07-13 05:38:22 +0000151
152 if (FH.Version >= 3)
153 Writer.write(R.PId);
154 else
155 Writer.write(Padding4B);
156
Dean Michael Berris6e1f0662017-01-10 02:38:11 +0000157 Writer.write(Padding4B);
158 Writer.write(Padding4B);
159 }
160}
161
Keith Wyssed2657e2017-11-07 00:28:28 +0000162namespace {
163
164// A structure that allows building a dictionary of stack ids for the Chrome
165// trace event format.
166struct StackIdData {
167 // Each Stack of function calls has a unique ID.
168 unsigned id;
169
170 // Bookkeeping so that IDs can be maintained uniquely across threads.
171 // Traversal keeps sibling pointers to other threads stacks. This is helpful
172 // to determine when a thread encounters a new stack and should assign a new
173 // unique ID.
174 SmallVector<TrieNode<StackIdData> *, 4> siblings;
175};
176
177using StackTrieNode = TrieNode<StackIdData>;
178
179// A helper function to find the sibling nodes for an encountered function in a
180// thread of execution. Relies on the invariant that each time a new node is
181// traversed in a thread, sibling bidirectional pointers are maintained.
182SmallVector<StackTrieNode *, 4>
183findSiblings(StackTrieNode *parent, int32_t FnId, uint32_t TId,
184 const DenseMap<uint32_t, SmallVector<StackTrieNode *, 4>>
185 &StackRootsByThreadId) {
186
187 SmallVector<StackTrieNode *, 4> Siblings{};
188
189 if (parent == nullptr) {
190 for (auto map_iter : StackRootsByThreadId) {
191 // Only look for siblings in other threads.
192 if (map_iter.first != TId)
193 for (auto node_iter : map_iter.second) {
194 if (node_iter->FuncId == FnId)
195 Siblings.push_back(node_iter);
196 }
197 }
198 return Siblings;
199 }
200
201 for (auto *ParentSibling : parent->ExtraData.siblings)
202 for (auto node_iter : ParentSibling->Callees)
203 if (node_iter->FuncId == FnId)
204 Siblings.push_back(node_iter);
205
206 return Siblings;
207}
208
209// Given a function being invoked in a thread with id TId, finds and returns the
210// StackTrie representing the function call stack. If no node exists, creates
211// the node. Assigns unique IDs to stacks newly encountered among all threads
212// and keeps sibling links up to when creating new nodes.
213StackTrieNode *findOrCreateStackNode(
214 StackTrieNode *Parent, int32_t FuncId, uint32_t TId,
215 DenseMap<uint32_t, SmallVector<StackTrieNode *, 4>> &StackRootsByThreadId,
216 DenseMap<unsigned, StackTrieNode *> &StacksByStackId, unsigned *id_counter,
217 std::forward_list<StackTrieNode> &NodeStore) {
218 SmallVector<StackTrieNode *, 4> &ParentCallees =
219 Parent == nullptr ? StackRootsByThreadId[TId] : Parent->Callees;
220 auto match = find_if(ParentCallees, [FuncId](StackTrieNode *ParentCallee) {
221 return FuncId == ParentCallee->FuncId;
222 });
223 if (match != ParentCallees.end())
224 return *match;
225
226 SmallVector<StackTrieNode *, 4> siblings =
227 findSiblings(Parent, FuncId, TId, StackRootsByThreadId);
228 if (siblings.empty()) {
229 NodeStore.push_front({FuncId, Parent, {}, {(*id_counter)++, {}}});
230 StackTrieNode *CurrentStack = &NodeStore.front();
231 StacksByStackId[*id_counter - 1] = CurrentStack;
232 ParentCallees.push_back(CurrentStack);
233 return CurrentStack;
234 }
235 unsigned stack_id = siblings[0]->ExtraData.id;
236 NodeStore.push_front({FuncId, Parent, {}, {stack_id, std::move(siblings)}});
237 StackTrieNode *CurrentStack = &NodeStore.front();
238 for (auto *sibling : CurrentStack->ExtraData.siblings)
239 sibling->ExtraData.siblings.push_back(CurrentStack);
240 ParentCallees.push_back(CurrentStack);
241 return CurrentStack;
242}
243
Hans Wennborg719641e42019-02-26 10:02:05 +0000244void writeTraceViewerRecord(uint16_t Version, raw_ostream &OS, int32_t FuncId,
245 uint32_t TId, uint32_t PId, bool Symbolize,
246 const FuncIdConversionHelper &FuncIdHelper,
247 double EventTimestampUs,
248 const StackTrieNode &StackCursor,
249 StringRef FunctionPhenotype) {
250 OS << " ";
251 if (Version >= 3) {
252 OS << llvm::formatv(
253 R"({ "name" : "{0}", "ph" : "{1}", "tid" : "{2}", "pid" : "{3}", )"
254 R"("ts" : "{4:f4}", "sf" : "{5}" })",
255 (Symbolize ? FuncIdHelper.SymbolOrNumber(FuncId)
256 : llvm::to_string(FuncId)),
257 FunctionPhenotype, TId, PId, EventTimestampUs,
258 StackCursor.ExtraData.id);
259 } else {
260 OS << llvm::formatv(
261 R"({ "name" : "{0}", "ph" : "{1}", "tid" : "{2}", "pid" : "1", )"
262 R"("ts" : "{3:f3}", "sf" : "{4}" })",
263 (Symbolize ? FuncIdHelper.SymbolOrNumber(FuncId)
264 : llvm::to_string(FuncId)),
265 FunctionPhenotype, TId, EventTimestampUs, StackCursor.ExtraData.id);
266 }
267}
268
Keith Wyssed2657e2017-11-07 00:28:28 +0000269} // namespace
270
271void TraceConverter::exportAsChromeTraceEventFormat(const Trace &Records,
272 raw_ostream &OS) {
273 const auto &FH = Records.getFileHeader();
Dean Michael Berris93177462018-07-13 05:38:22 +0000274 auto Version = FH.Version;
Keith Wyssed2657e2017-11-07 00:28:28 +0000275 auto CycleFreq = FH.CycleFrequency;
276
277 unsigned id_counter = 0;
278
Hans Wennborg719641e42019-02-26 10:02:05 +0000279 OS << "{\n \"traceEvents\": [";
Keith Wyssed2657e2017-11-07 00:28:28 +0000280 DenseMap<uint32_t, StackTrieNode *> StackCursorByThreadId{};
281 DenseMap<uint32_t, SmallVector<StackTrieNode *, 4>> StackRootsByThreadId{};
282 DenseMap<unsigned, StackTrieNode *> StacksByStackId{};
283 std::forward_list<StackTrieNode> NodeStore{};
Hans Wennborg719641e42019-02-26 10:02:05 +0000284 int loop_count = 0;
Dean Michael Berris93e0d052018-08-03 09:21:31 +0000285 for (const auto &R : Records) {
Hans Wennborg719641e42019-02-26 10:02:05 +0000286 if (loop_count++ == 0)
287 OS << "\n";
288 else
289 OS << ",\n";
290
Keith Wyssed2657e2017-11-07 00:28:28 +0000291 // Chrome trace event format always wants data in micros.
292 // CyclesPerMicro = CycleHertz / 10^6
293 // TSC / CyclesPerMicro == TSC * 10^6 / CycleHertz == MicroTimestamp
294 // Could lose some precision here by converting the TSC to a double to
295 // multiply by the period in micros. 52 bit mantissa is a good start though.
296 // TODO: Make feature request to Chrome Trace viewer to accept ticks and a
297 // frequency or do some more involved calculation to avoid dangers of
298 // conversion.
299 double EventTimestampUs = double(1000000) / CycleFreq * double(R.TSC);
300 StackTrieNode *&StackCursor = StackCursorByThreadId[R.TId];
301 switch (R.Type) {
Dean Michael Berrisb92b0b82018-11-06 08:51:37 +0000302 case RecordTypes::CUSTOM_EVENT:
303 case RecordTypes::TYPED_EVENT:
304 // TODO: Support typed and custom event rendering on Chrome Trace Viewer.
305 break;
Keith Wyssed2657e2017-11-07 00:28:28 +0000306 case RecordTypes::ENTER:
307 case RecordTypes::ENTER_ARG:
308 StackCursor = findOrCreateStackNode(StackCursor, R.FuncId, R.TId,
309 StackRootsByThreadId, StacksByStackId,
310 &id_counter, NodeStore);
311 // Each record is represented as a json dictionary with function name,
Dean Michael Berris93177462018-07-13 05:38:22 +0000312 // type of B for begin or E for end, thread id, process id,
Keith Wyssed2657e2017-11-07 00:28:28 +0000313 // timestamp in microseconds, and a stack frame id. The ids are logged
314 // in an id dictionary after the events.
Hans Wennborg719641e42019-02-26 10:02:05 +0000315 writeTraceViewerRecord(Version, OS, R.FuncId, R.TId, R.PId, Symbolize,
316 FuncIdHelper, EventTimestampUs, *StackCursor, "B");
Keith Wyssed2657e2017-11-07 00:28:28 +0000317 break;
318 case RecordTypes::EXIT:
319 case RecordTypes::TAIL_EXIT:
320 // No entries to record end for.
321 if (StackCursor == nullptr)
322 break;
323 // Should we emit an END record anyway or account this condition?
324 // (And/Or in loop termination below)
325 StackTrieNode *PreviousCursor = nullptr;
326 do {
Hans Wennborg719641e42019-02-26 10:02:05 +0000327 if (PreviousCursor != nullptr) {
328 OS << ",\n";
329 }
330 writeTraceViewerRecord(Version, OS, StackCursor->FuncId, R.TId, R.PId,
331 Symbolize, FuncIdHelper, EventTimestampUs,
332 *StackCursor, "E");
Keith Wyssed2657e2017-11-07 00:28:28 +0000333 PreviousCursor = StackCursor;
334 StackCursor = StackCursor->Parent;
335 } while (PreviousCursor->FuncId != R.FuncId && StackCursor != nullptr);
336 break;
337 }
338 }
Hans Wennborg719641e42019-02-26 10:02:05 +0000339 OS << "\n ],\n"; // Close the Trace Events array.
340 OS << " "
341 << "\"displayTimeUnit\": \"ns\",\n";
Keith Wyssed2657e2017-11-07 00:28:28 +0000342
343 // The stackFrames dictionary substantially reduces size of the output file by
344 // avoiding repeating the entire call stack of function names for each entry.
Hans Wennborg719641e42019-02-26 10:02:05 +0000345 OS << R"( "stackFrames": {)";
346 int stack_frame_count = 0;
347 for (auto map_iter : StacksByStackId) {
348 if (stack_frame_count++ == 0)
349 OS << "\n";
350 else
351 OS << ",\n";
352 OS << " ";
353 OS << llvm::formatv(
354 R"("{0}" : { "name" : "{1}")", map_iter.first,
355 (Symbolize ? FuncIdHelper.SymbolOrNumber(map_iter.second->FuncId)
356 : llvm::to_string(map_iter.second->FuncId)));
357 if (map_iter.second->Parent != nullptr)
358 OS << llvm::formatv(R"(, "parent": "{0}")",
359 map_iter.second->Parent->ExtraData.id);
360 OS << " }";
Keith Wyssed2657e2017-11-07 00:28:28 +0000361 }
Hans Wennborg719641e42019-02-26 10:02:05 +0000362 OS << "\n }\n"; // Close the stack frames map.
363 OS << "}\n"; // Close the JSON entry.
Keith Wyssed2657e2017-11-07 00:28:28 +0000364}
365
Dean Michael Berris6e1f0662017-01-10 02:38:11 +0000366namespace llvm {
367namespace xray {
368
369static CommandRegistration Unused(&Convert, []() -> Error {
370 // FIXME: Support conversion to BINARY when upgrading XRay trace versions.
Dean Michael Berris93789c82017-02-01 00:05:29 +0000371 InstrumentationMap Map;
372 if (!ConvertInstrMap.empty()) {
373 auto InstrumentationMapOrError = loadInstrumentationMap(ConvertInstrMap);
374 if (!InstrumentationMapOrError)
375 return joinErrors(make_error<StringError>(
376 Twine("Cannot open instrumentation map '") +
377 ConvertInstrMap + "'",
378 std::make_error_code(std::errc::invalid_argument)),
379 InstrumentationMapOrError.takeError());
380 Map = std::move(*InstrumentationMapOrError);
381 }
Dean Michael Berris6e1f0662017-01-10 02:38:11 +0000382
Dean Michael Berris93789c82017-02-01 00:05:29 +0000383 const auto &FunctionAddresses = Map.getFunctionAddresses();
Dean Michael Berris6e1f0662017-01-10 02:38:11 +0000384 symbolize::LLVMSymbolizer::Options Opts(
385 symbolize::FunctionNameKind::LinkageName, true, true, false, "");
386 symbolize::LLVMSymbolizer Symbolizer(Opts);
387 llvm::xray::FuncIdConversionHelper FuncIdHelper(ConvertInstrMap, Symbolizer,
388 FunctionAddresses);
389 llvm::xray::TraceConverter TC(FuncIdHelper, ConvertSymbolize);
Dean Michael Berris93789c82017-02-01 00:05:29 +0000390 std::error_code EC;
Dean Michael Berris6e1f0662017-01-10 02:38:11 +0000391 raw_fd_ostream OS(ConvertOutput, EC,
392 ConvertOutputFormat == ConvertFormats::BINARY
393 ? sys::fs::OpenFlags::F_None
394 : sys::fs::OpenFlags::F_Text);
395 if (EC)
396 return make_error<StringError>(
397 Twine("Cannot open file '") + ConvertOutput + "' for writing.", EC);
398
Dean Michael Berris93789c82017-02-01 00:05:29 +0000399 auto TraceOrErr = loadTraceFile(ConvertInput, ConvertSortInput);
400 if (!TraceOrErr)
Dean Michael Berris14cdbca2017-01-11 06:39:09 +0000401 return joinErrors(
402 make_error<StringError>(
403 Twine("Failed loading input file '") + ConvertInput + "'.",
Hans Wennborgfa3329a2017-01-12 18:33:14 +0000404 std::make_error_code(std::errc::executable_format_error)),
Dean Michael Berris14cdbca2017-01-11 06:39:09 +0000405 TraceOrErr.takeError());
Dean Michael Berris93789c82017-02-01 00:05:29 +0000406
407 auto &T = *TraceOrErr;
408 switch (ConvertOutputFormat) {
409 case ConvertFormats::YAML:
410 TC.exportAsYAML(T, OS);
411 break;
412 case ConvertFormats::BINARY:
413 TC.exportAsRAWv1(T, OS);
414 break;
Keith Wyssed2657e2017-11-07 00:28:28 +0000415 case ConvertFormats::CHROME_TRACE_EVENT:
416 TC.exportAsChromeTraceEventFormat(T, OS);
417 break;
Dean Michael Berris6e1f0662017-01-10 02:38:11 +0000418 }
419 return Error::success();
420});
421
422} // namespace xray
423} // namespace llvm