| 1 |
.. _trace_optimizer: |
| 2 |
|
| 3 |
Trace Optimizer |
| 4 |
=============== |
| 5 |
|
| 6 |
Traces of user programs are not directly translated into machine code. |
| 7 |
The optimizer module implements several different semantic preserving |
| 8 |
transformations that either allow operations to be swept from the trace |
| 9 |
or convert them to operations that need less time or space. |
| 10 |
|
| 11 |
The optimizer is in `rpython/jit/metainterp/optimizeopt/`. |
| 12 |
When you try to make sense of this module, this page might get you started. |
| 13 |
|
| 14 |
Before some optimizations are explained in more detail, it is essential to |
| 15 |
understand how traces look like. |
| 16 |
The optimizer comes with a test suite. It contains many trace |
| 17 |
examples and you might want to take a look at it |
| 18 |
(in `rpython/jit/metainterp/optimizeopt/test/*.py`). |
| 19 |
The allowed operations can be found in `rpython/jit/metainterp/resoperation.py`. |
| 20 |
Here is an example of a trace:: |
| 21 |
|
| 22 |
[p0,i0,i1] |
| 23 |
label(p0, i0, i1) |
| 24 |
i2 = getarrayitem_raw(p0, i0, descr=<Array Signed>) |
| 25 |
i3 = int_add(i1,i2) |
| 26 |
i4 = int_add(i0,1) |
| 27 |
i5 = int_le(i4, 100) # lower-or-equal |
| 28 |
guard_true(i5) |
| 29 |
jump(p0, i4, i3) |
| 30 |
|
| 31 |
At the beginning it might be clumsy to read but it makes sense when you start |
| 32 |
to compare the Python code that constructed the trace:: |
| 33 |
|
| 34 |
from array import array |
| 35 |
a = array('i', range(101)) |
| 36 |
sum = 0; i = 0 |
| 37 |
while i <= 100: # can be seen as label |
| 38 |
sum += a[i] |
| 39 |
i += 1 |
| 40 |
# jumps back to the while header |
| 41 |
|
| 42 |
There are better ways to compute the sum from ``[0..100]``, but it gives a better intuition on how |
| 43 |
traces are constructed than ``sum(range(101))``. |
| 44 |
Note that the trace syntax is the one used in the test suite. It is also very |
| 45 |
similar to traces printed at runtime by :doc:`PYPYLOG <../logging>`. The first |
| 46 |
line gives the input variables, the second line is a ``label`` operation, the |
| 47 |
last one is the backwards ``jump`` operation. |
| 48 |
|
| 49 |
These instructions mentioned earlier are special: |
| 50 |
|
| 51 |
* the input defines the input parameter type and name to enter the trace. |
| 52 |
* ``label`` is the instruction a ``jump`` can target. Label instructions have |
| 53 |
a ``JitCellToken`` associated that uniquely identifies the label. Any jump |
| 54 |
has a target token of a label. |
| 55 |
|
| 56 |
The token is saved in a so called `descriptor` of the instruction. It is |
| 57 |
not written explicitly because it is not done in the tests either. But |
| 58 |
the test suite creates a dummy token for each trace and adds it as descriptor |
| 59 |
to ``label`` and ``jump``. Of course the optimizer does the same at runtime, |
| 60 |
but using real values. |
| 61 |
The sample trace includes a descriptor in ``getarrayitem_raw``. Here it |
| 62 |
annotates the type of the array. It is a signed integer array. |
| 63 |
|
| 64 |
High level overview |
| 65 |
------------------- |
| 66 |
|
| 67 |
Before the JIT backend transforms any trace into machine code, it tries to |
| 68 |
transform the trace into an equivalent trace that executes faster. The method |
| 69 |
`optimize_trace` in `rpython/jit/metainterp/optimizeopt/__init__.py` is the |
| 70 |
main entry point. |
| 71 |
|
| 72 |
Optimizations are applied in a sequence one after another and the base |
| 73 |
sequence is as follows:: |
| 74 |
|
| 75 |
intbounds:rewrite:virtualize:string:earlyforce:pure:heap:unroll |
| 76 |
|
| 77 |
Each of the colon-separated name has a class attached, inheriting from |
| 78 |
the `Optimization` class. The `Optimizer` class itself also |
| 79 |
derives from the `Optimization` class and implements the control logic for |
| 80 |
the optimization. Most of the optimizations only require a single forward pass. |
| 81 |
The trace is 'propagated' into each optimization using the method |
| 82 |
`propagate_forward`. Instruction by instruction, it flows from the |
| 83 |
first optimization to the last optimization. The method `emit_operation` |
| 84 |
is called for every operation that is passed to the next optimizer. |
| 85 |
|
| 86 |
The intbounds optimizations (which is mostly concerned with optimizing integer |
| 87 |
operations) is mostly implemented with a :doc:`rule-based pattern matching DSL |
| 88 |
<ruleopt>`. |
| 89 |
|
| 90 |
A frequently encountered pattern |
| 91 |
-------------------------------- |
| 92 |
|
| 93 |
To find potential optimization targets it is necessary to know the instruction |
| 94 |
type. Simple solution is to switch using the operation number (= type):: |
| 95 |
|
| 96 |
for op in operations: |
| 97 |
if op.getopnum() == rop.INT_ADD: |
| 98 |
# handle this instruction |
| 99 |
pass |
| 100 |
elif op.getopnum() == rop.INT_FLOOR_DIV: |
| 101 |
pass |
| 102 |
# and many more |
| 103 |
|
| 104 |
Things get worse if you start to match the arguments |
| 105 |
(is argument one constant and two variable or vice versa?). The pattern to tackle |
| 106 |
this code bloat is to move it to a separate method using |
| 107 |
`make_dispatcher_method`. It associates methods with instruction types:: |
| 108 |
|
| 109 |
class OptX(Optimization): |
| 110 |
def prefix_INT_ADD(self, op): |
| 111 |
pass # emit, transform, ... |
| 112 |
|
| 113 |
dispatch_opt = make_dispatcher_method(OptX, 'prefix_', |
| 114 |
default=OptX.emit_operation) |
| 115 |
OptX.propagate_forward = dispatch_opt |
| 116 |
|
| 117 |
optX = OptX() |
| 118 |
for op in operations: |
| 119 |
optX.propagate_forward(op) |
| 120 |
|
| 121 |
``propagate_forward`` searches for the method that is able to handle the instruction |
| 122 |
type. As an example `INT_ADD` will invoke `prefix_INT_ADD`. If there is no function |
| 123 |
for the instruction, it is routed to the default implementation (``emit_operation`` |
| 124 |
in this example). |
| 125 |
|
| 126 |
Rewrite optimization |
| 127 |
-------------------- |
| 128 |
|
| 129 |
The second optimization is called 'rewrite' and is commonly also known as |
| 130 |
strength reduction. A simple example would be that an integer multiplied |
| 131 |
by 2 is equivalent to the bits shifted to the left once |
| 132 |
(e.g. ``x * 2 == x << 1``). Not only strength reduction is done in this |
| 133 |
optimization but also boolean or arithmetic simplifications. Other examples |
| 134 |
would be: ``x & 0 == 0``, ``x - 0 == x`` |
| 135 |
|
| 136 |
Whenever such an operation is encountered (e.g. ``y = x & 0``), no operation is |
| 137 |
emitted. Instead the variable y is made equal to 0 |
| 138 |
(= ``make_constant_int(op, 0)``). The variables found in a trace are instances |
| 139 |
of classes that can be found in `rpython/jit/metainterp/history.py`. When a |
| 140 |
value is made equal to another, its box is made to point to the other one. |
| 141 |
|
| 142 |
|
| 143 |
Pure optimization |
| 144 |
----------------- |
| 145 |
|
| 146 |
The 'pure' optimizations interwoven into the basic optimizer. It saves |
| 147 |
operations, results, arguments to be known to have pure semantics. |
| 148 |
|
| 149 |
"Pure" here means the same as the ``jit.elidable`` decorator: |
| 150 |
free of "observable" side effects and referentially transparent |
| 151 |
(the operation can be replaced with its result without changing the program |
| 152 |
semantics). The operations marked as ALWAYS_PURE in `resoperation.py` are a |
| 153 |
subset of the NOSIDEEFFECT operations. Operations such as new, new array, |
| 154 |
getfield_(raw/gc) are marked as NOSIDEEFFECT but not as ALWAYS_PURE. |
| 155 |
|
| 156 |
Pure operations are optimized in two different ways. If their arguments |
| 157 |
are constants, the operation is removed and the result is turned into a |
| 158 |
constant. If not, we can still use a memoization technique: if, later, |
| 159 |
we see the same operation on the same arguments again, we don't need to |
| 160 |
recompute its result, but can simply reuse the previous operation's |
| 161 |
result. |
| 162 |
|
| 163 |
Unroll optimization |
| 164 |
------------------- |
| 165 |
|
| 166 |
A detailed description can be found the document |
| 167 |
`Loop-Aware Optimizations in PyPy's Tracing JIT`__ |
| 168 |
|
| 169 |
.. __: http://www2.maths.lth.se/matematiklth/vision/publdb/reports/pdf/ardo-bolz-etal-dls-12.pdf |
| 170 |
|
| 171 |
This optimization does not fall into the traditional scheme of one forward |
| 172 |
pass only. In a nutshell it unrolls the trace _once_, connects the two |
| 173 |
traces (by inserting parameters into the jump and label of the peeled trace) |
| 174 |
and uses information to iron out allocations, propagate constants and |
| 175 |
do any other optimization currently present in the 'optimizeopt' module. |
| 176 |
|
| 177 |
It is prepended to all optimizations and thus extends the Optimizer class |
| 178 |
and unrolls the loop once before it proceeds. |
| 179 |
|
| 180 |
Vectorization |
| 181 |
------------- |
| 182 |
|
| 183 |
- :doc:`Vectorization <vectorization>` |
| 184 |
|
| 185 |
What is missing from this document |
| 186 |
---------------------------------- |
| 187 |
|
| 188 |
* Guards are not explained |
| 189 |
* Several optimizations are not explained |
| 190 |
|
| 191 |
|
| 192 |
Further references |
| 193 |
------------------ |
| 194 |
|
| 195 |
* `Allocation Removal by Partial Evaluation in a Tracing JIT`__ |
| 196 |
* `Loop-Aware Optimizations in PyPy's Tracing JIT`__ |
| 197 |
|
| 198 |
.. __: http://www.stups.uni-duesseldorf.de/mediawiki/images/b/b0/Pub-BoCuFiLePeRi2011.pdf |
| 199 |
.. __: http://www2.maths.lth.se/matematiklth/vision/publdb/reports/pdf/ardo-bolz-etal-dls-12.pdf |