Debian Codegraph @

rpython/doc/rtyper.rst

raw
1 .. _rtyper:
2
3 The RPython Typer
4 =================
5
6 .. contents::
7
8
9 The RPython Typer lives in the directory :source:`rpython/rtyper/`.
10
11
12 Overview
13 --------
14
15 The RPython Typer is the bridge between the :ref:`Annotator <annotator>` and
16 the code generators. The annotations of the :ref:`Annotator <annotator>` are
17 high-level, in the sense that they describe RPython types like lists or
18 instances of user-defined classes.
19
20 To emit code we need to represent these high-level annotations in the low-level
21 model of the target language; for C, this means structures and pointers and
22 arrays. The Typer both determines the appropriate low-level type for each
23 annotation and replaces each high-level operation in the control flow graphs
24 with one or a few low-level operations. Just like low-level types, there is
25 only a fairly restricted set of low-level operations, along the lines of
26 reading or writing from or to a field of a structure.
27
28 In theory, this step is optional; a code generator might be able to read the
29 high-level types directly. Our experience, however, suggests that this is very
30 unlikely to be practical. "Compiling" high-level types into low-level ones is
31 rather more messy than one would expect. This was the motivation for making
32 this step explicit and isolated in a single place. After RTyping, the graphs
33 only contain operations that already live on the level of the target language,
34 making the job of the code generators much simpler.
35
36
37 Example: Integer operations
38 ---------------------------
39
40 Integer operations are the easiest. Assume a graph containing the following
41 operation::
42
43 v3 = add(v1, v2)
44
45 annotated::
46
47 v1 -> SomeInteger()
48 v2 -> SomeInteger()
49 v3 -> SomeInteger()
50
51 then obviously we want to type it and replace it with::
52
53 v3 = int_add(v1, v2)
54
55 where -- in C notation -- all three variables v1, v2 and v3 are typed ``int``.
56 This is done by attaching an attribute ``concretetype`` to v1, v2 and v3
57 (which might be instances of Variable or possibly Constant). In our model,
58 this ``concretetype`` is ``rpython.rtyper.lltypesystem.lltype.Signed``. Of
59 course, the purpose of replacing the operation called ``add`` with
60 ``int_add`` is that code generators no longer have to worry about what kind
61 of addition (or concatenation maybe?) it means.
62
63
64 The process in more details
65 ---------------------------
66
67 The RPython Typer has a structure similar to that of the :ref:`Annotator <annotator>` both
68 consider each block of the flow graphs in turn, and perform some analysis on
69 each operation. In both cases the analysis of an operation depends on the
70 annotations of its input arguments. This is reflected in the usage of the same
71 ``__extend__`` syntax in the source files (compare e.g.
72 :source:`rpython/annotator/binaryop.py` and :source:`rpython/rtyper/rint.py`).
73
74 The analogy stops here, though: while it runs, the Annotator is in the middle
75 of computing the annotations, so it might need to reflow and generalize until
76 a fixpoint is reached. The Typer, by contrast, works on the final annotations
77 that the Annotator computed, without changing them, assuming that they are
78 globally consistent. There is no need to reflow: the Typer considers each
79 block only once. And unlike the Annotator, the Typer completely modifies the
80 flow graph, by replacing each operation with some low-level operations.
81
82 In addition to replacing operations, the RTyper creates a ``concretetype``
83 attribute on all Variables and Constants in the flow graphs, which tells code
84 generators which type to use for each of them. This attribute is a
85 :ref:`low-level type <low-level-types>`, as described below.
86
87
88 Representations
89 ---------------
90
91 Representations -- the Repr classes -- are the most important internal classes
92 used by the RTyper. (They are internal in the sense that they are an
93 "implementation detail" and their instances just go away after the RTyper is
94 finished; the code generators should only use the ``concretetype`` attributes,
95 which are not Repr instances but `low-level types`_.)
96
97 A representation contains all the logic about mapping a specific SomeXxx()
98 annotation to a specific low-level type. For the time being, the RTyper
99 assumes that each SomeXxx() instance needs only one "canonical" representation.
100 For example, all variables annotated with SomeInteger() will correspond to the
101 ``Signed`` low-level type via the ``IntegerRepr`` representation. More subtly,
102 variables annotated SomeList() can correspond either to a structure holding an
103 array of items of the correct type, or -- if the list in question is just a
104 range() with a constant step -- a structure with just start and stop fields.
105
106 This example shows that two representations may need very different low-level
107 implementations for the same high-level operations. This is the reason for
108 turning representations into explicit objects.
109
110 The base Repr class is defined in :source:`rpython/rtyper/rmodel.py`. Most of the
111 :source:`rpython/`\ ``r*.py`` files define one or a few subclasses of Repr. The method
112 getrepr() of the RTyper will build and cache a single Repr instance per
113 SomeXxx() instance; moreover, two SomeXxx() instances that are equal get the
114 same Repr instance.
115
116 The key attribute of a Repr instance is called ``lowleveltype``, which is what
117 gets copied into the attribute ``concretetype`` of the Variables that have been
118 given this representation. The RTyper also computes a ``concretetype`` for
119 Constants, to match the way they are used in the low-level operations (for
120 example, ``int_add(x, 1)`` requires a ``Constant(1)`` with
121 ``concretetype=Signed``).
122
123 In addition to ``lowleveltype``, each Repr subclass provides a set of methods
124 called ``rtype_op_xxx()`` which define how each high-level operation ``op_xxx``
125 is turned into low-level operations.
126
127
128 .. _low-level-types:
129
130 Low-Level Types
131 ---------------
132
133 The RPython Typer uses a standard low-level model which we believe can
134 correspond rather directly to various target languages such as C.
135 This model is implemented in the first part of
136 :source:`rpython/rtyper/lltypesystem/lltype.py`.
137
138 The second part of :source:`rpython/rtyper/lltypesystem/lltype.py` is a runnable
139 implementation of these types, for testing purposes. It allows us to write
140 and test plain Python code using a malloc() function to obtain and manipulate
141 structures and arrays. This is useful for example to implement and test
142 RPython types like 'list' with its operations and methods.
143
144 The basic assumption is that Variables (i.e. local variables and function
145 arguments and return value) all contain "simple" values: basically, just
146 integers or pointers. All the "container" data structures (struct and array)
147 are allocated in the heap, and they are always manipulated via pointers.
148 (There is no equivalent to the C notion of local variable of a ``struct`` type.)
149
150 Here is a quick tour:
151
152 >>> from rpython.rtyper.lltypesystem.lltype import *
153
154 Here are a few primitive low-level types, and the typeOf() function to figure
155 them out:
156
157 >>> Signed
158 <Signed>
159 >>> typeOf(5)
160 <Signed>
161 >>> typeOf(r_uint(12))
162 <Unsigned>
163 >>> typeOf('x')
164 <Char>
165
166 Let's say that we want to build a type "point", which is a structure with two
167 integer fields "x" and "y":
168
169 >>> POINT = GcStruct('point', ('x', Signed), ('y', Signed))
170 >>> POINT
171 <GcStruct point { x: Signed, y: Signed }>
172
173 The structure is a ``GcStruct``, which means a structure that can be allocated
174 in the heap and eventually freed by some garbage collector. (For platforms
175 where we use reference counting, think about ``GcStruct`` as a struct with an
176 additional reference counter field.)
177
178 Giving a name ('point') to the GcStruct is only for clarity: it is used in the
179 representation.
180
181 >>> p = malloc(POINT)
182 >>> p
183 <* struct point { x=0, y=0 }>
184 >>> p.x = 5
185 >>> p.x
186 5
187 >>> p
188 <* struct point { x=5, y=0 }>
189
190 ``malloc()`` allocates a structure from the heap, initializes it to 0
191 (currently), and returns a pointer to it. The point of all this is to work with
192 a very limited, easily controllable set of types, and define implementations of
193 types like list in this elementary world. The ``malloc()`` function is a kind
194 of placeholder, which must eventually be provided by the code generator for the
195 target platform; but as we have just seen its Python implementation in
196 :source:`rpython/rtyper/lltypesystem/lltype.py` works too, which is primarily useful for
197 testing, interactive exploring, etc.
198
199 The argument to ``malloc()`` is the structure type directly, but it returns a
200 pointer to the structure, as ``typeOf()`` tells you:
201
202 >>> typeOf(p)
203 <* GcStruct point { x: Signed, y: Signed }>
204
205 For the purpose of creating structures with pointers to other structures, we can
206 declare pointer types explicitly:
207
208 >>> typeOf(p) == Ptr(POINT)
209 True
210 >>> BIZARRE = GcStruct('bizarre', ('p1', Ptr(POINT)), ('p2', Ptr(POINT)))
211 >>> b = malloc(BIZARRE)
212 >>> b.p1
213 <* None>
214 >>> b.p1 = b.p2 = p
215 >>> b.p1.y = 42
216 >>> b.p2.y
217 42
218
219 The world of low-level types is more complicated than integers and GcStructs,
220 though. The next pages are a reference guide.
221
222
223 Primitive Types
224 ~~~~~~~~~~~~~~~
225
226 Signed
227 a signed integer in one machine word (a ``long``, in C)
228
229 Unsigned
230 a non-signed integer in one machine word (``unsigned long``)
231
232 Float
233 a 64-bit float (``double``)
234
235 Char
236 a single character (``char``)
237
238 Bool
239 a boolean value
240
241 Void
242 a constant. Meant for variables, function arguments, structure fields, etc.
243 which should disappear from the generated code.
244
245
246 Structure Types
247 ~~~~~~~~~~~~~~~
248
249 Structure types are built as instances of
250 ``rpython.rtyper.lltypesystem.lltype.Struct``::
251
252 MyStructType = Struct('somename', ('field1', Type1), ('field2', Type2)...)
253 MyStructType = GcStruct('somename', ('field1', Type1), ('field2', Type2)...)
254
255 This declares a structure (or a Pascal ``record``) containing the specified
256 named fields with the given types. The field names cannot start with an
257 underscore. As noted above, you cannot directly manipulate structure objects,
258 but only pointer to structures living in the heap.
259
260 By contrast, the fields themselves can be of primitive, pointer or container
261 type. When a structure contains another structure as a field we say that the
262 latter is "inlined" in the former: the bigger structure contains the smaller one
263 as part of its memory layout.
264
265 A structure can also contain an inlined array (see below), but only as its last
266 field: in this case it is a "variable-sized" structure, whose memory layout
267 starts with the non-variable fields and ends with a variable number of array
268 items. This number is determined when a structure is allocated in the heap.
269 Variable-sized structures cannot be inlined in other structures.
270
271 GcStructs have a platform-specific GC header (e.g. a reference counter); only
272 these can be dynamically malloc()ed. The non-GC version of Struct does not have
273 any header, and is suitable for being embedded ("inlined") inside other
274 structures. As an exception, a GcStruct can be embedded as the first field of a
275 GcStruct: the parent structure uses the same GC header as the substructure.
276
277
278 Array Types
279 ~~~~~~~~~~~
280
281 An array type is built as an instance of
282 ``rpython.rtyper.lltypesystem.lltype.Array``::
283
284 MyIntArray = Array(Signed)
285 MyOtherArray = Array(MyItemType)
286 MyOtherArray = GcArray(MyItemType)
287
288 Or, for arrays whose items are structures, as a shortcut::
289
290 MyArrayType = Array(('field1', Type1), ('field2', Type2)...)
291
292 You can build arrays whose items are either primitive or pointer types, or
293 (non-GC non-varsize) structures.
294
295 GcArrays can be malloc()ed. The length must be specified when malloc() is
296 called, and arrays cannot be resized; this length is stored explicitly in a
297 header.
298
299 The non-GC version of Array can be used as the last field of a structure, to
300 make a variable-sized structure. The whole structure can then be malloc()ed,
301 and the length of the array is specified at this time.
302
303
304 Pointer Types
305 ~~~~~~~~~~~~~
306
307 As in C, pointers provide the indirection needed to make a reference modifiable
308 or sharable. Pointers can only point to a structure, an array or a function
309 (see below). Pointers to primitive types, if needed, must be done by pointing
310 to a structure with a single field of the required type. Pointer types are
311 declared by::
312
313 Ptr(TYPE)
314
315 At run-time, pointers to GC structures (GcStruct, GcArray) hold a
316 reference to what they are pointing to. Pointers to non-GC structures that can
317 go away when their container is deallocated (Struct, Array) must be handled
318 with care: the bigger structure of which they are part of could be freed while
319 the Ptr to the substructure is still in use. In general, it is a good idea to
320 avoid passing around pointers to inlined substructures of malloc()ed structures.
321 (The testing implementation of :source:`rpython/rtyper/lltypesystem/lltype.py` checks to some
322 extent that you are not trying to use a pointer to a structure after its
323 container has been freed, using weak references. But pointers to non-GC
324 structures are not officially meant to be weak references: using them after what
325 they point to has been freed just crashes.)
326
327 The malloc() operation allocates and returns a Ptr to a new GC structure or
328 array. In a refcounting implementation, malloc() would allocate enough space
329 for a reference counter before the actual structure, and initialize it to 1.
330 Note that the testing implementation also allows malloc() to allocate a non-GC
331 structure or array with a keyword argument ``immortal=True``. Its purpose is to
332 declare and initialize prebuilt data structures which the code generators will
333 turn into static immortal non-GC'ed data.
334
335
336 Function Types
337 ~~~~~~~~~~~~~~
338
339 The declaration::
340
341 MyFuncType = FuncType([Type1, Type2, ...], ResultType)
342
343 declares a function type taking arguments of the given types and returning a
344 result of the given type. All these types must be primitives or pointers. The
345 function type itself is considered to be a "container" type: if you wish, a
346 function contains the bytes that make up its executable code. As with
347 structures and arrays, they can only be manipulated through pointers.
348
349 The testing implementation allows you to "create" functions by calling
350 ``functionptr(TYPE, name, **attrs)``. The extra attributes describe the
351 function in a way that isn't fully specified now, but the following attributes
352 *might* be present:
353
354 :_callable: a Python callable, typically a function object.
355 :graph: the flow graph of the function.
356
357
358 Opaque Types
359 ~~~~~~~~~~~~
360
361 Opaque types represent data implemented in a back-end specific way. This
362 data cannot be inspected or manipulated.
363
364 There is a predefined opaque type ``RuntimeTypeInfo``; at run-time, a
365 value of type ``RuntimeTypeInfo`` represents a low-level type. In
366 practice it is probably enough to be able to represent GcStruct and
367 GcArray types. This is useful if we have a pointer of type ``Ptr(S)``
368 which can at run-time point either to a malloc'ed ``S`` alone, or to the
369 ``S`` first field of a larger malloc'ed structure. The information about
370 the exact larger type that it points to can be computed or passed around
371 as a ``Ptr(RuntimeTypeInfo)``. Pointer equality on
372 ``Ptr(RuntimeTypeInfo)`` can be used to check the type at run-time.
373
374 At the moment, for memory management purposes, some back-ends actually
375 require such information to be available at run-time in the following
376 situation: when a GcStruct has another GcStruct as its first field. A
377 reference-counting back-end needs to be able to know when a pointer to the
378 smaller structure actually points to the larger one, so that it can also
379 decref the extra fields. Depending on the situation, it is possible to
380 reconstruct this information without having to store a flag in each and
381 every instance of the smaller GcStruct. For example, the instances of a
382 class hierarchy can be implemented by nested GcStructs, with instances of
383 subclasses extending instances of parent classes by embedding the parent
384 part of the instance as the first field. In this case, there is probably
385 already a way to know the run-time class of the instance (e.g. a vtable
386 pointer), but the back-end cannot guess this. This is the reason for
387 which ``RuntimeTypeInfo`` was originally introduced: just after the
388 GcStruct is created, the function attachRuntimeTypeInfo() should be called
389 to attach to the GcStruct a low-level function of signature
390 ``Ptr(GcStruct) -> Ptr(RuntimeTypeInfo)``. This function will be compiled
391 by the back-end and automatically called at run-time. In the above
392 example, it would follow the vtable pointer and fetch the opaque
393 ``Ptr(RuntimeTypeInfo)`` from the vtable itself. (The reference-counting
394 GenC back-end uses a pointer to the deallocation function as the opaque
395 ``RuntimeTypeInfo``.)
396
397
398 Implementing RPython types
399 --------------------------
400
401 As hinted above, the RPython types (e.g. 'list') are implemented in some
402 "restricted-restricted Python" format by manipulating only low-level types, as
403 provided by the testing implementation of malloc() and friends. What occurs
404 then is that the same (tested!) very-low-level Python code -- which looks really
405 just like C -- is then transformed into a flow graph and integrated with the
406 rest of the user program. In other words, we replace an operation like ``add``
407 between two variables annotated as SomeList, with a ``direct_call`` operation
408 invoking this very-low-level list concatenation.
409
410 This list concatenation flow graph is then annotated as usual, with one
411 difference: the annotator has to be taught about malloc() and the way the
412 pointer thus obtained can be manipulated. This generates a flow graph which is
413 hopefully completely annotated with SomePtr() annotation. Introduced just for
414 this case, SomePtr maps directly to a low-level pointer type. This is the only
415 change needed to the Annotator to allow it to perform type inference of our
416 very-low-level snippets of code.
417
418 See for example :source:`rpython/rtyper/rlist.py`.
419
420
421 HighLevelOp interface
422 ---------------------
423
424 In the absence of more extensive documentation about how RPython types are
425 implemented, here is the interface and intended usage of the 'hop'
426 argument that appears everywhere. A 'hop' is a HighLevelOp instance,
427 which represents a single high-level operation that must be turned into
428 one or several low-level operations.
429
430 ``hop.llops``
431 A list-like object that records the low-level operations that
432 correspond to the current block's high-level operations.
433
434 ``hop.genop(opname, list_of_variables, resulttype=resulttype)``
435 Append a low-level operation to ``hop.llops``. The operation has
436 the given opname and arguments, and returns the given low-level
437 resulttype. The arguments should come from the ``hop.input*()``
438 functions described below.
439
440 ``hop.gendirectcall(ll_function, var1, var2...)``
441 Like hop.genop(), but produces a ``direct_call`` operation that
442 invokes the given low-level function, which is automatically
443 annotated with low-level types based on the input arguments.
444
445 ``hop.inputargs(r1, r2...)``
446 Reads the high-level Variables and Constants that are the
447 arguments of the operation, and convert them if needed so that
448 they have the specified representations. You must provide as many
449 representations as the operation has arguments. Returns a list of
450 (possibly newly converted) Variables and Constants.
451
452 ``hop.inputarg(r, arg=i)``
453 Same as inputargs(), but only converts and returns the ith
454 argument.
455
456 ``hop.inputconst(lltype, value)``
457 Returns a Constant with a low-level type and value.
458
459 Manipulation of HighLevelOp instances (this is used e.g. to insert a
460 'self' implicit argument to translate method calls):
461
462 ``hop.copy()``
463 Returns a fresh copy that can be manipulated with the functions
464 below.
465
466 ``hop.r_s_popfirstarg()``
467 Removes the first argument of the high-level operation. This
468 doesn't really changes the source SpaceOperation, but modifies
469 'hop' in such a way that methods like inputargs() no longer see
470 the removed argument.
471
472 ``hop.v_s_insertfirstarg(v_newfirstarg, s_newfirstarg)``
473 Insert an argument in front of the hop. It must be specified by
474 a Variable (as in calls to hop.genop()) and a corresponding
475 annotation.
476
477 ``hop.swap_fst_snd_args()``
478 Self-descriptive.
479
480 Exception handling:
481
482 ``hop.has_implicit_exception(cls)``
483 Checks if hop is in the scope of a branch catching the exception
484 'cls'. This is useful for high-level operations like 'getitem'
485 that have several low-level equivalents depending on whether they
486 should check for an IndexError or not. Calling
487 has_implicit_exception() also has a side-effect: the rtyper
488 records that this exception is being taken care of explicitly.
489
490 ``hop.exception_is_here()``
491 To be called with no argument just before a llop is generated. It
492 means that the llop in question will be the one that should be
493 protected by the exception catching. If has_implicit_exception()
494 was called before, then exception_is_here() verifies that *all*
495 except links in the graph have indeed been checked for with an
496 has_implicit_exception(). This is not verified if
497 has_implicit_exception() has never been called -- useful for
498 'direct_call' and other operations that can just raise any exception.
499
500 ``hop.exception_cannot_occur()``
501 The RTyper normally verifies that exception_is_here() was really
502 called once for each high-level operation that is in the scope of
503 exception-catching links. By saying exception_cannot_occur(),
504 you say that after all this particular operation cannot raise
505 anything. (It can be the case that unexpected exception links are
506 attached to flow graphs; e.g. any method call within a
507 ``try:finally:`` block will have an Exception branch to the finally
508 part, which only the RTyper can remove if exception_cannot_occur()
509 is called.)
510
511
512 .. _llinterpreter:
513
514 The LLInterpreter
515 -----------------
516
517 The LLInterpreter is a simple piece of code that is able to interpret flow
518 graphs. This is very useful for testing purposes, especially if you work on
519 the RPython Typer. The most useful interface for it is the ``interpret``
520 function in the file :source:`rpython/rtyper/test/test_llinterp.py`. It takes as
521 arguments a function and a list of arguments with which the function is
522 supposed to be called. Then it generates the flow graph, annotates it
523 according to the types of the arguments you passed to it and runs the
524 LLInterpreter on the result. Example::
525
526 def test_invert():
527 def f(x):
528 return ~x
529 res = interpret(f, [3])
530 assert res == ~3
531
532 Furthermore there is a function ``interpret_raises`` which behaves much like
533 ``py.test.raises``. It takes an exception as a first argument, the function to
534 be called as a second and the list of function arguments as a third. Example::
535
536 def test_raise():
537 def raise_exception(i):
538 if i == 42:
539 raise IndexError
540 elif i == 43:
541 raise ValueError
542 return i
543 res = interpret(raise_exception, [41])
544 assert res == 41
545 interpret_raises(IndexError, raise_exception, [42])
546 interpret_raises(ValueError, raise_exception, [43])