Path: blob/main/contrib/llvm-project/llvm/tools/llvm-xray/xray-stacks.cpp
35231 views
//===- xray-stacks.cpp: XRay Function Call Stack Accounting ---------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements stack-based accounting. It takes XRay traces, and9// collates statistics across these traces to show a breakdown of time spent10// at various points of the stack to provide insight into which functions11// spend the most time in terms of a call stack. We provide a few12// sorting/filtering options for zero'ing in on the useful stacks.13//14//===----------------------------------------------------------------------===//1516#include <forward_list>17#include <numeric>1819#include "func-id-helper.h"20#include "trie-node.h"21#include "xray-registry.h"22#include "llvm/ADT/StringExtras.h"23#include "llvm/Support/CommandLine.h"24#include "llvm/Support/Errc.h"25#include "llvm/Support/ErrorHandling.h"26#include "llvm/Support/FormatAdapters.h"27#include "llvm/Support/FormatVariadic.h"28#include "llvm/XRay/Graph.h"29#include "llvm/XRay/InstrumentationMap.h"30#include "llvm/XRay/Trace.h"3132using namespace llvm;33using namespace llvm::xray;3435static cl::SubCommand Stack("stack", "Call stack accounting");36static cl::list<std::string> StackInputs(cl::Positional,37cl::desc("<xray trace>"), cl::Required,38cl::sub(Stack), cl::OneOrMore);3940static cl::opt<bool>41StackKeepGoing("keep-going", cl::desc("Keep going on errors encountered"),42cl::sub(Stack), cl::init(false));43static cl::alias StackKeepGoing2("k", cl::aliasopt(StackKeepGoing),44cl::desc("Alias for -keep-going"));4546// TODO: Does there need to be an option to deduce tail or sibling calls?4748static cl::opt<std::string> StacksInstrMap(49"instr_map",50cl::desc("instrumentation map used to identify function ids. "51"Currently supports elf file instrumentation maps."),52cl::sub(Stack), cl::init(""));53static cl::alias StacksInstrMap2("m", cl::aliasopt(StacksInstrMap),54cl::desc("Alias for -instr_map"));5556static cl::opt<bool>57SeparateThreadStacks("per-thread-stacks",58cl::desc("Report top stacks within each thread id"),59cl::sub(Stack), cl::init(false));6061static cl::opt<bool>62AggregateThreads("aggregate-threads",63cl::desc("Aggregate stack times across threads"),64cl::sub(Stack), cl::init(false));6566static cl::opt<bool>67DumpAllStacks("all-stacks",68cl::desc("Dump sum of timings for all stacks. "69"By default separates stacks per-thread."),70cl::sub(Stack), cl::init(false));71static cl::alias DumpAllStacksShort("all", cl::aliasopt(DumpAllStacks),72cl::desc("Alias for -all-stacks"));7374// TODO(kpw): Add other interesting formats. Perhaps chrome trace viewer format75// possibly with aggregations or just a linear trace of timings.76enum StackOutputFormat { HUMAN, FLAMETOOL };7778static cl::opt<StackOutputFormat> StacksOutputFormat(79"stack-format",80cl::desc("The format that output stacks should be "81"output in. Only applies with all-stacks."),82cl::values(83clEnumValN(HUMAN, "human",84"Human readable output. Only valid without -all-stacks."),85clEnumValN(FLAMETOOL, "flame",86"Format consumable by Brendan Gregg's FlameGraph tool. "87"Only valid with -all-stacks.")),88cl::sub(Stack), cl::init(HUMAN));8990// Types of values for each stack in a CallTrie.91enum class AggregationType {92TOTAL_TIME, // The total time spent in a stack and its callees.93INVOCATION_COUNT // The number of times the stack was invoked.94};9596static cl::opt<AggregationType> RequestedAggregation(97"aggregation-type",98cl::desc("The type of aggregation to do on call stacks."),99cl::values(100clEnumValN(101AggregationType::TOTAL_TIME, "time",102"Capture the total time spent in an all invocations of a stack."),103clEnumValN(AggregationType::INVOCATION_COUNT, "count",104"Capture the number of times a stack was invoked. "105"In flamegraph mode, this count also includes invocations "106"of all callees.")),107cl::sub(Stack), cl::init(AggregationType::TOTAL_TIME));108109/// A helper struct to work with formatv and XRayRecords. Makes it easier to110/// use instrumentation map names or addresses in formatted output.111struct format_xray_record : public FormatAdapter<XRayRecord> {112explicit format_xray_record(XRayRecord record,113const FuncIdConversionHelper &conv)114: FormatAdapter<XRayRecord>(std::move(record)), Converter(&conv) {}115void format(raw_ostream &Stream, StringRef Style) override {116Stream << formatv(117"{FuncId: \"{0}\", ThreadId: \"{1}\", RecordType: \"{2}\"}",118Converter->SymbolOrNumber(Item.FuncId), Item.TId,119DecodeRecordType(Item.RecordType));120}121122private:123Twine DecodeRecordType(uint16_t recordType) {124switch (recordType) {125case 0:126return Twine("Fn Entry");127case 1:128return Twine("Fn Exit");129default:130// TODO: Add Tail exit when it is added to llvm/XRay/XRayRecord.h131return Twine("Unknown");132}133}134135const FuncIdConversionHelper *Converter;136};137138/// The stack command will take a set of XRay traces as arguments, and collects139/// information about the stacks of instrumented functions that appear in the140/// traces. We track the following pieces of information:141///142/// - Total time: amount of time/cycles accounted for in the traces.143/// - Stack count: number of times a specific stack appears in the144/// traces. Only instrumented functions show up in stacks.145/// - Cumulative stack time: amount of time spent in a stack accumulated146/// across the invocations in the traces.147/// - Cumulative local time: amount of time spent in each instrumented148/// function showing up in a specific stack, accumulated across the traces.149///150/// Example output for the kind of data we'd like to provide looks like the151/// following:152///153/// Total time: 3.33234 s154/// Stack ID: ...155/// Stack Count: 2093156/// # Function Local Time (%) Stack Time (%)157/// 0 main 2.34 ms 0.07% 3.33234 s 100%158/// 1 foo() 3.30000 s 99.02% 3.33 s 99.92%159/// 2 bar() 30 ms 0.90% 30 ms 0.90%160///161/// We can also show distributions of the function call durations with162/// statistics at each level of the stack. This works by doing the following163/// algorithm:164///165/// 1. When unwinding, record the duration of each unwound function associated166/// with the path up to which the unwinding stops. For example:167///168/// Step Duration (? means has start time)169///170/// push a <start time> a = ?171/// push b <start time> a = ?, a->b = ?172/// push c <start time> a = ?, a->b = ?, a->b->c = ?173/// pop c <end time> a = ?, a->b = ?, emit duration(a->b->c)174/// pop b <end time> a = ?, emit duration(a->b)175/// push c <start time> a = ?, a->c = ?176/// pop c <end time> a = ?, emit duration(a->c)177/// pop a <end time> emit duration(a)178///179/// 2. We then account for the various stacks we've collected, and for each of180/// them will have measurements that look like the following (continuing181/// with the above simple example):182///183/// c : [<id("a->b->c"), [durations]>, <id("a->c"), [durations]>]184/// b : [<id("a->b"), [durations]>]185/// a : [<id("a"), [durations]>]186///187/// This allows us to compute, for each stack id, and each function that188/// shows up in the stack, some important statistics like:189///190/// - median191/// - 99th percentile192/// - mean + stddev193/// - count194///195/// 3. For cases where we don't have durations for some of the higher levels196/// of the stack (perhaps instrumentation wasn't activated when the stack was197/// entered), we can mark them appropriately.198///199/// Computing this data also allows us to implement lookup by call stack nodes,200/// so that we can find functions that show up in multiple stack traces and201/// show the statistical properties of that function in various contexts. We202/// can compute information similar to the following:203///204/// Function: 'c'205/// Stacks: 2 / 2206/// Stack ID: ...207/// Stack Count: ...208/// # Function ...209/// 0 a ...210/// 1 b ...211/// 2 c ...212///213/// Stack ID: ...214/// Stack Count: ...215/// # Function ...216/// 0 a ...217/// 1 c ...218/// ----------------...219///220/// Function: 'b'221/// Stacks: 1 / 2222/// Stack ID: ...223/// Stack Count: ...224/// # Function ...225/// 0 a ...226/// 1 b ...227/// 2 c ...228///229///230/// To do this we require a Trie data structure that will allow us to represent231/// all the call stacks of instrumented functions in an easily traversible232/// manner when we do the aggregations and lookups. For instrumented call233/// sequences like the following:234///235/// a()236/// b()237/// c()238/// d()239/// c()240///241/// We will have a representation like so:242///243/// a -> b -> c244/// | |245/// | +--> d246/// |247/// +--> c248///249/// We maintain a sequence of durations on the leaves and in the internal nodes250/// as we go through and process every record from the XRay trace. We also251/// maintain an index of unique functions, and provide a means of iterating252/// through all the instrumented call stacks which we know about.253254namespace {255struct StackDuration {256llvm::SmallVector<int64_t, 4> TerminalDurations;257llvm::SmallVector<int64_t, 4> IntermediateDurations;258};259} // namespace260261static StackDuration mergeStackDuration(const StackDuration &Left,262const StackDuration &Right) {263StackDuration Data{};264Data.TerminalDurations.reserve(Left.TerminalDurations.size() +265Right.TerminalDurations.size());266Data.IntermediateDurations.reserve(Left.IntermediateDurations.size() +267Right.IntermediateDurations.size());268// Aggregate the durations.269for (auto duration : Left.TerminalDurations)270Data.TerminalDurations.push_back(duration);271for (auto duration : Right.TerminalDurations)272Data.TerminalDurations.push_back(duration);273274for (auto duration : Left.IntermediateDurations)275Data.IntermediateDurations.push_back(duration);276for (auto duration : Right.IntermediateDurations)277Data.IntermediateDurations.push_back(duration);278return Data;279}280281using StackTrieNode = TrieNode<StackDuration>;282283template <AggregationType AggType>284static std::size_t GetValueForStack(const StackTrieNode *Node);285286// When computing total time spent in a stack, we're adding the timings from287// its callees and the timings from when it was a leaf.288template <>289std::size_t290GetValueForStack<AggregationType::TOTAL_TIME>(const StackTrieNode *Node) {291auto TopSum = std::accumulate(Node->ExtraData.TerminalDurations.begin(),292Node->ExtraData.TerminalDurations.end(), 0uLL);293return std::accumulate(Node->ExtraData.IntermediateDurations.begin(),294Node->ExtraData.IntermediateDurations.end(), TopSum);295}296297// Calculates how many times a function was invoked.298// TODO: Hook up option to produce stacks299template <>300std::size_t301GetValueForStack<AggregationType::INVOCATION_COUNT>(const StackTrieNode *Node) {302return Node->ExtraData.TerminalDurations.size() +303Node->ExtraData.IntermediateDurations.size();304}305306// Make sure there are implementations for each enum value.307template <AggregationType T> struct DependentFalseType : std::false_type {};308309template <AggregationType AggType>310std::size_t GetValueForStack(const StackTrieNode *Node) {311static_assert(DependentFalseType<AggType>::value,312"No implementation found for aggregation type provided.");313return 0;314}315316class StackTrie {317// Avoid the magic number of 4 propagated through the code with an alias.318// We use this SmallVector to track the root nodes in a call graph.319using RootVector = SmallVector<StackTrieNode *, 4>;320321// We maintain pointers to the roots of the tries we see.322DenseMap<uint32_t, RootVector> Roots;323324// We make sure all the nodes are accounted for in this list.325std::forward_list<StackTrieNode> NodeStore;326327// A map of thread ids to pairs call stack trie nodes and their start times.328DenseMap<uint32_t, SmallVector<std::pair<StackTrieNode *, uint64_t>, 8>>329ThreadStackMap;330331StackTrieNode *createTrieNode(uint32_t ThreadId, int32_t FuncId,332StackTrieNode *Parent) {333NodeStore.push_front(StackTrieNode{FuncId, Parent, {}, {{}, {}}});334auto I = NodeStore.begin();335auto *Node = &*I;336if (!Parent)337Roots[ThreadId].push_back(Node);338return Node;339}340341StackTrieNode *findRootNode(uint32_t ThreadId, int32_t FuncId) {342const auto &RootsByThread = Roots[ThreadId];343auto I = find_if(RootsByThread,344[&](StackTrieNode *N) { return N->FuncId == FuncId; });345return (I == RootsByThread.end()) ? nullptr : *I;346}347348public:349enum class AccountRecordStatus {350OK, // Successfully processed351ENTRY_NOT_FOUND, // An exit record had no matching call stack entry352UNKNOWN_RECORD_TYPE353};354355struct AccountRecordState {356// We keep track of whether the call stack is currently unwinding.357bool wasLastRecordExit;358359static AccountRecordState CreateInitialState() { return {false}; }360};361362AccountRecordStatus accountRecord(const XRayRecord &R,363AccountRecordState *state) {364auto &TS = ThreadStackMap[R.TId];365switch (R.Type) {366case RecordTypes::CUSTOM_EVENT:367case RecordTypes::TYPED_EVENT:368return AccountRecordStatus::OK;369case RecordTypes::ENTER:370case RecordTypes::ENTER_ARG: {371state->wasLastRecordExit = false;372// When we encounter a new function entry, we want to record the TSC for373// that entry, and the function id. Before doing so we check the top of374// the stack to see if there are callees that already represent this375// function.376if (TS.empty()) {377auto *Root = findRootNode(R.TId, R.FuncId);378TS.emplace_back(Root ? Root : createTrieNode(R.TId, R.FuncId, nullptr),379R.TSC);380return AccountRecordStatus::OK;381}382383auto &Top = TS.back();384auto I = find_if(Top.first->Callees,385[&](StackTrieNode *N) { return N->FuncId == R.FuncId; });386if (I == Top.first->Callees.end()) {387// We didn't find the callee in the stack trie, so we're going to388// add to the stack then set up the pointers properly.389auto N = createTrieNode(R.TId, R.FuncId, Top.first);390Top.first->Callees.emplace_back(N);391392// Top may be invalidated after this statement.393TS.emplace_back(N, R.TSC);394} else {395// We found the callee in the stack trie, so we'll use that pointer396// instead, add it to the stack associated with the TSC.397TS.emplace_back(*I, R.TSC);398}399return AccountRecordStatus::OK;400}401case RecordTypes::EXIT:402case RecordTypes::TAIL_EXIT: {403bool wasLastRecordExit = state->wasLastRecordExit;404state->wasLastRecordExit = true;405// The exit case is more interesting, since we want to be able to deduce406// missing exit records. To do that properly, we need to look up the stack407// and see whether the exit record matches any of the entry records. If it408// does match, we attempt to record the durations as we pop the stack to409// where we see the parent.410if (TS.empty()) {411// Short circuit, and say we can't find it.412413return AccountRecordStatus::ENTRY_NOT_FOUND;414}415416auto FunctionEntryMatch = find_if(417reverse(TS), [&](const std::pair<StackTrieNode *, uint64_t> &E) {418return E.first->FuncId == R.FuncId;419});420auto status = AccountRecordStatus::OK;421if (FunctionEntryMatch == TS.rend()) {422status = AccountRecordStatus::ENTRY_NOT_FOUND;423} else {424// Account for offset of 1 between reverse and forward iterators. We425// want the forward iterator to include the function that is exited.426++FunctionEntryMatch;427}428auto I = FunctionEntryMatch.base();429for (auto &E : make_range(I, TS.end() - 1))430E.first->ExtraData.IntermediateDurations.push_back(431std::max(E.second, R.TSC) - std::min(E.second, R.TSC));432auto &Deepest = TS.back();433if (wasLastRecordExit)434Deepest.first->ExtraData.IntermediateDurations.push_back(435std::max(Deepest.second, R.TSC) - std::min(Deepest.second, R.TSC));436else437Deepest.first->ExtraData.TerminalDurations.push_back(438std::max(Deepest.second, R.TSC) - std::min(Deepest.second, R.TSC));439TS.erase(I, TS.end());440return status;441}442}443return AccountRecordStatus::UNKNOWN_RECORD_TYPE;444}445446bool isEmpty() const { return Roots.empty(); }447448void printStack(raw_ostream &OS, const StackTrieNode *Top,449FuncIdConversionHelper &FN) {450// Traverse the pointers up to the parent, noting the sums, then print451// in reverse order (callers at top, callees down bottom).452SmallVector<const StackTrieNode *, 8> CurrentStack;453for (auto *F = Top; F != nullptr; F = F->Parent)454CurrentStack.push_back(F);455int Level = 0;456OS << formatv("{0,-5} {1,-60} {2,+12} {3,+16}\n", "lvl", "function",457"count", "sum");458for (auto *F : reverse(drop_begin(CurrentStack))) {459auto Sum = std::accumulate(F->ExtraData.IntermediateDurations.begin(),460F->ExtraData.IntermediateDurations.end(), 0LL);461auto FuncId = FN.SymbolOrNumber(F->FuncId);462OS << formatv("#{0,-4} {1,-60} {2,+12} {3,+16}\n", Level++,463FuncId.size() > 60 ? FuncId.substr(0, 57) + "..." : FuncId,464F->ExtraData.IntermediateDurations.size(), Sum);465}466auto *Leaf = *CurrentStack.begin();467auto LeafSum =468std::accumulate(Leaf->ExtraData.TerminalDurations.begin(),469Leaf->ExtraData.TerminalDurations.end(), 0LL);470auto LeafFuncId = FN.SymbolOrNumber(Leaf->FuncId);471OS << formatv("#{0,-4} {1,-60} {2,+12} {3,+16}\n", Level++,472LeafFuncId.size() > 60 ? LeafFuncId.substr(0, 57) + "..."473: LeafFuncId,474Leaf->ExtraData.TerminalDurations.size(), LeafSum);475OS << "\n";476}477478/// Prints top stacks for each thread.479void printPerThread(raw_ostream &OS, FuncIdConversionHelper &FN) {480for (const auto &iter : Roots) {481OS << "Thread " << iter.first << ":\n";482print(OS, FN, iter.second);483OS << "\n";484}485}486487/// Prints timing sums for each stack in each threads.488template <AggregationType AggType>489void printAllPerThread(raw_ostream &OS, FuncIdConversionHelper &FN,490StackOutputFormat format) {491for (const auto &iter : Roots)492printAll<AggType>(OS, FN, iter.second, iter.first, true);493}494495/// Prints top stacks from looking at all the leaves and ignoring thread IDs.496/// Stacks that consist of the same function IDs but were called in different497/// thread IDs are not considered unique in this printout.498void printIgnoringThreads(raw_ostream &OS, FuncIdConversionHelper &FN) {499RootVector RootValues;500501// Function to pull the values out of a map iterator.502using RootsType = decltype(Roots.begin())::value_type;503auto MapValueFn = [](const RootsType &Value) { return Value.second; };504505for (const auto &RootNodeRange :506make_range(map_iterator(Roots.begin(), MapValueFn),507map_iterator(Roots.end(), MapValueFn))) {508for (auto *RootNode : RootNodeRange)509RootValues.push_back(RootNode);510}511512print(OS, FN, RootValues);513}514515/// Creates a merged list of Tries for unique stacks that disregards their516/// thread IDs.517RootVector mergeAcrossThreads(std::forward_list<StackTrieNode> &NodeStore) {518RootVector MergedByThreadRoots;519for (const auto &MapIter : Roots) {520const auto &RootNodeVector = MapIter.second;521for (auto *Node : RootNodeVector) {522auto MaybeFoundIter =523find_if(MergedByThreadRoots, [Node](StackTrieNode *elem) {524return Node->FuncId == elem->FuncId;525});526if (MaybeFoundIter == MergedByThreadRoots.end()) {527MergedByThreadRoots.push_back(Node);528} else {529MergedByThreadRoots.push_back(mergeTrieNodes(530**MaybeFoundIter, *Node, nullptr, NodeStore, mergeStackDuration));531MergedByThreadRoots.erase(MaybeFoundIter);532}533}534}535return MergedByThreadRoots;536}537538/// Print timing sums for all stacks merged by Thread ID.539template <AggregationType AggType>540void printAllAggregatingThreads(raw_ostream &OS, FuncIdConversionHelper &FN,541StackOutputFormat format) {542std::forward_list<StackTrieNode> AggregatedNodeStore;543RootVector MergedByThreadRoots = mergeAcrossThreads(AggregatedNodeStore);544bool reportThreadId = false;545printAll<AggType>(OS, FN, MergedByThreadRoots,546/*threadId*/ 0, reportThreadId);547}548549/// Merges the trie by thread id before printing top stacks.550void printAggregatingThreads(raw_ostream &OS, FuncIdConversionHelper &FN) {551std::forward_list<StackTrieNode> AggregatedNodeStore;552RootVector MergedByThreadRoots = mergeAcrossThreads(AggregatedNodeStore);553print(OS, FN, MergedByThreadRoots);554}555556// TODO: Add a format option when more than one are supported.557template <AggregationType AggType>558void printAll(raw_ostream &OS, FuncIdConversionHelper &FN,559RootVector RootValues, uint32_t ThreadId, bool ReportThread) {560SmallVector<const StackTrieNode *, 16> S;561for (const auto *N : RootValues) {562S.clear();563S.push_back(N);564while (!S.empty()) {565auto *Top = S.pop_back_val();566printSingleStack<AggType>(OS, FN, ReportThread, ThreadId, Top);567for (const auto *C : Top->Callees)568S.push_back(C);569}570}571}572573/// Prints values for stacks in a format consumable for the flamegraph.pl574/// tool. This is a line based format that lists each level in the stack575/// hierarchy in a semicolon delimited form followed by a space and a numeric576/// value. If breaking down by thread, the thread ID will be added as the577/// root level of the stack.578template <AggregationType AggType>579void printSingleStack(raw_ostream &OS, FuncIdConversionHelper &Converter,580bool ReportThread, uint32_t ThreadId,581const StackTrieNode *Node) {582if (ReportThread)583OS << "thread_" << ThreadId << ";";584SmallVector<const StackTrieNode *, 5> lineage{};585lineage.push_back(Node);586while (lineage.back()->Parent != nullptr)587lineage.push_back(lineage.back()->Parent);588while (!lineage.empty()) {589OS << Converter.SymbolOrNumber(lineage.back()->FuncId) << ";";590lineage.pop_back();591}592OS << " " << GetValueForStack<AggType>(Node) << "\n";593}594595void print(raw_ostream &OS, FuncIdConversionHelper &FN,596RootVector RootValues) {597// Go through each of the roots, and traverse the call stack, producing the598// aggregates as you go along. Remember these aggregates and stacks, and599// show summary statistics about:600//601// - Total number of unique stacks602// - Top 10 stacks by count603// - Top 10 stacks by aggregate duration604SmallVector<std::pair<const StackTrieNode *, uint64_t>, 11>605TopStacksByCount;606SmallVector<std::pair<const StackTrieNode *, uint64_t>, 11> TopStacksBySum;607auto greater_second =608[](const std::pair<const StackTrieNode *, uint64_t> &A,609const std::pair<const StackTrieNode *, uint64_t> &B) {610return A.second > B.second;611};612uint64_t UniqueStacks = 0;613for (const auto *N : RootValues) {614SmallVector<const StackTrieNode *, 16> S;615S.emplace_back(N);616617while (!S.empty()) {618auto *Top = S.pop_back_val();619620// We only start printing the stack (by walking up the parent pointers)621// when we get to a leaf function.622if (!Top->ExtraData.TerminalDurations.empty()) {623++UniqueStacks;624auto TopSum =625std::accumulate(Top->ExtraData.TerminalDurations.begin(),626Top->ExtraData.TerminalDurations.end(), 0uLL);627{628auto E = std::make_pair(Top, TopSum);629TopStacksBySum.insert(630llvm::lower_bound(TopStacksBySum, E, greater_second), E);631if (TopStacksBySum.size() == 11)632TopStacksBySum.pop_back();633}634{635auto E =636std::make_pair(Top, Top->ExtraData.TerminalDurations.size());637TopStacksByCount.insert(638llvm::lower_bound(TopStacksByCount, E, greater_second), E);639if (TopStacksByCount.size() == 11)640TopStacksByCount.pop_back();641}642}643for (const auto *C : Top->Callees)644S.push_back(C);645}646}647648// Now print the statistics in the end.649OS << "\n";650OS << "Unique Stacks: " << UniqueStacks << "\n";651OS << "Top 10 Stacks by leaf sum:\n\n";652for (const auto &P : TopStacksBySum) {653OS << "Sum: " << P.second << "\n";654printStack(OS, P.first, FN);655}656OS << "\n";657OS << "Top 10 Stacks by leaf count:\n\n";658for (const auto &P : TopStacksByCount) {659OS << "Count: " << P.second << "\n";660printStack(OS, P.first, FN);661}662OS << "\n";663}664};665666static std::string CreateErrorMessage(StackTrie::AccountRecordStatus Error,667const XRayRecord &Record,668const FuncIdConversionHelper &Converter) {669switch (Error) {670case StackTrie::AccountRecordStatus::ENTRY_NOT_FOUND:671return std::string(672formatv("Found record {0} with no matching function entry\n",673format_xray_record(Record, Converter)));674default:675return std::string(formatv("Unknown error type for record {0}\n",676format_xray_record(Record, Converter)));677}678}679680static CommandRegistration Unused(&Stack, []() -> Error {681// Load each file provided as a command-line argument. For each one of them682// account to a single StackTrie, and just print the whole trie for now.683StackTrie ST;684InstrumentationMap Map;685if (!StacksInstrMap.empty()) {686auto InstrumentationMapOrError = loadInstrumentationMap(StacksInstrMap);687if (!InstrumentationMapOrError)688return joinErrors(689make_error<StringError>(690Twine("Cannot open instrumentation map: ") + StacksInstrMap,691std::make_error_code(std::errc::invalid_argument)),692InstrumentationMapOrError.takeError());693Map = std::move(*InstrumentationMapOrError);694}695696if (SeparateThreadStacks && AggregateThreads)697return make_error<StringError>(698Twine("Can't specify options for per thread reporting and reporting "699"that aggregates threads."),700std::make_error_code(std::errc::invalid_argument));701702if (!DumpAllStacks && StacksOutputFormat != HUMAN)703return make_error<StringError>(704Twine("Can't specify a non-human format without -all-stacks."),705std::make_error_code(std::errc::invalid_argument));706707if (DumpAllStacks && StacksOutputFormat == HUMAN)708return make_error<StringError>(709Twine("You must specify a non-human format when reporting with "710"-all-stacks."),711std::make_error_code(std::errc::invalid_argument));712713symbolize::LLVMSymbolizer Symbolizer;714FuncIdConversionHelper FuncIdHelper(StacksInstrMap, Symbolizer,715Map.getFunctionAddresses());716// TODO: Someday, support output to files instead of just directly to717// standard output.718for (const auto &Filename : StackInputs) {719auto TraceOrErr = loadTraceFile(Filename);720if (!TraceOrErr) {721if (!StackKeepGoing)722return joinErrors(723make_error<StringError>(724Twine("Failed loading input file '") + Filename + "'",725std::make_error_code(std::errc::invalid_argument)),726TraceOrErr.takeError());727logAllUnhandledErrors(TraceOrErr.takeError(), errs());728continue;729}730auto &T = *TraceOrErr;731StackTrie::AccountRecordState AccountRecordState =732StackTrie::AccountRecordState::CreateInitialState();733for (const auto &Record : T) {734auto error = ST.accountRecord(Record, &AccountRecordState);735if (error != StackTrie::AccountRecordStatus::OK) {736if (!StackKeepGoing)737return make_error<StringError>(738CreateErrorMessage(error, Record, FuncIdHelper),739make_error_code(errc::illegal_byte_sequence));740errs() << CreateErrorMessage(error, Record, FuncIdHelper);741}742}743}744if (ST.isEmpty()) {745return make_error<StringError>(746"No instrumented calls were accounted in the input file.",747make_error_code(errc::result_out_of_range));748}749750// Report the stacks in a long form mode for another tool to analyze.751if (DumpAllStacks) {752if (AggregateThreads) {753switch (RequestedAggregation) {754case AggregationType::TOTAL_TIME:755ST.printAllAggregatingThreads<AggregationType::TOTAL_TIME>(756outs(), FuncIdHelper, StacksOutputFormat);757break;758case AggregationType::INVOCATION_COUNT:759ST.printAllAggregatingThreads<AggregationType::INVOCATION_COUNT>(760outs(), FuncIdHelper, StacksOutputFormat);761break;762}763} else {764switch (RequestedAggregation) {765case AggregationType::TOTAL_TIME:766ST.printAllPerThread<AggregationType::TOTAL_TIME>(outs(), FuncIdHelper,767StacksOutputFormat);768break;769case AggregationType::INVOCATION_COUNT:770ST.printAllPerThread<AggregationType::INVOCATION_COUNT>(771outs(), FuncIdHelper, StacksOutputFormat);772break;773}774}775return Error::success();776}777778// We're only outputting top stacks.779if (AggregateThreads) {780ST.printAggregatingThreads(outs(), FuncIdHelper);781} else if (SeparateThreadStacks) {782ST.printPerThread(outs(), FuncIdHelper);783} else {784ST.printIgnoringThreads(outs(), FuncIdHelper);785}786return Error::success();787});788789790