| 1 |
The RPython Toolchain |
| 2 |
===================== |
| 3 |
|
| 4 |
.. contents:: |
| 5 |
|
| 6 |
|
| 7 |
This document describes the toolchain that we have developed to analyze |
| 8 |
and "compile" RPython programs (like PyPy itself) to various target |
| 9 |
platforms. |
| 10 |
|
| 11 |
It consists of three broad sections: a slightly simplified overview, a |
| 12 |
brief introduction to each of the major components of our toolchain and |
| 13 |
then a more comprehensive section describing how the pieces fit together. |
| 14 |
If you are reading this document for the first time, the Overview_ is |
| 15 |
likely to be most useful, if you are trying to refresh your PyPy memory |
| 16 |
then the `How It Fits Together`_ is probably what you want. |
| 17 |
|
| 18 |
|
| 19 |
Overview |
| 20 |
-------- |
| 21 |
|
| 22 |
The job of the translation toolchain is to translate RPython programs into an |
| 23 |
efficient version of that program for one of various target platforms, |
| 24 |
generally one that is considerably lower-level than Python. It divides |
| 25 |
this task into several steps, and the purpose of this document is to |
| 26 |
introduce them. |
| 27 |
|
| 28 |
To start with we describe the process of translating an :ref:`RPython <language>` program into |
| 29 |
C (which is the default and original target). |
| 30 |
|
| 31 |
.. _initialization-time: |
| 32 |
|
| 33 |
The RPython translation toolchain never sees Python source code or syntax |
| 34 |
trees, but rather starts with the *code objects* that define the |
| 35 |
behaviour of the function objects one gives it as input. The |
| 36 |
:ref:`flow graph builder<flow-graphs>` works through these |
| 37 |
code objects using `abstract interpretation`_ to produce a control |
| 38 |
flow graph (one per function): yet another representation of the |
| 39 |
source program, but one which is suitable for applying type inference |
| 40 |
and translation techniques and which is the fundamental data structure |
| 41 |
most of the translation steps operate on. |
| 42 |
|
| 43 |
It is helpful to consider translation as being made up of the following |
| 44 |
steps (see also the figure below): |
| 45 |
|
| 46 |
1. The complete program is imported, at which time arbitrary run-time |
| 47 |
initialization can be performed. Once this is done, the program must |
| 48 |
be present in memory as a form that is "static enough" in the sense of |
| 49 |
:doc:`RPython <rpython>`. |
| 50 |
|
| 51 |
2. The Annotator_ performs a global analysis starting from a specified |
| 52 |
entry point to deduce type and other information about what each |
| 53 |
variable can contain at run-time, :ref:`building flow graphs <flow-graphs>` |
| 54 |
as it encounters them. |
| 55 |
|
| 56 |
3. The :ref:`RPython Typer <rtyper>` (or RTyper) uses the high-level |
| 57 |
information inferred by the Annotator to turn the operations in the control |
| 58 |
flow graphs into low-level operations. |
| 59 |
|
| 60 |
4. After the RTyper there are several optional `optimizations`_ which can be |
| 61 |
applied and are intended to make the resulting program go faster. |
| 62 |
|
| 63 |
5. The next step is `preparing the graphs for source generation`_, which |
| 64 |
involves computing the names that the various functions and types in |
| 65 |
the program will have in the final source and applying transformations |
| 66 |
which insert explicit exception handling and memory management |
| 67 |
operations. |
| 68 |
|
| 69 |
6. `The C backend`_ (colloquially known as "GenC") produces a number of C |
| 70 |
source files (as noted above, we are ignoring the other backends for |
| 71 |
now). |
| 72 |
|
| 73 |
7. These source files are compiled to produce an executable. |
| 74 |
|
| 75 |
(although these steps are not quite as distinct as you might think from |
| 76 |
this presentation). |
| 77 |
|
| 78 |
There is an :ref:`interactive interface <try-out-the-translator>` called :source:`rpython/bin/translatorshell.py` to the |
| 79 |
translation process which allows you to interactively work through these |
| 80 |
stages. |
| 81 |
|
| 82 |
The following figure gives a simplified overview (`PDF color version`_): |
| 83 |
|
| 84 |
.. image:: _static/translation-greyscale-small.png |
| 85 |
|
| 86 |
|
| 87 |
.. _PDF color version: _static/translation.pdf |
| 88 |
.. _abstract interpretation: http://en.wikipedia.org/wiki/Abstract_interpretation |
| 89 |
|
| 90 |
|
| 91 |
.. _flow-graphs: |
| 92 |
|
| 93 |
Building Flow Graphs |
| 94 |
-------------------- |
| 95 |
|
| 96 |
Introduction |
| 97 |
~~~~~~~~~~~~ |
| 98 |
|
| 99 |
The task of the flow graph builder (the source is at :source:`rpython/flowspace/`) |
| 100 |
is to generate a control-flow graph from a function. This graph will also |
| 101 |
contain a trace of the individual operations, so that it is actually just an |
| 102 |
alternate representation for the function. |
| 103 |
|
| 104 |
The basic idea is that if an interpreter is given a function, e.g.:: |
| 105 |
|
| 106 |
def f(n): |
| 107 |
return 3*n+2 |
| 108 |
|
| 109 |
it will compile it to bytecode and then execute it on its VM. |
| 110 |
Instead, the flow graph builder contains an `abstract interpreter`_ which takes the bytecode |
| 111 |
and performs whatever stack-shuffling and variable juggling is needed, but |
| 112 |
merely records any actual operation performed on a Python object into |
| 113 |
a structure called a basic block. The result of the operation is represented by a |
| 114 |
placeholder value that can appear in further operations. |
| 115 |
|
| 116 |
.. _abstract interpreter: http://en.wikipedia.org/wiki/Abstract_interpretation |
| 117 |
|
| 118 |
For example, if the placeholder ``v1`` is given as the argument to the above |
| 119 |
function, the bytecode interpreter will call ``v2 = space.mul(space.wrap(3), |
| 120 |
v1)`` and then ``v3 = space.add(v2, space.wrap(2))`` and return ``v3`` as the |
| 121 |
result. During these calls, the following block is recorded:: |
| 122 |
|
| 123 |
Block(v1): # input argument |
| 124 |
v2 = mul(Constant(3), v1) |
| 125 |
v3 = add(v2, Constant(2)) |
| 126 |
|
| 127 |
|
| 128 |
Abstract interpretation |
| 129 |
~~~~~~~~~~~~~~~~~~~~~~~ |
| 130 |
|
| 131 |
``build_flow()`` works by recording all operations issued by the bytecode |
| 132 |
interpreter into basic blocks. A basic block ends in one of two cases: when |
| 133 |
the bytecode interpreters calls ``is_true()``, or when a joinpoint is reached. |
| 134 |
|
| 135 |
* A joinpoint occurs when the next operation is about to be recorded into the |
| 136 |
current block, but there is already another block that records an operation |
| 137 |
for the same bytecode position. This means that the bytecode interpreter |
| 138 |
has closed a loop and is interpreting already-seen code again. In this |
| 139 |
situation, we interrupt the bytecode interpreter and we make a link from the |
| 140 |
end of the current block back to the previous block, thus closing the loop |
| 141 |
in the flow graph as well. (Note that this occurs only when an operation is |
| 142 |
about to be recorded, which allows some amount of constant-folding.) |
| 143 |
|
| 144 |
* If the bytecode interpreter calls ``is_true()``, the abstract interpreter doesn't |
| 145 |
generally know if the answer should be True or False, so it puts a |
| 146 |
conditional jump and generates two successor blocks for the current basic |
| 147 |
block. There is some trickery involved so that the bytecode interpreter is |
| 148 |
fooled into thinking that ``is_true()`` first returns False (and the |
| 149 |
subsequent operations are recorded in the first successor block), and later |
| 150 |
the *same* call to ``is_true()`` also returns True (and the subsequent |
| 151 |
operations go this time to the other successor block). |
| 152 |
|
| 153 |
(This section to be extended...) |
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
.. _flow-model: |
| 158 |
|
| 159 |
The Flow Model |
| 160 |
-------------- |
| 161 |
|
| 162 |
Here we describe the data structures produced by ``build_flow()``, which are |
| 163 |
the basic data structures of the translation process. |
| 164 |
|
| 165 |
All these types are defined in :source:`rpython/flowspace/model.py` (which is a |
| 166 |
rather important module in the PyPy source base, to reinforce the point). |
| 167 |
|
| 168 |
The flow graph of a function is represented by the class ``FunctionGraph``. |
| 169 |
It contains a reference to a collection of ``Block``\ s connected by ``Link``\ s. |
| 170 |
|
| 171 |
A ``Block`` contains a list of ``SpaceOperation``\ s. Each ``SpaceOperation`` |
| 172 |
has an ``opname`` and a list of ``args`` and ``result``, which are either |
| 173 |
``Variable``\ s or ``Constant``\ s. |
| 174 |
|
| 175 |
We have an extremely useful PyGame viewer, which allows you to visually |
| 176 |
inspect the graphs at various stages of the translation process (very |
| 177 |
useful to try to work out why things are breaking). It looks like this: |
| 178 |
|
| 179 |
.. image:: _static/bpnn_update.png |
| 180 |
|
| 181 |
It is recommended to play with ``python bin/translatorshell.py`` on a few |
| 182 |
examples to get an idea of the structure of flow graphs. The following describes |
| 183 |
the types and their attributes in some detail: |
| 184 |
|
| 185 |
|
| 186 |
``FunctionGraph`` |
| 187 |
A container for one graph (corresponding to one function). |
| 188 |
|
| 189 |
:startblock: the first block. It is where the control goes when the |
| 190 |
function is called. The input arguments of the startblock |
| 191 |
are the function's arguments. If the function takes a |
| 192 |
``*args`` argument, the ``args`` tuple is given as the last |
| 193 |
input argument of the startblock. |
| 194 |
|
| 195 |
:returnblock: the (unique) block that performs a function return. It is |
| 196 |
empty, not actually containing any ``return`` operation; the |
| 197 |
return is implicit. The returned value is the unique input |
| 198 |
variable of the returnblock. |
| 199 |
|
| 200 |
:exceptblock: the (unique) block that raises an exception out of the |
| 201 |
function. The two input variables are the exception class |
| 202 |
and the exception value, respectively. (No other block will |
| 203 |
actually link to the exceptblock if the function does not |
| 204 |
explicitly raise exceptions.) |
| 205 |
|
| 206 |
|
| 207 |
``Block`` |
| 208 |
A basic block, containing a list of operations and ending in jumps to other |
| 209 |
basic blocks. All the values that are "live" during the execution of the |
| 210 |
block are stored in Variables. Each basic block uses its own distinct |
| 211 |
Variables. |
| 212 |
|
| 213 |
:inputargs: list of fresh, distinct Variables that represent all the |
| 214 |
values that can enter this block from any of the previous |
| 215 |
blocks. |
| 216 |
|
| 217 |
:operations: list of SpaceOperations. |
| 218 |
:exitswitch: see below |
| 219 |
|
| 220 |
:exits: list of Links representing possible jumps from the end of this |
| 221 |
basic block to the beginning of other basic blocks. |
| 222 |
|
| 223 |
Each Block ends in one of the following ways: |
| 224 |
|
| 225 |
* unconditional jump: exitswitch is None, exits contains a single Link. |
| 226 |
|
| 227 |
* conditional jump: exitswitch is one of the Variables that appear in the |
| 228 |
Block, and exits contains one or more Links (usually 2). Each Link's |
| 229 |
exitcase gives a concrete value. This is the equivalent of a "switch": |
| 230 |
the control follows the Link whose exitcase matches the run-time value of |
| 231 |
the exitswitch Variable. It is a run-time error if the Variable doesn't |
| 232 |
match any exitcase. |
| 233 |
|
| 234 |
* exception catching: exitswitch is ``Constant(last_exception)``. The first |
| 235 |
Link has exitcase set to None and represents the non-exceptional path. |
| 236 |
The next Links have exitcase set to a subclass of Exception, and are taken |
| 237 |
when the *last* operation of the basic block raises a matching exception. |
| 238 |
(Thus the basic block must not be empty, and only the last operation is |
| 239 |
protected by the handler.) |
| 240 |
|
| 241 |
* return or except: the returnblock and the exceptblock have operations set |
| 242 |
to an empty tuple, exitswitch to None, and exits empty. |
| 243 |
|
| 244 |
|
| 245 |
``Link`` |
| 246 |
A link from one basic block to another. |
| 247 |
|
| 248 |
:prevblock: the Block that this Link is an exit of. |
| 249 |
|
| 250 |
:target: the target Block to which this Link points to. |
| 251 |
|
| 252 |
:args: a list of Variables and Constants, of the same size as the |
| 253 |
target Block's inputargs, which gives all the values passed |
| 254 |
into the next block. (Note that each Variable used in the |
| 255 |
prevblock may appear zero, one or more times in the ``args`` |
| 256 |
list.) |
| 257 |
|
| 258 |
:exitcase: see above. |
| 259 |
|
| 260 |
:last_exception: None or a Variable; see below. |
| 261 |
|
| 262 |
:last_exc_value: None or a Variable; see below. |
| 263 |
|
| 264 |
Note that ``args`` uses Variables from the prevblock, which are matched to |
| 265 |
the target block's ``inputargs`` by position, as in a tuple assignment or |
| 266 |
function call would do. |
| 267 |
|
| 268 |
If the link is an exception-catching one, the ``last_exception`` and |
| 269 |
``last_exc_value`` are set to two fresh Variables that are considered to be |
| 270 |
created when the link is entered; at run-time, they will hold the exception |
| 271 |
class and value, respectively. These two new variables can only be used in |
| 272 |
the same link's ``args`` list, to be passed to the next block (as usual, |
| 273 |
they may actually not appear at all, or appear several times in ``args``). |
| 274 |
|
| 275 |
|
| 276 |
``SpaceOperation`` |
| 277 |
A recorded (or otherwise generated) basic operation. |
| 278 |
|
| 279 |
:opname: the name of the operation. ``build_flow()`` produces only operations |
| 280 |
from the list in ``rpython.flowspace.operation``, but later the |
| 281 |
names can be changed arbitrarily. |
| 282 |
|
| 283 |
:args: list of arguments. Each one is a Constant or a Variable seen |
| 284 |
previously in the basic block. |
| 285 |
|
| 286 |
:result: a *new* Variable into which the result is to be stored. |
| 287 |
|
| 288 |
Note that operations usually cannot implicitly raise exceptions at run-time; |
| 289 |
so for example, code generators can assume that a ``getitem`` operation on a |
| 290 |
list is safe and can be performed without bound checking. The exceptions to |
| 291 |
this rule are: (1) if the operation is the last in the block, which ends |
| 292 |
with ``exitswitch == Constant(last_exception)``, then the implicit |
| 293 |
exceptions must be checked for, generated, and caught appropriately; (2) |
| 294 |
calls to other functions, as per ``simple_call`` or ``call_args``, can |
| 295 |
always raise whatever the called function can raise --- and such exceptions |
| 296 |
must be passed through to the parent unless they are caught as above. |
| 297 |
|
| 298 |
|
| 299 |
``Variable`` |
| 300 |
A placeholder for a run-time value. There is mostly debugging stuff here. |
| 301 |
|
| 302 |
:name: it is good style to use the Variable object itself instead of its |
| 303 |
``name`` attribute to reference a value, although the ``name`` is |
| 304 |
guaranteed unique. |
| 305 |
|
| 306 |
|
| 307 |
``Constant`` |
| 308 |
A constant value used as argument to a SpaceOperation, or as value to pass |
| 309 |
across a Link to initialize an input Variable in the target Block. |
| 310 |
|
| 311 |
:value: the concrete value represented by this Constant. |
| 312 |
:key: a hashable object representing the value. |
| 313 |
|
| 314 |
A Constant can occasionally store a mutable Python object. It represents a |
| 315 |
static, pre-initialized, read-only version of that object. The flow graph |
| 316 |
should not attempt to actually mutate such Constants. |
| 317 |
|
| 318 |
|
| 319 |
.. _annotator: |
| 320 |
|
| 321 |
The Annotation Pass |
| 322 |
------------------- |
| 323 |
|
| 324 |
We describe briefly below how a control flow graph can be "annotated" to |
| 325 |
discover the types of the objects. This annotation pass is a form of type |
| 326 |
inference. It operates on the control flow graphs built by the Flow |
| 327 |
Object Space. |
| 328 |
|
| 329 |
For a more comprehensive description of the annotation process, see the |
| 330 |
corresponding section of our `EU report about translation`_. |
| 331 |
|
| 332 |
The major goal of the annotator is to "annotate" each variable that |
| 333 |
appears in a flow graph. An "annotation" describes all the possible |
| 334 |
Python objects that this variable could contain at run-time, based on a |
| 335 |
whole-program analysis of all the flow graphs -- one per function. |
| 336 |
|
| 337 |
An "annotation" is an instance of a subclass of ``SomeObject``. Each |
| 338 |
subclass that represents a specific family of objects. |
| 339 |
|
| 340 |
Here is an overview (see ``pypy/annotation/model/``): |
| 341 |
|
| 342 |
* ``SomeObject`` is the base class. An instance of ``SomeObject()`` |
| 343 |
represents any Python object, and as such usually means that the input |
| 344 |
program was not fully RPython. |
| 345 |
|
| 346 |
* ``SomeInteger()`` represents any integer. ``SomeInteger(nonneg=True)`` |
| 347 |
represent a non-negative integer (``>=0``). |
| 348 |
|
| 349 |
* ``SomeString()`` represents any string; ``SomeChar()`` a string of |
| 350 |
length 1. |
| 351 |
|
| 352 |
* ``SomeTuple([s1,s2,..,sn])`` represents a tuple of length ``n``. The |
| 353 |
elements in this tuple are themselves constrained by the given list of |
| 354 |
annotations. For example, ``SomeTuple([SomeInteger(), SomeString()])`` |
| 355 |
represents a tuple with two items: an integer and a string. |
| 356 |
|
| 357 |
|
| 358 |
The result of the annotation pass is essentially a large dictionary |
| 359 |
mapping ``Variable``\ s to annotations. |
| 360 |
|
| 361 |
All the ``SomeXxx`` instances are immutable. If the annotator needs to |
| 362 |
revise its belief about what a Variable can contain, it does so creating a |
| 363 |
new annotation, not mutating the existing one. |
| 364 |
|
| 365 |
.. _EU report about translation: https://foss.heptapod.net/pypy/extradoc/-/tree/branch/extradoc/D05.1_Publish_on_translating_a_very-high-level_description.pdf |
| 366 |
|
| 367 |
|
| 368 |
Mutable Values and Containers |
| 369 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 370 |
|
| 371 |
Mutable objects need special treatment during annotation, because |
| 372 |
the annotation of contained values needs to be possibly updated to account |
| 373 |
for mutation operations, and consequently the annotation information |
| 374 |
reflown through the relevant parts of the flow graphs. |
| 375 |
|
| 376 |
* ``SomeList`` stands for a list of homogeneous type (i.e. all the |
| 377 |
elements of the list are represented by a single common ``SomeXxx`` |
| 378 |
annotation). |
| 379 |
|
| 380 |
* ``SomeDict`` stands for a homogeneous dictionary (i.e. all keys have |
| 381 |
the same ``SomeXxx`` annotation, and so have all values). |
| 382 |
|
| 383 |
|
| 384 |
User-defined Classes and Instances |
| 385 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 386 |
|
| 387 |
``SomeInstance`` stands for an instance of the given class or any |
| 388 |
subclass of it. For each user-defined class seen by the annotator, we |
| 389 |
maintain a ClassDef (``pypy.annotation.classdef``) describing the |
| 390 |
attributes of the instances of the class; essentially, a ClassDef gives |
| 391 |
the set of all class-level and instance-level attributes, and for each |
| 392 |
one, a corresponding ``SomeXxx`` annotation. |
| 393 |
|
| 394 |
Instance-level attributes are discovered progressively as the annotation |
| 395 |
progresses. Assignments like:: |
| 396 |
|
| 397 |
inst.attr = value |
| 398 |
|
| 399 |
update the ClassDef of the given instance to record that the given |
| 400 |
attribute exists and can be as general as the given value. |
| 401 |
|
| 402 |
For every attribute, the ClassDef also records all the positions where |
| 403 |
the attribute is *read*. If, at some later time, we discover an |
| 404 |
assignment that forces the annotation about the attribute to be |
| 405 |
generalized, then all the places that read the attribute so far are |
| 406 |
marked as invalid and the annotator will restart its analysis |
| 407 |
from there. |
| 408 |
|
| 409 |
The distinction between instance-level and class-level attributes is |
| 410 |
thin; class-level attributes are essentially considered as initial |
| 411 |
values for instance-level attributes. Methods are not special in this |
| 412 |
respect, except that they are bound to the instance (i.e. ``self = |
| 413 |
SomeInstance(cls)``) when considered as the initial value for the |
| 414 |
instance. |
| 415 |
|
| 416 |
The inheritance rules are as follows: the union of two ``SomeInstance`` |
| 417 |
annotations is the ``SomeInstance`` of the most precise common base |
| 418 |
class. If an attribute is considered (i.e. read or written) through a |
| 419 |
``SomeInstance`` of a parent class, then we assume that all subclasses |
| 420 |
also have the same attribute, and that the same annotation applies to |
| 421 |
them all (so code like ``return self.x`` in a method of a parent class |
| 422 |
forces the parent class and all its subclasses to have an attribute |
| 423 |
``x``, whose annotation is general enough to contain all the values that |
| 424 |
all the subclasses might want to store in ``x``). However, distinct |
| 425 |
subclasses can have attributes of the same names with different, |
| 426 |
unrelated annotations if they are not used in a general way through the |
| 427 |
parent class. |
| 428 |
|
| 429 |
|
| 430 |
The RPython Typer |
| 431 |
----------------- |
| 432 |
|
| 433 |
See :doc:`rtyper`. |
| 434 |
|
| 435 |
|
| 436 |
.. _optimizations: |
| 437 |
|
| 438 |
Backend Optimizations |
| 439 |
--------------------- |
| 440 |
|
| 441 |
The point of the backend optimizations are to make the compiled program run |
| 442 |
faster. Compared to many parts of the PyPy translator, which are very unlike |
| 443 |
a traditional compiler, most of these will be fairly familiar to people who |
| 444 |
know how compilers work. |
| 445 |
|
| 446 |
|
| 447 |
Function Inlining |
| 448 |
~~~~~~~~~~~~~~~~~ |
| 449 |
|
| 450 |
To reduce the overhead of the many function calls that occur when running the |
| 451 |
PyPy interpreter we implemented function inlining. This is an optimization |
| 452 |
which takes a flow graph and a callsite and inserts a copy of the flow graph |
| 453 |
into the graph of the calling function, renaming occurring variables as |
| 454 |
appropriate. This leads to problems if the original function was surrounded by |
| 455 |
a ``try: ... except: ...`` guard. In this case inlining is not always |
| 456 |
possible. If the called function is not directly raising an exception (but an |
| 457 |
exception is potentially raised by further called functions) inlining is safe, |
| 458 |
though. |
| 459 |
|
| 460 |
In addition we also implemented heuristics which function to inline where. For |
| 461 |
this purpose we assign every function a "size". This size should roughly |
| 462 |
correspond to the increase in code-size which is to be expected should the |
| 463 |
function be inlined somewhere. This estimate is the sum of two numbers: for |
| 464 |
one every operations is assigned a specific weight, the default being a weight |
| 465 |
of one. Some operations are considered to be more effort than others, |
| 466 |
e.g. memory allocation and calls; others are considered to be no effort at all |
| 467 |
(casts...). The size estimate is for one the sum of the weights of all |
| 468 |
operations occurring in the graph. This is called the "static instruction |
| 469 |
count". The other part of the size estimate of a graph is the "median |
| 470 |
execution cost". This is again the sum of the weight of all operations in the |
| 471 |
graph, but this time weighted with a guess how often the operation is |
| 472 |
executed. To arrive at this guess we assume that at every branch we take both |
| 473 |
paths equally often, except for branches that are the end of loops, where the |
| 474 |
jump back to the end of the loop is considered more likely. This leads to a |
| 475 |
system of equations which can be solved to get approximate weights for all |
| 476 |
operations. |
| 477 |
|
| 478 |
After the size estimate for all function has been determined, functions are |
| 479 |
being inlined into their callsites, starting from the smallest functions. Every |
| 480 |
time a function is being inlined into another function, the size of the outer |
| 481 |
function is recalculated. This is done until the remaining functions all have a |
| 482 |
size greater than a predefined limit. |
| 483 |
|
| 484 |
|
| 485 |
Malloc Removal |
| 486 |
~~~~~~~~~~~~~~ |
| 487 |
|
| 488 |
Since RPython is a garbage collected language there is a lot of heap memory |
| 489 |
allocation going on all the time, which would either not occur at all in a more |
| 490 |
traditional explicitly managed language or results in an object which dies at |
| 491 |
a time known in advance and can thus be explicitly deallocated. For example a |
| 492 |
loop of the following form:: |
| 493 |
|
| 494 |
for i in range(n): |
| 495 |
... |
| 496 |
|
| 497 |
which simply iterates over all numbers from 0 to n - 1 is equivalent to the |
| 498 |
following in Python:: |
| 499 |
|
| 500 |
l = range(n) |
| 501 |
iterator = iter(l) |
| 502 |
try: |
| 503 |
while 1: |
| 504 |
i = iterator.next() |
| 505 |
... |
| 506 |
except StopIteration: |
| 507 |
pass |
| 508 |
|
| 509 |
Which means that three memory allocations are executed: The range object, the |
| 510 |
iterator for the range object and the StopIteration instance, which ends the |
| 511 |
loop. |
| 512 |
|
| 513 |
After a small bit of inlining all these three objects are never even passed as |
| 514 |
arguments to another function and are also not stored into a globally reachable |
| 515 |
position. In such a situation the object can be removed (since it would die |
| 516 |
anyway after the function returns) and can be replaced by its contained values. |
| 517 |
|
| 518 |
This pattern (an allocated object never leaves the current function and thus |
| 519 |
dies after the function returns) occurs quite often, especially after some |
| 520 |
inlining has happened. Therefore we implemented an optimization which |
| 521 |
"explodes" objects and thus saves one allocation in this simple (but quite |
| 522 |
common) situation. |
| 523 |
|
| 524 |
|
| 525 |
Escape Analysis and Stack Allocation |
| 526 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 527 |
|
| 528 |
Another technique to reduce the memory allocation penalty is to use stack |
| 529 |
allocation for objects that can be proved not to life longer than the stack |
| 530 |
frame they have been allocated in. This proved not to really gain us any |
| 531 |
speed, so over time it was removed again. |
| 532 |
|
| 533 |
|
| 534 |
.. _preparing the graphs for source generation: |
| 535 |
|
| 536 |
Preparation for Source Generation |
| 537 |
--------------------------------- |
| 538 |
|
| 539 |
This, perhaps slightly vaguely named, stage is the most recent to appear as a |
| 540 |
separate step. Its job is to make the final implementation decisions before |
| 541 |
source generation -- experience has shown that you really don't want to be |
| 542 |
doing *any* thinking at the same time as actually generating source code. For |
| 543 |
the C backend, this step does three things: |
| 544 |
|
| 545 |
- inserts explicit exception handling, |
| 546 |
|
| 547 |
- inserts explicit memory management operations, |
| 548 |
|
| 549 |
- decides on the names functions and types will have in the final |
| 550 |
source (this mapping of objects to names is sometimes referred to as |
| 551 |
the "low-level database"). |
| 552 |
|
| 553 |
|
| 554 |
Making Exception Handling Explicit |
| 555 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 556 |
|
| 557 |
RPython code is free to use exceptions in much the same way as unrestricted |
| 558 |
Python, but the final result is a C program, and C has no concept of |
| 559 |
exceptions. The exception transformer implements exception handling in a |
| 560 |
similar way to CPython: exceptions are indicated by special return values and |
| 561 |
the current exception is stored in a global data structure. |
| 562 |
|
| 563 |
In a sense the input to the exception transformer is a program in terms of the |
| 564 |
:term:`lltypesystem` with exceptions and the output is a program in terms of the bare |
| 565 |
lltypesystem. |
| 566 |
|
| 567 |
|
| 568 |
Memory Management Details |
| 569 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 570 |
|
| 571 |
As well as featuring exceptions, RPython is a garbage collected language; |
| 572 |
again, C is not. To square this circle, decisions about memory management |
| 573 |
must be made. In keeping with PyPy's approach to flexibility, there is |
| 574 |
freedom to change how to do it. There are three approaches implemented today: |
| 575 |
|
| 576 |
- reference counting (deprecated, too slow) |
| 577 |
- using the `Boehm-Demers-Weiser conservative garbage collector`_ |
| 578 |
- using one of our custom :doc:`exact GCs implemented in RPython <garbage_collection>` |
| 579 |
|
| 580 |
.. _Boehm-Demers-Weiser conservative garbage collector: http://hboehm.info/gc/ |
| 581 |
|
| 582 |
Almost all application-level Python code allocates objects at a very fast |
| 583 |
rate; this means that the memory management implementation is critical to the |
| 584 |
performance of the PyPy interpreter. |
| 585 |
|
| 586 |
|
| 587 |
.. _genc: |
| 588 |
|
| 589 |
The C Backend |
| 590 |
-------------- |
| 591 |
|
| 592 |
:source:`rpython/translator/c/` |
| 593 |
|
| 594 |
This is currently the sole code generation backend. |
| 595 |
|
| 596 |
|
| 597 |
A Historical Note |
| 598 |
----------------- |
| 599 |
|
| 600 |
As this document has shown, the translation step is divided into more |
| 601 |
steps than one might at first expect. It is certainly divided into more |
| 602 |
steps than we expected when the project started; the very first version of |
| 603 |
GenC operated on the high-level flow graphs and the output of the |
| 604 |
annotator, and even the concept of the RTyper didn't exist yet. More |
| 605 |
recently, the fact that preparing the graphs for source generation |
| 606 |
("databasing") and actually generating the source are best considered |
| 607 |
separately has become clear. |
| 608 |
|
| 609 |
|
| 610 |
How It Fits Together |
| 611 |
-------------------- |
| 612 |
|
| 613 |
As should be clear by now, the translation toolchain of PyPy is a flexible |
| 614 |
and complicated beast, formed from many separate components. |
| 615 |
|
| 616 |
.. digraph:: translation |
| 617 |
|
| 618 |
graph [fontname = "Sans-Serif", size="6.00"] |
| 619 |
node [fontname = "Sans-Serif"] |
| 620 |
edge [fontname = "Sans-Serif"] |
| 621 |
|
| 622 |
subgraph legend { |
| 623 |
"Input or Output" [shape=ellipse, style=filled] |
| 624 |
"Transformation Step" [shape=box, style="rounded,filled"] |
| 625 |
// Invisible edge to make sure they are placed vertically |
| 626 |
"Input or Output" -> "Transformation Step" [style=invis] |
| 627 |
} |
| 628 |
|
| 629 |
"Input Program" [shape=ellipse] |
| 630 |
"Flow Analysis" [shape=box, style=rounded] |
| 631 |
"Annotator" [shape=box, style=rounded] |
| 632 |
"RTyper" [shape=box, style=rounded] |
| 633 |
"Backend Optimizations (optional)" [shape=box, style=rounded] |
| 634 |
"Exception Transformer" [shape=box, style=rounded] |
| 635 |
"GC Transformer" [shape=box, style=rounded] |
| 636 |
"GenC" [shape=box, style=rounded] |
| 637 |
"ANSI C code" [shape=ellipse] |
| 638 |
|
| 639 |
"Input Program" -> "Flow Analysis" -> "Annotator" -> "RTyper" |
| 640 |
-> "Backend Optimizations (optional)" -> "Exception Transformer" |
| 641 |
-> "GC Transformer" |
| 642 |
"RTyper" -> "Exception Transformer" [style=dotted] |
| 643 |
"GC Transformer" -> "GenC" -> "ANSI C code" |
| 644 |
// "GC Transformer" -> "GenLLVM" -> "LLVM IR" |
| 645 |
|
| 646 |
A detail that has not yet been emphasized is the interaction of the |
| 647 |
various components. It makes for a nice presentation to say that |
| 648 |
after the annotator has finished the RTyper processes the graphs and |
| 649 |
then the exception handling is made explicit and so on, but it's not |
| 650 |
entirely true. For example, the RTyper inserts calls to many |
| 651 |
:term:`low-level helper`\ s which must first be annotated, and the GC |
| 652 |
transformer can use inlining (one of the `backend optimizations`_) of |
| 653 |
some of its small helper functions to improve performance. The |
| 654 |
following picture attempts to summarize the components involved in |
| 655 |
performing each step of the default translation process: |
| 656 |
|
| 657 |
.. image:: _static/translation-detail-0.9.png |
| 658 |
:align: center |
| 659 |
|
| 660 |
A component not mentioned before is the "MixLevelAnnotator"; it |
| 661 |
provides a convenient interface for a "late" (after RTyping) |
| 662 |
translation step to declare that it needs to be able to call each of a |
| 663 |
collection of functions (which may refer to each other in a mutually |
| 664 |
recursive fashion) and annotate and rtype them all at once. |