xref: /llvm-project/llvm/docs/CommandGuide/llvm-exegesis.rst (revision 72225ca27f561b74da292433400f250592d73b13)
1llvm-exegesis - LLVM Machine Instruction Benchmark
2==================================================
3
4.. program:: llvm-exegesis
5
6SYNOPSIS
7--------
8
9:program:`llvm-exegesis` [*options*]
10
11DESCRIPTION
12-----------
13
14:program:`llvm-exegesis` is a benchmarking tool that uses information available
15in LLVM to measure host machine instruction characteristics like latency,
16throughput, or port decomposition.
17
18Given an LLVM opcode name and a benchmarking mode, :program:`llvm-exegesis`
19generates a code snippet that makes execution as serial (resp. as parallel) as
20possible so that we can measure the latency (resp. inverse throughput/uop decomposition)
21of the instruction.
22The code snippet is jitted and, unless requested not to, executed on the
23host subtarget. The time taken (resp. resource usage) is measured using
24hardware performance counters. The result is printed out as YAML
25to the standard output.
26
27The main goal of this tool is to automatically (in)validate the LLVM's TableDef
28scheduling models. To that end, we also provide analysis of the results.
29
30:program:`llvm-exegesis` can also benchmark arbitrary user-provided code
31snippets.
32
33SUPPORTED PLATFORMS
34-------------------
35
36:program:`llvm-exegesis` currently only supports X86 (64-bit only), ARM
37(AArch64 only, snippet generation is sparse), MIPS, and PowerPC (PowerPC64LE
38only) on Linux for benchmarking. Not all benchmarking functionality is
39guaranteed to work on every platform. :program:`llvm-exegesis` also has a
40separate analysis mode that is supported on every platform that LLVM is.
41
42To enable benchmarking in llvm-exegesis, LLVM must be configured and built with
43`LLVM_ENABLE_LIBPFM` enabled, as :program:`llvm-exegesis` depends on libpfm4
44for accessing performance counters. Benchmarking may fail if the target CPU is
45unsupported by libpfm. This can be verified by setting `LIBPFM_VERBOSE` and
46`LIBPFM_DEBUG` environment variables to enable verbose or debug mode for
47libpfm. If libpfm is installed in a non-standard directory, LLVM can be
48configured to locate the necessary library and header files by setting
49`LIBRARY_PATH`, `C_INCLUDE_PATH`, and `CPLUS_INCLUDE_PATH` environment
50variables. Additionally, `LD_LIBRARY_PATH` should be set so that
51:program:`llvm-exegesis` can locate the libpfm library during execution.
52
53SNIPPET ANNOTATIONS
54-------------------
55
56:program:`llvm-exegesis` supports benchmarking arbitrary snippets of assembly.
57However, benchmarking these snippets often requires some setup so that they
58can execute properly. :program:`llvm-exegesis` has five annotations and some
59additional utilities to help with setup so that snippets can be benchmarked
60properly.
61
62* `LLVM-EXEGESIS-DEFREG <register name>` - Adding this annotation to the text
63  assembly snippet to be benchmarked marks the register as requiring a definition.
64  A value will automatically be provided unless a second parameter, a hex value,
65  is passed in. This is done with the `LLVM-EXEGESIS-DEFREG <register name> <hex value>`
66  format. `<hex value>` is a bit pattern used to fill the register. If it is a
67  value smaller than the register, it is sign extended to match the size of the
68  register.
69* `LLVM-EXEGESIS-LIVEIN <register name>` - This annotation allows specifying
70  registers that should keep their value upon starting the benchmark. Values
71  can be passed through registers from the benchmarking setup in some cases.
72  The registers and the values assigned to them that can be utilized in the
73  benchmarking script with a `LLVM-EXEGESIS-LIVEIN` are as follows:
74
75  * Scratch memory register - The specific register that this value is put in
76    is platform dependent (e.g., it is the RDI register on X86 Linux). Setting
77    this register as a live in ensures that a pointer to a block of memory (1MB)
78    is placed within this register that can be used by the snippet.
79* `LLVM-EXEGESIS-MEM-DEF <value name> <size> <value>` - This annotation allows
80  specifying memory definitions that can later be mapped into the execution
81  process of a snippet with the `LLVM-EXEGESIS-MEM-MAP` annotation. Each
82  value is named using the `<value name>` argument so that it can be referenced
83  later within a map annotation. The size is specified in a decimal number of
84  bytes and the value is given in hexadecimal. If the size of the value is less
85  than the specified size, the value will be repeated until it fills the entire
86  section of memory. Using this annotation requires using the subprocess execution
87  mode.
88* `LLVM-EXEGESIS-MEM-MAP <value name> <address>` - This annotation allows for
89  mapping previously defined memory definitions into the execution context of a
90  process. The value name refers to a previously defined memory definition and
91  the address is a decimal number that specifies the address the memory
92  definition should start at. Note that a single memory definition can be
93  mapped multiple times. Using this annotation requires the subprocess
94  execution mode.
95* `LLVM-EXEGESIS-SNIPPET-ADDRESS <address>` - This annotation allows for
96  setting the address where the beginning of the snippet to be executed will
97  be mapped in at. The address is given in hexadecimal. Note that the snippet
98  also includes setup code, so the instruction exactly at the specified
99  address will not be the first instruction in the snippet. Using this
100  annotation requires the subprocess execution mode. This is useful in
101  cases where the memory accessed by the snippet depends on the location
102  of the snippet, like RIP-relative addressing.
103* `LLVM-EXEGESIS-LOOP-REGISTER <register name>` - This annotation specifies
104  the loop register to use for keeping track of the current iteration when
105  using the loop repetition mode. :program:`llvm-exegesis` needs to keep track
106  of the current loop iteration within the loop repetition mode in a performant
107  manner (i.e., no memory accesses), and uses a register to do this. This register
108  has an architecture specific default (e.g., `R8` on X86), but this might conflict
109  with some snippets. This annotation allows changing the register to prevent
110  interference between the loop index register and the snippet.
111
112EXAMPLE 1: benchmarking instructions
113------------------------------------
114
115Assume you have an X86-64 machine. To measure the latency of a single
116instruction, run:
117
118.. code-block:: bash
119
120    $ llvm-exegesis --mode=latency --opcode-name=ADD64rr
121
122Measuring the uop decomposition or inverse throughput of an instruction works similarly:
123
124.. code-block:: bash
125
126    $ llvm-exegesis --mode=uops --opcode-name=ADD64rr
127    $ llvm-exegesis --mode=inverse_throughput --opcode-name=ADD64rr
128
129
130The output is a YAML document (the default is to write to stdout, but you can
131redirect the output to a file using `--benchmarks-file`):
132
133.. code-block:: none
134
135  ---
136  key:
137    opcode_name:     ADD64rr
138    mode:            latency
139    config:          ''
140  cpu_name:        haswell
141  llvm_triple:     x86_64-unknown-linux-gnu
142  num_repetitions: 10000
143  measurements:
144    - { key: latency, value: 1.0058, debug_string: '' }
145  error:           ''
146  info:            'explicit self cycles, selecting one aliasing configuration.
147  Snippet:
148  ADD64rr R8, R8, R10
149  '
150  ...
151
152To measure the latency of all instructions for the host architecture, run:
153
154.. code-block:: bash
155
156    $ llvm-exegesis --mode=latency --opcode-index=-1
157
158
159EXAMPLE 2: benchmarking a custom code snippet
160---------------------------------------------
161
162To measure the latency/uops of a custom piece of code, you can specify the
163`snippets-file` option (`-` reads from standard input).
164
165.. code-block:: bash
166
167    $ echo "vzeroupper" | llvm-exegesis --mode=uops --snippets-file=-
168
169Real-life code snippets typically depend on registers or memory.
170:program:`llvm-exegesis` checks the liveliness of registers (i.e. any register
171use has a corresponding def or is a "live in"). If your code depends on the
172value of some registers, you need to use snippet annotations to ensure setup
173is performed properly.
174
175For example, the following code snippet depends on the values of XMM1 (which
176will be set by the tool) and the memory buffer passed in RDI (live in).
177
178.. code-block:: none
179
180  # LLVM-EXEGESIS-LIVEIN RDI
181  # LLVM-EXEGESIS-DEFREG XMM1 42
182  vmulps	(%rdi), %xmm1, %xmm2
183  vhaddps	%xmm2, %xmm2, %xmm3
184  addq $0x10, %rdi
185
186
187Example 3: benchmarking with memory annotations
188-----------------------------------------------
189
190Some snippets require memory setup in specific places to execute without
191crashing. Setting up memory can be accomplished with the `LLVM-EXEGESIS-MEM-DEF`
192and `LLVM-EXEGESIS-MEM-MAP` annotations. To execute the following snippet:
193
194.. code-block:: none
195
196    movq $8192, %rax
197    movq (%rax), %rdi
198
199We need to have at least eight bytes of memory allocated starting `0x2000`.
200We can create the necessary execution environment with the following
201annotations added to the snippet:
202
203.. code-block:: none
204
205  # LLVM-EXEGESIS-MEM-DEF test1 4096 7fffffff
206  # LLVM-EXEGESIS-MEM-MAP test1 8192
207
208  movq $8192, %rax
209  movq (%rax), %rdi
210
211EXAMPLE 4: analysis
212-------------------
213
214Assuming you have a set of benchmarked instructions (either latency or uops) as
215YAML in file `/tmp/benchmarks.yaml`, you can analyze the results using the
216following command:
217
218.. code-block:: bash
219
220    $ llvm-exegesis --mode=analysis \
221  --benchmarks-file=/tmp/benchmarks.yaml \
222  --analysis-clusters-output-file=/tmp/clusters.csv \
223  --analysis-inconsistencies-output-file=/tmp/inconsistencies.html
224
225This will group the instructions into clusters with the same performance
226characteristics. The clusters will be written out to `/tmp/clusters.csv` in the
227following format:
228
229.. code-block:: none
230
231  cluster_id,opcode_name,config,sched_class
232  ...
233  2,ADD32ri8_DB,,WriteALU,1.00
234  2,ADD32ri_DB,,WriteALU,1.01
235  2,ADD32rr,,WriteALU,1.01
236  2,ADD32rr_DB,,WriteALU,1.00
237  2,ADD32rr_REV,,WriteALU,1.00
238  2,ADD64i32,,WriteALU,1.01
239  2,ADD64ri32,,WriteALU,1.01
240  2,MOVSX64rr32,,BSWAP32r_BSWAP64r_MOVSX64rr32,1.00
241  2,VPADDQYrr,,VPADDBYrr_VPADDDYrr_VPADDQYrr_VPADDWYrr_VPSUBBYrr_VPSUBDYrr_VPSUBQYrr_VPSUBWYrr,1.02
242  2,VPSUBQYrr,,VPADDBYrr_VPADDDYrr_VPADDQYrr_VPADDWYrr_VPSUBBYrr_VPSUBDYrr_VPSUBQYrr_VPSUBWYrr,1.01
243  2,ADD64ri8,,WriteALU,1.00
244  2,SETBr,,WriteSETCC,1.01
245  ...
246
247:program:`llvm-exegesis` will also analyze the clusters to point out
248inconsistencies in the scheduling information. The output is an html file. For
249example, `/tmp/inconsistencies.html` will contain messages like the following :
250
251.. image:: llvm-exegesis-analysis.png
252  :align: center
253
254Note that the scheduling class names will be resolved only when
255:program:`llvm-exegesis` is compiled in debug mode, else only the class id will
256be shown. This does not invalidate any of the analysis results though.
257
258OPTIONS
259-------
260
261.. option:: --help
262
263 Print a summary of command line options.
264
265.. option:: --opcode-index=<LLVM opcode index>
266
267 Specify the opcode to measure, by index. Specifying `-1` will result
268 in measuring every existing opcode. See example 1 for details.
269 Either `opcode-index`, `opcode-name` or `snippets-file` must be set.
270
271.. option:: --opcode-name=<opcode name 1>,<opcode name 2>,...
272
273 Specify the opcode to measure, by name. Several opcodes can be specified as
274 a comma-separated list. See example 1 for details.
275 Either `opcode-index`, `opcode-name` or `snippets-file` must be set.
276
277.. option:: --snippets-file=<filename>
278
279 Specify the custom code snippet to measure. See example 2 for details.
280 Either `opcode-index`, `opcode-name` or `snippets-file` must be set.
281
282.. option:: --mode=[latency|uops|inverse_throughput|analysis]
283
284 Specify the run mode. Note that some modes have additional requirements and options.
285
286 `latency` mode can be  make use of either RDTSC or LBR.
287 `latency[LBR]` is only available on X86 (at least `Skylake`).
288 To run in `latency` mode, a positive value must be specified
289 for `x86-lbr-sample-period` and `--repetition-mode=loop`.
290
291 In `analysis` mode, you also need to specify at least one of the
292 `-analysis-clusters-output-file=` and `-analysis-inconsistencies-output-file=`.
293
294.. option:: --benchmark-phase=[prepare-snippet|prepare-and-assemble-snippet|assemble-measured-code|measure]
295
296  By default, when `-mode=` is specified, the generated snippet will be executed
297  and measured, and that requires that we are running on the hardware for which
298  the snippet was generated, and that supports performance measurements.
299  However, it is possible to stop at some stage before measuring. Choices are:
300  * ``prepare-snippet``: Only generate the minimal instruction sequence.
301  * ``prepare-and-assemble-snippet``: Same as ``prepare-snippet``, but also dumps an excerpt of the sequence (hex encoded).
302  * ``assemble-measured-code``: Same as ``prepare-and-assemble-snippet``. but also creates the full sequence that can be dumped to a file using ``--dump-object-to-disk``.
303  * ``measure``: Same as ``assemble-measured-code``, but also runs the measurement.
304
305.. option:: --x86-lbr-sample-period=<nBranches/sample>
306
307  Specify the LBR sampling period - how many branches before we take a sample.
308  When a positive value is specified for this option and when the mode is `latency`,
309  we will use LBRs for measuring.
310  On choosing the "right" sampling period, a small value is preferred, but throttling
311  could occur if the sampling is too frequent. A prime number should be used to
312  avoid consistently skipping certain blocks.
313
314.. option:: --x86-disable-upper-sse-registers
315
316  Using the upper xmm registers (xmm8-xmm15) forces a longer instruction encoding
317  which may put greater pressure on the frontend fetch and decode stages,
318  potentially reducing the rate that instructions are dispatched to the backend,
319  particularly on older hardware. Comparing baseline results with this mode
320  enabled can help determine the effects of the frontend and can be used to
321  improve latency and throughput estimates.
322
323.. option:: --repetition-mode=[duplicate|loop|min|middle-half-duplicate|middle-half-loop]
324
325 Specify the repetition mode. `duplicate` will create a large, straight line
326 basic block with `min-instructions` instructions (repeating the snippet
327 `min-instructions`/`snippet size` times). `loop` will, optionally, duplicate the
328 snippet until the loop body contains at least `loop-body-size` instructions,
329 and then wrap the result in a loop which will execute `min-instructions`
330 instructions (thus, again, repeating the snippet
331 `min-instructions`/`snippet size` times). The `loop` mode, especially with loop
332 unrolling tends to better hide the effects of the CPU frontend on architectures
333 that cache decoded instructions, but consumes a register for counting
334 iterations. If performing an analysis over many opcodes, it may be best to
335 instead use the `min` mode, which will run each other mode,
336 and produce the minimal measured result. The middle half repetition modes
337 will either duplicate or run the snippet in a loop depending upon the specific
338 mode. The middle half repetition modes will run two benchmarks, one twice the
339 length of the first one, and then subtract the difference between them to get
340 values without overhead.
341
342.. option:: --min-instructions=<Number of instructions>
343
344 Specify the target number of executed instructions. Note that the actual
345 repetition count of the snippet will be `min-instructions`/`snippet size`.
346 Higher values lead to more accurate measurements but lengthen the benchmark.
347
348.. option:: --loop-body-size=<Preferred loop body size>
349
350 Only effective for `-repetition-mode=[loop|min]`.
351 Instead of looping over the snippet directly, first duplicate it so that the
352 loop body contains at least this many instructions. This potentially results
353 in loop body being cached in the CPU Op Cache / Loop Cache, which allows to
354 which may have higher throughput than the CPU decoders.
355
356.. option:: --max-configs-per-opcode=<value>
357
358 Specify the maximum configurations that can be generated for each opcode.
359 By default this is `1`, meaning that we assume that a single measurement is
360 enough to characterize an opcode. This might not be true of all instructions:
361 for example, the performance characteristics of the LEA instruction on X86
362 depends on the value of assigned registers and immediates. Setting a value of
363 `-max-configs-per-opcode` larger than `1` allows `llvm-exegesis` to explore
364 more configurations to discover if some register or immediate assignments
365 lead to different performance characteristics.
366
367
368.. option:: --benchmarks-file=</path/to/file>
369
370 File to read (`analysis` mode) or write (`latency`/`uops`/`inverse_throughput`
371 modes) benchmark results. "-" uses stdin/stdout.
372
373.. option:: --analysis-clusters-output-file=</path/to/file>
374
375 If provided, write the analysis clusters as CSV to this file. "-" prints to
376 stdout. By default, this analysis is not run.
377
378.. option:: --analysis-inconsistencies-output-file=</path/to/file>
379
380 If non-empty, write inconsistencies found during analysis to this file. `-`
381 prints to stdout. By default, this analysis is not run.
382
383.. option:: --analysis-filter=[all|reg-only|mem-only]
384
385 By default, all benchmark results are analysed, but sometimes it may be useful
386 to only look at those that to not involve memory, or vice versa. This option
387 allows to either keep all benchmarks, or filter out (ignore) either all the
388 ones that do involve memory (involve instructions that may read or write to
389 memory), or the opposite, to only keep such benchmarks.
390
391.. option:: --analysis-clustering=[dbscan,naive]
392
393 Specify the clustering algorithm to use. By default DBSCAN will be used.
394 Naive clustering algorithm is better for doing further work on the
395 `-analysis-inconsistencies-output-file=` output, it will create one cluster
396 per opcode, and check that the cluster is stable (all points are neighbours).
397
398.. option:: --analysis-numpoints=<dbscan numPoints parameter>
399
400 Specify the numPoints parameters to be used for DBSCAN clustering
401 (`analysis` mode, DBSCAN only).
402
403.. option:: --analysis-clustering-epsilon=<dbscan epsilon parameter>
404
405 Specify the epsilon parameter used for clustering of benchmark points
406 (`analysis` mode).
407
408.. option:: --analysis-inconsistency-epsilon=<epsilon>
409
410 Specify the epsilon parameter used for detection of when the cluster
411 is different from the LLVM schedule profile values (`analysis` mode).
412
413.. option:: --analysis-display-unstable-clusters
414
415 If there is more than one benchmark for an opcode, said benchmarks may end up
416 not being clustered into the same cluster if the measured performance
417 characteristics are different. by default all such opcodes are filtered out.
418 This flag will instead show only such unstable opcodes.
419
420.. option:: --ignore-invalid-sched-class=false
421
422 If set, ignore instructions that do not have a sched class (class idx = 0).
423
424.. option:: --mtriple=<triple name>
425
426 Target triple. See `-version` for available targets.
427
428.. option:: --mcpu=<cpu name>
429
430 If set, measure the cpu characteristics using the counters for this CPU. This
431 is useful when creating new sched models (the host CPU is unknown to LLVM).
432 (`-mcpu=help` for details)
433
434.. option:: --analysis-override-benchmark-triple-and-cpu
435
436  By default, llvm-exegesis will analyze the benchmarks for the triple/CPU they
437  were measured for, but if you want to analyze them for some other combination
438  (specified via `-mtriple`/`-mcpu`), you can pass this flag.
439
440.. option:: --dump-object-to-disk=true
441
442 If set,  llvm-exegesis will dump the generated code to a temporary file to
443 enable code inspection. Disabled by default.
444
445.. option:: --use-dummy-perf-counters
446
447 If set, llvm-exegesis will not read any real performance counters and
448 return a dummy value instead. This can be used to ensure a snippet doesn't
449 crash when hardware performance counters are unavailable and for
450 debugging :program:`llvm-exegesis` itself.
451
452.. option:: --execution-mode=[inprocess,subprocess]
453
454  This option specifies what execution mode to use. The `inprocess` execution
455  mode is the default. The `subprocess` execution mode allows for additional
456  features such as memory annotations but is currently restricted to X86-64
457  on Linux.
458
459.. option:: --benchmark-repeat-count=<repeat-count>
460
461  This option enables specifying the number of times to repeat the measurement
462  when performing latency measurements. By default, llvm-exegesis will repeat
463  a latency measurement enough times to balance run-time and noise reduction.
464
465.. option:: --validation-counter=[instructions-retired,l1d-cache-load-misses,
466   l1d-cache-store-misses,l1i-cache-load-misses,data-tlb-load-misses,
467   data-tld-store-misses,instruction-tlb-load-misses]
468
469   This option enables the use of validation counters, which measure additional
470   microarchitectural events like cache misses to validate snippet execution
471   conditions. These events are measured using the perf subsystem in a group
472   with the performance counter used to measure the value of interest. This
473   flag can be specified multiple times to measure multiple events. The maximum
474   number of validation counters is platform dependent.
475
476.. option:: --benchmark-process-cpu=<cpu id>
477
478  This option specifies the number of the CPU that should be used to run the
479  benchmarking subprocess. When starting the subprocess,
480  :program:`llvm-exegesis` will set the affinity of the subprocess to only
481  include the specified CPU. This option only works in the subprocess execution
482  mode.
483
484EXIT STATUS
485-----------
486
487:program:`llvm-exegesis` returns 0 on success. Otherwise, an error message is
488printed to standard error, and the tool returns a non 0 value.
489