Debian Codegraph @

clang/utils/perf-training/perf-helper.py

raw
1 # ===- perf-helper.py - Clang Python Bindings -----------------*- python -*--===#
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 from __future__ import absolute_import, division, print_function
10
11 import sys
12 import os
13 import subprocess
14 import argparse
15 import time
16 import bisect
17 import shlex
18 import tempfile
19
20 test_env = {"PATH": os.environ["PATH"]}
21
22
23 def findFilesWithExtension(path, extension):
24 filenames = []
25 for root, dirs, files in os.walk(path):
26 for filename in files:
27 if filename.endswith(f".{extension}"):
28 filenames.append(os.path.join(root, filename))
29 return filenames
30
31
32 def clean(args):
33 if len(args) < 2:
34 print(
35 "Usage: %s clean <paths> <extension>\n" % __file__
36 + "\tRemoves all files with extension from <path>."
37 )
38 return 1
39 for path in args[0:-1]:
40 for filename in findFilesWithExtension(path, args[-1]):
41 os.remove(filename)
42 return 0
43
44
45 def merge(args):
46 if len(args) < 3:
47 print(
48 "Usage: %s merge <llvm-profdata> <output> <paths>\n" % __file__
49 + "\tMerges all profraw files from path into output."
50 )
51 return 1
52 cmd = [args[0], "merge", "-o", args[1]]
53 for path in args[2:]:
54 cmd.extend(findFilesWithExtension(path, "profraw"))
55 subprocess.check_call(cmd)
56 return 0
57
58
59 def merge_fdata(args):
60 if len(args) != 3:
61 print(
62 "Usage: %s merge-fdata <merge-fdata> <output> <path>\n" % __file__
63 + "\tMerges all fdata files from path into output."
64 )
65 return 1
66 cmd = [args[0], "-o", args[1]]
67 cmd.extend(findFilesWithExtension(args[2], "fdata"))
68 subprocess.check_call(cmd)
69 return 0
70
71
72 def perf(args):
73 parser = argparse.ArgumentParser(
74 prog="perf-helper perf", description="perf wrapper for BOLT profile collection"
75 )
76 parser.add_argument(
77 "--lbr", action="store_true", help="Use perf with branch stacks"
78 )
79 parser.add_argument("cmd", nargs=argparse.REMAINDER, help="")
80
81 opts = parser.parse_args(args)
82 cmd = opts.cmd[1:]
83
84 perf_args = [
85 "perf",
86 "record",
87 "--event=cycles:u",
88 "--freq=max",
89 "--output=%d.perf.data" % os.getpid(),
90 ]
91 if opts.lbr:
92 perf_args += ["--branch-filter=any,u"]
93 perf_args.extend(cmd)
94
95 start_time = time.time()
96 subprocess.check_call(perf_args)
97
98 elapsed = time.time() - start_time
99 print("... data collection took %.4fs" % elapsed)
100 return 0
101
102
103 def perf2bolt(args):
104 parser = argparse.ArgumentParser(
105 prog="perf-helper perf2bolt",
106 description="perf2bolt conversion wrapper for perf.data files",
107 )
108 parser.add_argument("bolt", help="Path to llvm-bolt")
109 parser.add_argument("path", help="Path containing perf.data files")
110 parser.add_argument("binary", help="Input binary")
111 parser.add_argument("--lbr", action="store_true", help="Use LBR perf2bolt mode")
112 opts = parser.parse_args(args)
113
114 p2b_args = [
115 opts.bolt,
116 opts.binary,
117 "--aggregate-only",
118 "--profile-format=yaml",
119 ]
120 if not opts.lbr:
121 p2b_args += ["-nl"]
122 p2b_args += ["-p"]
123 for filename in findFilesWithExtension(opts.path, "perf.data"):
124 subprocess.check_call(p2b_args + [filename, "-o", filename + ".fdata"])
125 return 0
126
127
128 def dtrace(args):
129 parser = argparse.ArgumentParser(
130 prog="perf-helper dtrace",
131 description="dtrace wrapper for order file generation",
132 )
133 parser.add_argument(
134 "--buffer-size",
135 metavar="size",
136 type=int,
137 required=False,
138 default=1,
139 help="dtrace buffer size in MB (default 1)",
140 )
141 parser.add_argument(
142 "--use-oneshot",
143 required=False,
144 action="store_true",
145 help="Use dtrace's oneshot probes",
146 )
147 parser.add_argument(
148 "--use-ustack",
149 required=False,
150 action="store_true",
151 help="Use dtrace's ustack to print function names",
152 )
153 parser.add_argument(
154 "--cc1",
155 required=False,
156 action="store_true",
157 help="Execute cc1 directly (don't profile the driver)",
158 )
159 parser.add_argument("cmd", nargs="*", help="")
160
161 # Use python's arg parser to handle all leading option arguments, but pass
162 # everything else through to dtrace
163 first_cmd = next(arg for arg in args if not arg.startswith("--"))
164 last_arg_idx = args.index(first_cmd)
165
166 opts = parser.parse_args(args[:last_arg_idx])
167 cmd = args[last_arg_idx:]
168
169 if opts.cc1:
170 cmd = get_cc1_command_for_args(cmd, test_env)
171
172 if opts.use_oneshot:
173 target = "oneshot$target:::entry"
174 else:
175 target = "pid$target:::entry"
176 predicate = '%s/probemod=="%s"/' % (target, os.path.basename(cmd[0]))
177 log_timestamp = 'printf("dtrace-TS: %d\\n", timestamp)'
178 if opts.use_ustack:
179 action = "ustack(1);"
180 else:
181 action = 'printf("dtrace-Symbol: %s\\n", probefunc);'
182 dtrace_script = "%s { %s; %s }" % (predicate, log_timestamp, action)
183
184 dtrace_args = []
185 if not os.geteuid() == 0:
186 print(
187 "Script must be run as root, or you must add the following to your sudoers:"
188 + "%%admin ALL=(ALL) NOPASSWD: /usr/sbin/dtrace"
189 )
190 dtrace_args.append("sudo")
191
192 dtrace_args.extend(
193 (
194 "dtrace",
195 "-xevaltime=exec",
196 "-xbufsize=%dm" % (opts.buffer_size),
197 "-q",
198 "-n",
199 dtrace_script,
200 "-c",
201 " ".join(cmd),
202 )
203 )
204
205 if sys.platform == "darwin":
206 dtrace_args.append("-xmangled")
207
208 start_time = time.time()
209
210 with open("%d.dtrace" % os.getpid(), "w") as f:
211 f.write("### Command: %s" % dtrace_args)
212 subprocess.check_call(dtrace_args, stdout=f, stderr=subprocess.PIPE)
213
214 elapsed = time.time() - start_time
215 print("... data collection took %.4fs" % elapsed)
216
217 return 0
218
219
220 def get_cc1_command_for_args(cmd, env):
221 # Find the cc1 command used by the compiler. To do this we execute the
222 # compiler with '-###' to figure out what it wants to do.
223 cmd = cmd + ["-###"]
224 cc_output = subprocess.check_output(
225 cmd, stderr=subprocess.STDOUT, env=env, universal_newlines=True
226 ).strip()
227 cc_commands = []
228 for ln in cc_output.split("\n"):
229 # Filter out known garbage.
230 if (
231 ln == "Using built-in specs."
232 or ln.startswith("Configured with:")
233 or ln.startswith("Target:")
234 or ln.startswith("Thread model:")
235 or ln.startswith("InstalledDir:")
236 or ln.startswith("LLVM Profile Note")
237 or ln.startswith(" (in-process)")
238 or " version " in ln
239 ):
240 continue
241 cc_commands.append(ln)
242
243 if len(cc_commands) != 1:
244 print("Fatal error: unable to determine cc1 command: %r" % cc_output)
245 exit(1)
246
247 cc1_cmd = shlex.split(cc_commands[0])
248 if not cc1_cmd:
249 print("Fatal error: unable to determine cc1 command: %r" % cc_output)
250 exit(1)
251
252 return cc1_cmd
253
254
255 def cc1(args):
256 parser = argparse.ArgumentParser(
257 prog="perf-helper cc1", description="cc1 wrapper for order file generation"
258 )
259 parser.add_argument("cmd", nargs="*", help="")
260
261 # Use python's arg parser to handle all leading option arguments, but pass
262 # everything else through to dtrace
263 first_cmd = next(arg for arg in args if not arg.startswith("--"))
264 last_arg_idx = args.index(first_cmd)
265
266 opts = parser.parse_args(args[:last_arg_idx])
267 cmd = args[last_arg_idx:]
268
269 # clear the profile file env, so that we don't generate profdata
270 # when capturing the cc1 command
271 cc1_env = test_env
272 cc1_env["LLVM_PROFILE_FILE"] = os.devnull
273 cc1_cmd = get_cc1_command_for_args(cmd, cc1_env)
274
275 subprocess.check_call(cc1_cmd)
276 return 0
277
278
279 def parse_dtrace_symbol_file(path, all_symbols, all_symbols_set, missing_symbols, opts):
280 def fix_mangling(symbol):
281 if sys.platform == "darwin":
282 if symbol[0] != "_" and symbol != "start":
283 symbol = "_" + symbol
284 return symbol
285
286 def get_symbols_with_prefix(symbol):
287 start_index = bisect.bisect_left(all_symbols, symbol)
288 for s in all_symbols[start_index:]:
289 if not s.startswith(symbol):
290 break
291 yield s
292
293 # Extract the list of symbols from the given file, which is assumed to be
294 # the output of a dtrace run logging either probefunc or ustack(1) and
295 # nothing else. The dtrace -xdemangle option needs to be used.
296 #
297 # This is particular to OS X at the moment, because of the '_' handling.
298 with open(path) as f:
299 current_timestamp = None
300 for ln in f:
301 # Drop leading and trailing whitespace.
302 ln = ln.strip()
303 if not ln.startswith("dtrace-"):
304 continue
305
306 # If this is a timestamp specifier, extract it.
307 if ln.startswith("dtrace-TS: "):
308 _, data = ln.split(": ", 1)
309 if not data.isdigit():
310 print(
311 "warning: unrecognized timestamp line %r, ignoring" % ln,
312 file=sys.stderr,
313 )
314 continue
315 current_timestamp = int(data)
316 continue
317 elif ln.startswith("dtrace-Symbol: "):
318
319 _, ln = ln.split(": ", 1)
320 if not ln:
321 continue
322
323 # If there is a '`' in the line, assume it is a ustack(1) entry in
324 # the form of <modulename>`<modulefunc>, where <modulefunc> is never
325 # truncated (but does need the mangling patched).
326 if "`" in ln:
327 yield (current_timestamp, fix_mangling(ln.split("`", 1)[1]))
328 continue
329
330 # Otherwise, assume this is a probefunc printout. DTrace on OS X
331 # seems to have a bug where it prints the mangled version of symbols
332 # which aren't C++ mangled. We just add a '_' to anything but start
333 # which doesn't already have a '_'.
334 symbol = fix_mangling(ln)
335
336 # If we don't know all the symbols, or the symbol is one of them,
337 # just return it.
338 if not all_symbols_set or symbol in all_symbols_set:
339 yield (current_timestamp, symbol)
340 continue
341
342 # Otherwise, we have a symbol name which isn't present in the
343 # binary. We assume it is truncated, and try to extend it.
344
345 # Get all the symbols with this prefix.
346 possible_symbols = list(get_symbols_with_prefix(symbol))
347 if not possible_symbols:
348 continue
349
350 # If we found too many possible symbols, ignore this as a prefix.
351 if len(possible_symbols) > 100:
352 print(
353 "warning: ignoring symbol %r " % symbol
354 + "(no match and too many possible suffixes)",
355 file=sys.stderr,
356 )
357 continue
358
359 # Report that we resolved a missing symbol.
360 if opts.show_missing_symbols and symbol not in missing_symbols:
361 print(
362 "warning: resolved missing symbol %r" % symbol, file=sys.stderr
363 )
364 missing_symbols.add(symbol)
365
366 # Otherwise, treat all the possible matches as having occurred. This
367 # is an over-approximation, but it should be ok in practice.
368 for s in possible_symbols:
369 yield (current_timestamp, s)
370
371
372 def uniq(list):
373 seen = set()
374 for item in list:
375 if item not in seen:
376 yield item
377 seen.add(item)
378
379
380 def form_by_call_order(symbol_lists):
381 # Simply strategy, just return symbols in order of occurrence, even across
382 # multiple runs.
383 return uniq(s for symbols in symbol_lists for s in symbols)
384
385
386 def form_by_call_order_fair(symbol_lists):
387 # More complicated strategy that tries to respect the call order across all
388 # of the test cases, instead of giving a huge preference to the first test
389 # case.
390
391 # First, uniq all the lists.
392 uniq_lists = [list(uniq(symbols)) for symbols in symbol_lists]
393
394 # Compute the successors for each list.
395 succs = {}
396 for symbols in uniq_lists:
397 for a, b in zip(symbols[:-1], symbols[1:]):
398 succs[a] = items = succs.get(a, [])
399 if b not in items:
400 items.append(b)
401
402 # Emit all the symbols, but make sure to always emit all successors from any
403 # call list whenever we see a symbol.
404 #
405 # There isn't much science here, but this sometimes works better than the
406 # more naive strategy. Then again, sometimes it doesn't so more research is
407 # probably needed.
408 return uniq(
409 s
410 for symbols in symbol_lists
411 for node in symbols
412 for s in ([node] + succs.get(node, []))
413 )
414
415
416 def form_by_frequency(symbol_lists):
417 # Form the order file by just putting the most commonly occurring symbols
418 # first. This assumes the data files didn't use the oneshot dtrace method.
419
420 counts = {}
421 for symbols in symbol_lists:
422 for a in symbols:
423 counts[a] = counts.get(a, 0) + 1
424
425 by_count = list(counts.items())
426 by_count.sort(key=lambda __n: -__n[1])
427 return [s for s, n in by_count]
428
429
430 def form_by_random(symbol_lists):
431 # Randomize the symbols.
432 merged_symbols = uniq(s for symbols in symbol_lists for s in symbols)
433 random.shuffle(merged_symbols)
434 return merged_symbols
435
436
437 def form_by_alphabetical(symbol_lists):
438 # Alphabetize the symbols.
439 merged_symbols = list(set(s for symbols in symbol_lists for s in symbols))
440 merged_symbols.sort()
441 return merged_symbols
442
443
444 methods = dict(
445 (name[len("form_by_") :], value)
446 for name, value in locals().items()
447 if name.startswith("form_by_")
448 )
449
450
451 def genOrderFile(args):
452 parser = argparse.ArgumentParser("%prog [options] <dtrace data file directories>]")
453 parser.add_argument("input", nargs="+", help="")
454 parser.add_argument(
455 "--binary",
456 metavar="PATH",
457 type=str,
458 dest="binary_path",
459 help="Path to the binary being ordered (for getting all symbols)",
460 default=None,
461 )
462 parser.add_argument(
463 "--output",
464 dest="output_path",
465 help="path to output order file to write",
466 default=None,
467 required=True,
468 metavar="PATH",
469 )
470 parser.add_argument(
471 "--show-missing-symbols",
472 dest="show_missing_symbols",
473 help="show symbols which are 'fixed up' to a valid name (requires --binary)",
474 action="store_true",
475 default=None,
476 )
477 parser.add_argument(
478 "--output-unordered-symbols",
479 dest="output_unordered_symbols_path",
480 help="write a list of the unordered symbols to PATH (requires --binary)",
481 default=None,
482 metavar="PATH",
483 )
484 parser.add_argument(
485 "--method",
486 dest="method",
487 help="order file generation method to use",
488 choices=list(methods.keys()),
489 default="call_order",
490 )
491 opts = parser.parse_args(args)
492
493 # If the user gave us a binary, get all the symbols in the binary by
494 # snarfing 'nm' output.
495 if opts.binary_path is not None:
496 output = subprocess.check_output(
497 ["nm", "-P", opts.binary_path], universal_newlines=True
498 )
499 lines = output.split("\n")
500 all_symbols = [ln.split(" ", 1)[0] for ln in lines if ln.strip()]
501 print("found %d symbols in binary" % len(all_symbols))
502 all_symbols.sort()
503 else:
504 all_symbols = []
505 all_symbols_set = set(all_symbols)
506
507 # Compute the list of input files.
508 input_files = []
509 for dirname in opts.input:
510 input_files.extend(findFilesWithExtension(dirname, "dtrace"))
511
512 # Load all of the input files.
513 print("loading from %d data files" % len(input_files))
514 missing_symbols = set()
515 timestamped_symbol_lists = [
516 list(
517 parse_dtrace_symbol_file(
518 path, all_symbols, all_symbols_set, missing_symbols, opts
519 )
520 )
521 for path in input_files
522 ]
523
524 # Reorder each symbol list.
525 symbol_lists = []
526 for timestamped_symbols_list in timestamped_symbol_lists:
527 timestamped_symbols_list.sort()
528 symbol_lists.append([symbol for _, symbol in timestamped_symbols_list])
529
530 # Execute the desire order file generation method.
531 method = methods.get(opts.method)
532 result = list(method(symbol_lists))
533
534 # Report to the user on what percentage of symbols are present in the order
535 # file.
536 num_ordered_symbols = len(result)
537 if all_symbols:
538 print(
539 "note: order file contains %d/%d symbols (%.2f%%)"
540 % (
541 num_ordered_symbols,
542 len(all_symbols),
543 100.0 * num_ordered_symbols / len(all_symbols),
544 ),
545 file=sys.stderr,
546 )
547
548 if opts.output_unordered_symbols_path:
549 ordered_symbols_set = set(result)
550 with open(opts.output_unordered_symbols_path, "w") as f:
551 f.write("\n".join(s for s in all_symbols if s not in ordered_symbols_set))
552
553 # Write the order file.
554 with open(opts.output_path, "w") as f:
555 f.write("\n".join(result))
556 f.write("\n")
557
558 return 0
559
560
561 commands = {
562 "clean": clean,
563 "merge": merge,
564 "dtrace": dtrace,
565 "cc1": cc1,
566 "gen-order-file": genOrderFile,
567 "merge-fdata": merge_fdata,
568 "perf": perf,
569 "perf2bolt": perf2bolt,
570 }
571
572
573 def main():
574 f = commands[sys.argv[1]]
575 sys.exit(f(sys.argv[2:]))
576
577
578 if __name__ == "__main__":
579 main()