| 1 |
# Introduction for Mypyc Contributors |
| 2 |
|
| 3 |
This is a short introduction aimed at anybody who is interested in |
| 4 |
contributing to mypyc, or anybody who is curious to understand how |
| 5 |
mypyc works internally. |
| 6 |
|
| 7 |
## Developer Documentation in the Wiki |
| 8 |
|
| 9 |
We have more mypyc developer documentation in our |
| 10 |
[wiki](https://github.com/python/mypy/wiki/Developer-Guides). |
| 11 |
|
| 12 |
For basic information common to both mypy and mypyc development, refer |
| 13 |
to the [mypy wiki home page](https://github.com/python/mypy/wiki). |
| 14 |
|
| 15 |
## Key Differences from Python |
| 16 |
|
| 17 |
Code compiled using mypyc is often much faster than CPython since it |
| 18 |
does these things differently: |
| 19 |
|
| 20 |
* Mypyc generates C that is compiled to native code, instead of |
| 21 |
compiling to interpreted byte code, which CPython uses. Interpreted |
| 22 |
byte code always has some interpreter overhead, which slows things |
| 23 |
down. |
| 24 |
|
| 25 |
* Mypyc doesn't let you arbitrarily monkey patch classes and functions |
| 26 |
in compiled modules. This allows *early binding* -- mypyc |
| 27 |
statically binds calls to compiled functions, instead of going |
| 28 |
through a namespace dictionary. Mypyc can also call methods of |
| 29 |
compiled classes using vtables, which are more efficient than |
| 30 |
dictionary lookups used by CPython. |
| 31 |
|
| 32 |
* Mypyc compiles classes to C extension classes, which are generally |
| 33 |
more efficient than normal Python classes. They use an efficient, |
| 34 |
fixed memory representation (essentially a C struct). This lets us |
| 35 |
use direct memory access instead of (typically) two hash table |
| 36 |
lookups to access an attribute. |
| 37 |
|
| 38 |
* As a result of early binding, compiled code can use C calls to call |
| 39 |
compiled functions. Keyword arguments can be translated to |
| 40 |
positional arguments during compilation. Thus most calls to native |
| 41 |
functions and methods directly map to simple C calls. CPython calls |
| 42 |
are quite expensive, since mapping of keyword arguments, `*args`, |
| 43 |
and so on has to mostly happen at runtime. |
| 44 |
|
| 45 |
* Compiled code has runtime type checks to ensure that runtimes types |
| 46 |
match the declared static types. Compiled code can thus make |
| 47 |
assumptions about the types of expressions, resulting in both faster |
| 48 |
and smaller code, since many runtime type checks performed by the |
| 49 |
CPython interpreter can be omitted. |
| 50 |
|
| 51 |
* Compiled code can often use unboxed (not heap allocated) |
| 52 |
representations for integers, booleans and tuples. |
| 53 |
|
| 54 |
## Supported Python Features |
| 55 |
|
| 56 |
Mypyc supports a large subset of Python. Note that if you try to |
| 57 |
compile something that is not supported, you may not always get a very |
| 58 |
good error message. |
| 59 |
|
| 60 |
Here are some major things that aren't yet supported in compiled code: |
| 61 |
|
| 62 |
* Some dunder methods (most work though) |
| 63 |
* Monkey patching compiled functions or classes |
| 64 |
* General multiple inheritance (a limited form is supported) |
| 65 |
|
| 66 |
We are generally happy to accept contributions that implement new Python |
| 67 |
features. |
| 68 |
|
| 69 |
## Development Environment |
| 70 |
|
| 71 |
First you should set up the mypy development environment as described in |
| 72 |
the [mypy docs](https://github.com/python/mypy/blob/master/README.md). |
| 73 |
macOS, Linux and Windows are supported. |
| 74 |
|
| 75 |
## Compiling and Running Programs |
| 76 |
|
| 77 |
When working on a mypyc feature or a fix, you'll often need to run |
| 78 |
compiled code. For example, you may want to do interactive testing or |
| 79 |
to run benchmarks. This is also handy if you want to inspect the |
| 80 |
generated C code (see Inspecting Generated C). |
| 81 |
|
| 82 |
Run `python -m mypyc` to compile a module to a C extension using your |
| 83 |
development version of mypyc: |
| 84 |
|
| 85 |
``` |
| 86 |
$ python -m mypyc program.py |
| 87 |
``` |
| 88 |
|
| 89 |
This will generate a C extension for `program` in the current working |
| 90 |
directory. For example, on a macOS system the generated file may be |
| 91 |
called `program.cpython-313-darwin.so`. |
| 92 |
|
| 93 |
Since C extensions can't be run as programs, use `python3 -c` to run |
| 94 |
the compiled module as a program: |
| 95 |
|
| 96 |
``` |
| 97 |
$ python3 -c "import program" |
| 98 |
``` |
| 99 |
|
| 100 |
Note that `__name__` in `program.py` will now be `program`, not |
| 101 |
`__main__`! |
| 102 |
|
| 103 |
You can manually delete the C extension to get back to an interpreted |
| 104 |
version (this example works on macOS or Linux): |
| 105 |
|
| 106 |
``` |
| 107 |
$ rm program.*.so |
| 108 |
``` |
| 109 |
|
| 110 |
Another option is to invoke mypyc through tests (see Testing below). |
| 111 |
|
| 112 |
## High-level Overview of Mypyc |
| 113 |
|
| 114 |
Mypyc compiles a Python module (or a set of modules) to C, and |
| 115 |
compiles the generated C to a Python C extension module (or |
| 116 |
modules). You can compile only a subset of your program to C -- |
| 117 |
compiled and interpreted code can freely and transparently |
| 118 |
interact. You can also freely use any Python libraries (including C |
| 119 |
extensions) in compiled code. |
| 120 |
|
| 121 |
Mypyc will only make compiled code faster. To see a significant |
| 122 |
speedup, you must make sure that most of the time is spent in compiled |
| 123 |
code, and not in libraries or I/O. |
| 124 |
|
| 125 |
Mypyc has these main passes: |
| 126 |
|
| 127 |
* Type check the code using mypy and infer types for variables and |
| 128 |
expressions. This produces a mypy AST (defined in `mypy.nodes`) and |
| 129 |
a type map that describes the inferred types (`mypy.types.Type`) of |
| 130 |
all expressions (as PEP 484 types). |
| 131 |
|
| 132 |
* Translate the mypy AST into a mypyc-specific intermediate representation (IR). |
| 133 |
* The IR is defined in `mypyc.ir` (see below for an explanation of the IR). |
| 134 |
* Various primitive operations used in the IR are defined in `mypyc.primitives`. |
| 135 |
* The translation to IR happens in `mypyc.irbuild`. The top-level logic is in |
| 136 |
`mypyc.irbuild.main`. |
| 137 |
|
| 138 |
* Insert checks for uses of potentially uninitialized variables |
| 139 |
(`mypyc.transform.uninit`). |
| 140 |
|
| 141 |
* Insert exception handling (`mypyc.transform.exceptions`). |
| 142 |
|
| 143 |
* Insert explicit reference count inc/dec opcodes (`mypyc.transform.refcount`). |
| 144 |
|
| 145 |
* Translate the IR into C (`mypyc.codegen`). |
| 146 |
|
| 147 |
* Compile the generated C code using a C compiler (`mypyc.build`). |
| 148 |
|
| 149 |
## Useful Background Information |
| 150 |
|
| 151 |
Beyond the mypy documentation, here are some things that are helpful to |
| 152 |
know for mypyc contributors: |
| 153 |
|
| 154 |
* Experience with C |
| 155 |
([The C Programming Language](https://en.wikipedia.org/wiki/The_C_Programming_Language) |
| 156 |
is a classic book about C) |
| 157 |
* Basic familiarity with the Python C API (see |
| 158 |
[Python C API documentation](https://docs.python.org/3/c-api/intro.html)). [Extending and Embedding the Python Interpreter](https://docs.python.org/3/extending/index.html) is a good tutorial for beginners. |
| 159 |
* Basics of compilers (see the |
| 160 |
[mypy wiki](https://github.com/python/mypy/wiki/Learning-Resources) |
| 161 |
for some ideas) |
| 162 |
|
| 163 |
## Mypyc Intermediate Representation (IR) |
| 164 |
|
| 165 |
The mypyc IR is defined in `mypyc.ir`. It covers several key concepts |
| 166 |
that are essential to understand by all mypyc contributors: |
| 167 |
|
| 168 |
* `mypyc.ir.ops.Op` is an Abstract Base Class for all IR |
| 169 |
operations. These are low-level and generally map to simple |
| 170 |
fragments of C each. Mypy expressions are translated to |
| 171 |
linear sequences of these ops. |
| 172 |
|
| 173 |
* `mypyc.ir.ops.BasicBlock` is a container of a sequence of ops with a |
| 174 |
branch/goto/return at the end, and no branch/goto/return ops in the |
| 175 |
middle. Each function is compiled to a bunch of basic blocks. |
| 176 |
|
| 177 |
* `mypyc.ir.rtypes.RType` and its subclasses are the types used for |
| 178 |
everything in the IR. These are lower-level and simpler than mypy or |
| 179 |
PEP 484 types. For example, there are no general-purpose generic |
| 180 |
types types here. Each `List[X]` type (for any `X`) is represented |
| 181 |
by a single `list` type, for example. |
| 182 |
|
| 183 |
* Primitive types are special RTypes of which mypyc has some special |
| 184 |
understanding, and there are typically some specialized |
| 185 |
ops. Examples include `int` (referred to as `int_rprimitive` in the |
| 186 |
code) and `list` (`list_rprimitive`). Python types for which there |
| 187 |
is no specific RType type will be represented by the catch-all |
| 188 |
`object_rprimitive` type. |
| 189 |
|
| 190 |
* Instances of compiled classes are generally represented using the |
| 191 |
`RInstance` type. Classes are compiled to C extension classes and |
| 192 |
contain vtables for fast method calls and fast attribute access. |
| 193 |
|
| 194 |
* IR representations of functions and classes live in |
| 195 |
`mypyc.ir.func_ir` and `mypyc.ir.class_ir`, respectively. |
| 196 |
|
| 197 |
Look at the docstrings and comments in `mypyc.ir` for additional |
| 198 |
information. See the test cases in |
| 199 |
`mypyc/test-data/irbuild-basic.test` for examples of what the IR looks |
| 200 |
like in a pretty-printed form. |
| 201 |
|
| 202 |
## Testing Overview |
| 203 |
|
| 204 |
Most mypyc test cases are defined in the same format (`.test`) as used |
| 205 |
for test cases for mypy. Look at mypy developer documentation for a |
| 206 |
general overview of how things work. Test cases live under |
| 207 |
`mypyc/test-data/`, and you can run all mypyc tests via `pytest |
| 208 |
mypyc`. If you don't make changes to code under `mypy/`, it's not |
| 209 |
important to regularly run mypy tests during development. |
| 210 |
|
| 211 |
You can use `python runtests.py mypyc-fast` to run a subset of mypyc |
| 212 |
tests that covers most functionality but runs significantly quicker |
| 213 |
than the entire test suite. |
| 214 |
|
| 215 |
When you create a PR, we have Continuous Integration jobs set up that |
| 216 |
compile mypy using mypyc and run the mypy test suite using the |
| 217 |
compiled mypy. This will sometimes catch additional issues not caught |
| 218 |
by the mypyc test suite. It's okay to not do this in your local |
| 219 |
development environment. |
| 220 |
|
| 221 |
We discuss writing tests in more detail later in this document. |
| 222 |
|
| 223 |
## Inspecting Generated IR |
| 224 |
|
| 225 |
It's often useful to look at the generated IR when debugging issues or |
| 226 |
when trying to understand how mypyc compiles some code. When you |
| 227 |
compile some module by running `mypyc`, mypyc will write the |
| 228 |
pretty-printed IR into `build/ops.txt`. This is the final IR that |
| 229 |
includes the output from exception and reference count handling |
| 230 |
insertion passes. |
| 231 |
|
| 232 |
We also have tests that verify the generated IR |
| 233 |
(`mypyc/test-data/irbuild-*.text`). |
| 234 |
|
| 235 |
## Type-checking Mypyc |
| 236 |
|
| 237 |
`./runtests.py self` type checks mypy and mypyc. This is a little slow, |
| 238 |
however, since it's using an uncompiled mypy. |
| 239 |
|
| 240 |
Installing a released version of mypy using `pip` (which is compiled) |
| 241 |
and using `dmypy` (mypy daemon) is a much, much faster way to type |
| 242 |
check mypyc during development. |
| 243 |
|
| 244 |
## Value Representation |
| 245 |
|
| 246 |
Mypyc uses a tagged pointer representation for values of type `int` |
| 247 |
(`CPyTagged`), `char` for booleans, and C structs for tuples. For most |
| 248 |
other objects mypyc uses the CPython `PyObject *`. |
| 249 |
|
| 250 |
Python integers that fit in 31/63 bits (depending on whether we are on |
| 251 |
a 32-bit or 64-bit platform) are represented as C integers |
| 252 |
(`CPyTagged`) shifted left by 1. Integers that don't fit in this |
| 253 |
representation are represented as pointers to a `PyObject *` (this is |
| 254 |
always a Python `int` object) with the least significant bit |
| 255 |
set. Tagged integer operations are defined in `mypyc/lib-rt/int_ops.c` |
| 256 |
and `mypyc/lib-rt/CPy.h`. |
| 257 |
|
| 258 |
There are also low-level integer types, such as `int32` (see |
| 259 |
`mypyc.ir.rtypes`), that don't use the tagged representation. These |
| 260 |
types are not exposed to users, but they are used in generated code. |
| 261 |
|
| 262 |
## Overview of Generated C |
| 263 |
|
| 264 |
Mypyc compiles a function into two functions, a native function and |
| 265 |
a wrapper function: |
| 266 |
|
| 267 |
* The native function takes a fixed number of C arguments with the |
| 268 |
correct C types. It assumes that all argument have correct types. |
| 269 |
|
| 270 |
* The wrapper function conforms to the Python C API calling convention |
| 271 |
and takes an arbitrary set of arguments. It processes the arguments, |
| 272 |
checks their types, unboxes values with special representations and |
| 273 |
calls the native function. The return value from the native function |
| 274 |
is translated back to a Python object ("boxing"). |
| 275 |
|
| 276 |
Calls to other compiled functions don't go through the Python module |
| 277 |
namespace but directly call the target native C function. This makes |
| 278 |
calls very fast compared to CPython. |
| 279 |
|
| 280 |
The generated code does runtime checking so that it can assume that |
| 281 |
values always have the declared types. Whenever accessing CPython |
| 282 |
values which might have unexpected types we need to insert a runtime |
| 283 |
type check operation. For example, when getting a list item we need to |
| 284 |
insert a runtime type check (an unbox or a cast operation), since |
| 285 |
Python lists can contain arbitrary objects. |
| 286 |
|
| 287 |
The generated code uses various helpers defined in |
| 288 |
`mypyc/lib-rt/CPy.h`. The implementations are in various `.c` files |
| 289 |
under `mypyc/lib-rt`. |
| 290 |
|
| 291 |
## Inspecting Generated C |
| 292 |
|
| 293 |
It's often useful to inspect the C code generated by mypyc to debug |
| 294 |
issues. Mypyc stores the generated C code as `build/__native.c`. |
| 295 |
Compiled native functions have the prefix `CPyDef_`, while wrapper |
| 296 |
functions used for calling functions from interpreted Python code have |
| 297 |
the `CPyPy_` prefix. |
| 298 |
|
| 299 |
When running a test, the first test failure will copy generated C code |
| 300 |
into the `.mypyc_test_output` directory. You will see something like |
| 301 |
this in the test output: |
| 302 |
|
| 303 |
``` |
| 304 |
... |
| 305 |
---------------------------- Captured stderr call ----------------------------- |
| 306 |
|
| 307 |
Generated files: /Users/me/src/mypy/.mypyc_test_output (for first failure only) |
| 308 |
|
| 309 |
... |
| 310 |
``` |
| 311 |
|
| 312 |
You can also run pytest with `--mypyc-showc` to display C code on every |
| 313 |
test failure. |
| 314 |
|
| 315 |
## Other Important Limitations |
| 316 |
|
| 317 |
All of these limitations will likely be fixed in the future: |
| 318 |
|
| 319 |
* We don't detect stack overflows. |
| 320 |
|
| 321 |
* We don't handle Ctrl-C in compiled code. |
| 322 |
|
| 323 |
## Hints for Implementing Typical Mypyc Features |
| 324 |
|
| 325 |
This section gives an overview of where to look for and |
| 326 |
what to do to implement specific kinds of mypyc features. |
| 327 |
|
| 328 |
### Testing |
| 329 |
|
| 330 |
Our bread-and-butter testing strategy is compiling code with mypyc and |
| 331 |
running it. There are downsides to this (kind of slow, tests a huge |
| 332 |
number of components at once, insensitive to the particular details of |
| 333 |
the IR), but there really is no substitute for running code. You can |
| 334 |
also write tests that test the generated IR, however. |
| 335 |
|
| 336 |
### Tests That Compile and Run Code |
| 337 |
|
| 338 |
Test cases that compile and run code are located in |
| 339 |
`mypyc/test-data/run*.test` and the test runner is in |
| 340 |
`mypyc.test.test_run`. The code to compile comes after `[case |
| 341 |
test<name>]`. The code gets saved into the file `native.py`, and it |
| 342 |
gets compiled into the module `native`. |
| 343 |
|
| 344 |
Each test case uses a non-compiled Python driver that imports the |
| 345 |
`native` module and typically calls some compiled functions. Some |
| 346 |
tests also perform assertions and print messages in the driver. |
| 347 |
|
| 348 |
If you don't provide a driver, a default driver is used. The default |
| 349 |
driver just calls each module-level function that is prefixed with |
| 350 |
`test_` and reports any uncaught exceptions as failures. (Failure to |
| 351 |
build or a segfault also count as failures.) `testStringOps` in |
| 352 |
`mypyc/test-data/run-strings.test` is an example of a test that uses |
| 353 |
the default driver. |
| 354 |
|
| 355 |
You should usually use the default driver (don't include |
| 356 |
`driver.py`). It's the simplest way to write most tests. |
| 357 |
|
| 358 |
Here's an example test case that uses the default driver: |
| 359 |
|
| 360 |
``` |
| 361 |
[case testConcatenateLists] |
| 362 |
def test_concat_lists() -> None: |
| 363 |
assert [1, 2] + [5, 6] == [1, 2, 5, 6] |
| 364 |
|
| 365 |
def test_concat_empty_lists() -> None: |
| 366 |
assert [] + [] == [] |
| 367 |
``` |
| 368 |
|
| 369 |
There is one test case, `testConcatenateLists`. It has two sub-cases, |
| 370 |
`test_concat_lists` and `test_concat_empty_lists`. Note that you can |
| 371 |
use the pytest -k argument to only run `testConcetanateLists`, but you |
| 372 |
can't filter tests at the sub-case level. |
| 373 |
|
| 374 |
It's recommended to have multiple sub-cases per test case, since each |
| 375 |
test case has significant fixed overhead. Each test case is run in a |
| 376 |
fresh Python subprocess. |
| 377 |
|
| 378 |
Many of the existing test cases provide a custom driver by having |
| 379 |
`[file driver.py]`, followed by the driver implementation. Here the |
| 380 |
driver is not compiled, which is useful if you want to test |
| 381 |
interactions between compiled and non-compiled code. However, many of |
| 382 |
the tests don't have a good reason to use a custom driver -- when they |
| 383 |
were written, the default driver wasn't available. |
| 384 |
|
| 385 |
Test cases can also have a `[out]` section, which specifies the |
| 386 |
expected contents of stdout the test case should produce. New test |
| 387 |
cases should prefer assert statements to `[out]` sections. |
| 388 |
|
| 389 |
### Adding Debug Prints and Editing Generated C |
| 390 |
|
| 391 |
Sometimes it's helpful to add some debug prints or other debugging helpers |
| 392 |
to the generated C code. You can run mypyc using `--skip-c-gen` to skip the C |
| 393 |
generation step, so all manual changes to C files are preserved. Here is |
| 394 |
an example of how to use the workflow: |
| 395 |
|
| 396 |
* Compile some file you want to debug: `python -m mypyc foo.py`. |
| 397 |
* Add debug prints to the generated C in `build/__native.c`. |
| 398 |
* Run the same compilation command line again, but add `--skip-c-gen`: |
| 399 |
`python -m mypyc --skip-c-gen foo.py`. This will only rebuild the |
| 400 |
binaries. |
| 401 |
* Run the compiled code, including your changes: `python -c 'import foo'`. |
| 402 |
You should now see the output from the debug prints you added. |
| 403 |
|
| 404 |
This can also be helpful if you want to quickly experiment with different |
| 405 |
implementation techniques, without having to first figure out how to |
| 406 |
modify mypyc to generate the desired C code. |
| 407 |
|
| 408 |
### Debugging Segfaults |
| 409 |
|
| 410 |
If you experience a segfault, it's recommended to use a debugger that supports |
| 411 |
C, such as gdb or lldb, to look into the segfault. |
| 412 |
|
| 413 |
If a test case segfaults, you can run tests using the debugger, so |
| 414 |
you can inspect the stack. Example of inspecting the C stack when a |
| 415 |
test case segfaults (user input after `$` and `(gdb)` prompts): |
| 416 |
|
| 417 |
``` |
| 418 |
$ pytest mypyc -n0 -s --mypyc-debug=gdb -k <name-of-test> |
| 419 |
... |
| 420 |
(gdb) r |
| 421 |
... |
| 422 |
Program received signal SIGSEGV, Segmentation fault. |
| 423 |
... |
| 424 |
(gdb) bt |
| 425 |
#0 0x00005555556ed1a2 in _PyObject_HashFast (op=0x0) at ./Include/object.h:336 |
| 426 |
#1 PyDict_GetItemWithError (op=0x7ffff6c894c0, key=0x0) at Objects/dictobject.c:2394 |
| 427 |
... |
| 428 |
``` |
| 429 |
|
| 430 |
You must use `-n0 -s` to enable interactive input to the debugger. |
| 431 |
Instead of `gdb`, you can also try `lldb` (especially on macOS). |
| 432 |
|
| 433 |
To get better C stack tracebacks and more assertions in the Python |
| 434 |
runtime, you can build Python in debug mode and use that to run tests, |
| 435 |
or to manually run the debugger outside the test framework. |
| 436 |
|
| 437 |
**Note:** You may need to build Python yourself on macOS, as official |
| 438 |
Python builds may not have sufficient entitlements to use a debugger. |
| 439 |
|
| 440 |
Here are some hints about building a debug version of CPython that may |
| 441 |
help (for Ubuntu, macOS is mostly similar except for installing build |
| 442 |
dependencies): |
| 443 |
|
| 444 |
``` |
| 445 |
$ sudo apt install gdb build-essential libncursesw5-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev libbz2-dev libffi-dev libgdbm-compat-dev |
| 446 |
$ <download Python tarball and extract it> |
| 447 |
$ cd Python-3.XX.Y |
| 448 |
$ ./configure --with-pydebug |
| 449 |
$ make -s -j16 |
| 450 |
$ ./python -m venv ~/<venv-location> # Use ./python.exe -m venv ... on macOS |
| 451 |
$ source ~/<venv-location>/bin/activate |
| 452 |
$ cd <mypy-repo-dir> |
| 453 |
$ pip install -r test-requirements.txt |
| 454 |
``` |
| 455 |
|
| 456 |
### IR Tests |
| 457 |
|
| 458 |
If the specifics of the generated IR of a change is important |
| 459 |
(because, for example, you want to make sure a particular optimization |
| 460 |
is triggering), you should add a `mypyc.irbuild` test as well. Test |
| 461 |
cases are located in `mypyc/test-data/irbuild-*.test` and the test |
| 462 |
driver is in `mypyc.test.test_irbuild`. IR build tests do a direct |
| 463 |
comparison of the IR output, so try to make the test as targeted as |
| 464 |
possible so as to capture only the important details. (Some of our |
| 465 |
existing IR build tests do not follow this advice, unfortunately!) |
| 466 |
|
| 467 |
If you pass the `--update-data` flag to pytest, it will automatically |
| 468 |
update the expected output of any tests to match the actual |
| 469 |
output. This is very useful for changing or creating IR build tests, |
| 470 |
but make sure to carefully inspect the diff! |
| 471 |
|
| 472 |
You may also need to add some definitions to the stubs used for |
| 473 |
builtins during tests (`mypyc/test-data/fixtures/ir.py`). We don't use |
| 474 |
full typeshed stubs to run tests since they would seriously slow down |
| 475 |
tests. |
| 476 |
|
| 477 |
### Benchmarking |
| 478 |
|
| 479 |
Many mypyc improvements attempt to make some operations faster. For |
| 480 |
any such change, you should run some measurements to verify that |
| 481 |
there actually is a measurable performance impact. |
| 482 |
|
| 483 |
A typical benchmark would initialize some data to be operated on, and |
| 484 |
then measure time spent in some function. In particular, you should |
| 485 |
not measure time needed to run the entire benchmark program, as this |
| 486 |
would include Python startup overhead and other things that aren't |
| 487 |
relevant. In general, for microbenchmarks, you want to do as little as |
| 488 |
possible in the timed portion. So ideally you'll just have some loops |
| 489 |
and the code under test. Be ready to provide your benchmark in code |
| 490 |
review so that mypyc developers can check that the benchmark is fine |
| 491 |
(writing a good benchmark is non-trivial). |
| 492 |
|
| 493 |
You should run a benchmark at least five times, in both original and |
| 494 |
changed versions, ignore outliers, and report the average |
| 495 |
runtime. Actual performance of a typical desktop or laptop computer is |
| 496 |
quite variable, due to dynamic CPU clock frequency changes, background |
| 497 |
processes, etc. If you observe a high variance in timings, you'll need |
| 498 |
to run the benchmark more times. Also try closing most applications, |
| 499 |
including web browsers. |
| 500 |
|
| 501 |
Interleave original and changed runs. Don't run 10 runs with variant A |
| 502 |
followed by 10 runs with variant B, but run an A run, a B run, an A |
| 503 |
run, etc. Otherwise you risk that the CPU frequency will be different |
| 504 |
between variants. You can also try adding a delay of 5 to 20s between |
| 505 |
runs to avoid CPU frequency changes. |
| 506 |
|
| 507 |
Instead of averaging over many measurements, you can try to adjust |
| 508 |
your environment to provide more stable measurements. However, this |
| 509 |
can be hard to do with some hardware, including many laptops. Victor |
| 510 |
Stinner has written a series of blog posts about making measurements |
| 511 |
stable: |
| 512 |
|
| 513 |
* https://vstinner.github.io/journey-to-stable-benchmark-system.html |
| 514 |
* https://vstinner.github.io/journey-to-stable-benchmark-average.html |
| 515 |
|
| 516 |
### Adding C Helpers |
| 517 |
|
| 518 |
If you add an operation that compiles into a lot of C code, you may |
| 519 |
also want to add a C helper function for the operation to make the |
| 520 |
generated code smaller. Here is how to do this: |
| 521 |
|
| 522 |
* Declare the operation in `mypyc/lib-rt/CPy.h`. We avoid macros, and |
| 523 |
we generally avoid inline functions to make it easier to target |
| 524 |
additional backends in the future. |
| 525 |
|
| 526 |
* Consider adding a unit test for your C helper in `mypyc/lib-rt/test_capi.cc`. |
| 527 |
We use |
| 528 |
[Google Test](https://github.com/google/googletest) for writing |
| 529 |
tests in C++. The framework is included in the repository under the |
| 530 |
directory `googletest/`. The C unit tests are run as part of the |
| 531 |
pytest test suite (`test_c_unit_test`). |
| 532 |
|
| 533 |
### Adding a Specialized Primitive Operation |
| 534 |
|
| 535 |
Mypyc speeds up operations on primitive types such as `list` and `int` |
| 536 |
by having primitive operations specialized for specific types. These |
| 537 |
operations are declared in `mypyc.primitives` (and |
| 538 |
`mypyc/lib-rt/CPy.h`). For example, `mypyc.primitives.list_ops` |
| 539 |
contains primitives that target list objects. |
| 540 |
|
| 541 |
The operation definitions are data driven: you specify the kind of |
| 542 |
operation (such as a call to `builtins.len` or a binary addition) and |
| 543 |
the operand types (such as `list_primitive`), and what code should be |
| 544 |
generated for the operation. Mypyc does AST matching to find the most |
| 545 |
suitable primitive operation automatically. |
| 546 |
|
| 547 |
Look at the existing primitive definitions and the docstrings in |
| 548 |
`mypyc.primitives.registry` for examples and more information. |
| 549 |
|
| 550 |
### Adding a New Primitive Type |
| 551 |
|
| 552 |
Some types (typically Python Python built-in types), such as `int` and |
| 553 |
`list`, are special cased in mypyc to generate optimized operations |
| 554 |
specific to these types. We'll occasionally want to add additional |
| 555 |
primitive types. |
| 556 |
|
| 557 |
Here are some hints about how to add support for a new primitive type |
| 558 |
(this may be incomplete): |
| 559 |
|
| 560 |
* Decide whether the primitive type has an "unboxed" representation (a |
| 561 |
representation that is not just `PyObject *`). For most types we'll |
| 562 |
use a boxed representation, as it's easier to implement and more |
| 563 |
closely matches Python semantics. |
| 564 |
|
| 565 |
* Create a new instance of `RPrimitive` to support the primitive type |
| 566 |
and add it to `mypyc.ir.rtypes`. Make sure all the attributes are |
| 567 |
set correctly and also define `<foo>_rprimitive` and |
| 568 |
`is_<foo>_rprimitive`. |
| 569 |
|
| 570 |
* Update `mypyc.irbuild.mapper.Mapper.type_to_rtype()`. |
| 571 |
|
| 572 |
* If the type is not unboxed, update `emit_cast` in `mypyc.codegen.emit`. |
| 573 |
|
| 574 |
If the type is unboxed, there are some additional steps: |
| 575 |
|
| 576 |
* Update `emit_box` in `mypyc.codegen.emit`. |
| 577 |
|
| 578 |
* Update `emit_unbox` in `mypyc.codegen.emit`. |
| 579 |
|
| 580 |
* Update `emit_inc_ref` and `emit_dec_ref` in `mypypc.codegen.emit`. |
| 581 |
If the unboxed representation does not need reference counting, |
| 582 |
these can be no-ops. |
| 583 |
|
| 584 |
* Update `emit_error_check` in `mypyc.codegen.emit`. |
| 585 |
|
| 586 |
* Update `emit_gc_visit` and `emit_gc_clear` in `mypyc.codegen.emit` |
| 587 |
if the type has an unboxed representation with pointers. |
| 588 |
|
| 589 |
The above may be enough to allow you to declare variables with the |
| 590 |
type, pass values around, perform runtime type checks, and use generic |
| 591 |
fallback primitive operations to perform method calls, binary |
| 592 |
operations, and so on. You likely also want to add some faster, |
| 593 |
specialized primitive operations for the type (see Adding a |
| 594 |
Specialized Primitive Operation above for how to do this). |
| 595 |
|
| 596 |
Add a test case to `mypyc/test-data/run*.test` to test compilation and |
| 597 |
running compiled code. Ideas for things to test: |
| 598 |
|
| 599 |
* Test using the type as an argument. |
| 600 |
|
| 601 |
* Test using the type as a return value. |
| 602 |
|
| 603 |
* Test passing a value of the type to a function both within |
| 604 |
compiled code and from regular Python code. Also test this |
| 605 |
for return values. |
| 606 |
|
| 607 |
* Test using the type as list item type. Test both getting a list item |
| 608 |
and setting a list item. |
| 609 |
|
| 610 |
### Supporting More Python Syntax |
| 611 |
|
| 612 |
Mypyc supports most Python syntax, but there are still some gaps. |
| 613 |
|
| 614 |
Support for syntactic sugar that doesn't need additional IR operations |
| 615 |
typically only requires changes to `mypyc.irbuild`. |
| 616 |
|
| 617 |
Some new syntax also needs new IR primitives to be added to |
| 618 |
`mypyc.primitives`. See `mypyc.primitives.registry` for documentation |
| 619 |
about how to do this. |
| 620 |
|
| 621 |
### Other Hints |
| 622 |
|
| 623 |
* This developer documentation is not aimed to be very complete. Much |
| 624 |
of our documentation is in comments and docstring in the code. If |
| 625 |
something is unclear, study the code. |
| 626 |
|
| 627 |
* It can be useful to look through some recent PRs to get an idea of |
| 628 |
what typical code changes, test cases, etc. look like. |
| 629 |
|
| 630 |
* Feel free to open GitHub issues with questions if you need help when |
| 631 |
contributing, or ask questions in existing issues. Note that we only |
| 632 |
support contributors. Mypyc is not (yet) an end-user product. You |
| 633 |
can also ask questions in our Gitter chat |
| 634 |
(https://gitter.im/mypyc-dev/community). |
| 635 |
|
| 636 |
## Undocumented Workflows |
| 637 |
|
| 638 |
These workflows would be useful for mypyc contributors. We should add |
| 639 |
them to mypyc developer documentation: |
| 640 |
|
| 641 |
* How to inspect the generated IR before some transform passes. |