1 llvm-mca - LLVM Machine Code Analyzer
2 =====================================
9 :program:`llvm-mca` [*options*] [input]
14 :program:`llvm-mca` is a performance analysis tool that uses information
15 available in LLVM (e.g. scheduling models) to statically measure the performance
16 of machine code in a specific CPU.
18 Performance is measured in terms of throughput as well as processor resource
19 consumption. The tool currently works for processors with an out-of-order
20 backend, for which there is a scheduling model available in LLVM.
22 The main goal of this tool is not just to predict the performance of the code
23 when run on the target, but also help with diagnosing potential performance
26 Given an assembly code sequence, :program:`llvm-mca` estimates the Instructions
27 Per Cycle (IPC), as well as hardware resource pressure. The analysis and
28 reporting style were inspired by the IACA tool from Intel.
30 For example, you can compile code with clang, output assembly, and pipe it
31 directly into :program:`llvm-mca` for analysis:
35 $ clang foo.c -O2 -target x86_64-unknown-unknown -S -o - | llvm-mca -mcpu=btver2
41 $ clang foo.c -O2 -target x86_64-unknown-unknown -mllvm -x86-asm-syntax=intel -S -o - | llvm-mca -mcpu=btver2
43 Scheduling models are not just used to compute instruction latencies and
44 throughput, but also to understand what processor resources are available
45 and how to simulate them.
47 By design, the quality of the analysis conducted by :program:`llvm-mca` is
48 inevitably affected by the quality of the scheduling models in LLVM.
50 If you see that the performance report is not accurate for a processor,
51 please `file a bug <https://bugs.llvm.org/enter_bug.cgi?product=libraries>`_
52 against the appropriate backend.
57 If ``input`` is "``-``" or omitted, :program:`llvm-mca` reads from standard
58 input. Otherwise, it will read from the specified filename.
60 If the :option:`-o` option is omitted, then :program:`llvm-mca` will send its output
61 to standard output if the input is from standard input. If the :option:`-o`
62 option specifies "``-``", then the output will also be sent to standard output.
67 Print a summary of command line options.
69 .. option:: -o <filename>
71 Use ``<filename>`` as the output filename. See the summary above for more
74 .. option:: -mtriple=<target triple>
76 Specify a target triple string.
78 .. option:: -march=<arch>
80 Specify the architecture for which to analyze the code. It defaults to the
83 .. option:: -mcpu=<cpuname>
85 Specify the processor for which to analyze the code. By default, the cpu name
86 is autodetected from the host.
88 .. option:: -output-asm-variant=<variant id>
90 Specify the output assembly variant for the report generated by the tool.
91 On x86, possible values are [0, 1]. A value of 0 (vic. 1) for this flag enables
92 the AT&T (vic. Intel) assembly format for the code printed out by the tool in
95 .. option:: -dispatch=<width>
97 Specify a different dispatch width for the processor. The dispatch width
98 defaults to field 'IssueWidth' in the processor scheduling model. If width is
99 zero, then the default dispatch width is used.
101 .. option:: -register-file-size=<size>
103 Specify the size of the register file. When specified, this flag limits how
104 many physical registers are available for register renaming purposes. A value
105 of zero for this flag means "unlimited number of physical registers".
107 .. option:: -iterations=<number of iterations>
109 Specify the number of iterations to run. If this flag is set to 0, then the
110 tool sets the number of iterations to a default value (i.e. 100).
112 .. option:: -noalias=<bool>
114 If set, the tool assumes that loads and stores don't alias. This is the
117 .. option:: -lqueue=<load queue size>
119 Specify the size of the load queue in the load/store unit emulated by the tool.
120 By default, the tool assumes an unbound number of entries in the load queue.
121 A value of zero for this flag is ignored, and the default load queue size is
124 .. option:: -squeue=<store queue size>
126 Specify the size of the store queue in the load/store unit emulated by the
127 tool. By default, the tool assumes an unbound number of entries in the store
128 queue. A value of zero for this flag is ignored, and the default store queue
129 size is used instead.
131 .. option:: -timeline
133 Enable the timeline view.
135 .. option:: -timeline-max-iterations=<iterations>
137 Limit the number of iterations to print in the timeline view. By default, the
138 timeline view prints information for up to 10 iterations.
140 .. option:: -timeline-max-cycles=<cycles>
142 Limit the number of cycles in the timeline view. By default, the number of
145 .. option:: -resource-pressure
147 Enable the resource pressure view. This is enabled by default.
149 .. option:: -register-file-stats
151 Enable register file usage statistics.
153 .. option:: -dispatch-stats
155 Enable extra dispatch statistics. This view collects and analyzes instruction
156 dispatch events, as well as static/dynamic dispatch stall events. This view
157 is disabled by default.
159 .. option:: -scheduler-stats
161 Enable extra scheduler statistics. This view collects and analyzes instruction
162 issue events. This view is disabled by default.
164 .. option:: -retire-stats
166 Enable extra retire control unit statistics. This view is disabled by default.
168 .. option:: -instruction-info
170 Enable the instruction info view. This is enabled by default.
172 .. option:: -all-stats
174 Print all hardware statistics. This enables extra statistics related to the
175 dispatch logic, the hardware schedulers, the register file(s), and the retire
176 control unit. This option is disabled by default.
178 .. option:: -all-views
182 .. option:: -instruction-tables
184 Prints resource pressure information based on the static information
185 available from the processor model. This differs from the resource pressure
186 view because it doesn't require that the code is simulated. It instead prints
187 the theoretical uniform distribution of resource pressure for every
188 instruction in sequence.
190 .. option:: -bottleneck-analysis
192 Print information about bottlenecks that affect the throughput. This analysis
193 can be expensive, and it is disabled by default. Bottlenecks are highlighted
200 :program:`llvm-mca` returns 0 on success. Otherwise, an error message is printed
201 to standard error, and the tool returns 1.
203 USING MARKERS TO ANALYZE SPECIFIC CODE BLOCKS
204 ---------------------------------------------
205 :program:`llvm-mca` allows for the optional usage of special code comments to
206 mark regions of the assembly code to be analyzed. A comment starting with
207 substring ``LLVM-MCA-BEGIN`` marks the beginning of a code region. A comment
208 starting with substring ``LLVM-MCA-END`` marks the end of a code region. For
217 If no user-defined region is specified, then :program:`llvm-mca` assumes a
218 default region which contains every instruction in the input file. Every region
219 is analyzed in isolation, and the final performance report is the union of all
220 the reports generated for every code region.
222 Code regions can have names. For example:
226 # LLVM-MCA-BEGIN A simple example
230 The code from the example above defines a region named "A simple example" with a
231 single instruction in it. Note how the region name doesn't have to be repeated
232 in the ``LLVM-MCA-END`` directive. In the absence of overlapping regions,
233 an anonymous ``LLVM-MCA-END`` directive always ends the currently active user
236 Example of nesting regions:
247 Example of overlapping regions:
259 Note that multiple anonymous regions cannot overlap. Also, overlapping regions
260 cannot have the same name.
262 There is no support for marking regions from high-level source code, like C or
263 C++. As a workaround, inline assembly directives may be used:
267 int foo(int a, int b) {
268 __asm volatile("# LLVM-MCA-BEGIN foo");
270 __asm volatile("# LLVM-MCA-END");
275 However, this interferes with optimizations like loop vectorization and may have
276 an impact on the code generated. This is because the ``__asm`` statements are
277 seen as real code having important side effects, which limits how the code
278 around them can be transformed. If users want to make use of inline assembly
279 to emit markers, then the recommendation is to always verify that the output
280 assembly is equivalent to the assembly generated in the absence of markers.
281 The `Clang options to emit optimization reports <https://clang.llvm.org/docs/UsersManual.html#options-to-emit-optimization-reports>`_
282 can also help in detecting missed optimizations.
287 :program:`llvm-mca` takes assembly code as input. The assembly code is parsed
288 into a sequence of MCInst with the help of the existing LLVM target assembly
289 parsers. The parsed sequence of MCInst is then analyzed by a ``Pipeline`` module
290 to generate a performance report.
292 The Pipeline module simulates the execution of the machine code sequence in a
293 loop of iterations (default is 100). During this process, the pipeline collects
294 a number of execution related statistics. At the end of this process, the
295 pipeline generates and prints a report from the collected statistics.
297 Here is an example of a performance report generated by the tool for a
298 dot-product of two packed float vectors of four elements. The analysis is
299 conducted for target x86, cpu btver2. The following result can be produced via
300 the following command using the example located at
301 ``test/tools/llvm-mca/X86/BtVer2/dot-product.s``:
305 $ llvm-mca -mtriple=x86_64-unknown-unknown -mcpu=btver2 -iterations=300 dot-product.s
317 Block RThroughput: 2.0
326 [6]: HasSideEffects (U)
328 [1] [2] [3] [4] [5] [6] Instructions:
329 1 2 1.00 vmulps %xmm0, %xmm1, %xmm2
330 1 3 1.00 vhaddps %xmm2, %xmm2, %xmm3
331 1 3 1.00 vhaddps %xmm3, %xmm3, %xmm4
351 Resource pressure per iteration:
352 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13]
353 - - - 2.00 1.00 2.00 1.00 - - - - - - -
355 Resource pressure by instruction:
356 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] Instructions:
357 - - - - 1.00 - 1.00 - - - - - - - vmulps %xmm0, %xmm1, %xmm2
358 - - - 1.00 - 1.00 - - - - - - - - vhaddps %xmm2, %xmm2, %xmm3
359 - - - 1.00 - 1.00 - - - - - - - - vhaddps %xmm3, %xmm3, %xmm4
361 According to this report, the dot-product kernel has been executed 300 times,
362 for a total of 900 simulated instructions. The total number of simulated micro
363 opcodes (uOps) is also 900.
365 The report is structured in three main sections. The first section collects a
366 few performance numbers; the goal of this section is to give a very quick
367 overview of the performance throughput. Important performance indicators are
368 **IPC**, **uOps Per Cycle**, and **Block RThroughput** (Block Reciprocal
371 IPC is computed dividing the total number of simulated instructions by the total
372 number of cycles. In the absence of loop-carried data dependencies, the
373 observed IPC tends to a theoretical maximum which can be computed by dividing
374 the number of instructions of a single iteration by the *Block RThroughput*.
376 Field 'uOps Per Cycle' is computed dividing the total number of simulated micro
377 opcodes by the total number of cycles. A delta between Dispatch Width and this
378 field is an indicator of a performance issue. In the absence of loop-carried
379 data dependencies, the observed 'uOps Per Cycle' should tend to a theoretical
380 maximum throughput which can be computed by dividing the number of uOps of a
381 single iteration by the *Block RThroughput*.
383 Field *uOps Per Cycle* is bounded from above by the dispatch width. That is
384 because the dispatch width limits the maximum size of a dispatch group. Both IPC
385 and 'uOps Per Cycle' are limited by the amount of hardware parallelism. The
386 availability of hardware resources affects the resource pressure distribution,
387 and it limits the number of instructions that can be executed in parallel every
388 cycle. A delta between Dispatch Width and the theoretical maximum uOps per
389 Cycle (computed by dividing the number of uOps of a single iteration by the
390 *Block RTrhoughput*) is an indicator of a performance bottleneck caused by the
391 lack of hardware resources.
392 In general, the lower the Block RThroughput, the better.
394 In this example, ``uOps per iteration/Block RThroughput`` is 1.50. Since there
395 are no loop-carried dependencies, the observed *uOps Per Cycle* is expected to
396 approach 1.50 when the number of iterations tends to infinity. The delta between
397 the Dispatch Width (2.00), and the theoretical maximum uOp throughput (1.50) is
398 an indicator of a performance bottleneck caused by the lack of hardware
399 resources, and the *Resource pressure view* can help to identify the problematic
402 The second section of the report shows the latency and reciprocal
403 throughput of every instruction in the sequence. That section also reports
404 extra information related to the number of micro opcodes, and opcode properties
405 (i.e., 'MayLoad', 'MayStore', and 'HasSideEffects').
407 The third section is the *Resource pressure view*. This view reports
408 the average number of resource cycles consumed every iteration by instructions
409 for every processor resource unit available on the target. Information is
410 structured in two tables. The first table reports the number of resource cycles
411 spent on average every iteration. The second table correlates the resource
412 cycles to the machine instruction in the sequence. For example, every iteration
413 of the instruction vmulps always executes on resource unit [6]
414 (JFPU1 - floating point pipeline #1), consuming an average of 1 resource cycle
415 per iteration. Note that on AMD Jaguar, vector floating-point multiply can
416 only be issued to pipeline JFPU1, while horizontal floating-point additions can
417 only be issued to pipeline JFPU0.
419 The resource pressure view helps with identifying bottlenecks caused by high
420 usage of specific hardware resources. Situations with resource pressure mainly
421 concentrated on a few resources should, in general, be avoided. Ideally,
422 pressure should be uniformly distributed between multiple resources.
426 The timeline view produces a detailed report of each instruction's state
427 transitions through an instruction pipeline. This view is enabled by the
428 command line option ``-timeline``. As instructions transition through the
429 various stages of the pipeline, their states are depicted in the view report.
430 These states are represented by the following characters:
432 * D : Instruction dispatched.
433 * e : Instruction executing.
434 * E : Instruction executed.
435 * R : Instruction retired.
436 * = : Instruction already dispatched, waiting to be executed.
437 * \- : Instruction executed, waiting to be retired.
439 Below is the timeline view for a subset of the dot-product example located in
440 ``test/tools/llvm-mca/X86/BtVer2/dot-product.s`` and processed by
441 :program:`llvm-mca` using the following command:
445 $ llvm-mca -mtriple=x86_64-unknown-unknown -mcpu=btver2 -iterations=3 -timeline dot-product.s
453 [0,0] DeeER. . . vmulps %xmm0, %xmm1, %xmm2
454 [0,1] D==eeeER . . vhaddps %xmm2, %xmm2, %xmm3
455 [0,2] .D====eeeER . vhaddps %xmm3, %xmm3, %xmm4
456 [1,0] .DeeE-----R . vmulps %xmm0, %xmm1, %xmm2
457 [1,1] . D=eeeE---R . vhaddps %xmm2, %xmm2, %xmm3
458 [1,2] . D====eeeER . vhaddps %xmm3, %xmm3, %xmm4
459 [2,0] . DeeE-----R . vmulps %xmm0, %xmm1, %xmm2
460 [2,1] . D====eeeER . vhaddps %xmm2, %xmm2, %xmm3
461 [2,2] . D======eeeER vhaddps %xmm3, %xmm3, %xmm4
464 Average Wait times (based on the timeline view):
466 [1]: Average time spent waiting in a scheduler's queue
467 [2]: Average time spent waiting in a scheduler's queue while ready
468 [3]: Average time elapsed from WB until retire stage
471 0. 3 1.0 1.0 3.3 vmulps %xmm0, %xmm1, %xmm2
472 1. 3 3.3 0.7 1.0 vhaddps %xmm2, %xmm2, %xmm3
473 2. 3 5.7 0.0 0.0 vhaddps %xmm3, %xmm3, %xmm4
475 The timeline view is interesting because it shows instruction state changes
476 during execution. It also gives an idea of how the tool processes instructions
477 executed on the target, and how their timing information might be calculated.
479 The timeline view is structured in two tables. The first table shows
480 instructions changing state over time (measured in cycles); the second table
481 (named *Average Wait times*) reports useful timing statistics, which should
482 help diagnose performance bottlenecks caused by long data dependencies and
483 sub-optimal usage of hardware resources.
485 An instruction in the timeline view is identified by a pair of indices, where
486 the first index identifies an iteration, and the second index is the
487 instruction index (i.e., where it appears in the code sequence). Since this
488 example was generated using 3 iterations: ``-iterations=3``, the iteration
489 indices range from 0-2 inclusively.
491 Excluding the first and last column, the remaining columns are in cycles.
492 Cycles are numbered sequentially starting from 0.
494 From the example output above, we know the following:
496 * Instruction [1,0] was dispatched at cycle 1.
497 * Instruction [1,0] started executing at cycle 2.
498 * Instruction [1,0] reached the write back stage at cycle 4.
499 * Instruction [1,0] was retired at cycle 10.
501 Instruction [1,0] (i.e., vmulps from iteration #1) does not have to wait in the
502 scheduler's queue for the operands to become available. By the time vmulps is
503 dispatched, operands are already available, and pipeline JFPU1 is ready to
504 serve another instruction. So the instruction can be immediately issued on the
505 JFPU1 pipeline. That is demonstrated by the fact that the instruction only
506 spent 1cy in the scheduler's queue.
508 There is a gap of 5 cycles between the write-back stage and the retire event.
509 That is because instructions must retire in program order, so [1,0] has to wait
510 for [0,2] to be retired first (i.e., it has to wait until cycle 10).
512 In the example, all instructions are in a RAW (Read After Write) dependency
513 chain. Register %xmm2 written by vmulps is immediately used by the first
514 vhaddps, and register %xmm3 written by the first vhaddps is used by the second
515 vhaddps. Long data dependencies negatively impact the ILP (Instruction Level
518 In the dot-product example, there are anti-dependencies introduced by
519 instructions from different iterations. However, those dependencies can be
520 removed at register renaming stage (at the cost of allocating register aliases,
521 and therefore consuming physical registers).
523 Table *Average Wait times* helps diagnose performance issues that are caused by
524 the presence of long latency instructions and potentially long data dependencies
525 which may limit the ILP. Note that :program:`llvm-mca`, by default, assumes at
526 least 1cy between the dispatch event and the issue event.
528 When the performance is limited by data dependencies and/or long latency
529 instructions, the number of cycles spent while in the *ready* state is expected
530 to be very small when compared with the total number of cycles spent in the
531 scheduler's queue. The difference between the two counters is a good indicator
532 of how large of an impact data dependencies had on the execution of the
533 instructions. When performance is mostly limited by the lack of hardware
534 resources, the delta between the two counters is small. However, the number of
535 cycles spent in the queue tends to be larger (i.e., more than 1-3cy),
536 especially when compared to other low latency instructions.
538 Extra Statistics to Further Diagnose Performance Issues
539 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
540 The ``-all-stats`` command line option enables extra statistics and performance
541 counters for the dispatch logic, the reorder buffer, the retire control unit,
542 and the register file.
544 Below is an example of ``-all-stats`` output generated by :program:`llvm-mca`
545 for 300 iterations of the dot-product example discussed in the previous
550 Dynamic Dispatch Stall Cycles:
551 RAT - Register unavailable: 0
552 RCU - Retire tokens unavailable: 0
553 SCHEDQ - Scheduler full: 272 (44.6%)
554 LQ - Load queue full: 0
555 SQ - Store queue full: 0
556 GROUP - Static restrictions on the dispatch group: 0
559 Dispatch Logic - number of cycles where we saw N micro opcodes dispatched:
560 [# dispatched], [# cycles]
566 Schedulers - number of cycles where we saw N micro opcodes issued:
567 [# issued], [# cycles]
572 Scheduler's queue usage:
574 [2] Average number of used buffer entries.
575 [3] Maximum number of used buffer entries.
576 [4] Total number of buffer entries.
584 Retire Control Unit - number of cycles where we saw N instructions retired:
585 [# retired], [# cycles]
590 Total ROB Entries: 64
591 Max Used ROB Entries: 35 ( 54.7% )
592 Average Used ROB Entries per cy: 32 ( 50.0% )
595 Register File statistics:
596 Total number of mappings created: 900
597 Max number of mappings used: 35
599 * Register File #1 -- JFpuPRF:
600 Number of physical registers: 72
601 Total number of mappings created: 900
602 Max number of mappings used: 35
604 * Register File #2 -- JIntegerPRF:
605 Number of physical registers: 64
606 Total number of mappings created: 0
607 Max number of mappings used: 0
609 If we look at the *Dynamic Dispatch Stall Cycles* table, we see the counter for
610 SCHEDQ reports 272 cycles. This counter is incremented every time the dispatch
611 logic is unable to dispatch a full group because the scheduler's queue is full.
613 Looking at the *Dispatch Logic* table, we see that the pipeline was only able to
614 dispatch two micro opcodes 51.5% of the time. The dispatch group was limited to
615 one micro opcode 44.6% of the cycles, which corresponds to 272 cycles. The
616 dispatch statistics are displayed by either using the command option
617 ``-all-stats`` or ``-dispatch-stats``.
619 The next table, *Schedulers*, presents a histogram displaying a count,
620 representing the number of micro opcodes issued on some number of cycles. In
621 this case, of the 610 simulated cycles, single opcodes were issued 306 times
622 (50.2%) and there were 7 cycles where no opcodes were issued.
624 The *Scheduler's queue usage* table shows that the average and maximum number of
625 buffer entries (i.e., scheduler queue entries) used at runtime. Resource JFPU01
626 reached its maximum (18 of 18 queue entries). Note that AMD Jaguar implements
629 * JALU01 - A scheduler for ALU instructions.
630 * JFPU01 - A scheduler floating point operations.
631 * JLSAGU - A scheduler for address generation.
633 The dot-product is a kernel of three floating point instructions (a vector
634 multiply followed by two horizontal adds). That explains why only the floating
635 point scheduler appears to be used.
637 A full scheduler queue is either caused by data dependency chains or by a
638 sub-optimal usage of hardware resources. Sometimes, resource pressure can be
639 mitigated by rewriting the kernel using different instructions that consume
640 different scheduler resources. Schedulers with a small queue are less resilient
641 to bottlenecks caused by the presence of long data dependencies. The scheduler
642 statistics are displayed by using the command option ``-all-stats`` or
643 ``-scheduler-stats``.
645 The next table, *Retire Control Unit*, presents a histogram displaying a count,
646 representing the number of instructions retired on some number of cycles. In
647 this case, of the 610 simulated cycles, two instructions were retired during the
648 same cycle 399 times (65.4%) and there were 109 cycles where no instructions
649 were retired. The retire statistics are displayed by using the command option
650 ``-all-stats`` or ``-retire-stats``.
652 The last table presented is *Register File statistics*. Each physical register
653 file (PRF) used by the pipeline is presented in this table. In the case of AMD
654 Jaguar, there are two register files, one for floating-point registers (JFpuPRF)
655 and one for integer registers (JIntegerPRF). The table shows that of the 900
656 instructions processed, there were 900 mappings created. Since this dot-product
657 example utilized only floating point registers, the JFPuPRF was responsible for
658 creating the 900 mappings. However, we see that the pipeline only used a
659 maximum of 35 of 72 available register slots at any given time. We can conclude
660 that the floating point PRF was the only register file used for the example, and
661 that it was never resource constrained. The register file statistics are
662 displayed by using the command option ``-all-stats`` or
663 ``-register-file-stats``.
665 In this example, we can conclude that the IPC is mostly limited by data
666 dependencies, and not by resource pressure.
670 This section describes the instruction flow through the default pipeline of
671 :program:`llvm-mca`, as well as the functional units involved in the process.
673 The default pipeline implements the following sequence of stages used to
674 process instructions.
676 * Dispatch (Instruction is dispatched to the schedulers).
677 * Issue (Instruction is issued to the processor pipelines).
678 * Write Back (Instruction is executed, and results are written back).
679 * Retire (Instruction is retired; writes are architecturally committed).
681 The default pipeline only models the out-of-order portion of a processor.
682 Therefore, the instruction fetch and decode stages are not modeled. Performance
683 bottlenecks in the frontend are not diagnosed. :program:`llvm-mca` assumes that
684 instructions have all been decoded and placed into a queue before the simulation
685 start. Also, :program:`llvm-mca` does not model branch prediction.
689 During the dispatch stage, instructions are picked in program order from a
690 queue of already decoded instructions, and dispatched in groups to the
691 simulated hardware schedulers.
693 The size of a dispatch group depends on the availability of the simulated
694 hardware resources. The processor dispatch width defaults to the value
695 of the ``IssueWidth`` in LLVM's scheduling model.
697 An instruction can be dispatched if:
699 * The size of the dispatch group is smaller than processor's dispatch width.
700 * There are enough entries in the reorder buffer.
701 * There are enough physical registers to do register renaming.
702 * The schedulers are not full.
704 Scheduling models can optionally specify which register files are available on
705 the processor. :program:`llvm-mca` uses that information to initialize register
706 file descriptors. Users can limit the number of physical registers that are
707 globally available for register renaming by using the command option
708 ``-register-file-size``. A value of zero for this option means *unbounded*. By
709 knowing how many registers are available for renaming, the tool can predict
710 dispatch stalls caused by the lack of physical registers.
712 The number of reorder buffer entries consumed by an instruction depends on the
713 number of micro-opcodes specified for that instruction by the target scheduling
714 model. The reorder buffer is responsible for tracking the progress of
715 instructions that are "in-flight", and retiring them in program order. The
716 number of entries in the reorder buffer defaults to the value specified by field
717 `MicroOpBufferSize` in the target scheduling model.
719 Instructions that are dispatched to the schedulers consume scheduler buffer
720 entries. :program:`llvm-mca` queries the scheduling model to determine the set
721 of buffered resources consumed by an instruction. Buffered resources are
722 treated like scheduler resources.
726 Each processor scheduler implements a buffer of instructions. An instruction
727 has to wait in the scheduler's buffer until input register operands become
728 available. Only at that point, does the instruction becomes eligible for
729 execution and may be issued (potentially out-of-order) for execution.
730 Instruction latencies are computed by :program:`llvm-mca` with the help of the
733 :program:`llvm-mca`'s scheduler is designed to simulate multiple processor
734 schedulers. The scheduler is responsible for tracking data dependencies, and
735 dynamically selecting which processor resources are consumed by instructions.
736 It delegates the management of processor resource units and resource groups to a
737 resource manager. The resource manager is responsible for selecting resource
738 units that are consumed by instructions. For example, if an instruction
739 consumes 1cy of a resource group, the resource manager selects one of the
740 available units from the group; by default, the resource manager uses a
741 round-robin selector to guarantee that resource usage is uniformly distributed
742 between all units of a group.
744 :program:`llvm-mca`'s scheduler internally groups instructions into three sets:
746 * WaitSet: a set of instructions whose operands are not ready.
747 * ReadySet: a set of instructions ready to execute.
748 * IssuedSet: a set of instructions executing.
750 Depending on the operands availability, instructions that are dispatched to the
751 scheduler are either placed into the WaitSet or into the ReadySet.
753 Every cycle, the scheduler checks if instructions can be moved from the WaitSet
754 to the ReadySet, and if instructions from the ReadySet can be issued to the
755 underlying pipelines. The algorithm prioritizes older instructions over younger
758 Write-Back and Retire Stage
759 """""""""""""""""""""""""""
760 Issued instructions are moved from the ReadySet to the IssuedSet. There,
761 instructions wait until they reach the write-back stage. At that point, they
762 get removed from the queue and the retire control unit is notified.
764 When instructions are executed, the retire control unit flags the instruction as
767 Instructions are retired in program order. The register file is notified of the
768 retirement so that it can free the physical registers that were allocated for
769 the instruction during the register renaming stage.
771 Load/Store Unit and Memory Consistency Model
772 """"""""""""""""""""""""""""""""""""""""""""
773 To simulate an out-of-order execution of memory operations, :program:`llvm-mca`
774 utilizes a simulated load/store unit (LSUnit) to simulate the speculative
775 execution of loads and stores.
777 Each load (or store) consumes an entry in the load (or store) queue. Users can
778 specify flags ``-lqueue`` and ``-squeue`` to limit the number of entries in the
779 load and store queues respectively. The queues are unbounded by default.
781 The LSUnit implements a relaxed consistency model for memory loads and stores.
784 1. A younger load is allowed to pass an older load only if there are no
785 intervening stores or barriers between the two loads.
786 2. A younger load is allowed to pass an older store provided that the load does
787 not alias with the store.
788 3. A younger store is not allowed to pass an older store.
789 4. A younger store is not allowed to pass an older load.
791 By default, the LSUnit optimistically assumes that loads do not alias
792 (`-noalias=true`) store operations. Under this assumption, younger loads are
793 always allowed to pass older stores. Essentially, the LSUnit does not attempt
794 to run any alias analysis to predict when loads and stores do not alias with
797 Note that, in the case of write-combining memory, rule 3 could be relaxed to
798 allow reordering of non-aliasing store operations. That being said, at the
799 moment, there is no way to further relax the memory model (``-noalias`` is the
800 only option). Essentially, there is no option to specify a different memory
801 type (e.g., write-back, write-combining, write-through; etc.) and consequently
802 to weaken, or strengthen, the memory model.
804 Other limitations are:
806 * The LSUnit does not know when store-to-load forwarding may occur.
807 * The LSUnit does not know anything about cache hierarchy and memory types.
808 * The LSUnit does not know how to identify serializing operations and memory
811 The LSUnit does not attempt to predict if a load or store hits or misses the L1
812 cache. It only knows if an instruction "MayLoad" and/or "MayStore." For
813 loads, the scheduling model provides an "optimistic" load-to-use latency (which
814 usually matches the load-to-use latency for when there is a hit in the L1D).
816 :program:`llvm-mca` does not know about serializing operations or memory-barrier
817 like instructions. The LSUnit conservatively assumes that an instruction which
818 has both "MayLoad" and unmodeled side effects behaves like a "soft"
819 load-barrier. That means, it serializes loads without forcing a flush of the
820 load queue. Similarly, instructions that "MayStore" and have unmodeled side
821 effects are treated like store barriers. A full memory barrier is a "MayLoad"
822 and "MayStore" instruction with unmodeled side effects. This is inaccurate, but
823 it is the best that we can do at the moment with the current information
826 A load/store barrier consumes one entry of the load/store queue. A load/store
827 barrier enforces ordering of loads/stores. A younger load cannot pass a load
828 barrier. Also, a younger store cannot pass a store barrier. A younger load
829 has to wait for the memory/load barrier to execute. A load/store barrier is
830 "executed" when it becomes the oldest entry in the load/store queue(s). That
831 also means, by construction, all of the older loads/stores have been executed.
833 In conclusion, the full set of load/store consistency rules are:
835 #. A store may not pass a previous store.
836 #. A store may not pass a previous load (regardless of ``-noalias``).
837 #. A store has to wait until an older store barrier is fully executed.
838 #. A load may pass a previous load.
839 #. A load may not pass a previous store unless ``-noalias`` is set.
840 #. A load has to wait until an older load barrier is fully executed.