#!/usr/bin/env python3 """Turn a callgrind profile into folded stacks for flamegraph.pl, or a table. `perf` cannot record call graphs on this machine (`kernel.perf_event_paranoid=2` refuses stack sampling, and lowering it needs root), so the call tree comes from valgrind instead: valgrind --tool=callgrind --separate-threads=yes \\ --callgrind-out-file=/tmp/cg/callgrind.out ./target/debug/cia ... scripts/callgrind-flamegraph.py /tmp/cg/callgrind.out.1234-01 > folded.txt flamegraph.pl folded.txt > restore.svg The output is rooted at `main`; `--root=SUBSTRING` roots it at the first frame whose name contains SUBSTRING, which is how one interaction (`Conversation::restore`) gets a flame graph of its own. `--table=N` prints the heaviest functions instead. How the numbers are read ------------------------ callgrind writes, for each function and each caller, the cost of the calls it made. Those are the edges used here, and an edge's cost is the *inclusive* cost of the callee: trusted, because it is what callgrind measured, not something this script adds up. A function's own cost is then what is left after its callees, and the tree keeps each function under the caller that spends the most in it. A cost line can also appear inside a call block for work the caller did around it, which shows up as a slightly heavy callee for repeated call sites, so treat widths as close rather than exact; `--check` prints how far the decomposition is from the profile's own total. Costs are instruction counts, not seconds. They rank work, and they miss waiting: a syscall or a GPU upload reads small here and large in `perf`. """ import argparse import re import sys from collections import defaultdict # valgrind writes `fn=(123) name` the first time it names something and `fn=(123)` # after that; the id is what the later ones refer to. NAMES = {} # A cost line: a position (`*`, `+N`, `-N` or a number) and its event counts, of # which the first is the one this profile records (`events: Ir`). COST = re.compile(r"^(?:\*|\+?\d+|-\d+)\s+(\d+)(?:\s+\d+)*$") def name_of(token): """The name a `fn=`/`cfn=` line refers to, defining it if it brings one.""" match = re.match(r"\((\d+)\)\s*(.*)$", token) if match: index, label = match.group(1), match.group(2) if label: NAMES[index] = label return label return NAMES.get(index, f"?{index}") return token def short(name): """A frame label worth reading in a flame graph.""" name = re.sub(r"<([^<>]*) as [^<>]*>::", r"\1::", name) # `::m` -> `X::m` name = re.sub(r"<([^<>]*)>::", r"\1::", name) # `::m` -> `X::m` name = re.sub(r"::<.*$", "", name) # drop generic arguments name = re.sub(r"\.llvm\.\d+", "", name) if name.startswith("/"): # A C library frame: the file is noise, the function is the point. name = name.rsplit(":", 1)[-1] return name.replace(";", ":") or "?" def parse(stream): """{(caller, callee): inclusive cost of the callee's calls from it}.""" edges = defaultdict(int) total = 0 current = None callee = None for line in stream: line = line.strip() if not line or line.startswith("#"): continue if line.startswith("fn="): current = name_of(line[3:]) callee = None continue if line.startswith("cfn="): callee = name_of(line[4:]) continue if line.startswith("calls="): continue if line.startswith(("jump=", "jcnd=")): # A jump is not a call: what follows is this function's own cost, # and that is derived from the edges rather than read from here. callee = None continue if line.startswith("summary:"): total += int(line.split()[1]) continue if "=" in line: continue # another header: `events:`, `positions:`, `fl=` ... match = COST.match(line) if not match or callee is None: continue edges[(current, callee)] += int(match.group(1)) return edges, total def reachable(edges, root): """The functions `root` can call, itself included.""" children = defaultdict(list) for caller, callee in edges: children[caller].append(callee) seen = {root} queue = [root] while queue: for child in children.get(queue.pop(), ()): if child not in seen: seen.add(child) queue.append(child) return seen def costs(edges): """Each function's inclusive and own cost, from the edges alone. Inclusive is everything its callers spent in it; own cost is what its callees do not account for. A function nothing calls is only visible through its callees, and a recursive one has its own cost left out of the difference, so both are clamped at zero rather than going negative. """ inclusive = defaultdict(int) spent = defaultdict(int) for (caller, callee), cost in edges.items(): if caller != callee: inclusive[callee] += cost spent[caller] += cost own = {} for name in set(inclusive) | set(spent): own[name] = max(0, inclusive[name] - spent[name]) return inclusive, own def tree(edges, inclusive, own, root): """Each function's parent and children, as a tree rooted at `root`. A call graph is not a tree: a function can be called from a dozen places and a recursive one calls itself, so expanding it as written either explodes or double counts. Each function is given the one caller that spends the most in it, which gives widths that add up and depths that follow the dominant call paths. A cycle (mutual recursion) is broken at its cheapest edge. """ under = reachable(edges, root) best = {} for (caller, callee), cost in edges.items(): if callee in under and caller in under and callee != root and caller != callee: if cost > best.get(callee, (None, -1))[1]: best[callee] = (caller, cost) settled = set() for start in list(best): path, seen, node = [], set(), start while node in best and node not in settled: if node in seen: cycle = path[path.index(node) :] weakest = min(cycle, key=lambda name: best[name][1]) del best[weakest] break seen.add(node) path.append(node) node = best[node][0] settled.update(seen) children = defaultdict(list) for callee, (caller, _) in best.items(): children[caller].append(callee) roots = [name for name in under if name not in best] return children, roots def stacks(children, roots, own, limit): """One folded line per function that spent anything of its own.""" folded = [] def walk(frame, path): if len(path) > limit: return if own.get(frame, 0) > 0: folded.append((path, own[frame])) for child in children.get(frame, ()): walk(child, path + [child]) for root in roots: walk(root, [root]) return folded def table(children, roots, own, count, base): """The heaviest functions, by the cost of what they and their callees did.""" inclusive = {} def total(frame): if frame not in inclusive: inclusive[frame] = own.get(frame, 0) + sum( total(child) for child in children.get(frame, ()) ) return inclusive[frame] for root in roots: total(root) print(f"{'inclusive':>14} {'own':>14} function") for frame, cost in sorted(inclusive.items(), key=lambda kv: -kv[1])[:count]: print( f"{cost:>14,} {own.get(frame, 0):>14,} " f"{100.0 * cost / max(1, base):5.1f}% {short(frame)}" ) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("profile", help="a callgrind.out.[-] file") parser.add_argument( "--root", default="main", help="root the tree at the first frame containing this (default: main)", ) parser.add_argument( "--depth", type=int, default=64, help="give up below this many frames" ) parser.add_argument( "--table", type=int, default=0, metavar="N", help="print the N heaviest functions by inclusive cost instead", ) parser.add_argument( "--check", action="store_true", help="print how the decomposition compares with the profile's total", ) args = parser.parse_args() with open(args.profile, encoding="utf-8", errors="replace") as stream: edges, total = parse(stream) inclusive, own = costs(edges) names = set(inclusive) | set(own) # Rust demangles `Conversation::restore` as ` # ::restore`, so the angle brackets are not part of what anybody types. plain = {name: name.replace("<", "").replace(">", "") for name in names} # An exact match first: `main` is also inside `Domain`, and the profile has # frames from libraries that have nothing to do with the app. root = next((name for name, text in plain.items() if text == args.root), None) if root is None: root = next( (name for name, text in sorted(plain.items()) if args.root in text), None ) if root is None: sys.exit(f"no function matches {args.root!r}") if args.check: print( f"own costs add to {sum(own.values()):,} Ir; " f"the profile says {total:,}", file=sys.stderr, ) children, roots = tree(edges, inclusive, own, root) if args.table: table(children, roots, own, args.table, inclusive.get(root, 0) or total) return folded = stacks(children, roots, own, args.depth) print( f"# {short(root)} carries {inclusive.get(root, 0):,} Ir " f"in {len(folded)} stacks", file=sys.stderr, ) for path, cost in folded: print(";".join(short(name) for name in path), cost) if __name__ == "__main__": main()