diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/Makefile b/openflamingo/lib/python3.10/site-packages/mypyc/doc/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..d4bb2cbb9eddb1bb1b4f366623044af8e4830919 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/__pycache__/conf.cpython-310.pyc b/openflamingo/lib/python3.10/site-packages/mypyc/doc/__pycache__/conf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b676d2d992c9350026c0c6952452fd4f2af1adb Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/doc/__pycache__/conf.cpython-310.pyc differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/bool_operations.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/bool_operations.rst new file mode 100644 index 0000000000000000000000000000000000000000..8e46514b06c44ed6ba20292ec0cbbc8d31a824c7 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/bool_operations.rst @@ -0,0 +1,27 @@ +.. _bool-ops: + +Native boolean operations +========================= + +Operations on ``bool`` values that are listed here have fast, +optimized implementations. + +Construction +------------ + +* ``True`` +* ``False`` +* ``bool(obj)`` + +Operators +--------- + +* ``b1 and b2`` +* ``b1 or b2`` +* ``not b`` + +Functions +--------- + +* ``any(expr for ... in ...)`` +* ``all(expr for ... in ...)`` diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/bytes_operations.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/bytes_operations.rst new file mode 100644 index 0000000000000000000000000000000000000000..038da63919491bc6e11079a909fe304fdcbd6bcb --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/bytes_operations.rst @@ -0,0 +1,46 @@ +.. _bytes-ops: + +Native bytes operations +======================== + +These ``bytes`` operations have fast, optimized implementations. Other +bytes operations use generic implementations that are often slower. + +Construction +------------ + +* Bytes literal +* ``bytes(x: list)`` + +Operators +--------- + +* Concatenation (``b1 + b2``) +* Indexing (``b[n]``) +* Slicing (``b[n:m]``, ``b[n:]``, ``b[:m]``) +* Comparisons (``==``, ``!=``) + +.. _bytes-methods: + +Methods +------- + +* ``b.decode()`` +* ``b.decode(encoding: str)`` +* ``b.decode(encoding: str, errors: str)`` +* ``b.join(x: Iterable)`` + +.. note:: + + :ref:`str.encode() ` is also optimized. + +Formatting +---------- + +A subset of % formatting operations are optimized (``b"..." % (...)``). + +Functions +--------- + +* ``len(b: bytes)`` +* ``ord(b: bytes)`` diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/compilation_units.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/compilation_units.rst new file mode 100644 index 0000000000000000000000000000000000000000..732f91723ee1ed9199ef1809bb55c58a8075f6d8 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/compilation_units.rst @@ -0,0 +1,20 @@ +.. _compilation-units: + +Compilation units +================= + +When you run mypyc to compile a set of modules, these modules form a +*compilation unit*. Mypyc will use early binding for references within +the compilation unit. + +If you run mypyc multiple times to compile multiple sets of modules, +each invocation will result in a new compilation unit. References +between separate compilation units will fall back to late binding, +i.e. looking up names using Python namespace dictionaries. Also, all +calls will use the slower Python calling convention, where arguments +and the return value will be boxed (and potentially unboxed again in +the called function). + +For maximal performance, minimize interactions across compilation +units. The simplest way to achieve this is to compile your entire +program as a single compilation unit. diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/conf.py b/openflamingo/lib/python3.10/site-packages/mypyc/doc/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..fdd98c12a221d03d3667c7ab6066602353b84ca3 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/conf.py @@ -0,0 +1,59 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +from __future__ import annotations + +import os +import sys + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("../..")) + +from mypy.version import __version__ as mypy_version + +# -- Project information ----------------------------------------------------- + +project = "mypyc" +copyright = "2020-2022, mypyc team" +author = "mypyc team" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = mypy_version.split("-")[0] +# The full version, including alpha/beta/rc tags. +release = mypy_version + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions: list[str] = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "furo" + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/cpython-timings.md b/openflamingo/lib/python3.10/site-packages/mypyc/doc/cpython-timings.md new file mode 100644 index 0000000000000000000000000000000000000000..360d9cfa3961061ca83b34a8fdfaf93208138550 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/cpython-timings.md @@ -0,0 +1,25 @@ +# Timings of CPython Operations + +Here are some *very rough* approximate timings of CPython interpreter +operations: + +* `f(1)` (empty function body): 70-90ns +* `f(n=1)` (empty function body): 90-110ns +* `o.x`: 30-40ns +* `o.f(1)` (empty method body): 80-160ns +* `Cls(1)` (initialize attribute in `__init__`): 290-330ns +* `x + y` (integers): 20-35ns +* `a[i]` (list) : 20-40ns +* `[i]` (also dealloc): 35-55ns +* `a.append(i)` (list, average over 5 appends): 70ns +* `d[s]` (dict, shared str key): 20ns +* `d[s] = i` (dict, shared str key): 40ns +* `isinstance(x, A)`: 100ns +* `(x, y)`: 20-35ns +* `x, y = t` (tuple expand): 10ns + +Note that these results are very imprecise due to many factors, but +these should give a rough idea of the relative costs of various +operations. + +Details: CPython 3.6.2, Macbook Pro 15" (Mid 2015), macOS Sierra diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/dev-intro.md b/openflamingo/lib/python3.10/site-packages/mypyc/doc/dev-intro.md new file mode 100644 index 0000000000000000000000000000000000000000..461a19d3712125a20f09dbd7f50d3798fb621407 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/dev-intro.md @@ -0,0 +1,552 @@ +# Introduction for Mypyc Contributors + +This is a short introduction aimed at anybody who is interested in +contributing to mypyc, or anybody who is curious to understand how +mypyc works internally. + +## Key Differences from Python + +Code compiled using mypyc is often much faster than CPython since it +does these things differently: + +* Mypyc generates C that is compiled to native code, instead of + compiling to interpreted byte code, which CPython uses. Interpreted + byte code always has some interpreter overhead, which slows things + down. + +* Mypyc doesn't let you arbitrarily monkey patch classes and functions + in compiled modules. This allows *early binding* -- mypyc + statically binds calls to compiled functions, instead of going + through a namespace dictionary. Mypyc can also call methods of + compiled classes using vtables, which are more efficient than + dictionary lookups used by CPython. + +* Mypyc compiles classes to C extension classes, which are generally + more efficient than normal Python classes. They use an efficient, + fixed memory representation (essentially a C struct). This lets us + use direct memory access instead of (typically) two hash table + lookups to access an attribute. + +* As a result of early binding, compiled code can use C calls to call + compiled functions. Keyword arguments can be translated to + positional arguments during compilation. Thus most calls to native + functions and methods directly map to simple C calls. CPython calls + are quite expensive, since mapping of keyword arguments, `*args`, + and so on has to mostly happen at runtime. + +* Compiled code has runtime type checks to ensure that runtimes types + match the declared static types. Compiled code can thus make + assumptions about the types of expressions, resulting in both faster + and smaller code, since many runtime type checks performed by the + CPython interpreter can be omitted. + +* Compiled code can often use unboxed (not heap allocated) + representations for integers, booleans and tuples. + +## Supported Python Features + +Mypyc supports a large subset of Python. Note that if you try to +compile something that is not supported, you may not always get a very +good error message. + +Here are some major things that aren't yet supported in compiled code: + +* Many dunder methods (only some work, such as `__init__` and `__eq__`) +* Monkey patching compiled functions or classes +* General multiple inheritance (a limited form is supported) +* Named tuple defined using the class-based syntax +* Defining protocols + +We are generally happy to accept contributions that implement new Python +features. + +## Development Environment + +First you should set up the mypy development environment as described in +the [mypy docs](https://github.com/python/mypy/blob/master/README.md). +macOS, Linux and Windows are supported. + +## Compiling and Running Programs + +When working on a mypyc feature or a fix, you'll often need to run +compiled code. For example, you may want to do interactive testing or +to run benchmarks. This is also handy if you want to inspect the +generated C code (see Inspecting Generated C). + +Run `mypyc` to compile a module to a C extension using your +development version of mypyc: + +``` +$ mypyc program.py +``` + +This will generate a C extension for `program` in the current working +directory. For example, on a Linux system the generated file may be +called `program.cpython-37m-x86_64-linux-gnu.so`. + +Since C extensions can't be run as programs, use `python3 -c` to run +the compiled module as a program: + +``` +$ python3 -c "import program" +``` + +Note that `__name__` in `program.py` will now be `program`, not +`__main__`! + +You can manually delete the C extension to get back to an interpreted +version (this example works on Linux): + +``` +$ rm program.*.so +``` + +Another option is to invoke mypyc through tests (see Testing below). + +## High-level Overview of Mypyc + +Mypyc compiles a Python module (or a set of modules) to C, and +compiles the generated C to a Python C extension module (or +modules). You can compile only a subset of your program to C -- +compiled and interpreted code can freely and transparently +interact. You can also freely use any Python libraries (including C +extensions) in compiled code. + +Mypyc will only make compiled code faster. To see a significant +speedup, you must make sure that most of the time is spent in compiled +code -- and not in libraries, for example. + +Mypyc has these passes: + +* Type check the code using mypy and infer types for variables and + expressions. This produces a mypy AST (defined in `mypy.nodes`) and + a type map that describes the inferred types (`mypy.types.Type`) of + all expressions (as PEP 484 types). + +* Translate the mypy AST into a mypyc-specific intermediate representation (IR). + * The IR is defined in `mypyc.ir` (see below for an explanation of the IR). + * Various primitive operations used in the IR are defined in `mypyc.primitives`. + * The translation to IR happens in `mypyc.irbuild`. The top-level logic is in + `mypyc.irbuild.main`. + +* Insert checks for uses of potentially uninitialized variables + (`mypyc.transform.uninit`). + +* Insert exception handling (`mypyc.transform.exceptions`). + +* Insert explicit reference count inc/dec opcodes (`mypyc.transform.refcount`). + +* Translate the IR into C (`mypyc.codegen`). + +* Compile the generated C code using a C compiler (`mypyc.build`). + +## Useful Background Information + +Beyond the mypy documentation, here are some things that are helpful to +know for mypyc contributors: + +* Experience with C + ([The C Programming Language](https://en.wikipedia.org/wiki/The_C_Programming_Language) + is a classic book about C) +* Basic familiarity with the Python C API (see + [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. +* Basics of compilers (see the + [mypy wiki](https://github.com/python/mypy/wiki/Learning-Resources) + for some ideas) + +## Mypyc Intermediate Representation (IR) + +The mypyc IR is defined in `mypyc.ir`. It covers several key concepts +that are essential to understand by all mypyc contributors: + +* `mypyc.ir.ops.Op` is an Abstract Base Class for all IR + operations. These are low-level and generally map to simple + fragments of C each. Mypy expressions are translated to + linear sequences of these ops. + +* `mypyc.ir.ops.BasicBlock` is a container of a sequence of ops with a + branch/goto/return at the end, and no branch/goto/return ops in the + middle. Each function is compiled to a bunch of basic blocks. + +* `mypyc.ir.rtypes.RType` and its subclasses are the types used for + everything in the IR. These are lower-level and simpler than mypy or + PEP 484 types. For example, there are no general-purpose generic + types types here. Each `List[X]` type (for any `X`) is represented + by a single `list` type, for example. + +* Primitive types are special RTypes of which mypyc has some special + understanding, and there are typically some specialized + ops. Examples include `int` (referred to as `int_rprimitive` in the + code) and `list` (`list_rprimitive`). Python types for which there + is no specific RType type will be represented by the catch-all + `object_rprimitive` type. + +* Instances of compiled classes are generally represented using the + `RInstance` type. Classes are compiled to C extension classes and + contain vtables for fast method calls and fast attribute access. + +* IR representations of functions and classes live in + `mypyc.ir.func_ir` and `mypyc.ir.class_ir`, respectively. + +Look at the docstrings and comments in `mypyc.ir` for additional +information. See the test cases in +`mypyc/test-data/irbuild-basic.test` for examples of what the IR looks +like in a pretty-printed form. + +## Testing overview + +Most mypyc test cases are defined in the same format (`.test`) as used +for test cases for mypy. Look at mypy developer documentation for a +general overview of how things work. Test cases live under +`mypyc/test-data/`, and you can run all mypyc tests via `pytest +-q mypyc`. If you don't make changes to code under `mypy/`, it's not +important to regularly run mypy tests during development. + +You can use `python runtests.py mypyc-fast` to run a subset of mypyc +tests that covers most functionality but runs significantly quicker +than the entire test suite. + +When you create a PR, we have Continuous Integration jobs set up that +compile mypy using mypyc and run the mypy test suite using the +compiled mypy. This will sometimes catch additional issues not caught +by the mypyc test suite. It's okay to not do this in your local +development environment. + +We discuss writing tests in more detail later in this document. + +## Inspecting Generated IR + +It's often useful to look at the generated IR when debugging issues or +when trying to understand how mypyc compiles some code. When you +compile some module by running `mypyc`, mypyc will write the +pretty-printed IR into `build/ops.txt`. This is the final IR that +includes the output from exception and reference count handling +insertion passes. + +We also have tests that verify the generate IR +(`mypyc/test-data/irbuild-*.text`). + +## Type-checking Mypyc + +`./runtests.py self` type checks mypy and mypyc. This is pretty slow, +however, since it's using an uncompiled mypy. + +Installing a released version of mypy using `pip` (which is compiled) +and using `dmypy` (mypy daemon) is a much, much faster way to type +check mypyc during development. + +## Value Representation + +Mypyc uses a tagged pointer representation for values of type `int` +(`CPyTagged`), `char` for booleans, and C structs for tuples. For most +other objects mypyc uses the CPython `PyObject *`. + +Python integers that fit in 31/63 bits (depending on whether we are on +a 32-bit or 64-bit platform) are represented as C integers +(`CPyTagged`) shifted left by 1. Integers that don't fit in this +representation are represented as pointers to a `PyObject *` (this is +always a Python `int` object) with the least significant bit +set. Tagged integer operations are defined in `mypyc/lib-rt/int_ops.c` +and `mypyc/lib-rt/CPy.h`. + +There are also low-level integer types, such as `int32` (see +`mypyc.ir.rtypes`), that don't use the tagged representation. These +types are not exposed to users, but they are used in generated code. + +## Overview of Generated C + +Mypyc compiles a function into two functions, a native function and +a wrapper function: + +* The native function takes a fixed number of C arguments with the + correct C types. It assumes that all argument have correct types. + +* The wrapper function conforms to the Python C API calling convention + and takes an arbitrary set of arguments. It processes the arguments, + checks their types, unboxes values with special representations and + calls the native function. The return value from the native function + is translated back to a Python object ("boxing"). + +Calls to other compiled functions don't go through the Python module +namespace but directly call the target native C function. This makes +calls very fast compared to CPython. + +The generated code does runtime checking so that it can assume that +values always have the declared types. Whenever accessing CPython +values which might have unexpected types we need to insert a runtime +type check operation. For example, when getting a list item we need to +insert a runtime type check (an unbox or a cast operation), since +Python lists can contain arbitrary objects. + +The generated code uses various helpers defined in +`mypyc/lib-rt/CPy.h`. The implementations are in various `.c` files +under `mypyc/lib-rt`. + +## Inspecting Generated C + +It's often useful to inspect the C code genenerate by mypyc to debug +issues. Mypyc stores the generated C code as `build/__native.c`. +Compiled native functions have the prefix `CPyDef_`, while wrapper +functions used for calling functions from interpreted Python code have +the `CPyPy_` prefix. + +## Other Important Limitations + +All of these limitations will likely be fixed in the future: + +* We don't detect stack overflows. + +* We don't handle Ctrl-C in compiled code. + +## Hints for Implementing Typical Mypyc Features + +This section gives an overview of where to look for and +what to do to implement specific kinds of mypyc features. + +### Testing + +Our bread-and-butter testing strategy is compiling code with mypyc and +running it. There are downsides to this (kind of slow, tests a huge +number of components at once, insensitive to the particular details of +the IR), but there really is no substitute for running code. You can +also write tests that test the generated IR, however. + +### Tests that compile and run code + +Test cases that compile and run code are located in +`mypyc/test-data/run*.test` and the test runner is in +`mypyc.test.test_run`. The code to compile comes after `[case +test]`. The code gets saved into the file `native.py`, and it +gets compiled into the module `native`. + +Each test case uses a non-compiled Python driver that imports the +`native` module and typically calls some compiled functions. Some +tests also perform assertions and print messages in the driver. + +If you don't provide a driver, a default driver is used. The default +driver just calls each module-level function that is prefixed with +`test_` and reports any uncaught exceptions as failures. (Failure to +build or a segfault also count as failures.) `testStringOps` in +`mypyc/test-data/run-strings.test` is an example of a test that uses +the default driver. + +You should usually use the default driver (don't include +`driver.py`). It's the simplest way to write most tests. + +Here's an example test case that uses the default driver: + +``` +[case testConcatenateLists] +def test_concat_lists() -> None: + assert [1, 2] + [5, 6] == [1, 2, 5, 6] + +def test_concat_empty_lists() -> None: + assert [] + [] == [] +``` + +There is one test case, `testConcatenateLists`. It has two sub-cases, +`test_concat_lists` and `test_concat_empty_lists`. Note that you can +use the pytest -k argument to only run `testConcetanateLists`, but you +can't filter tests at the sub-case level. + +It's recommended to have multiple sub-cases per test case, since each +test case has significant fixed overhead. Each test case is run in a +fresh Python subprocess. + +Many of the existing test cases provide a custom driver by having +`[file driver.py]`, followed by the driver implementation. Here the +driver is not compiled, which is useful if you want to test +interactions between compiled and non-compiled code. However, many of +the tests don't have a good reason to use a custom driver -- when they +were written, the default driver wasn't available. + +Test cases can also have a `[out]` section, which specifies the +expected contents of stdout the test case should produce. New test +cases should prefer assert statements to `[out]` sections. + +### IR tests + +If the specifics of the generated IR of a change is important +(because, for example, you want to make sure a particular optimization +is triggering), you should add a `mypyc.irbuild` test as well. Test +cases are located in `mypyc/test-data/irbuild-*.test` and the test +driver is in `mypyc.test.test_irbuild`. IR build tests do a direct +comparison of the IR output, so try to make the test as targeted as +possible so as to capture only the important details. (Many of our +existing IR build tests do not follow this advice, unfortunately!) + +If you pass the `--update-data` flag to pytest, it will automatically +update the expected output of any tests to match the actual +output. This is very useful for changing or creating IR build tests, +but make sure to carefully inspect the diff! + +You may also need to add some definitions to the stubs used for +builtins during tests (`mypyc/test-data/fixtures/ir.py`). We don't use +full typeshed stubs to run tests since they would seriously slow down +tests. + +### Benchmarking + +Many mypyc improvements attempt to make some operations faster. For +any such change, you should run some measurements to verify that +there actually is a measurable performance impact. + +A typical benchmark would initialize some data to be operated on, and +then measure time spent in some function. In particular, you should +not measure time needed to run the entire benchmark program, as this +would include Python startup overhead and other things that aren't +relevant. In general, for microbenchmarks, you want to do as little as +possible in the timed portion. So ideally you'll just have some loops +and the code under test. Be ready to provide your benchmark in code +review so that mypyc developers can check that the benchmark is fine +(writing a good benchmark is non-trivial). + +You should run a benchmark at least five times, in both original and +changed versions, ignore outliers, and report the average +runtime. Actual performance of a typical desktop or laptop computer is +quite variable, due to dynamic CPU clock frequency changes, background +processes, etc. If you observe a high variance in timings, you'll need +to run the benchmark more times. Also try closing most applications, +including web browsers. + +Interleave original and changed runs. Don't run 10 runs with variant A +followed by 10 runs with variant B, but run an A run, a B run, an A +run, etc. Otherwise you risk that the CPU frequency will be different +between variants. You can also try adding a delay of 5 to 20s between +runs to avoid CPU frequency changes. + +Instead of averaging over many measurements, you can try to adjust +your environment to provide more stable measurements. However, this +can be hard to do with some hardware, including many laptops. Victor +Stinner has written a series of blog posts about making measurements +stable: + +* https://vstinner.github.io/journey-to-stable-benchmark-system.html +* https://vstinner.github.io/journey-to-stable-benchmark-average.html + +### Adding C Helpers + +If you add an operation that compiles into a lot of C code, you may +also want to add a C helper function for the operation to make the +generated code smaller. Here is how to do this: + +* Declare the operation in `mypyc/lib-rt/CPy.h`. We avoid macros, and + we generally avoid inline functions to make it easier to target + additional backends in the future. + +* Consider adding a unit test for your C helper in `mypyc/lib-rt/test_capi.cc`. + We use + [Google Test](https://github.com/google/googletest) for writing + tests in C++. The framework is included in the repository under the + directory `googletest/`. The C unit tests are run as part of the + pytest test suite (`test_c_unit_test`). + +### Adding a Specialized Primitive Operation + +Mypyc speeds up operations on primitive types such as `list` and `int` +by having primitive operations specialized for specific types. These +operations are declared in `mypyc.primitives` (and +`mypyc/lib-rt/CPy.h`). For example, `mypyc.primitives.list_ops` +contains primitives that target list objects. + +The operation definitions are data driven: you specify the kind of +operation (such as a call to `builtins.len` or a binary addition) and +the operand types (such as `list_primitive`), and what code should be +generated for the operation. Mypyc does AST matching to find the most +suitable primitive operation automatically. + +Look at the existing primitive definitions and the docstrings in +`mypyc.primitives.registry` for examples and more information. + +### Adding a New Primitive Type + +Some types (typically Python Python built-in types), such as `int` and +`list`, are special cased in mypyc to generate optimized operations +specific to these types. We'll occasionally want to add additional +primitive types. + +Here are some hints about how to add support for a new primitive type +(this may be incomplete): + +* Decide whether the primitive type has an "unboxed" representation (a + representation that is not just `PyObject *`). For most types we'll + use a boxed representation, as it's easier to implement and more + closely matches Python semantics. + +* Create a new instance of `RPrimitive` to support the primitive type + and add it to `mypyc.ir.rtypes`. Make sure all the attributes are + set correctly and also define `_rprimitive` and + `is__rprimitive`. + +* Update `mypyc.irbuild.mapper.Mapper.type_to_rtype()`. + +* If the type is not unboxed, update `emit_cast` in `mypyc.codegen.emit`. + +If the type is unboxed, there are some additional steps: + +* Update `emit_box` in `mypyc.codegen.emit`. + +* Update `emit_unbox` in `mypyc.codegen.emit`. + +* Update `emit_inc_ref` and `emit_dec_ref` in `mypypc.codegen.emit`. + If the unboxed representation does not need reference counting, + these can be no-ops. + +* Update `emit_error_check` in `mypyc.codegen.emit`. + +* Update `emit_gc_visit` and `emit_gc_clear` in `mypyc.codegen.emit` + if the type has an unboxed representation with pointers. + +The above may be enough to allow you to declare variables with the +type, pass values around, perform runtime type checks, and use generic +fallback primitive operations to perform method calls, binary +operations, and so on. You likely also want to add some faster, +specialized primitive operations for the type (see Adding a +Specialized Primitive Operation above for how to do this). + +Add a test case to `mypyc/test-data/run*.test` to test compilation and +running compiled code. Ideas for things to test: + +* Test using the type as an argument. + +* Test using the type as a return value. + +* Test passing a value of the type to a function both within + compiled code and from regular Python code. Also test this + for return values. + +* Test using the type as list item type. Test both getting a list item + and setting a list item. + +### Supporting More Python Syntax + +Mypyc supports most Python syntax, but there are still some gaps. + +Support for syntactic sugar that doesn't need additional IR operations +typically only requires changes to `mypyc.irbuild`. + +Some new syntax also needs new IR primitives to be added to +`mypyc.primitives`. See `mypyc.primitives.registry` for documentation +about how to do this. + +### Other Hints + +* This developer documentation is not aimed to be very complete. Much + of our documentation is in comments and docstring in the code. If + something is unclear, study the code. + +* It can be useful to look through some recent PRs to get an idea of + what typical code changes, test cases, etc. look like. + +* Feel free to open GitHub issues with questions if you need help when + contributing, or ask questions in existing issues. Note that we only + support contributors. Mypyc is not (yet) an end-user product. You + can also ask questions in our Gitter chat + (https://gitter.im/mypyc-dev/community). + +## Undocumented Workflows + +These workflows would be useful for mypyc contributors. We should add +them to mypyc developer documentation: + +* How to inspect the generated IR before some transform passes. diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/dict_operations.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/dict_operations.rst new file mode 100644 index 0000000000000000000000000000000000000000..e3104172133a6477bf5bc0a229b453d3bac946dc --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/dict_operations.rst @@ -0,0 +1,59 @@ +.. _dict-ops: + +Native dict operations +====================== + +These ``dict`` operations have fast, optimized implementations. Other +dictionary operations use generic implementations that are often slower. + +Construction +------------ + +Construct dict from keys and values: + +* ``{key: value, ...}`` + +Construct empty dict: + +* ``{}`` +* ``dict()`` + +Construct dict from another object: + +* ``dict(d: dict)`` +* ``dict(x: Iterable)`` + +Dict comprehensions: + +* ``{...: ... for ... in ...}`` +* ``{...: ... for ... in ... if ...}`` + +Operators +--------- + +* ``d[key]`` +* ``value in d`` + +Statements +---------- + +* ``d[key] = value`` +* ``for key in d:`` + +Methods +------- + +* ``d.get(key)`` +* ``d.get(key, default)`` +* ``d.keys()`` +* ``d.values()`` +* ``d.items()`` +* ``d.copy()`` +* ``d.clear()`` +* ``d1.update(d2: dict)`` +* ``d.update(x: Iterable)`` + +Functions +--------- + +* ``len(d: dict)`` diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/differences_from_python.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/differences_from_python.rst new file mode 100644 index 0000000000000000000000000000000000000000..f1d4d05a3a87178f6350bd6bf46f8bfcbbd0fe63 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/differences_from_python.rst @@ -0,0 +1,332 @@ +.. _differences-from-python: + +Differences from Python +======================= + +Mypyc aims to be sufficiently compatible with Python semantics so that +migrating code to mypyc often doesn't require major code +changes. There are various differences to enable performance gains +that you need to be aware of, however. + +This section documents notable differences from Python. We discuss +many of them also elsewhere, but it's convenient to have them here in +one place. + +Running compiled modules +------------------------ + +You can't use ``python3 .py`` or ``python3 -m `` +to run compiled modules. Use ``python3 -c "import "`` instead, +or write a wrapper script that imports your module. + +As a side effect, you can't rely on checking the ``__name__`` attribute in compiled +code, like this:: + + if __name__ == "__main__": # Can't be used in compiled code + main() + +Type errors prevent compilation +------------------------------- + +You can't compile code that generates mypy type check errors. You can +sometimes ignore these with a ``# type: ignore`` comment, but this can +result in bad code being generated, and it's considered dangerous. + +.. note:: + + In the future, mypyc may reject ``# type: ignore`` comments that + may be unsafe. + +Runtime type checking +--------------------- + +Non-erased types in annotations will be type checked at runtime. For example, +consider this function:: + + def twice(x: int) -> int: + return x * 2 + +If you try to call this function with a ``float`` or ``str`` argument, +you'll get a type error on the call site, even if the call site is not +being type checked:: + + twice(5) # OK + twice(2.2) # TypeError + twice("blah") # TypeError + +Also, values with *inferred* types will be type checked. For example, +consider a call to the stdlib function ``socket.gethostname()`` in +compiled code. This function is not compiled (no stdlib modules are +compiled with mypyc), but mypyc uses a *library stub file* to infer +the return type as ``str``. Compiled code calling ``gethostname()`` +will fail with ``TypeError`` if ``gethostname()`` would return an +incompatible value, such as ``None``:: + + import socket + + # Fail if returned value is not a str + name = socket.gethostname() + +Note that ``gethostname()`` is defined like this in the stub file for +``socket`` (in typeshed):: + + def gethostname() -> str: ... + +Thus mypyc verifies that library stub files and annotations in +non-compiled code match runtime values. This adds an extra layer of +type safety. + +Casts such as ``cast(str, x)`` will also result in strict type +checks. Consider this example:: + + from typing import cast + ... + x = cast(str, y) + +The last line is essentially equivalent to this Python code when compiled:: + + if not isinstance(y, str): + raise TypeError(...) + x = y + +In interpreted mode ``cast`` does not perform a runtime type check. + +Native classes +-------------- + +Native classes behave differently from Python classes. See +:ref:`native-classes` for the details. + +Primitive types +--------------- + +Some primitive types behave differently in compiled code to improve +performance. + +``int`` objects use an unboxed (non-heap-allocated) representation for small +integer values. A side effect of this is that the exact runtime type of +``int`` values is lost. For example, consider this simple function:: + + def first_int(x: List[int]) -> int: + return x[0] + + print(first_int([True])) # Output is 1, instead of True! + +``bool`` is a subclass of ``int``, so the above code is +valid. However, when the list value is converted to ``int``, ``True`` +is converted to the corresponding ``int`` value, which is ``1``. + +Note that integers still have an arbitrary precision in compiled code, +similar to normal Python integers. + +Fixed-length tuples are unboxed, similar to integers. The exact type +and identity of fixed-length tuples is not preserved, and you can't +reliably use ``is`` checks to compare tuples that are used in compiled +code. + +.. _early-binding: + +Early binding +------------- + +References to functions, types, most attributes, and methods in the +same :ref:`compilation unit ` use *early binding*: +the target of the reference is decided at compile time, whenever +possible. This contrasts with normal Python behavior of *late +binding*, where the target is found by a namespace lookup at +runtime. Omitting these namespace lookups improves performance, but +some Python idioms don't work without changes. + +Note that non-final module-level variables still use late binding. +You may want to avoid these in very performance-critical code. + +Examples of early and late binding:: + + from typing import Final + + import lib # "lib" is not compiled + + x = 0 + y: Final = 1 + + def func() -> None: + pass + + class Cls: + def __init__(self, attr: int) -> None: + self.attr = attr + + def method(self) -> None: + pass + + def example() -> None: + # Early binding: + var = y + func() + o = Cls() + o.x + o.method() + + # Late binding: + var = x # Module-level variable + lib.func() # Accessing library that is not compiled + +Pickling and copying objects +---------------------------- + +Mypyc tries to enforce that instances native classes are properly +initialized by calling ``__init__`` implicitly when constructing +objects, even if objects are constructed through ``pickle``, +``copy.copy`` or ``copy.deepcopy``, for example. + +If a native class doesn't support calling ``__init__`` without arguments, +you can't pickle or copy instances of the class. Use the +``mypy_extensions.mypyc_attr`` class decorator to override this behavior +and enable pickling through the ``serializable`` flag:: + + from mypy_extensions import mypyc_attr + import pickle + + @mypyc_attr(serializable=True) + class Cls: + def __init__(self, n: int) -> None: + self.n = n + + data = pickle.dumps(Cls(5)) + obj = pickle.loads(data) # OK + +Additional notes: + +* All subclasses inherit the ``serializable`` flag. +* If a class has the ``allow_interpreted_subclasses`` attribute, it + implicitly supports serialization. +* Enabling serialization may slow down attribute access, since compiled + code has to be always prepared to raise ``AttributeError`` in case an + attribute is not defined at runtime. +* If you try to pickle an object without setting the ``serializable`` + flag, you'll get a ``TypeError`` about missing arguments to + ``__init__``. + + +Monkey patching +--------------- + +Since mypyc function and class definitions are immutable, you can't +perform arbitrary monkey patching, such as replacing functions or +methods with mocks in tests. + +.. note:: + + Each compiled module has a Python namespace that is initialized to + point to compiled functions and type objects. This namespace is a + regular ``dict`` object, and it *can* be modified. However, + compiled code generally doesn't use this namespace, so any changes + will only be visible to non-compiled code. + +Stack overflows +--------------- + +Compiled code currently doesn't check for stack overflows. Your +program may crash in an unrecoverable fashion if you have too many +nested function calls, typically due to out-of-control recursion. + +.. note:: + + This limitation will be fixed in the future. + +Final values +------------ + +Compiled code replaces a reference to an attribute declared ``Final`` with +the value of the attribute computed at compile time. This is an example of +:ref:`early binding `. Example:: + + MAX: Final = 100 + + def limit_to_max(x: int) -> int: + if x > MAX: + return MAX + return x + +The two references to ``MAX`` don't involve any module namespace lookups, +and are equivalent to this code:: + + def limit_to_max(x: int) -> int: + if x > 100: + return 100 + return x + +When run as interpreted, the first example will execute slower due to +the extra namespace lookups. In interpreted code final attributes can +also be modified. + +Unsupported features +-------------------- + +Some Python features are not supported by mypyc (yet). They can't be +used in compiled code, or there are some limitations. You can +partially work around some of these limitations by running your code +in interpreted mode. + +Nested classes +************** + +Nested classes are not supported. + +Conditional functions or classes +******************************** + +Function and class definitions guarded by an if-statement are not supported. + +Dunder methods +************** + +Native classes **cannot** use these dunders. If defined, they will not +work as expected. + +* ``__del__`` +* ``__index__`` +* ``__getattr__``, ``__getattribute__`` +* ``__setattr__`` +* ``__delattr__`` + +Generator expressions +********************* + +Generator expressions are not supported. To make it easier to compile +existing code, they are implicitly replaced with list comprehensions. +*This does not always produce the same behavior.* + +To work around this limitation, you can usually use a generator +function instead. You can sometimes replace the generator expression +with an explicit list comprehension. + +Descriptors +*********** + +Native classes can't contain arbitrary descriptors. Properties, static +methods and class methods are supported. + +Introspection +************* + +Various methods of introspection may break by using mypyc. Here's an +non-exhaustive list of what won't work: + +- Instance ``__annotations__`` is usually not kept +- Frames of compiled functions can't be inspected using ``inspect`` +- Compiled methods aren't considered methods by ``inspect.ismethod`` +- ``inspect.signature`` chokes on compiled functions + +Profiling hooks and tracing +*************************** + +Compiled functions don't trigger profiling and tracing hooks, such as +when using the ``profile``, ``cProfile``, or ``trace`` modules. + +Debuggers +********* + +You can't set breakpoints in compiled functions or step through +compiled functions using ``pdb``. Often you can debug your code in +interpreted mode instead. diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/float_operations.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/float_operations.rst new file mode 100644 index 0000000000000000000000000000000000000000..feae5a806c70b220e2354cb8d2560b2cf66a6a50 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/float_operations.rst @@ -0,0 +1,50 @@ +.. _float-ops: + +Native float operations +======================== + +These ``float`` operations have fast, optimized implementations. Other +floating point operations use generic implementations that are often +slower. + +Construction +------------ + +* Float literal +* ``float(x: int)`` +* ``float(x: i64)`` +* ``float(x: i32)`` +* ``float(x: i16)`` +* ``float(x: u8)`` +* ``float(x: str)`` +* ``float(x: float)`` (no-op) + +Operators +--------- + +* Arithmetic (``+``, ``-``, ``*``, ``/``, ``//``, ``%``) +* Comparisons (``==``, ``!=``, ``<``, etc.) +* Augmented assignment (``x += y``, etc.) + +Functions +--------- + +* ``int(f)`` +* ``i64(f)`` (convert to 64-bit signed integer) +* ``i32(f)`` (convert to 32-bit signed integer) +* ``i16(f)`` (convert to 16-bit signed integer) +* ``u8(f)`` (convert to 8-bit unsigned integer) +* ``abs(f)`` +* ``math.sin(f)`` +* ``math.cos(f)`` +* ``math.tan(f)`` +* ``math.sqrt(f)`` +* ``math.exp(f)`` +* ``math.log(f)`` +* ``math.floor(f)`` +* ``math.ceil(f)`` +* ``math.fabs(f)`` +* ``math.pow(x, y)`` +* ``math.copysign(x, y)`` +* ``math.isinf(f)`` +* ``math.isnan(f)`` diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/future.md b/openflamingo/lib/python3.10/site-packages/mypyc/doc/future.md new file mode 100644 index 0000000000000000000000000000000000000000..2d8a454e94a0a54f43e890198069120720338430 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/future.md @@ -0,0 +1,42 @@ +# Future + +This document introduces some ideas for future improvements. + +## Basic Optimizations + +Implement basic optimizations such as common subexpression elimination and +loop invariant code motion. + +Importantly, common subexpression elimination could be used to avoid +redundant type checks. + +## Operation-specific Optimizations + +Some operations or combinations of successive operations can be +replaced with more efficient operations. Examples: + +* If `s` is a string, `s[i] == 'x'` doesn't need to construct the + intermediate single-character string object `s[i]` but just compare + the character value to `ord('x')`. + +* `a + ':' + b` (two string concetenations) can be implemented as + single three-operand concatenation that doesn't construct an + intermediate object. + +* `x in {1, 3}` can be translated into `x == 1 or x == 3` (more + generally we need to evaluate all right-hand-side items). + +## Integer Range Analysis + +Implement integer range analysis. This can be used in various ways: + +* Use untagged representations for some registers. +* Use faster integer arithmetic operations for operations that + only deal with short integers or that can't overflow. +* Remove redundant list and string index checks. + +## Always Defined Attributes + +Somehow make it possible to enforce that attributes in a class are always +defined. This makes attribute access faster since we don't need to explicitly +check if the attribute is defined. diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/getting_started.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/getting_started.rst new file mode 100644 index 0000000000000000000000000000000000000000..adc617419ffa31f839679f48b69c919b405ff533 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/getting_started.rst @@ -0,0 +1,240 @@ +Getting started +=============== + +Here you will learn some basic things you need to know to get started with mypyc. + +Prerequisites +------------- + +You need a Python C extension development environment. The way to set this up +depends on your operating system. + +macOS +***** + +Install Xcode command line tools: + +.. code-block:: + + $ xcode-select --install + +Linux +***** + +You need a C compiler and CPython headers and libraries. The specifics +of how to install these varies by distribution. Here are instructions for +Ubuntu 18.04, for example: + +.. code-block:: + + $ sudo apt install python3-dev + +Windows +******* + +From `Build Tools for Visual Studio 2022 `_, install MSVC C++ build tools for your architecture and a Windows SDK. (latest versions recommended) + +Installation +------------ + +Mypyc is shipped as part of the mypy distribution. Install mypy like +this (you need Python 3.8 or later): + +.. code-block:: + + $ python3 -m pip install -U 'mypy[mypyc]' + +On some systems you need to use this instead: + +.. code-block:: + + $ python -m pip install -U 'mypy[mypyc]' + +Example program +--------------- + +Let's start with a classic micro-benchmark, recursive fibonacci. Save +this file as ``fib.py``: + +.. code-block:: python + + import time + + def fib(n: int) -> int: + if n <= 1: + return n + else: + return fib(n - 2) + fib(n - 1) + + t0 = time.time() + fib(32) + print(time.time() - t0) + +Note that we gave the ``fib`` function a type annotation. Without it, +performance won't be as impressive after compilation. + +.. note:: + + `Mypy documentation + `_ is a good + introduction if you are new to type annotations or mypy. Mypyc uses + mypy to perform type checking and type inference, so some familiarity + with mypy is very useful. + +Compiling and running +--------------------- + +We can run ``fib.py`` as a regular, interpreted program using CPython: + +.. code-block:: console + + $ python3 fib.py + 0.4125328063964844 + +It took about 0.41s to run on my computer. + +Run ``mypyc`` to compile the program to a binary C extension: + +.. code-block:: console + + $ mypyc fib.py + +This will generate a C extension for ``fib`` in the current working +directory. For example, on a Linux system the generated file may be +called ``fib.cpython-37m-x86_64-linux-gnu.so``. + +Since C extensions can't be run as programs, use ``python3 -c`` to run +the compiled module as a program: + +.. code-block:: console + + $ python3 -c "import fib" + 0.04097270965576172 + +After compilation, the program is about 10x faster. Nice! + +.. note:: + + ``__name__`` in ``fib.py`` would now be ``"fib"``, not ``"__main__"``. + +You can also pass most +`mypy command line options `_ +to ``mypyc``. + +Deleting compiled binary +------------------------ + +You can manually delete the C extension to get back to an interpreted +version (this example works on Linux): + +.. code-block:: + + $ rm fib.*.so + +Using setup.py +-------------- + +You can also use ``setup.py`` to compile modules using mypyc. Here is an +example ``setup.py`` file:: + + from setuptools import setup + + from mypyc.build import mypycify + + setup( + name='mylib', + packages=['mylib'], + ext_modules=mypycify([ + 'mylib/__init__.py', + 'mylib/mod.py', + ]), + ) + +We used ``mypycify(...)`` to specify which files to compile using +mypyc. Your ``setup.py`` can include additional Python files outside +``mypycify(...)`` that won't be compiled. + +Now you can build a wheel (.whl) file for the package:: + + python3 setup.py bdist_wheel + +The wheel is created under ``dist/``. + +You can also compile the C extensions in-place, in the current directory (similar +to using ``mypyc`` to compile modules):: + + python3 setup.py build_ext --inplace + +You can include most `mypy command line options +`_ in the +list of arguments passed to ``mypycify()``. For example, here we use +the ``--disallow-untyped-defs`` flag to require that all functions +have type annotations:: + + ... + setup( + name='frobnicate', + packages=['frobnicate'], + ext_modules=mypycify([ + '--disallow-untyped-defs', # Pass a mypy flag + 'frobnicate.py', + ]), + ) + +.. note: + + You may be tempted to use `--check-untyped-defs + `_ + to type check functions without type annotations. Note that this + may reduce performance, due to many transitions between type-checked and unchecked + code. + +Recommended workflow +-------------------- + +A simple way to use mypyc is to always compile your code after any +code changes, but this can get tedious, especially if you have a lot +of code. Instead, you can do most development in interpreted mode. +This development workflow has worked smoothly for developing mypy and +mypyc (often we forget that we aren't working on a vanilla Python +project): + +1. During development, use interpreted mode. This gives you a fast + edit-run cycle. + +2. Use type annotations liberally and use mypy to type check your code + during development. Mypy and tests can find most errors that would + break your compiled code, if you have good type annotation + coverage. (Running mypy is pretty quick.) + +3. After you've implemented a feature or a fix, compile your project + and run tests again, now in compiled mode. Usually nothing will + break here, assuming your type annotation coverage is good. This + can happen locally or in a Continuous Integration (CI) job. If you + have CI, compiling locally may be rarely needed. + +4. Release or deploy a compiled version. Optionally, include a + fallback interpreted version for platforms that mypyc doesn't + support. + +This mypyc workflow only involves minor tweaks to a typical Python +workflow. Most of development, testing and debugging happens in +interpreted mode. Incremental mypy runs, especially when using the +mypy daemon, are very quick (often a few hundred milliseconds). + +Next steps +---------- + +You can sometimes get good results by just annotating your code and +compiling it. If this isn't providing meaningful performance gains, if +you have trouble getting your code to work under mypyc, or if you want +to optimize your code for maximum performance, you should read the +rest of the documentation in some detail. + +Here are some specific recommendations, or you can just read the +documentation in order: + +* :ref:`using-type-annotations` +* :ref:`native-classes` +* :ref:`differences-from-python` +* :ref:`performance-tips` diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/index.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..584d6739e803094d675bd73f7e6e4fd2acc7d221 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/index.rst @@ -0,0 +1,62 @@ +.. mypyc documentation master file, created by + sphinx-quickstart on Sun Apr 5 14:01:55 2020. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to mypyc documentation! +=============================== + +Mypyc compiles Python modules to C extensions. It uses standard Python +`type hints +`_ to +generate fast code. + +.. toctree:: + :maxdepth: 2 + :caption: First steps + + introduction + getting_started + +.. toctree:: + :maxdepth: 2 + :caption: Using mypyc + + using_type_annotations + native_classes + differences_from_python + compilation_units + +.. toctree:: + :maxdepth: 2 + :caption: Native operations reference + + native_operations + int_operations + bool_operations + float_operations + str_operations + bytes_operations + list_operations + dict_operations + set_operations + tuple_operations + +.. toctree:: + :maxdepth: 2 + :caption: Advanced topics + + performance_tips_and_tricks + +.. toctree:: + :hidden: + :caption: Project Links + + GitHub + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/int_operations.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/int_operations.rst new file mode 100644 index 0000000000000000000000000000000000000000..eb875f5c9452337fe8e30b6d8d2941d70f895d16 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/int_operations.rst @@ -0,0 +1,162 @@ +.. _int-ops: + +Native integer operations +========================= + +Mypyc supports these integer types: + +* ``int`` (arbitrary-precision integer) +* ``i64`` (64-bit signed integer) +* ``i32`` (32-bit signed integer) +* ``i16`` (16-bit signed integer) +* ``u8`` (8-bit unsigned integer) + +``i64``, ``i32``, ``i16`` and ``u8`` are *native integer types* and +are available in the ``mypy_extensions`` module. ``int`` corresponds +to the Python ``int`` type, but uses a more efficient runtime +representation (tagged pointer). Native integer types are value types. + +All integer types have optimized primitive operations, but the native +integer types are more efficient than ``int``, since they don't +require range or bounds checks. + +Operations on integers that are listed here have fast, optimized +implementations. Other integer operations use generic implementations +that are generally slower. Some operations involving integers and other +types, such as list indexing, are documented elsewhere. + +Construction +------------ + +``int`` type: + +* Integer literal +* ``int(x: float)`` +* ``int(x: i64)`` +* ``int(x: i32)`` +* ``int(x: i16)`` +* ``int(x: u8)`` +* ``int(x: str)`` +* ``int(x: str, base: int)`` +* ``int(x: int)`` (no-op) + +``i64`` type: + +* ``i64(x: int)`` +* ``i64(x: float)`` +* ``i64(x: i64)`` (no-op) +* ``i64(x: i32)`` +* ``i64(x: i16)`` +* ``i64(x: u8)`` +* ``i64(x: str)`` +* ``i64(x: str, base: int)`` + +``i32`` type: + +* ``i32(x: int)`` +* ``i32(x: float)`` +* ``i32(x: i64)`` (truncate) +* ``i32(x: i32)`` (no-op) +* ``i32(x: i16)`` +* ``i32(x: u8)`` +* ``i32(x: str)`` +* ``i32(x: str, base: int)`` + +``i16`` type: + +* ``i16(x: int)`` +* ``i16(x: float)`` +* ``i16(x: i64)`` (truncate) +* ``i16(x: i32)`` (truncate) +* ``i16(x: i16)`` (no-op) +* ``i16(x: u8)`` +* ``i16(x: str)`` +* ``i16(x: str, base: int)`` + +Conversions from ``int`` to a native integer type raise +``OverflowError`` if the value is too large or small. Conversions from +a wider native integer type to a narrower one truncate the value and never +fail. More generally, operations between native integer types don't +check for overflow. + +Implicit conversions +-------------------- + +``int`` values can be implicitly converted to a native integer type, +for convenience. This means that these are equivalent:: + + from mypy_extensions import i64 + + def implicit() -> None: + # Implicit conversion of 0 (int) to i64 + x: i64 = 0 + + def explicit() -> None: + # Explicit conversion of 0 (int) to i64 + x = i64(0) + +Similarly, a native integer value can be implicitly converted to an +arbitrary-precision integer. These two functions are equivalent:: + + def implicit(x: i64) -> int: + # Implicit conversion from i64 to int + return x + + def explicit(x: i64) -> int: + # Explicit conversion from i64 to int + return int(x) + +Operators +--------- + +* Arithmetic (``+``, ``-``, ``*``, ``//``, ``/``, ``%``) +* Bitwise operations (``&``, ``|``, ``^``, ``<<``, ``>>``, ``~``) +* Comparisons (``==``, ``!=``, ``<``, etc.) +* Augmented assignment (``x += y``, etc.) + +If one of the above native integer operations overflows or underflows +with signed operands, the behavior is undefined. Signed native integer +types should only be used if all possible values are small enough for +the type. For this reason, the arbitrary-precision ``int`` type is +recommended for signed values unless the performance of integer +operations is critical. + +Operations on unsigned integers (``u8``) wrap around on overflow. + +It's a compile-time error to mix different native integer types in a +binary operation such as addition. An explicit conversion is required:: + + from mypy_extensions import i64, i32 + + def add(x: i64, y: i32) -> None: + a = x + y # Error (i64 + i32) + b = x + i64(y) # OK + +You can freely mix a native integer value and an arbitrary-precision +``int`` value in an operation. The native integer type is "sticky" +and the ``int`` operand is coerced to the native integer type:: + + def example(x: i64, y: int) -> None: + a = x * y + # Type of "a" is "i64" + ... + b = 1 - x + # Similarly, type of "b" is "i64" + +Statements +---------- + +For loop over a range is compiled efficiently, if the ``range(...)`` object +is constructed in the for statement (after ``in``): + +* ``for x in range(end)`` +* ``for x in range(start, end)`` +* ``for x in range(start, end, step)`` + +If one of the arguments to ``range`` in a for loop is a native integer +type, the type of the loop variable is inferred to have this native +integer type, instead of ``int``:: + + for x in range(i64(n)): + # Type of "x" is "i64" + ... diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/introduction.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/introduction.rst new file mode 100644 index 0000000000000000000000000000000000000000..53c86ecdab1b54bef4a6ddc05de29c3531cfbb5a --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/introduction.rst @@ -0,0 +1,150 @@ +Introduction +============ + +Mypyc compiles Python modules to C extensions. It uses standard Python +`type hints +`_ to +generate fast code. + +The compiled language is a strict, *gradually typed* Python variant. It +restricts the use of some dynamic Python features to gain performance, +but it's mostly compatible with standard Python. + +Mypyc uses `mypy `_ to perform type +checking and type inference. Most type system features in the stdlib +`typing `_ module are +supported. + +Compiled modules can import arbitrary Python modules and third-party +libraries. You can compile anything from a single performance-critical +module to your entire codebase. You can run the modules you compile +also as normal, interpreted Python modules. + +Existing code with type annotations is often **1.5x to 5x** faster +when compiled. Code tuned for mypyc can be **5x to 10x** faster. + +Mypyc currently aims to speed up non-numeric code, such as server +applications. Mypyc is also used to compile itself (and mypy). + +Why mypyc? +---------- + +**Easy to get started.** Compiled code has the look and feel of +regular Python code. Mypyc supports familiar Python syntax and idioms. + +**Expressive types.** Mypyc fully supports standard Python type hints. +Mypyc has local type inference, generics, optional types, tuple types, +union types, and more. Type hints act as machine-checked +documentation, making code not only faster but also easier to +understand and modify. + +**Python ecosystem.** Mypyc runs on top of CPython, the +standard Python implementation. You can use any third-party libraries, +including C extensions, installed with pip. Mypyc uses only valid Python +syntax, so all Python editors and IDEs work perfectly. + +**Fast program startup.** Mypyc uses ahead-of-time compilation, so +compilation does not slow down program startup. Slow program startup +is a common issue with JIT compilers. + +**Migration path for existing code.** Existing Python code often +requires only minor changes to compile using mypyc. + +**Waiting for compilation is optional.** Compiled code also runs as +normal Python code. You can use interpreted Python during development, +with familiar and fast workflows. + +**Runtime type safety.** Mypyc protects you from segfaults and memory +corruption. Any unexpected runtime type safety violation is a bug in +mypyc. Runtime values are checked against type annotations. (Without +mypyc, type annotations are ignored at runtime.) + +**Find errors statically.** Mypyc uses mypy for static type checking +that helps catch many bugs. + +Use cases +--------- + +**Fix only performance bottlenecks.** Often most time is spent in a few +Python modules or functions. Add type annotations and compile these +modules for easy performance gains. + +**Compile it all.** During development you can use interpreted mode, +for a quick edit-run cycle. In releases all non-test code is compiled. +This is how mypy achieved a 4x performance improvement over interpreted +Python. + +**Take advantage of existing type hints.** If you already use type +annotations in your code, adopting mypyc will be easier. You've already +done most of the work needed to use mypyc. + +**Alternative to a lower-level language.** Instead of writing +performance-critical code in C, C++, Cython or Rust, you may get good +performance while staying in the comfort of Python. + +**Migrate C extensions.** Maintaining C extensions is not always fun +for a Python developer. With mypyc you may get performance similar to +the original C, with the convenience of Python. + +Differences from Cython +----------------------- + +Mypyc targets many similar use cases as Cython. Mypyc does many things +differently, however: + +* No need to use non-standard syntax, such as ``cpdef``, or extra + decorators to get good performance. Clean, normal-looking + type-annotated Python code can be fast without language extensions. + This makes it practical to compile entire codebases without a + developer productivity hit. + +* Mypyc has first-class support for features in the ``typing`` module, + such as tuple types, union types and generics. + +* Mypyc has powerful type inference, provided by mypy. Variable type + annotations are not needed for optimal performance. + +* Mypyc fully integrates with mypy for robust and seamless static type + checking. + +* Mypyc performs strict enforcement of type annotations at runtime, + resulting in better runtime type safety and easier debugging. + +Unlike Cython, mypyc doesn't directly support interfacing with C libraries +or speeding up numeric code. + +How does it work +---------------- + +Mypyc uses several techniques to produce fast code: + +* Mypyc uses *ahead-of-time compilation* to native code. This removes + CPython interpreter overhead. + +* Mypyc enforces type annotations (and type comments) at runtime, + raising ``TypeError`` if runtime values don't match annotations. + Value types only need to be checked in the boundaries between + dynamic and static typing. + +* Compiled code uses optimized, type-specific primitives. + +* Mypyc uses *early binding* to resolve called functions and name + references at compile time. Mypyc avoids many dynamic namespace + lookups. + +* Classes are compiled to *C extension classes*. They use `vtables + `_ for fast + method calls and attribute access. + +* Mypyc treats compiled functions, classes, and attributes declared + ``Final`` as immutable. + +* Mypyc has memory-efficient, unboxed representations for integers and + booleans. + +Development status +------------------ + +Mypyc is currently alpha software. It's only recommended for +production use cases with careful testing, and if you are willing to +contribute fixes or to work around issues you will encounter. diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/list_operations.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/list_operations.rst new file mode 100644 index 0000000000000000000000000000000000000000..5993c0a656bda924a98f34c76a3f4172e81c4aac --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/list_operations.rst @@ -0,0 +1,65 @@ +.. _list-ops: + +Native list operations +====================== + +These ``list`` operations have fast, optimized implementations. Other +list operations use generic implementations that are often slower. + +Construction +------------ + +Construct list with specific items: + +* ``[item0, ..., itemN]`` + +Construct empty list: + +* ``[]`` +* ``list()`` + +Construct list from iterable: + +* ``list(x: Iterable)`` + +List comprehensions: + +* ``[... for ... in ...]`` +* ``[... for ... in ... if ...]`` + +Operators +--------- + +* ``lst[n]`` (get item by integer index) +* ``lst[n:m]``, ``lst[n:]``, ``lst[:m]``, ``lst[:]`` (slicing) +* ``lst * n``, ``n * lst`` +* ``obj in lst`` + +Statements +---------- + +Set item by integer index: + +* ``lst[n] = x`` + +For loop over a list: + +* ``for item in lst:`` + +Methods +------- + +* ``lst.append(obj)`` +* ``lst.extend(x: Iterable)`` +* ``lst.insert(index, obj)`` +* ``lst.pop(index=-1)`` +* ``lst.remove(obj)`` +* ``lst.count(obj)`` +* ``lst.index(obj)`` +* ``lst.reverse()`` +* ``lst.sort()`` + +Functions +--------- + +* ``len(lst: list)`` diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/native_classes.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/native_classes.rst new file mode 100644 index 0000000000000000000000000000000000000000..b2935a6f71856832f46713748a7abd8902819dc5 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/native_classes.rst @@ -0,0 +1,206 @@ +.. _native-classes: + +Native classes +============== + +Classes in compiled modules are *native classes* by default (some +exceptions are discussed below). Native classes are compiled to C +extension classes, which have some important differences from normal +Python classes. Native classes are similar in many ways to built-in +types, such as ``int``, ``str``, and ``list``. + +Immutable namespaces +-------------------- + +The type object namespace of native classes is mostly immutable (but +class variables can be assigned to):: + + class Cls: + def method1(self) -> None: + print("method1") + + def method2(self) -> None: + print("method2") + + Cls.method1 = Cls.method2 # Error + Cls.new_method = Cls.method2 # Error + +Only attributes defined within a class definition (or in a base class) +can be assigned to (similar to using ``__slots__``):: + + class Cls: + x: int + + def __init__(self, y: int) -> None: + self.x = 0 + self.y = y + + def method(self) -> None: + self.z = "x" + + o = Cls(0) + print(o.x, o.y) # OK + o.z = "y" # OK + o.extra = 3 # Error: no attribute "extra" + +.. _inheritance: + +Inheritance +----------- + +Only single inheritance is supported (except for :ref:`traits +`). Most non-native classes can't be used as base +classes. + +These non-native classes can be used as base classes of native +classes: + +* ``object`` +* ``dict`` (and ``Dict[k, v]``) +* ``BaseException`` +* ``Exception`` +* ``ValueError`` +* ``IndexError`` +* ``LookupError`` +* ``UserWarning`` +* ``typing.NamedTuple`` +* ``enum.Enum`` + +By default, a non-native class can't inherit a native class, and you +can't inherit from a native class outside the compilation unit that +defines the class. You can enable these through +``mypy_extensions.mypyc_attr``:: + + from mypy_extensions import mypyc_attr + + @mypyc_attr(allow_interpreted_subclasses=True) + class Cls: + ... + +Allowing interpreted subclasses has only minor impact on performance +of instances of the native class. Accessing methods and attributes of +a *non-native* subclass (or a subclass defined in another compilation +unit) will be slower, since it needs to use the normal Python +attribute access mechanism. + +You need to install ``mypy-extensions`` to use ``@mypyc_attr``: + +.. code-block:: text + + pip install --upgrade mypy-extensions + +Class variables +--------------- + +Class variables must be explicitly declared using ``attr: ClassVar`` +or ``attr: ClassVar[]``. You can't assign to a class variable +through an instance. Example:: + + from typing import ClassVar + + class Cls: + cv: ClassVar = 0 + + Cls.cv = 2 # OK + o = Cls() + print(o.cv) # OK (2) + o.cv = 3 # Error! + +.. tip:: + + Constant class variables can be declared using ``typing.Final`` or + ``typing.Final[]``. + +Generic native classes +---------------------- + +Native classes can be generic. Type variables are *erased* at runtime, +and instances don't keep track of type variable values. + +Compiled code thus can't check the values of type variables when +performing runtime type checks. These checks are delayed to when +reading a value with a type variable type:: + + from typing import TypeVar, Generic, cast + + T = TypeVar('T') + + class Box(Generic[T]): + def __init__(self, item: T) -> None: + self.item = item + + x = Box(1) # Box[int] + y = cast(Box[str], x) # OK (type variable value not checked) + y.item # Runtime error: item is "int", but "str" expected + +Metaclasses +----------- + +Most metaclasses aren't supported with native classes, since their +behavior is too dynamic. You can use these metaclasses, however: + +* ``abc.ABCMeta`` +* ``typing.GenericMeta`` (used by ``typing.Generic``) + +.. note:: + + If a class definition uses an unsupported metaclass, *mypyc + compiles the class into a regular Python class*. + +Class decorators +---------------- + +Similar to metaclasses, most class decorators aren't supported with +native classes, as they are usually too dynamic. These class +decorators can be used with native classes, however: + +* ``mypy_extensions.trait`` (for defining :ref:`trait types `) +* ``mypy_extensions.mypyc_attr`` (see :ref:`above `) +* ``dataclasses.dataclass`` +* ``@attr.s(auto_attribs=True)`` + +Dataclasses and attrs classes have partial native support, and they aren't as +efficient as pure native classes. + +.. note:: + + If a class definition uses an unsupported class decorator, *mypyc + compiles the class into a regular Python class*. + +Deleting attributes +------------------- + +By default, attributes defined in native classes can't be deleted. You +can explicitly allow certain attributes to be deleted by using +``__deletable__``:: + + class Cls: + x: int = 0 + y: int = 0 + other: int = 0 + + __deletable__ = ['x', 'y'] # 'x' and 'y' can be deleted + + o = Cls() + del o.x # OK + del o.y # OK + del o.other # Error + +You must initialize the ``__deletable__`` attribute in the class body, +using a list or a tuple expression with only string literal items that +refer to attributes. These are not valid:: + + a = ['x', 'y'] + + class Cls: + x: int + y: int + + __deletable__ = a # Error: cannot use variable 'a' + + __deletable__ = ('a',) # Error: not in a class body + +Other properties +---------------- + +Instances of native classes don't usually have a ``__dict__`` attribute. diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/native_operations.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/native_operations.rst new file mode 100644 index 0000000000000000000000000000000000000000..2587e982feac6484a2e03073bf115c85a4b32c91 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/native_operations.rst @@ -0,0 +1,55 @@ +Miscellaneous native operations +=============================== + +This is a list of various non-type-specific operations that have +custom native implementations. If an operation has no native +implementation, mypyc will use fallback generic implementations that +are often not as fast. + +.. note:: + + Operations specific to various primitive types are described + in the following sections. + +Operators +--------- + +* ``x is y`` (this is very fast for all types) + +Functions +--------- + +* ``isinstance(obj, type: type)`` +* ``isinstance(obj, type: tuple)`` +* ``cast(, obj)`` +* ``type(obj)`` +* ``len(obj)`` +* ``abs(obj)`` +* ``id(obj)`` +* ``iter(obj)`` +* ``next(iter: Iterator)`` +* ``hash(obj)`` +* ``getattr(obj, attr)`` +* ``getattr(obj, attr, default)`` +* ``setattr(obj, attr, value)`` +* ``hasattr(obj, attr)`` +* ``delattr(obj, name)`` +* ``slice(start, stop, step)`` +* ``globals()`` + +Method decorators +----------------- + +* ``@property`` +* ``@staticmethod`` +* ``@classmethod`` +* ``@abc.abstractmethod`` + +Statements +---------- + +These variants of statements have custom implementations: + +* ``for ... in seq:`` (for loop over a sequence) +* ``for ... in enumerate(...):`` +* ``for ... in zip(...):`` diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/performance_tips_and_tricks.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/performance_tips_and_tricks.rst new file mode 100644 index 0000000000000000000000000000000000000000..ae0b2950814c730d22d202706b99b23c493b61cb --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/performance_tips_and_tricks.rst @@ -0,0 +1,244 @@ +.. _performance-tips: + +Performance tips and tricks +=========================== + +Performance optimization is part art, part science. Just using mypyc +in a simple manner will likely make your code faster, but squeezing +the most performance out of your code requires the use of some +techniques we'll summarize below. + +Profiling +--------- + +If you are speeding up existing code, understanding where time is +spent is important. Mypyc speeds up code that you compile. If most of +the time is spent elsewhere, you may come back disappointed. For +example, if you spend 40% of time outside compiled code, even if +compiled code would go 100x faster, overall performance will only be +2.5x faster. + +A simple (but often effective) approach is to record the time in +various points of program execution using ``time.time()``, and to +print out elapsed time (or to write it to a log file). + +The stdlib modules ``profile`` and ``cProfile`` can provide much more +detailed data. (But these only work well with non-compiled code.) + +Avoiding slow libraries +----------------------- + +If profiling indicates that a lot of time is spent in the stdlib or +third-party libraries, you still have several options. + +First, if most time is spent in a few library features, you can +perhaps easily reimplement them in type-annotated Python, or extract +the relevant code and annotate it. Now it may be easy to compile this +code to speed it up. + +Second, you may be able to avoid the library altogether, or use an +alternative, more efficient library to achieve the same purpose. + +Type annotations +---------------- + +As discussed earlier, type annotations are key to major performance +gains. You should at least consider adding annotations to any +performance-critical functions and classes. It may also be helpful to +annotate code called by this code, even if it's not compiled, since +this may help mypy infer better types in the compile code. If you use +libraries, ensure they have stub files with decent type annotation +coverage. Writing a stub file is often easy, and you only need to +annotate features you use a lot. + +If annotating external code or writing stubs feel too burdensome, a +simple workaround is to annotate variables explicitly. For example, +here we call ``acme.get_items()``, but it has no type annotation. We +can use an explicit type annotation for the variable to which we +assign the result:: + + from typing import List, Tuple + import acme + + def work() -> None: + # Annotate "items" to help mypyc + items: List[Tuple[int, str]] = acme.get_items() + for item in items: + ... # Do some work here + +Without the annotation on ``items``, the type would be ``Any`` (since +``acme`` has no type annotation), resulting in slower, generic +operations being used later in the function. + +Avoiding slow Python features +----------------------------- + +Mypyc can optimize some features more effectively than others. Here +the difference is sometimes big -- some things only get marginally +faster at best, while others can get 10x faster, or more. Avoiding +these slow features in performance-critical parts of your code can +help a lot. + +These are some of the most important things to avoid: + +* Using class decorators or metaclasses in compiled code (that aren't + properly supported by mypyc) + +* Heavy reliance on interpreted Python libraries (C extensions are + usually fine) + +These things also tend to be relatively slow: + +* Using Python classes and instances of Python classes (native classes + are much faster) + +* Calling decorated functions (``@property``, ``@staticmethod``, and + ``@classmethod`` are special cased and thus fast) + +* Calling nested functions + +* Calling functions or methods defined in other compilation units + +* Using ``*args`` or ``**kwargs`` + +* Using generator functions + +* Using callable values (i.e. not leveraging early binding to call + functions or methods) + +Nested functions can often be replaced with module-level functions or +methods of native classes. + +Callable values and nested functions can sometimes be replaced with an +instance of a native class with a single method only, such as +``call(...)``. You can derive the class from an ABC, if there are +multiple possible functions. + +.. note:: + + Some slow features will likely get efficient implementations in the + future. You should check this section every once in a while to see + if some additional operations are fast. + +Using fast native features +-------------------------- + +Some native operations are particularly quick relative to the +corresponding interpreted operations. Using them as much as possible +may allow you to see 10x or more in performance gains. + +Some things are not much (or any) faster in compiled code, such as set +math operations. In contrast, calling a method of a native class is +much faster in compiled code. + +If you are used to optimizing for CPython, you might have replaced +some class instances with dictionaries, as they can be +faster. However, in compiled code, this "optimization" would likely +slow down your code. + +Similarly, caching a frequently called method in a local variable can +help in CPython, but it can slow things down in compiled code, since +the code won't use :ref:`early binding `:: + + def squares(n: int) -> List[int]: + a = [] + append = a.append # Not a good idea in compiled code! + for i in range(n): + append(i * i) + return a + +Here are examples of features that are fast, in no particular order +(this list is *not* exhaustive): + +* Calling compiled functions directly defined in the same compilation + unit (with positional and/or keyword arguments) + +* Calling methods of native classes defined in the same compilation + unit (with positional and/or keyword arguments) + +* Many integer operations + +* Many ``float`` operations + +* Booleans + +* :ref:`Native list operations `, such as indexing, + ``append``, and list comprehensions + +* While loops + +* For loops over ranges and lists, and with ``enumerate`` or ``zip`` + +* Reading dictionary items + +* ``isinstance()`` checks against native classes and instances of + primitive types (and unions of them) + +* Accessing local variables + +* Accessing attributes of native classes + +* Accessing final module-level attributes + +* Comparing strings for equality + +These features are also fast, but somewhat less so (relative to other +related operations): + +* Constructing instances of native classes + +* Constructing dictionaries + +* Setting dictionary items + +* Native :ref:`dict ` and :ref:`set ` operations + +* Accessing module-level variables + +Generally anything documented as a native operation is fast, even if +it's not explicitly mentioned here + +Adjusting garbage collection +---------------------------- + +Compilation does not speed up cyclic garbage collection. If everything +else gets much faster, it's possible that garbage collection will take +a big fraction of time. You can use ``gc.set_threshold()`` to adjust +the garbage collector to run less often:: + + import gc + + # Spend less time in gc; do this before significant computation + gc.set_threshold(150000) + + ... # Actual work happens here + +Fast interpreter shutdown +------------------------- + +If you allocate many objects, it's possible that your program spends a +lot of time cleaning up when the Python runtime shuts down. Mypyc +won't speed up the shutdown of a Python process much. + +You can call ``os._exit(code)`` to immediately terminate the Python +process, skipping normal cleanup. This can give a nice boost to a +batch process or a command-line tool. + +.. note:: + + This can be dangerous and can lose data. You need to ensure + that all streams are flushed and everything is otherwise cleaned up + properly. + +Work smarter +------------ + +Usually there are many things you can do to improve performance, even +if most tweaks will yield only minor gains. The key to being effective +is to focus on things that give a large gain with a small effort. + +For example, low-level optimizations, such as avoiding a nested +function, can be pointless, if you could instead avoid a metaclass -- +to allow a key class to be compiled as a native class. The latter +optimization could speed up numerous method calls and attribute +accesses, just like that. diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/set_operations.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/set_operations.rst new file mode 100644 index 0000000000000000000000000000000000000000..433e29ea123a8da3ea784a322c53f4ba706ea571 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/set_operations.rst @@ -0,0 +1,47 @@ +.. _set-ops: + +Native set operations +====================== + +These ``set`` operations have fast, optimized implementations. Other +set operations use generic implementations that are often slower. + +Construction +------------ + +Construct set with specific items: + +* ``{item0, ..., itemN}`` + +Construct empty set: + +* ``set()`` + +Construct set from iterable: + +* ``set(x: Iterable)`` + +Set comprehensions: + +* ``{... for ... in ...}`` +* ``{... for ... in ... if ...}`` + +Operators +--------- + +* ``item in s`` + +Methods +------- + +* ``s.add(item)`` +* ``s.remove(item)`` +* ``s.discard(item)`` +* ``s.update(x: Iterable)`` +* ``s.clear()`` +* ``s.pop()`` + +Functions +--------- + +* ``len(s: set)`` diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/str_operations.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/str_operations.rst new file mode 100644 index 0000000000000000000000000000000000000000..9e94f1b6d7bbe761294deb64040b321aeaf66ad1 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/str_operations.rst @@ -0,0 +1,59 @@ +.. _str-ops: + +Native string operations +======================== + +These ``str`` operations have fast, optimized implementations. Other +string operations use generic implementations that are often slower. + +Construction +------------ + +* String literal +* ``str(x: int)`` +* ``str(x: object)`` + +Operators +--------- + +* Concatenation (``s1 + s2``) +* Indexing (``s[n]``) +* Slicing (``s[n:m]``, ``s[n:]``, ``s[:m]``) +* Comparisons (``==``, ``!=``) +* Augmented assignment (``s1 += s2``) + +.. _str-methods: + +Methods +------- + +* ``s.encode()`` +* ``s.encode(encoding: str)`` +* ``s.encode(encoding: str, errors: str)`` +* ``s1.endswith(s2: str)`` +* ``s.join(x: Iterable)`` +* ``s.replace(old: str, new: str)`` +* ``s.replace(old: str, new: str, count: int)`` +* ``s.split()`` +* ``s.split(sep: str)`` +* ``s.split(sep: str, maxsplit: int)`` +* ``s1.startswith(s2: str)`` + +.. note:: + + :ref:`bytes.decode() ` is also optimized. + +Formatting +---------- + +A subset of these common string formatting expressions are optimized: + +* F-strings +* ``"...".format(...)`` +* ``"..." % (...)`` + +Functions +--------- + +* ``len(s: str)`` +* ``ord(s: str)`` diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/doc/using_type_annotations.rst b/openflamingo/lib/python3.10/site-packages/mypyc/doc/using_type_annotations.rst new file mode 100644 index 0000000000000000000000000000000000000000..04c923819d547f9729388b166042bbbdba9772eb --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/doc/using_type_annotations.rst @@ -0,0 +1,398 @@ +.. _using-type-annotations: + +Using type annotations +====================== + +You will get the most out of mypyc if you compile code with precise +type annotations. Not all type annotations will help performance +equally, however. Using types such as :ref:`primitive types +`, :ref:`native classes `, +:ref:`union types `, :ref:`trait types `, +and :ref:`tuple types ` as much as possible is a key to +major performance gains over CPython. + +In contrast, some other types, including ``Any``, are treated as +:ref:`erased types `. Operations on erased types use +generic operations that work with arbitrary objects, similar to how +the CPython interpreter works. If you only use erased types, the only +notable benefits over CPython will be the removal of interpreter +overhead (from compilation) and a bit of :ref:`early binding +`, which will usually only give minor performance +gains. + +.. _primitive-types: + +Primitive types +--------------- + +The following built-in types are treated as *primitive types* by +mypyc, and many operations on these types have efficient +implementations: + +* ``int`` (:ref:`native operations `) +* ``i64`` (:ref:`documentation `, :ref:`native operations `) +* ``i32`` (:ref:`documentation `, :ref:`native operations `) +* ``i16`` (:ref:`documentation `, :ref:`native operations `) +* ``u8`` (:ref:`documentation `, :ref:`native operations `) +* ``float`` (:ref:`native operations `) +* ``bool`` (:ref:`native operations `) +* ``str`` (:ref:`native operations `) +* ``List[T]`` (:ref:`native operations `) +* ``Dict[K, V]`` (:ref:`native operations `) +* ``Set[T]`` (:ref:`native operations `) +* ``Tuple[T, ...]`` (variable-length tuple; :ref:`native operations `) +* ``None`` + +The link after each type lists all supported native, optimized +operations for the type. You can use all operations supported by +Python, but *native operations* will have custom, optimized +implementations. + +Primitive containers +-------------------- + +Primitive container objects such as ``list`` and ``dict`` don't +maintain knowledge of the item types at runtime -- the item type is +*erased*. + +This means that item types are checked when items are accessed, not +when a container is passed as an argument or assigned to another +variable. For example, here we have a runtime type error on the final +line of ``example`` (the ``Any`` type means an arbitrary, unchecked +value):: + + from typing import List, Any + + def example(a: List[Any]) -> None: + b: List[int] = a # No error -- items are not checked + print(b[0]) # Error here -- got str, but expected int + + example(["x"]) + +.. _native-class-intro: + +Native classes +-------------- + +Classes that get compiled to C extensions are called native +classes. Most common operations on instances of these classes are +optimized, including construction, attribute access and method calls. + +Native class definitions look exactly like normal Python class +definitions. A class is usually native if it's in a compiled module +(though there are some exceptions). + +Consider this example: + +.. code-block:: + + class Point: + def __init__(self, x: int, y: int) -> None: + self.x = x + self.y = y + + def shift(p: Point) -> Point: + return Point(p.x + 1, p.y + 1) + +All operations in the above example use native operations, if the file +is compiled. + +Native classes have some notable different from Python classes: + +* Only attributes and methods defined in the class body or methods are + supported. If you try to assign to an undefined attribute outside + the class definition, ``AttributeError`` will be raised. This enables + an efficient memory layout and fast method calls for native classes. + +* Native classes usually don't define the ``__dict__`` attribute (they + don't have an attribute dictionary). This follows from only having + a specific set of attributes. + +* Native classes can't have an arbitrary metaclass or use most class + decorators. + +Native classes only support single inheritance. A limited form of +multiple inheritance is supported through *trait types*. You generally +must inherit from another native class (or ``object``). By default, +you can't inherit a Python class from a native class (but there's +an :ref:`override ` to allow that). + +See :ref:`native-classes` for more details. + +.. _tuple-types: + +Tuple types +----------- + +Fixed-length +`tuple types `_ +such as ``Tuple[int, str]`` are represented +as :ref:`value types ` when stored in variables, +passed as arguments, or returned from functions. Value types are +allocated in the low-level machine stack or in CPU registers, as +opposed to *heap types*, which are allocated dynamically from the +heap. + +Like all value types, tuples will be *boxed*, i.e. converted to +corresponding heap types, when stored in Python containers, or passed +to non-native code. A boxed tuple value will be a regular Python tuple +object. + +.. _union-types: + +Union types +----------- + +`Union types `_ +and +`optional types `_ +that contain primitive types, native class types and +trait types are also efficient. If a union type has +:ref:`erased ` items, accessing items with +non-erased types is often still quite efficient. + +A value with a union types is always :ref:`boxed `, +even if it contains a value that also has an unboxed representation, such +as an integer or a boolean. + +For example, using ``Optional[int]`` is quite efficient, but the value +will always be boxed. A plain ``int`` value will usually be faster, since +it has an unboxed representation. + +.. _trait-types: + +Trait types +----------- + +Trait types enable a form of multiple inheritance for native classes. +A native class can inherit any number of traits. Trait types are +defined as classes using the ``mypy_extensions.trait`` decorator:: + + from mypy_extensions import trait + + @trait + class MyTrait: + def method(self) -> None: + ... + +Traits can define methods, properties and attributes. They often +define abstract methods. Traits can be generic. + +If a class subclasses both a non-trait class and traits, the traits +must be placed at the end of the base class list:: + + class Base: ... + + class Derived(Base, MyTrait, FooTrait): # OK + ... + + class Derived2(MyTrait, FooTrait, Base): + # Error: traits should come last + ... + +Traits have some special properties: + +* You shouldn't create instances of traits (though mypyc does not + prevent it yet). + +* Traits can subclass other traits or native classes, but the MRO must be + linear (just like with native classes). + +* Accessing methods or attributes through a trait type is somewhat + less efficient than through a native class type, but this is much + faster than through Python class types or other + :ref:`erased types `. + +You need to install ``mypy-extensions`` to use ``@trait``: + +.. code-block:: text + + pip install --upgrade mypy-extensions + +.. _erased-types: + +Erased types +------------ + +Mypyc supports many other kinds of types as well, beyond those +described above. However, these types don't have customized +operations, and they are implemented using *type erasure*. Type +erasure means that all other types are equivalent to untyped values at +runtime, i.e. they are the equivalent of the type ``Any``. Erased +types include these: + +* Python classes (including ABCs) + +* Non-mypyc extension types and primitive types (including built-in + types that are not primitives) + +* `Callable types `_ + +* `Type variable types `_ + +* Type `Any `_ + +* Protocol types + +Using erased types can still improve performance, since they can +enable better types to be inferred for expressions that use these +types. For example, a value with type ``Callable[[], int]`` will not +allow native calls. However, the return type is a primitive type, and +we can use fast operations on the return value:: + + from typing import Callable + + def call_and_inc(f: Callable[[], int]) -> int: + # Slow call, since f has an erased type + n = f() + # Fast increment; inferred type of n is int (primitive type) + n += 1 + return n + +If the type of the argument ``f`` was ``Any``, the type of ``n`` would +also be ``Any``, resulting in a generic, slower increment operation +being used. + +Strict runtime type checking +---------------------------- + +Compiled code ensures that any variable or expression with a +non-erased type only has compatible values at runtime. This is in +contrast with using *optional static typing*, such as by using mypy, +when type annotations are not enforced at runtime. Mypyc ensures +type safety both statically and at runtime. + +``Any`` types and erased types in general can compromise type safety, +and this is by design. Inserting strict runtime type checks for all +possible values would be too expensive and against the goal of +high performance. + +.. _value-and-heap-types: + +Value and heap types +-------------------- + +In CPython, memory for all objects is dynamically allocated on the +heap. All Python types are thus *heap types*. In compiled code, some +types are *value types* -- no object is (necessarily) allocated on the +heap. ``bool``, ``float``, ``None``, :ref:`native integer types ` +and fixed-length tuples are value types. + +``int`` is a hybrid. For typical integer values, it is a value +type. Large enough integer values, those that require more than 63 +bits (or 31 bits on 32-bit platforms) to represent, use a heap-based +representation (same as CPython). + +Value types have a few differences from heap types: + +* When an instance of a value type is used in a context that expects a + heap value, for example as a list item, it will transparently switch + to a heap-based representation (boxing) as needed. + +* Similarly, mypyc transparently changes from a heap-based + representation to a value representation (unboxing). + +* Object identity of integers, floating point values and tuples is not + preserved. You should use ``==`` instead of ``is`` if you are comparing + two integers, floats or fixed-length tuples. + +* When an instance of a subclass of a value type is converted to the + base type, it is implicitly converted to an instance of the target + type. For example, a ``bool`` value assigned to a variable with an + ``int`` type will be converted to the corresponding integer. + +The latter conversion is the only implicit type conversion that +happens in mypyc programs. + +Example:: + + def example() -> None: + # A small integer uses the value (unboxed) representation + x = 5 + # A large integer uses the heap (boxed) representation + x = 2**500 + # Lists always contain boxed integers + a = [55] + # When reading from a list, the object is automatically unboxed + x = a[0] + # True is converted to 1 on assignment + x = True + +Since integers and floating point values have a different runtime +representations and neither can represent all the values of the other +type, type narrowing of floating point values through assignment is +disallowed in compiled code. For consistency, mypyc rejects assigning +an integer value to a float variable even in variable initialization. +An explicit conversion is required. + +Examples:: + + def narrowing(n: int) -> None: + # Error: Incompatible value representations in assignment + # (expression has type "int", variable has type "float") + x: float = 0 + + y: float = 0.0 # Ok + + if f(): + y = n # Error + if f(): + y = float(n) # Ok + +.. _native-ints: + +Native integer types +-------------------- + +You can use the native integer types ``i64`` (64-bit signed integer), +``i32`` (32-bit signed integer), ``i16`` (16-bit signed integer), and +``u8`` (8-bit unsigned integer) if you know that integer values will +always fit within fixed bounds. These types are faster than the +arbitrary-precision ``int`` type, since they don't require overflow +checks on operations. They may also use less memory than ``int`` +values. The types are imported from the ``mypy_extensions`` module +(installed via ``pip install mypy_extensions``). + +Example:: + + from mypy_extensions import i64 + + def sum_list(l: list[i64]) -> i64: + s: i64 = 0 + for n in l: + s += n + return s + + # Implicit conversions from int to i64 + print(sum_list([1, 3, 5])) + +.. note:: + + Since there are no overflow checks when performing native integer + arithmetic, the above function could result in an overflow or other + undefined behavior if the sum might not fit within 64 bits. + + The behavior when running as interpreted Python program will be + different if there are overflows. Declaring native integer types + have no effect unless code is compiled. Native integer types are + effectively equivalent to ``int`` when interpreted. + +Native integer types have these additional properties: + +* Values can be implicitly converted between ``int`` and a native + integer type (both ways). + +* Conversions between different native integer types must be explicit. + A conversion to a narrower native integer type truncates the value + without a runtime overflow check. + +* If a binary operation (such as ``+``) or an augmented assignment + (such as ``+=``) mixes native integer and ``int`` values, the + ``int`` operand is implicitly coerced to the native integer type + (native integer types are "sticky"). + +* You can't mix different native integer types in binary + operations. Instead, convert between types explicitly. + +For more information about native integer types, refer to +:ref:`native integer operations `. diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/ir/__pycache__/func_ir.cpython-310.pyc b/openflamingo/lib/python3.10/site-packages/mypyc/ir/__pycache__/func_ir.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34ba9e83cf186fd9148262c0de210f7442552a62 Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/ir/__pycache__/func_ir.cpython-310.pyc differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/ir/class_ir.py b/openflamingo/lib/python3.10/site-packages/mypyc/ir/class_ir.py new file mode 100644 index 0000000000000000000000000000000000000000..94bf714b28d48f2d3f81bd3434ed62c8bf9ff15a --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/ir/class_ir.py @@ -0,0 +1,503 @@ +"""Intermediate representation of classes.""" + +from __future__ import annotations + +from typing import List, NamedTuple + +from mypyc.common import PROPSET_PREFIX, JsonDict +from mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature +from mypyc.ir.ops import DeserMaps, Value +from mypyc.ir.rtypes import RInstance, RType, deserialize_type +from mypyc.namegen import NameGenerator, exported_name + +# Some notes on the vtable layout: Each concrete class has a vtable +# that contains function pointers for its methods. So that subclasses +# may be efficiently used when their parent class is expected, the +# layout of child vtables must be an extension of their base class's +# vtable. +# +# This makes multiple inheritance tricky, since obviously we cannot be +# an extension of multiple parent classes. We solve this by requiring +# all but one parent to be "traits", which we can operate on in a +# somewhat less efficient way. For each trait implemented by a class, +# we generate a separate vtable for the methods in that trait. +# We then store an array of (trait type, trait vtable) pointers alongside +# a class's main vtable. When we want to call a trait method, we +# (at runtime!) search the array of trait vtables to find the correct one, +# then call through it. +# Trait vtables additionally need entries for attribute getters and setters, +# since they can't always be in the same location. +# +# To keep down the number of indirections necessary, we store the +# array of trait vtables in the memory *before* the class vtable, and +# search it backwards. (This is a trick we can only do once---there +# are only two directions to store data in---but I don't think we'll +# need it again.) +# There are some tricks we could try in the future to store the trait +# vtables inline in the trait table (which would cut down one indirection), +# but this seems good enough for now. +# +# As an example: +# Imagine that we have a class B that inherits from a concrete class A +# and traits T1 and T2, and that A has methods foo() and +# bar() and B overrides bar() with a more specific type. +# Then B's vtable will look something like: +# +# T1 type object +# ptr to B's T1 trait vtable +# T2 type object +# ptr to B's T2 trait vtable +# -> | A.foo +# | Glue function that converts between A.bar's type and B.bar +# B.bar +# B.baz +# +# The arrow points to the "start" of the vtable (what vtable pointers +# point to) and the bars indicate which parts correspond to the parent +# class A's vtable layout. +# +# Classes that allow interpreted code to subclass them also have a +# "shadow vtable" that contains implementations that delegate to +# making a pycall, so that overridden methods in interpreted children +# will be called. (A better strategy could dynamically generate these +# vtables based on which methods are overridden in the children.) + +# Descriptions of method and attribute entries in class vtables. +# The 'cls' field is the class that the method/attr was defined in, +# which might be a parent class. +# The 'shadow_method', if present, contains the method that should be +# placed in the class's shadow vtable (if it has one). + + +class VTableMethod(NamedTuple): + cls: "ClassIR" # noqa: UP037 + name: str + method: FuncIR + shadow_method: FuncIR | None + + +VTableEntries = List[VTableMethod] + + +class ClassIR: + """Intermediate representation of a class. + + This also describes the runtime structure of native instances. + """ + + def __init__( + self, + name: str, + module_name: str, + is_trait: bool = False, + is_generated: bool = False, + is_abstract: bool = False, + is_ext_class: bool = True, + is_final_class: bool = False, + ) -> None: + self.name = name + self.module_name = module_name + self.is_trait = is_trait + self.is_generated = is_generated + self.is_abstract = is_abstract + self.is_ext_class = is_ext_class + self.is_final_class = is_final_class + # An augmented class has additional methods separate from what mypyc generates. + # Right now the only one is dataclasses. + self.is_augmented = False + # Does this inherit from a Python class? + self.inherits_python = False + # Do instances of this class have __dict__? + self.has_dict = False + # Do we allow interpreted subclasses? Derived from a mypyc_attr. + self.allow_interpreted_subclasses = False + # Does this class need getseters to be generated for its attributes? (getseters are also + # added if is_generated is False) + self.needs_getseters = False + # Is this class declared as serializable (supports copy.copy + # and pickle) using @mypyc_attr(serializable=True)? + # + # Additionally, any class with this attribute False but with + # an __init__ that can be called without any arguments is + # *implicitly serializable*. In this case __init__ will be + # called during deserialization without arguments. If this is + # True, we match Python semantics and __init__ won't be called + # during deserialization. + # + # This impacts also all subclasses. Use is_serializable() to + # also consider base classes. + self._serializable = False + # If this a subclass of some built-in python class, the name + # of the object for that class. We currently only support this + # in a few ad-hoc cases. + self.builtin_base: str | None = None + # Default empty constructor + self.ctor = FuncDecl(name, None, module_name, FuncSignature([], RInstance(self))) + # Attributes defined in the class (not inherited) + self.attributes: dict[str, RType] = {} + # Deletable attributes + self.deletable: list[str] = [] + # We populate method_types with the signatures of every method before + # we generate methods, and we rely on this information being present. + self.method_decls: dict[str, FuncDecl] = {} + # Map of methods that are actually present in an extension class + self.methods: dict[str, FuncIR] = {} + # Glue methods for boxing/unboxing when a class changes the type + # while overriding a method. Maps from (parent class overridden, method) + # to IR of glue method. + self.glue_methods: dict[tuple[ClassIR, str], FuncIR] = {} + + # Properties are accessed like attributes, but have behavior like method calls. + # They don't belong in the methods dictionary, since we don't want to expose them to + # Python's method API. But we want to put them into our own vtable as methods, so that + # they are properly handled and overridden. The property dictionary values are a tuple + # containing a property getter and an optional property setter. + self.properties: dict[str, tuple[FuncIR, FuncIR | None]] = {} + # We generate these in prepare_class_def so that we have access to them when generating + # other methods and properties that rely on these types. + self.property_types: dict[str, RType] = {} + + self.vtable: dict[str, int] | None = None + self.vtable_entries: VTableEntries = [] + self.trait_vtables: dict[ClassIR, VTableEntries] = {} + # N.B: base might not actually quite be the direct base. + # It is the nearest concrete base, but we allow a trait in between. + self.base: ClassIR | None = None + self.traits: list[ClassIR] = [] + # Supply a working mro for most generated classes. Real classes will need to + # fix it up. + self.mro: list[ClassIR] = [self] + # base_mro is the chain of concrete (non-trait) ancestors + self.base_mro: list[ClassIR] = [self] + + # Direct subclasses of this class (use subclasses() to also include non-direct ones) + # None if separate compilation prevents this from working. + # + # Often it's better to use has_no_subclasses() or subclasses() instead. + self.children: list[ClassIR] | None = [] + + # Instance attributes that are initialized in the class body. + self.attrs_with_defaults: set[str] = set() + + # Attributes that are always initialized in __init__ or class body + # (inferred in mypyc.analysis.attrdefined using interprocedural analysis) + self._always_initialized_attrs: set[str] = set() + + # Attributes that are sometimes initialized in __init__ + self._sometimes_initialized_attrs: set[str] = set() + + # If True, __init__ can make 'self' visible to unanalyzed/arbitrary code + self.init_self_leak = False + + # Definedness of these attributes is backed by a bitmap. Index in the list + # indicates the bit number. Includes inherited attributes. We need the + # bitmap for types such as native ints that can't have a dedicated error + # value that doesn't overlap a valid value. The bitmap is used if the + # value of an attribute is the same as the error value. + self.bitmap_attrs: list[str] = [] + + def __repr__(self) -> str: + return ( + "ClassIR(" + "name={self.name}, module_name={self.module_name}, " + "is_trait={self.is_trait}, is_generated={self.is_generated}, " + "is_abstract={self.is_abstract}, is_ext_class={self.is_ext_class}, " + "is_final_class={self.is_final_class}" + ")".format(self=self) + ) + + @property + def fullname(self) -> str: + return f"{self.module_name}.{self.name}" + + def real_base(self) -> ClassIR | None: + """Return the actual concrete base class, if there is one.""" + if len(self.mro) > 1 and not self.mro[1].is_trait: + return self.mro[1] + return None + + def vtable_entry(self, name: str) -> int: + assert self.vtable is not None, "vtable not computed yet" + assert name in self.vtable, f"{self.name!r} has no attribute {name!r}" + return self.vtable[name] + + def attr_details(self, name: str) -> tuple[RType, ClassIR]: + for ir in self.mro: + if name in ir.attributes: + return ir.attributes[name], ir + if name in ir.property_types: + return ir.property_types[name], ir + raise KeyError(f"{self.name!r} has no attribute {name!r}") + + def attr_type(self, name: str) -> RType: + return self.attr_details(name)[0] + + def method_decl(self, name: str) -> FuncDecl: + for ir in self.mro: + if name in ir.method_decls: + return ir.method_decls[name] + raise KeyError(f"{self.name!r} has no attribute {name!r}") + + def method_sig(self, name: str) -> FuncSignature: + return self.method_decl(name).sig + + def has_method(self, name: str) -> bool: + try: + self.method_decl(name) + except KeyError: + return False + return True + + def is_method_final(self, name: str) -> bool: + subs = self.subclasses() + if subs is None: + return self.is_final_class + + if self.has_method(name): + method_decl = self.method_decl(name) + for subc in subs: + if subc.method_decl(name) != method_decl: + return False + return True + else: + return not any(subc.has_method(name) for subc in subs) + + def has_attr(self, name: str) -> bool: + try: + self.attr_type(name) + except KeyError: + return False + return True + + def is_deletable(self, name: str) -> bool: + return any(name in ir.deletable for ir in self.mro) + + def is_always_defined(self, name: str) -> bool: + if self.is_deletable(name): + return False + return name in self._always_initialized_attrs + + def name_prefix(self, names: NameGenerator) -> str: + return names.private_name(self.module_name, self.name) + + def struct_name(self, names: NameGenerator) -> str: + return f"{exported_name(self.fullname)}Object" + + def get_method_and_class( + self, name: str, *, prefer_method: bool = False + ) -> tuple[FuncIR, ClassIR] | None: + for ir in self.mro: + if name in ir.methods: + func_ir = ir.methods[name] + if not prefer_method and func_ir.decl.implicit: + # This is an implicit accessor, so there is also an attribute definition + # which the caller prefers. This happens if an attribute overrides a + # property. + return None + return func_ir, ir + + return None + + def get_method(self, name: str, *, prefer_method: bool = False) -> FuncIR | None: + res = self.get_method_and_class(name, prefer_method=prefer_method) + return res[0] if res else None + + def has_method_decl(self, name: str) -> bool: + return any(name in ir.method_decls for ir in self.mro) + + def has_no_subclasses(self) -> bool: + return self.children == [] and not self.allow_interpreted_subclasses + + def subclasses(self) -> set[ClassIR] | None: + """Return all subclasses of this class, both direct and indirect. + + Return None if it is impossible to identify all subclasses, for example + because we are performing separate compilation. + """ + if self.children is None or self.allow_interpreted_subclasses: + return None + result = set(self.children) + for child in self.children: + if child.children: + child_subs = child.subclasses() + if child_subs is None: + return None + result.update(child_subs) + return result + + def concrete_subclasses(self) -> list[ClassIR] | None: + """Return all concrete (i.e. non-trait and non-abstract) subclasses. + + Include both direct and indirect subclasses. Place classes with no children first. + """ + subs = self.subclasses() + if subs is None: + return None + concrete = {c for c in subs if not (c.is_trait or c.is_abstract)} + # We place classes with no children first because they are more likely + # to appear in various isinstance() checks. We then sort leaves by name + # to get stable order. + return sorted(concrete, key=lambda c: (len(c.children or []), c.name)) + + def is_serializable(self) -> bool: + return any(ci._serializable for ci in self.mro) + + def serialize(self) -> JsonDict: + return { + "name": self.name, + "module_name": self.module_name, + "is_trait": self.is_trait, + "is_ext_class": self.is_ext_class, + "is_abstract": self.is_abstract, + "is_generated": self.is_generated, + "is_augmented": self.is_augmented, + "is_final_class": self.is_final_class, + "inherits_python": self.inherits_python, + "has_dict": self.has_dict, + "allow_interpreted_subclasses": self.allow_interpreted_subclasses, + "needs_getseters": self.needs_getseters, + "_serializable": self._serializable, + "builtin_base": self.builtin_base, + "ctor": self.ctor.serialize(), + # We serialize dicts as lists to ensure order is preserved + "attributes": [(k, t.serialize()) for k, t in self.attributes.items()], + # We try to serialize a name reference, but if the decl isn't in methods + # then we can't be sure that will work so we serialize the whole decl. + "method_decls": [ + (k, d.id if k in self.methods else d.serialize()) + for k, d in self.method_decls.items() + ], + # We serialize method fullnames out and put methods in a separate dict + "methods": [(k, m.id) for k, m in self.methods.items()], + "glue_methods": [ + ((cir.fullname, k), m.id) for (cir, k), m in self.glue_methods.items() + ], + # We serialize properties and property_types separately out of an + # abundance of caution about preserving dict ordering... + "property_types": [(k, t.serialize()) for k, t in self.property_types.items()], + "properties": list(self.properties), + "vtable": self.vtable, + "vtable_entries": serialize_vtable(self.vtable_entries), + "trait_vtables": [ + (cir.fullname, serialize_vtable(v)) for cir, v in self.trait_vtables.items() + ], + # References to class IRs are all just names + "base": self.base.fullname if self.base else None, + "traits": [cir.fullname for cir in self.traits], + "mro": [cir.fullname for cir in self.mro], + "base_mro": [cir.fullname for cir in self.base_mro], + "children": ( + [cir.fullname for cir in self.children] if self.children is not None else None + ), + "deletable": self.deletable, + "attrs_with_defaults": sorted(self.attrs_with_defaults), + "_always_initialized_attrs": sorted(self._always_initialized_attrs), + "_sometimes_initialized_attrs": sorted(self._sometimes_initialized_attrs), + "init_self_leak": self.init_self_leak, + } + + @classmethod + def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> ClassIR: + fullname = data["module_name"] + "." + data["name"] + assert fullname in ctx.classes, "Class %s not in deser class map" % fullname + ir = ctx.classes[fullname] + + ir.is_trait = data["is_trait"] + ir.is_generated = data["is_generated"] + ir.is_abstract = data["is_abstract"] + ir.is_ext_class = data["is_ext_class"] + ir.is_augmented = data["is_augmented"] + ir.is_final_class = data["is_final_class"] + ir.inherits_python = data["inherits_python"] + ir.has_dict = data["has_dict"] + ir.allow_interpreted_subclasses = data["allow_interpreted_subclasses"] + ir.needs_getseters = data["needs_getseters"] + ir._serializable = data["_serializable"] + ir.builtin_base = data["builtin_base"] + ir.ctor = FuncDecl.deserialize(data["ctor"], ctx) + ir.attributes = {k: deserialize_type(t, ctx) for k, t in data["attributes"]} + ir.method_decls = { + k: ctx.functions[v].decl if isinstance(v, str) else FuncDecl.deserialize(v, ctx) + for k, v in data["method_decls"] + } + ir.methods = {k: ctx.functions[v] for k, v in data["methods"]} + ir.glue_methods = { + (ctx.classes[c], k): ctx.functions[v] for (c, k), v in data["glue_methods"] + } + ir.property_types = {k: deserialize_type(t, ctx) for k, t in data["property_types"]} + ir.properties = { + k: (ir.methods[k], ir.methods.get(PROPSET_PREFIX + k)) for k in data["properties"] + } + + ir.vtable = data["vtable"] + ir.vtable_entries = deserialize_vtable(data["vtable_entries"], ctx) + ir.trait_vtables = { + ctx.classes[k]: deserialize_vtable(v, ctx) for k, v in data["trait_vtables"] + } + + base = data["base"] + ir.base = ctx.classes[base] if base else None + ir.traits = [ctx.classes[s] for s in data["traits"]] + ir.mro = [ctx.classes[s] for s in data["mro"]] + ir.base_mro = [ctx.classes[s] for s in data["base_mro"]] + ir.children = data["children"] and [ctx.classes[s] for s in data["children"]] + ir.deletable = data["deletable"] + ir.attrs_with_defaults = set(data["attrs_with_defaults"]) + ir._always_initialized_attrs = set(data["_always_initialized_attrs"]) + ir._sometimes_initialized_attrs = set(data["_sometimes_initialized_attrs"]) + ir.init_self_leak = data["init_self_leak"] + + return ir + + +class NonExtClassInfo: + """Information needed to construct a non-extension class (Python class). + + Includes the class dictionary, a tuple of base classes, + the class annotations dictionary, and the metaclass. + """ + + def __init__(self, dict: Value, bases: Value, anns: Value, metaclass: Value) -> None: + self.dict = dict + self.bases = bases + self.anns = anns + self.metaclass = metaclass + + +def serialize_vtable_entry(entry: VTableMethod) -> JsonDict: + return { + ".class": "VTableMethod", + "cls": entry.cls.fullname, + "name": entry.name, + "method": entry.method.decl.id, + "shadow_method": entry.shadow_method.decl.id if entry.shadow_method else None, + } + + +def serialize_vtable(vtable: VTableEntries) -> list[JsonDict]: + return [serialize_vtable_entry(v) for v in vtable] + + +def deserialize_vtable_entry(data: JsonDict, ctx: DeserMaps) -> VTableMethod: + if data[".class"] == "VTableMethod": + return VTableMethod( + ctx.classes[data["cls"]], + data["name"], + ctx.functions[data["method"]], + ctx.functions[data["shadow_method"]] if data["shadow_method"] else None, + ) + assert False, "Bogus vtable .class: %s" % data[".class"] + + +def deserialize_vtable(data: list[JsonDict], ctx: DeserMaps) -> VTableEntries: + return [deserialize_vtable_entry(x, ctx) for x in data] + + +def all_concrete_classes(class_ir: ClassIR) -> list[ClassIR] | None: + """Return all concrete classes among the class itself and its subclasses.""" + concrete = class_ir.concrete_subclasses() + if concrete is None: + return None + if not (class_ir.is_abstract or class_ir.is_trait): + concrete.append(class_ir) + return concrete diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/ir/pprint.py b/openflamingo/lib/python3.10/site-packages/mypyc/ir/pprint.py new file mode 100644 index 0000000000000000000000000000000000000000..59ee994f012d13e9722a4f8c60206e2881b0320f --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/ir/pprint.py @@ -0,0 +1,516 @@ +"""Utilities for pretty-printing IR in a human-readable form.""" + +from __future__ import annotations + +from collections import defaultdict +from typing import Any, Final, Sequence, Union + +from mypyc.common import short_name +from mypyc.ir.func_ir import FuncIR, all_values_full +from mypyc.ir.module_ir import ModuleIRs +from mypyc.ir.ops import ( + ERR_NEVER, + Assign, + AssignMulti, + BasicBlock, + Box, + Branch, + Call, + CallC, + Cast, + ComparisonOp, + ControlOp, + DecRef, + Extend, + Float, + FloatComparisonOp, + FloatNeg, + FloatOp, + GetAttr, + GetElementPtr, + Goto, + IncRef, + InitStatic, + Integer, + IntOp, + KeepAlive, + LoadAddress, + LoadErrorValue, + LoadGlobal, + LoadLiteral, + LoadMem, + LoadStatic, + MethodCall, + Op, + OpVisitor, + PrimitiveOp, + RaiseStandardError, + Register, + Return, + SetAttr, + SetMem, + Truncate, + TupleGet, + TupleSet, + Unborrow, + Unbox, + Unreachable, + Value, +) +from mypyc.ir.rtypes import RType, is_bool_rprimitive, is_int_rprimitive + +ErrorSource = Union[BasicBlock, Op] + + +class IRPrettyPrintVisitor(OpVisitor[str]): + """Internal visitor that pretty-prints ops.""" + + def __init__(self, names: dict[Value, str]) -> None: + # This should contain a name for all values that are shown as + # registers in the output. This is not just for Register + # instances -- all Ops that produce values need (generated) names. + self.names = names + + def visit_goto(self, op: Goto) -> str: + return self.format("goto %l", op.label) + + branch_op_names: Final = {Branch.BOOL: ("%r", "bool"), Branch.IS_ERROR: ("is_error(%r)", "")} + + def visit_branch(self, op: Branch) -> str: + fmt, typ = self.branch_op_names[op.op] + if op.negated: + fmt = f"not {fmt}" + + cond = self.format(fmt, op.value) + tb = "" + if op.traceback_entry: + tb = " (error at %s:%d)" % op.traceback_entry + fmt = f"if {cond} goto %l{tb} else goto %l" + if typ: + fmt += f" :: {typ}" + return self.format(fmt, op.true, op.false) + + def visit_return(self, op: Return) -> str: + return self.format("return %r", op.value) + + def visit_unreachable(self, op: Unreachable) -> str: + return "unreachable" + + def visit_assign(self, op: Assign) -> str: + return self.format("%r = %r", op.dest, op.src) + + def visit_assign_multi(self, op: AssignMulti) -> str: + return self.format("%r = [%s]", op.dest, ", ".join(self.format("%r", v) for v in op.src)) + + def visit_load_error_value(self, op: LoadErrorValue) -> str: + return self.format("%r = :: %s", op, op.type) + + def visit_load_literal(self, op: LoadLiteral) -> str: + prefix = "" + # For values that have a potential unboxed representation, make + # it explicit that this is a Python object. + if isinstance(op.value, int): + prefix = "object " + + rvalue = repr(op.value) + if isinstance(op.value, frozenset): + # We need to generate a string representation that won't vary + # run-to-run because sets are unordered, otherwise we may get + # spurious irbuild test failures. + # + # Sorting by the item's string representation is a bit of a + # hack, but it's stable and won't cause TypeErrors. + formatted_items = [repr(i) for i in sorted(op.value, key=str)] + rvalue = "frozenset({" + ", ".join(formatted_items) + "})" + return self.format("%r = %s%s", op, prefix, rvalue) + + def visit_get_attr(self, op: GetAttr) -> str: + return self.format("%r = %s%r.%s", op, self.borrow_prefix(op), op.obj, op.attr) + + def borrow_prefix(self, op: Op) -> str: + if op.is_borrowed: + return "borrow " + return "" + + def visit_set_attr(self, op: SetAttr) -> str: + if op.is_init: + assert op.error_kind == ERR_NEVER + if op.error_kind == ERR_NEVER: + # Initialization and direct struct access can never fail + return self.format("%r.%s = %r", op.obj, op.attr, op.src) + else: + return self.format("%r.%s = %r; %r = is_error", op.obj, op.attr, op.src, op) + + def visit_load_static(self, op: LoadStatic) -> str: + ann = f" ({repr(op.ann)})" if op.ann else "" + name = op.identifier + if op.module_name is not None: + name = f"{op.module_name}.{name}" + return self.format("%r = %s :: %s%s", op, name, op.namespace, ann) + + def visit_init_static(self, op: InitStatic) -> str: + name = op.identifier + if op.module_name is not None: + name = f"{op.module_name}.{name}" + return self.format("%s = %r :: %s", name, op.value, op.namespace) + + def visit_tuple_get(self, op: TupleGet) -> str: + return self.format("%r = %s%r[%d]", op, self.borrow_prefix(op), op.src, op.index) + + def visit_tuple_set(self, op: TupleSet) -> str: + item_str = ", ".join(self.format("%r", item) for item in op.items) + return self.format("%r = (%s)", op, item_str) + + def visit_inc_ref(self, op: IncRef) -> str: + s = self.format("inc_ref %r", op.src) + # TODO: Remove bool check (it's unboxed) + if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type): + s += f" :: {short_name(op.src.type.name)}" + return s + + def visit_dec_ref(self, op: DecRef) -> str: + s = self.format("%sdec_ref %r", "x" if op.is_xdec else "", op.src) + # TODO: Remove bool check (it's unboxed) + if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type): + s += f" :: {short_name(op.src.type.name)}" + return s + + def visit_call(self, op: Call) -> str: + args = ", ".join(self.format("%r", arg) for arg in op.args) + # TODO: Display long name? + short_name = op.fn.shortname + s = f"{short_name}({args})" + if not op.is_void: + s = self.format("%r = ", op) + s + return s + + def visit_method_call(self, op: MethodCall) -> str: + args = ", ".join(self.format("%r", arg) for arg in op.args) + s = self.format("%r.%s(%s)", op.obj, op.method, args) + if not op.is_void: + s = self.format("%r = ", op) + s + return s + + def visit_cast(self, op: Cast) -> str: + return self.format("%r = %scast(%s, %r)", op, self.borrow_prefix(op), op.type, op.src) + + def visit_box(self, op: Box) -> str: + return self.format("%r = box(%s, %r)", op, op.src.type, op.src) + + def visit_unbox(self, op: Unbox) -> str: + return self.format("%r = unbox(%s, %r)", op, op.type, op.src) + + def visit_raise_standard_error(self, op: RaiseStandardError) -> str: + if op.value is not None: + if isinstance(op.value, str): + return self.format("%r = raise %s(%s)", op, op.class_name, repr(op.value)) + elif isinstance(op.value, Value): + return self.format("%r = raise %s(%r)", op, op.class_name, op.value) + else: + assert False, "value type must be either str or Value" + else: + return self.format("%r = raise %s", op, op.class_name) + + def visit_call_c(self, op: CallC) -> str: + args_str = ", ".join(self.format("%r", arg) for arg in op.args) + if op.is_void: + return self.format("%s(%s)", op.function_name, args_str) + else: + return self.format("%r = %s(%s)", op, op.function_name, args_str) + + def visit_primitive_op(self, op: PrimitiveOp) -> str: + args = [] + arg_index = 0 + type_arg_index = 0 + for arg_type in zip(op.desc.arg_types): + if arg_type: + args.append(self.format("%r", op.args[arg_index])) + arg_index += 1 + else: + assert op.type_args + args.append(self.format("%r", op.type_args[type_arg_index])) + type_arg_index += 1 + + args_str = ", ".join(args) + if op.is_void: + return self.format("%s %s", op.desc.name, args_str) + else: + return self.format("%r = %s %s", op, op.desc.name, args_str) + + def visit_truncate(self, op: Truncate) -> str: + return self.format("%r = truncate %r: %t to %t", op, op.src, op.src_type, op.type) + + def visit_extend(self, op: Extend) -> str: + if op.signed: + extra = " signed" + else: + extra = "" + return self.format("%r = extend%s %r: %t to %t", op, extra, op.src, op.src_type, op.type) + + def visit_load_global(self, op: LoadGlobal) -> str: + ann = f" ({repr(op.ann)})" if op.ann else "" + return self.format("%r = load_global %s :: static%s", op, op.identifier, ann) + + def visit_int_op(self, op: IntOp) -> str: + return self.format("%r = %r %s %r", op, op.lhs, IntOp.op_str[op.op], op.rhs) + + def visit_comparison_op(self, op: ComparisonOp) -> str: + if op.op in (ComparisonOp.SLT, ComparisonOp.SGT, ComparisonOp.SLE, ComparisonOp.SGE): + sign_format = " :: signed" + elif op.op in (ComparisonOp.ULT, ComparisonOp.UGT, ComparisonOp.ULE, ComparisonOp.UGE): + sign_format = " :: unsigned" + else: + sign_format = "" + return self.format( + "%r = %r %s %r%s", op, op.lhs, ComparisonOp.op_str[op.op], op.rhs, sign_format + ) + + def visit_float_op(self, op: FloatOp) -> str: + return self.format("%r = %r %s %r", op, op.lhs, FloatOp.op_str[op.op], op.rhs) + + def visit_float_neg(self, op: FloatNeg) -> str: + return self.format("%r = -%r", op, op.src) + + def visit_float_comparison_op(self, op: FloatComparisonOp) -> str: + return self.format("%r = %r %s %r", op, op.lhs, op.op_str[op.op], op.rhs) + + def visit_load_mem(self, op: LoadMem) -> str: + return self.format("%r = load_mem %r :: %t*", op, op.src, op.type) + + def visit_set_mem(self, op: SetMem) -> str: + return self.format("set_mem %r, %r :: %t*", op.dest, op.src, op.dest_type) + + def visit_get_element_ptr(self, op: GetElementPtr) -> str: + return self.format("%r = get_element_ptr %r %s :: %t", op, op.src, op.field, op.src_type) + + def visit_load_address(self, op: LoadAddress) -> str: + if isinstance(op.src, Register): + return self.format("%r = load_address %r", op, op.src) + elif isinstance(op.src, LoadStatic): + name = op.src.identifier + if op.src.module_name is not None: + name = f"{op.src.module_name}.{name}" + return self.format("%r = load_address %s :: %s", op, name, op.src.namespace) + else: + return self.format("%r = load_address %s", op, op.src) + + def visit_keep_alive(self, op: KeepAlive) -> str: + if op.steal: + steal = "steal " + else: + steal = "" + return self.format( + "keep_alive {}{}".format(steal, ", ".join(self.format("%r", v) for v in op.src)) + ) + + def visit_unborrow(self, op: Unborrow) -> str: + return self.format("%r = unborrow %r", op, op.src) + + # Helpers + + def format(self, fmt: str, *args: Any) -> str: + """Helper for formatting strings. + + These format sequences are supported in fmt: + + %s: arbitrary object converted to string using str() + %r: name of IR value/register + %d: int + %f: float + %l: BasicBlock (formatted as label 'Ln') + %t: RType + """ + result = [] + i = 0 + arglist = list(args) + while i < len(fmt): + n = fmt.find("%", i) + if n < 0: + n = len(fmt) + result.append(fmt[i:n]) + if n < len(fmt): + typespec = fmt[n + 1] + arg = arglist.pop(0) + if typespec == "r": + # Register/value + assert isinstance(arg, Value) + if isinstance(arg, Integer): + result.append(str(arg.value)) + elif isinstance(arg, Float): + result.append(repr(arg.value)) + else: + result.append(self.names[arg]) + elif typespec == "d": + # Integer + result.append("%d" % arg) + elif typespec == "f": + # Float + result.append("%f" % arg) + elif typespec == "l": + # Basic block (label) + assert isinstance(arg, BasicBlock) + result.append("L%s" % arg.label) + elif typespec == "t": + # RType + assert isinstance(arg, RType) + result.append(arg.name) + elif typespec == "s": + # String + result.append(str(arg)) + else: + raise ValueError(f"Invalid format sequence %{typespec}") + i = n + 2 + else: + i = n + return "".join(result) + + +def format_registers(func_ir: FuncIR, names: dict[Value, str]) -> list[str]: + result = [] + i = 0 + regs = all_values_full(func_ir.arg_regs, func_ir.blocks) + while i < len(regs): + i0 = i + group = [names[regs[i0]]] + while i + 1 < len(regs) and regs[i + 1].type == regs[i0].type: + i += 1 + group.append(names[regs[i]]) + i += 1 + result.append("{} :: {}".format(", ".join(group), regs[i0].type)) + return result + + +def format_blocks( + blocks: list[BasicBlock], + names: dict[Value, str], + source_to_error: dict[ErrorSource, list[str]], +) -> list[str]: + """Format a list of IR basic blocks into a human-readable form.""" + # First label all of the blocks + for i, block in enumerate(blocks): + block.label = i + + handler_map: dict[BasicBlock, list[BasicBlock]] = {} + for b in blocks: + if b.error_handler: + handler_map.setdefault(b.error_handler, []).append(b) + + visitor = IRPrettyPrintVisitor(names) + + lines = [] + for i, block in enumerate(blocks): + handler_msg = "" + if block in handler_map: + labels = sorted("L%d" % b.label for b in handler_map[block]) + handler_msg = " (handler for {})".format(", ".join(labels)) + + lines.append("L%d:%s" % (block.label, handler_msg)) + if block in source_to_error: + for error in source_to_error[block]: + lines.append(f" ERR: {error}") + ops = block.ops + if ( + isinstance(ops[-1], Goto) + and i + 1 < len(blocks) + and ops[-1].label == blocks[i + 1] + and not source_to_error.get(ops[-1], []) + ): + # Hide the last goto if it just goes to the next basic block, + # and there are no assocatiated errors with the op. + ops = ops[:-1] + for op in ops: + line = " " + op.accept(visitor) + lines.append(line) + if op in source_to_error: + for error in source_to_error[op]: + lines.append(f" ERR: {error}") + + if not isinstance(block.ops[-1], (Goto, Branch, Return, Unreachable)): + # Each basic block needs to exit somewhere. + lines.append(" [MISSING BLOCK EXIT OPCODE]") + return lines + + +def format_func(fn: FuncIR, errors: Sequence[tuple[ErrorSource, str]] = ()) -> list[str]: + lines = [] + cls_prefix = fn.class_name + "." if fn.class_name else "" + lines.append( + "def {}{}({}):".format(cls_prefix, fn.name, ", ".join(arg.name for arg in fn.args)) + ) + names = generate_names_for_ir(fn.arg_regs, fn.blocks) + for line in format_registers(fn, names): + lines.append(" " + line) + + source_to_error = defaultdict(list) + for source, error in errors: + source_to_error[source].append(error) + + code = format_blocks(fn.blocks, names, source_to_error) + lines.extend(code) + return lines + + +def format_modules(modules: ModuleIRs) -> list[str]: + ops = [] + for module in modules.values(): + for fn in module.functions: + ops.extend(format_func(fn)) + ops.append("") + return ops + + +def generate_names_for_ir(args: list[Register], blocks: list[BasicBlock]) -> dict[Value, str]: + """Generate unique names for IR values. + + Give names such as 'r5' to temp values in IR which are useful when + pretty-printing or generating C. Ensure generated names are unique. + """ + names: dict[Value, str] = {} + used_names = set() + + temp_index = 0 + + for arg in args: + names[arg] = arg.name + used_names.add(arg.name) + + for block in blocks: + for op in block.ops: + values = [] + + for source in op.sources(): + if source not in names: + values.append(source) + + if isinstance(op, (Assign, AssignMulti)): + values.append(op.dest) + elif isinstance(op, ControlOp) or op.is_void: + continue + elif op not in names: + values.append(op) + + for value in values: + if value in names: + continue + if isinstance(value, Register) and value.name: + name = value.name + elif isinstance(value, (Integer, Float)): + continue + else: + name = "r%d" % temp_index + temp_index += 1 + + # Append _2, _3, ... if needed to make the name unique. + if name in used_names: + n = 2 + while True: + candidate = "%s_%d" % (name, n) + if candidate not in used_names: + name = candidate + break + n += 1 + + names[value] = name + used_names.add(name) + + return names diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/ir/rtypes.py b/openflamingo/lib/python3.10/site-packages/mypyc/ir/rtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..53e3cee74e560a0f4113adcb2b38b1034b3512f7 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/ir/rtypes.py @@ -0,0 +1,1038 @@ +"""Types used in the intermediate representation. + +These are runtime types (RTypes), as opposed to mypy Type objects. +The latter are only used during type checking and not directly used at +runtime. Runtime types are derived from mypy types, but there's no +simple one-to-one correspondence. (Here 'runtime' means 'runtime +checked'.) + +The generated IR ensures some runtime type safety properties based on +RTypes. Compiled code can assume that the runtime value matches the +static RType of a value. If the RType of a register is 'builtins.str' +(str_rprimitive), for example, the generated IR will ensure that the +register will have a 'str' object. + +RTypes are simpler and less expressive than mypy (or PEP 484) +types. For example, all mypy types of form 'list[T]' (for arbitrary T) +are erased to the single RType 'builtins.list' (list_rprimitive). + +mypyc.irbuild.mapper.Mapper.type_to_rtype converts mypy Types to mypyc +RTypes. +""" + +from __future__ import annotations + +from abc import abstractmethod +from typing import TYPE_CHECKING, ClassVar, Final, Generic, TypeVar +from typing_extensions import TypeGuard + +from mypyc.common import IS_32_BIT_PLATFORM, PLATFORM_SIZE, JsonDict, short_name +from mypyc.namegen import NameGenerator + +if TYPE_CHECKING: + from mypyc.ir.class_ir import ClassIR + from mypyc.ir.ops import DeserMaps + +T = TypeVar("T") + + +class RType: + """Abstract base class for runtime types (erased, only concrete; no generics).""" + + name: str + # If True, the type has a special unboxed representation. If False, the + # type is represented as PyObject *. Even if True, the representation + # may contain pointers. + is_unboxed = False + # This is the C undefined value for this type. It's used for initialization + # if there's no value yet, and for function return value on error/exception. + # + # TODO: This shouldn't be specific to C or a string + c_undefined: str + # If unboxed: does the unboxed version use reference counting? + is_refcounted = True + # C type; use Emitter.ctype() to access + _ctype: str + # If True, error/undefined value overlaps with a valid value. To + # detect an exception, PyErr_Occurred() must be used in addition + # to checking for error value as the return value of a function. + # + # For example, no i64 value can be reserved for error value, so we + # pick an arbitrary value (e.g. -113) to signal error, but this is + # also a valid non-error value. + error_overlap = False + + @abstractmethod + def accept(self, visitor: RTypeVisitor[T]) -> T: + raise NotImplementedError() + + def short_name(self) -> str: + return short_name(self.name) + + def __str__(self) -> str: + return short_name(self.name) + + def __repr__(self) -> str: + return "<%s>" % self.__class__.__name__ + + def serialize(self) -> JsonDict | str: + raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance") + + +def deserialize_type(data: JsonDict | str, ctx: DeserMaps) -> RType: + """Deserialize a JSON-serialized RType. + + Arguments: + data: The decoded JSON of the serialized type + ctx: The deserialization maps to use + """ + # Since there are so few types, we just case on them directly. If + # more get added we should switch to a system like mypy.types + # uses. + if isinstance(data, str): + if data in ctx.classes: + return RInstance(ctx.classes[data]) + elif data in RPrimitive.primitive_map: + return RPrimitive.primitive_map[data] + elif data == "void": + return RVoid() + else: + assert False, f"Can't find class {data}" + elif data[".class"] == "RTuple": + return RTuple.deserialize(data, ctx) + elif data[".class"] == "RUnion": + return RUnion.deserialize(data, ctx) + raise NotImplementedError("unexpected .class {}".format(data[".class"])) + + +class RTypeVisitor(Generic[T]): + """Generic visitor over RTypes (uses the visitor design pattern).""" + + @abstractmethod + def visit_rprimitive(self, typ: RPrimitive) -> T: + raise NotImplementedError + + @abstractmethod + def visit_rinstance(self, typ: RInstance) -> T: + raise NotImplementedError + + @abstractmethod + def visit_runion(self, typ: RUnion) -> T: + raise NotImplementedError + + @abstractmethod + def visit_rtuple(self, typ: RTuple) -> T: + raise NotImplementedError + + @abstractmethod + def visit_rstruct(self, typ: RStruct) -> T: + raise NotImplementedError + + @abstractmethod + def visit_rarray(self, typ: RArray) -> T: + raise NotImplementedError + + @abstractmethod + def visit_rvoid(self, typ: RVoid) -> T: + raise NotImplementedError + + +class RVoid(RType): + """The void type (no value). + + This is a singleton -- use void_rtype (below) to refer to this instead of + constructing a new instance. + """ + + is_unboxed = False + name = "void" + ctype = "void" + + def accept(self, visitor: RTypeVisitor[T]) -> T: + return visitor.visit_rvoid(self) + + def serialize(self) -> str: + return "void" + + def __eq__(self, other: object) -> bool: + return isinstance(other, RVoid) + + def __hash__(self) -> int: + return hash(RVoid) + + +# Singleton instance of RVoid +void_rtype: Final = RVoid() + + +class RPrimitive(RType): + """Primitive type such as 'object' or 'int'. + + These often have custom ops associated with them. The 'object' + primitive type can be used to hold arbitrary Python objects. + + Different primitive types have different representations, and + primitives may be unboxed or boxed. Primitive types don't need to + directly correspond to Python types, but most do. + + NOTE: All supported primitive types are defined below + (e.g. object_rprimitive). + """ + + # Map from primitive names to primitive types and is used by deserialization + primitive_map: ClassVar[dict[str, RPrimitive]] = {} + + def __init__( + self, + name: str, + *, + is_unboxed: bool, + is_refcounted: bool, + is_native_int: bool = False, + is_signed: bool = False, + ctype: str = "PyObject *", + size: int = PLATFORM_SIZE, + error_overlap: bool = False, + ) -> None: + RPrimitive.primitive_map[name] = self + + self.name = name + self.is_unboxed = is_unboxed + self.is_refcounted = is_refcounted + self.is_native_int = is_native_int + self.is_signed = is_signed + self._ctype = ctype + self.size = size + self.error_overlap = error_overlap + if ctype == "CPyTagged": + self.c_undefined = "CPY_INT_TAG" + elif ctype in ("int16_t", "int32_t", "int64_t"): + # This is basically an arbitrary value that is pretty + # unlikely to overlap with a real value. + self.c_undefined = "-113" + elif ctype == "CPyPtr": + # TODO: Invent an overlapping error value? + self.c_undefined = "0" + elif ctype == "PyObject *": + # Boxed types use the null pointer as the error value. + self.c_undefined = "NULL" + elif ctype == "char": + self.c_undefined = "2" + elif ctype in ("PyObject **", "void *"): + self.c_undefined = "NULL" + elif ctype == "double": + self.c_undefined = "-113.0" + elif ctype in ("uint8_t", "uint16_t", "uint32_t", "uint64_t"): + self.c_undefined = "239" # An arbitrary number + else: + assert False, "Unrecognized ctype: %r" % ctype + + def accept(self, visitor: RTypeVisitor[T]) -> T: + return visitor.visit_rprimitive(self) + + def serialize(self) -> str: + return self.name + + def __repr__(self) -> str: + return "" % self.name + + def __eq__(self, other: object) -> bool: + return isinstance(other, RPrimitive) and other.name == self.name + + def __hash__(self) -> int: + return hash(self.name) + + +# NOTE: All the supported instances of RPrimitive are defined +# below. Use these instead of creating new instances. + +# Used to represent arbitrary objects and dynamically typed (Any) +# values. There are various ops that let you perform generic, runtime +# checked operations on these (that match Python semantics). See the +# ops in mypyc.primitives.misc_ops, including py_getattr_op, +# py_call_op, and many others. +# +# If there is no more specific RType available for some value, we fall +# back to using this type. +# +# NOTE: Even though this is very flexible, this type should be used as +# little as possible, as generic ops are typically slow. Other types, +# including other primitive types and RInstance, are usually much +# faster. +object_rprimitive: Final = RPrimitive("builtins.object", is_unboxed=False, is_refcounted=True) + +# represents a low level pointer of an object +object_pointer_rprimitive: Final = RPrimitive( + "object_ptr", is_unboxed=False, is_refcounted=False, ctype="PyObject **" +) + +# Arbitrary-precision integer (corresponds to Python 'int'). Small +# enough values are stored unboxed, while large integers are +# represented as a tagged pointer to a Python 'int' PyObject. The +# lowest bit is used as the tag to decide whether it is a signed +# unboxed value (shifted left by one) or a PyObject * pointing to an +# 'int' object. Pointers have the least significant bit set. +# +# The undefined/error value is the null pointer (1 -- only the least +# significant bit is set)). +# +# This cannot represent a subclass of int. An instance of a subclass +# of int is coerced to the corresponding 'int' value. +int_rprimitive: Final = RPrimitive( + "builtins.int", is_unboxed=True, is_refcounted=True, ctype="CPyTagged" +) + +# An unboxed integer. The representation is the same as for unboxed +# int_rprimitive (shifted left by one). These can be used when an +# integer is known to be small enough to fit size_t (CPyTagged). +short_int_rprimitive: Final = RPrimitive( + "short_int", is_unboxed=True, is_refcounted=False, ctype="CPyTagged" +) + +# Low level integer types (correspond to C integer types) + +int16_rprimitive: Final = RPrimitive( + "i16", + is_unboxed=True, + is_refcounted=False, + is_native_int=True, + is_signed=True, + ctype="int16_t", + size=2, + error_overlap=True, +) +int32_rprimitive: Final = RPrimitive( + "i32", + is_unboxed=True, + is_refcounted=False, + is_native_int=True, + is_signed=True, + ctype="int32_t", + size=4, + error_overlap=True, +) +int64_rprimitive: Final = RPrimitive( + "i64", + is_unboxed=True, + is_refcounted=False, + is_native_int=True, + is_signed=True, + ctype="int64_t", + size=8, + error_overlap=True, +) +uint8_rprimitive: Final = RPrimitive( + "u8", + is_unboxed=True, + is_refcounted=False, + is_native_int=True, + is_signed=False, + ctype="uint8_t", + size=1, + error_overlap=True, +) + +# The following unsigned native int types (u16, u32, u64) are not +# exposed to the user. They are for internal use within mypyc only. + +u16_rprimitive: Final = RPrimitive( + "u16", + is_unboxed=True, + is_refcounted=False, + is_native_int=True, + is_signed=False, + ctype="uint16_t", + size=2, + error_overlap=True, +) +uint32_rprimitive: Final = RPrimitive( + "u32", + is_unboxed=True, + is_refcounted=False, + is_native_int=True, + is_signed=False, + ctype="uint32_t", + size=4, + error_overlap=True, +) +uint64_rprimitive: Final = RPrimitive( + "u64", + is_unboxed=True, + is_refcounted=False, + is_native_int=True, + is_signed=False, + ctype="uint64_t", + size=8, + error_overlap=True, +) + +# The C 'int' type +c_int_rprimitive = int32_rprimitive + +if IS_32_BIT_PLATFORM: + c_size_t_rprimitive = uint32_rprimitive + c_pyssize_t_rprimitive = RPrimitive( + "native_int", + is_unboxed=True, + is_refcounted=False, + is_native_int=True, + is_signed=True, + ctype="int32_t", + size=4, + ) +else: + c_size_t_rprimitive = uint64_rprimitive + c_pyssize_t_rprimitive = RPrimitive( + "native_int", + is_unboxed=True, + is_refcounted=False, + is_native_int=True, + is_signed=True, + ctype="int64_t", + size=8, + ) + +# Untyped pointer, represented as integer in the C backend +pointer_rprimitive: Final = RPrimitive("ptr", is_unboxed=True, is_refcounted=False, ctype="CPyPtr") + +# Untyped pointer, represented as void * in the C backend +c_pointer_rprimitive: Final = RPrimitive( + "c_ptr", is_unboxed=False, is_refcounted=False, ctype="void *" +) + +# The type corresponding to mypyc.common.BITMAP_TYPE +bitmap_rprimitive: Final = uint32_rprimitive + +# Floats are represent as 'float' PyObject * values. (In the future +# we'll likely switch to a more efficient, unboxed representation.) +float_rprimitive: Final = RPrimitive( + "builtins.float", + is_unboxed=True, + is_refcounted=False, + ctype="double", + size=8, + error_overlap=True, +) + +# An unboxed Python bool value. This actually has three possible values +# (0 -> False, 1 -> True, 2 -> error). If you only need True/False, use +# bit_rprimitive instead. +bool_rprimitive: Final = RPrimitive( + "builtins.bool", is_unboxed=True, is_refcounted=False, ctype="char", size=1 +) + +# A low-level boolean value with two possible values: 0 and 1. Any +# other value results in undefined behavior. Undefined or error values +# are not supported. +bit_rprimitive: Final = RPrimitive( + "bit", is_unboxed=True, is_refcounted=False, ctype="char", size=1 +) + +# The 'None' value. The possible values are 0 -> None and 2 -> error. +none_rprimitive: Final = RPrimitive( + "builtins.None", is_unboxed=True, is_refcounted=False, ctype="char", size=1 +) + +# Python list object (or an instance of a subclass of list). +list_rprimitive: Final = RPrimitive("builtins.list", is_unboxed=False, is_refcounted=True) + +# Python dict object (or an instance of a subclass of dict). +dict_rprimitive: Final = RPrimitive("builtins.dict", is_unboxed=False, is_refcounted=True) + +# Python set object (or an instance of a subclass of set). +set_rprimitive: Final = RPrimitive("builtins.set", is_unboxed=False, is_refcounted=True) + +# Python str object. At the C layer, str is referred to as unicode +# (PyUnicode). +str_rprimitive: Final = RPrimitive("builtins.str", is_unboxed=False, is_refcounted=True) + +# Python bytes object. +bytes_rprimitive: Final = RPrimitive("builtins.bytes", is_unboxed=False, is_refcounted=True) + +# Tuple of an arbitrary length (corresponds to Tuple[t, ...], with +# explicit '...'). +tuple_rprimitive: Final = RPrimitive("builtins.tuple", is_unboxed=False, is_refcounted=True) + +# Python range object. +range_rprimitive: Final = RPrimitive("builtins.range", is_unboxed=False, is_refcounted=True) + + +def is_tagged(rtype: RType) -> bool: + return rtype is int_rprimitive or rtype is short_int_rprimitive + + +def is_int_rprimitive(rtype: RType) -> bool: + return rtype is int_rprimitive + + +def is_short_int_rprimitive(rtype: RType) -> bool: + return rtype is short_int_rprimitive + + +def is_int16_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]: + return rtype is int16_rprimitive + + +def is_int32_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]: + return rtype is int32_rprimitive or ( + rtype is c_pyssize_t_rprimitive and rtype._ctype == "int32_t" + ) + + +def is_int64_rprimitive(rtype: RType) -> bool: + return rtype is int64_rprimitive or ( + rtype is c_pyssize_t_rprimitive and rtype._ctype == "int64_t" + ) + + +def is_fixed_width_rtype(rtype: RType) -> TypeGuard[RPrimitive]: + return ( + is_int64_rprimitive(rtype) + or is_int32_rprimitive(rtype) + or is_int16_rprimitive(rtype) + or is_uint8_rprimitive(rtype) + ) + + +def is_uint8_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]: + return rtype is uint8_rprimitive + + +def is_uint32_rprimitive(rtype: RType) -> bool: + return rtype is uint32_rprimitive + + +def is_uint64_rprimitive(rtype: RType) -> bool: + return rtype is uint64_rprimitive + + +def is_c_py_ssize_t_rprimitive(rtype: RType) -> bool: + return rtype is c_pyssize_t_rprimitive + + +def is_pointer_rprimitive(rtype: RType) -> bool: + return rtype is pointer_rprimitive + + +def is_float_rprimitive(rtype: RType) -> bool: + return isinstance(rtype, RPrimitive) and rtype.name == "builtins.float" + + +def is_bool_rprimitive(rtype: RType) -> bool: + return isinstance(rtype, RPrimitive) and rtype.name == "builtins.bool" + + +def is_bit_rprimitive(rtype: RType) -> bool: + return isinstance(rtype, RPrimitive) and rtype.name == "bit" + + +def is_object_rprimitive(rtype: RType) -> bool: + return isinstance(rtype, RPrimitive) and rtype.name == "builtins.object" + + +def is_none_rprimitive(rtype: RType) -> bool: + return isinstance(rtype, RPrimitive) and rtype.name == "builtins.None" + + +def is_list_rprimitive(rtype: RType) -> bool: + return isinstance(rtype, RPrimitive) and rtype.name == "builtins.list" + + +def is_dict_rprimitive(rtype: RType) -> bool: + return isinstance(rtype, RPrimitive) and rtype.name == "builtins.dict" + + +def is_set_rprimitive(rtype: RType) -> bool: + return isinstance(rtype, RPrimitive) and rtype.name == "builtins.set" + + +def is_str_rprimitive(rtype: RType) -> bool: + return isinstance(rtype, RPrimitive) and rtype.name == "builtins.str" + + +def is_bytes_rprimitive(rtype: RType) -> bool: + return isinstance(rtype, RPrimitive) and rtype.name == "builtins.bytes" + + +def is_tuple_rprimitive(rtype: RType) -> bool: + return isinstance(rtype, RPrimitive) and rtype.name == "builtins.tuple" + + +def is_range_rprimitive(rtype: RType) -> bool: + return isinstance(rtype, RPrimitive) and rtype.name == "builtins.range" + + +def is_sequence_rprimitive(rtype: RType) -> bool: + return isinstance(rtype, RPrimitive) and ( + is_list_rprimitive(rtype) or is_tuple_rprimitive(rtype) or is_str_rprimitive(rtype) + ) + + +class TupleNameVisitor(RTypeVisitor[str]): + """Produce a tuple name based on the concrete representations of types.""" + + def visit_rinstance(self, t: RInstance) -> str: + return "O" + + def visit_runion(self, t: RUnion) -> str: + return "O" + + def visit_rprimitive(self, t: RPrimitive) -> str: + if t._ctype == "CPyTagged": + return "I" + elif t._ctype == "char": + return "C" + elif t._ctype == "int64_t": + return "8" # "8 byte integer" + elif t._ctype == "int32_t": + return "4" # "4 byte integer" + elif t._ctype == "int16_t": + return "2" # "2 byte integer" + elif t._ctype == "uint8_t": + return "U1" # "1 byte unsigned integer" + elif t._ctype == "double": + return "F" + assert not t.is_unboxed, f"{t} unexpected unboxed type" + return "O" + + def visit_rtuple(self, t: RTuple) -> str: + parts = [elem.accept(self) for elem in t.types] + return "T{}{}".format(len(parts), "".join(parts)) + + def visit_rstruct(self, t: RStruct) -> str: + assert False, "RStruct not supported in tuple" + + def visit_rarray(self, t: RArray) -> str: + assert False, "RArray not supported in tuple" + + def visit_rvoid(self, t: RVoid) -> str: + assert False, "rvoid in tuple?" + + +class RTuple(RType): + """Fixed-length unboxed tuple (represented as a C struct). + + These are used to represent mypy TupleType values (fixed-length + Python tuples). Since this is unboxed, the identity of a tuple + object is not preserved within compiled code. If the identity of a + tuple is important, or there is a need to have multiple references + to a single tuple object, a variable-length tuple should be used + (tuple_rprimitive or Tuple[T, ...] with explicit '...'), as they + are boxed. + + These aren't immutable. However, user code won't be able to mutate + individual tuple items. + """ + + is_unboxed = True + + def __init__(self, types: list[RType]) -> None: + self.name = "tuple" + self.types = tuple(types) + self.is_refcounted = any(t.is_refcounted for t in self.types) + # Generate a unique id which is used in naming corresponding C identifiers. + # This is necessary since C does not have anonymous structural type equivalence + # in the same way python can just assign a Tuple[int, bool] to a Tuple[int, bool]. + self.unique_id = self.accept(TupleNameVisitor()) + # Nominally the max c length is 31 chars, but I'm not honestly worried about this. + self.struct_name = f"tuple_{self.unique_id}" + self._ctype = f"{self.struct_name}" + self.error_overlap = all(t.error_overlap for t in self.types) and bool(self.types) + + def accept(self, visitor: RTypeVisitor[T]) -> T: + return visitor.visit_rtuple(self) + + def __str__(self) -> str: + return "tuple[%s]" % ", ".join(str(typ) for typ in self.types) + + def __repr__(self) -> str: + return "" % ", ".join(repr(typ) for typ in self.types) + + def __eq__(self, other: object) -> bool: + return isinstance(other, RTuple) and self.types == other.types + + def __hash__(self) -> int: + return hash((self.name, self.types)) + + def serialize(self) -> JsonDict: + types = [x.serialize() for x in self.types] + return {".class": "RTuple", "types": types} + + @classmethod + def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RTuple: + types = [deserialize_type(t, ctx) for t in data["types"]] + return RTuple(types) + + +# Exception tuple: (exception class, exception instance, traceback object) +exc_rtuple = RTuple([object_rprimitive, object_rprimitive, object_rprimitive]) + +# Dictionary iterator tuple: (should continue, internal offset, key, value) +# See mypyc.irbuild.for_helpers.ForDictionaryCommon for more details. +dict_next_rtuple_pair = RTuple( + [bool_rprimitive, short_int_rprimitive, object_rprimitive, object_rprimitive] +) +# Same as above but just for key or value. +dict_next_rtuple_single = RTuple([bool_rprimitive, short_int_rprimitive, object_rprimitive]) + + +def compute_rtype_alignment(typ: RType) -> int: + """Compute alignment of a given type based on platform alignment rule""" + platform_alignment = PLATFORM_SIZE + if isinstance(typ, RPrimitive): + return typ.size + elif isinstance(typ, RInstance): + return platform_alignment + elif isinstance(typ, RUnion): + return platform_alignment + elif isinstance(typ, RArray): + return compute_rtype_alignment(typ.item_type) + else: + if isinstance(typ, RTuple): + items = list(typ.types) + elif isinstance(typ, RStruct): + items = typ.types + else: + assert False, "invalid rtype for computing alignment" + max_alignment = max(compute_rtype_alignment(item) for item in items) + return max_alignment + + +def compute_rtype_size(typ: RType) -> int: + """Compute unaligned size of rtype""" + if isinstance(typ, RPrimitive): + return typ.size + elif isinstance(typ, RTuple): + return compute_aligned_offsets_and_size(list(typ.types))[1] + elif isinstance(typ, RUnion): + return PLATFORM_SIZE + elif isinstance(typ, RStruct): + return compute_aligned_offsets_and_size(typ.types)[1] + elif isinstance(typ, RInstance): + return PLATFORM_SIZE + elif isinstance(typ, RArray): + alignment = compute_rtype_alignment(typ) + aligned_size = (compute_rtype_size(typ.item_type) + (alignment - 1)) & ~(alignment - 1) + return aligned_size * typ.length + else: + assert False, "invalid rtype for computing size" + + +def compute_aligned_offsets_and_size(types: list[RType]) -> tuple[list[int], int]: + """Compute offsets and total size of a list of types after alignment + + Note that the types argument are types of values that are stored + sequentially with platform default alignment. + """ + unaligned_sizes = [compute_rtype_size(typ) for typ in types] + alignments = [compute_rtype_alignment(typ) for typ in types] + + current_offset = 0 + offsets = [] + final_size = 0 + for i in range(len(unaligned_sizes)): + offsets.append(current_offset) + if i + 1 < len(unaligned_sizes): + cur_size = unaligned_sizes[i] + current_offset += cur_size + next_alignment = alignments[i + 1] + # compute aligned offset, + # check https://en.wikipedia.org/wiki/Data_structure_alignment for more information + current_offset = (current_offset + (next_alignment - 1)) & -next_alignment + else: + struct_alignment = max(alignments) + final_size = current_offset + unaligned_sizes[i] + final_size = (final_size + (struct_alignment - 1)) & -struct_alignment + return offsets, final_size + + +class RStruct(RType): + """C struct type""" + + def __init__(self, name: str, names: list[str], types: list[RType]) -> None: + self.name = name + self.names = names + self.types = types + # generate dummy names + if len(self.names) < len(self.types): + for i in range(len(self.types) - len(self.names)): + self.names.append("_item" + str(i)) + self.offsets, self.size = compute_aligned_offsets_and_size(types) + self._ctype = name + + def accept(self, visitor: RTypeVisitor[T]) -> T: + return visitor.visit_rstruct(self) + + def __str__(self) -> str: + # if not tuple(unnamed structs) + return "{}{{{}}}".format( + self.name, + ", ".join(name + ":" + str(typ) for name, typ in zip(self.names, self.types)), + ) + + def __repr__(self) -> str: + return "".format( + self.name, + ", ".join(name + ":" + repr(typ) for name, typ in zip(self.names, self.types)), + ) + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, RStruct) + and self.name == other.name + and self.names == other.names + and self.types == other.types + ) + + def __hash__(self) -> int: + return hash((self.name, tuple(self.names), tuple(self.types))) + + def serialize(self) -> JsonDict: + assert False + + @classmethod + def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RStruct: + assert False + + +class RInstance(RType): + """Instance of user-defined class (compiled to C extension class). + + The runtime representation is 'PyObject *', and these are always + boxed and thus reference-counted. + + These support fast method calls and fast attribute access using + vtables, and they usually use a dict-free, struct-based + representation of attributes. Method calls and attribute access + can skip the vtable if we know that there is no overriding. + + These are also sometimes called 'native' types, since these have + the most efficient representation and ops (along with certain + RPrimitive types and RTuple). + """ + + is_unboxed = False + + def __init__(self, class_ir: ClassIR) -> None: + # name is used for formatting the name in messages and debug output + # so we want the fullname for precision. + self.name = class_ir.fullname + self.class_ir = class_ir + self._ctype = "PyObject *" + + def accept(self, visitor: RTypeVisitor[T]) -> T: + return visitor.visit_rinstance(self) + + def struct_name(self, names: NameGenerator) -> str: + return self.class_ir.struct_name(names) + + def getter_index(self, name: str) -> int: + return self.class_ir.vtable_entry(name) + + def setter_index(self, name: str) -> int: + return self.getter_index(name) + 1 + + def method_index(self, name: str) -> int: + return self.class_ir.vtable_entry(name) + + def attr_type(self, name: str) -> RType: + return self.class_ir.attr_type(name) + + def __repr__(self) -> str: + return "" % self.name + + def __eq__(self, other: object) -> bool: + return isinstance(other, RInstance) and other.name == self.name + + def __hash__(self) -> int: + return hash(self.name) + + def serialize(self) -> str: + return self.name + + +class RUnion(RType): + """union[x, ..., y]""" + + is_unboxed = False + + def __init__(self, items: list[RType]) -> None: + self.name = "union" + self.items = items + self.items_set = frozenset(items) + self._ctype = "PyObject *" + + @staticmethod + def make_simplified_union(items: list[RType]) -> RType: + """Return a normalized union that covers the given items. + + Flatten nested unions and remove duplicate items. + + Overlapping items are *not* simplified. For example, + [object, str] will not be simplified. + """ + items = flatten_nested_unions(items) + assert items + + unique_items = dict.fromkeys(items) + if len(unique_items) > 1: + return RUnion(list(unique_items)) + else: + return next(iter(unique_items)) + + def accept(self, visitor: RTypeVisitor[T]) -> T: + return visitor.visit_runion(self) + + def __repr__(self) -> str: + return "" % ", ".join(str(item) for item in self.items) + + def __str__(self) -> str: + return "union[%s]" % ", ".join(str(item) for item in self.items) + + # We compare based on the set because order in a union doesn't matter + def __eq__(self, other: object) -> bool: + return isinstance(other, RUnion) and self.items_set == other.items_set + + def __hash__(self) -> int: + return hash(("union", self.items_set)) + + def serialize(self) -> JsonDict: + types = [x.serialize() for x in self.items] + return {".class": "RUnion", "types": types} + + @classmethod + def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RUnion: + types = [deserialize_type(t, ctx) for t in data["types"]] + return RUnion(types) + + +def flatten_nested_unions(types: list[RType]) -> list[RType]: + if not any(isinstance(t, RUnion) for t in types): + return types # Fast path + + flat_items: list[RType] = [] + for t in types: + if isinstance(t, RUnion): + flat_items.extend(flatten_nested_unions(t.items)) + else: + flat_items.append(t) + return flat_items + + +def optional_value_type(rtype: RType) -> RType | None: + """If rtype is the union of none_rprimitive and another type X, return X. + + Otherwise return None. + """ + if isinstance(rtype, RUnion) and len(rtype.items) == 2: + if rtype.items[0] == none_rprimitive: + return rtype.items[1] + elif rtype.items[1] == none_rprimitive: + return rtype.items[0] + return None + + +def is_optional_type(rtype: RType) -> bool: + """Is rtype an optional type with exactly two union items?""" + return optional_value_type(rtype) is not None + + +class RArray(RType): + """Fixed-length C array type (for example, int[5]). + + Note that the implementation is a bit limited, and these can basically + be only used for local variables that are initialized in one location. + """ + + def __init__(self, item_type: RType, length: int) -> None: + self.item_type = item_type + # Number of items + self.length = length + self.is_refcounted = False + + def accept(self, visitor: RTypeVisitor[T]) -> T: + return visitor.visit_rarray(self) + + def __str__(self) -> str: + return f"{self.item_type}[{self.length}]" + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, RArray) + and self.item_type == other.item_type + and self.length == other.length + ) + + def __hash__(self) -> int: + return hash((self.item_type, self.length)) + + def serialize(self) -> JsonDict: + assert False + + @classmethod + def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RArray: + assert False + + +PyObject = RStruct( + name="PyObject", + names=["ob_refcnt", "ob_type"], + types=[c_pyssize_t_rprimitive, pointer_rprimitive], +) + +PyVarObject = RStruct( + name="PyVarObject", names=["ob_base", "ob_size"], types=[PyObject, c_pyssize_t_rprimitive] +) + +setentry = RStruct( + name="setentry", names=["key", "hash"], types=[pointer_rprimitive, c_pyssize_t_rprimitive] +) + +smalltable = RStruct(name="smalltable", names=[], types=[setentry] * 8) + +PySetObject = RStruct( + name="PySetObject", + names=[ + "ob_base", + "fill", + "used", + "mask", + "table", + "hash", + "finger", + "smalltable", + "weakreflist", + ], + types=[ + PyObject, + c_pyssize_t_rprimitive, + c_pyssize_t_rprimitive, + c_pyssize_t_rprimitive, + pointer_rprimitive, + c_pyssize_t_rprimitive, + c_pyssize_t_rprimitive, + smalltable, + pointer_rprimitive, + ], +) + +PyListObject = RStruct( + name="PyListObject", + names=["ob_base", "ob_item", "allocated"], + types=[PyVarObject, pointer_rprimitive, c_pyssize_t_rprimitive], +) + + +def check_native_int_range(rtype: RPrimitive, n: int) -> bool: + """Is n within the range of a native, fixed-width int type? + + Assume the type is a fixed-width int type. + """ + if not rtype.is_signed: + return 0 <= n < (1 << (8 * rtype.size)) + else: + limit = 1 << (rtype.size * 8 - 1) + return -limit <= n < limit diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/__init__.py b/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/builder.py b/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..a0837ba2bfc791cbb050eb25369993f770890cac --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/builder.py @@ -0,0 +1,1457 @@ +"""Builder class used to transform a mypy AST to the IR form. + +The IRBuilder class maintains transformation state and provides access +to various helpers used to implement the transform. + +The top-level transform control logic is in mypyc.irbuild.main. + +mypyc.irbuild.visitor.IRBuilderVisitor is used to dispatch based on mypy +AST node type to code that actually does the bulk of the work. For +example, expressions are transformed in mypyc.irbuild.expression and +functions are transformed in mypyc.irbuild.function. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from typing import Any, Callable, Final, Iterator, Sequence, Union +from typing_extensions import overload + +from mypy.build import Graph +from mypy.maptype import map_instance_to_supertype +from mypy.nodes import ( + ARG_NAMED, + ARG_POS, + GDEF, + LDEF, + PARAM_SPEC_KIND, + TYPE_VAR_KIND, + TYPE_VAR_TUPLE_KIND, + ArgKind, + CallExpr, + Decorator, + Expression, + FuncDef, + IndexExpr, + IntExpr, + Lvalue, + MemberExpr, + MypyFile, + NameExpr, + OpExpr, + OverloadedFuncDef, + RefExpr, + StarExpr, + Statement, + SymbolNode, + TupleExpr, + TypeAlias, + TypeInfo, + TypeParam, + UnaryExpr, + Var, +) +from mypy.types import ( + AnyType, + DeletedType, + Instance, + ProperType, + TupleType, + Type, + TypedDictType, + TypeOfAny, + UninhabitedType, + UnionType, + get_proper_type, +) +from mypy.util import module_prefix, split_target +from mypy.visitor import ExpressionVisitor, StatementVisitor +from mypyc.common import BITMAP_BITS, SELF_NAME, TEMP_ATTR_NAME +from mypyc.crash import catch_errors +from mypyc.errors import Errors +from mypyc.ir.class_ir import ClassIR, NonExtClassInfo +from mypyc.ir.func_ir import INVALID_FUNC_DEF, FuncDecl, FuncIR, FuncSignature, RuntimeArg +from mypyc.ir.ops import ( + NAMESPACE_MODULE, + NAMESPACE_TYPE_VAR, + Assign, + BasicBlock, + Branch, + ComparisonOp, + GetAttr, + InitStatic, + Integer, + IntOp, + LoadStatic, + Op, + PrimitiveDescription, + RaiseStandardError, + Register, + SetAttr, + TupleGet, + Unreachable, + Value, +) +from mypyc.ir.rtypes import ( + RInstance, + RTuple, + RType, + RUnion, + bitmap_rprimitive, + c_pyssize_t_rprimitive, + dict_rprimitive, + int_rprimitive, + is_float_rprimitive, + is_list_rprimitive, + is_none_rprimitive, + is_object_rprimitive, + is_tagged, + is_tuple_rprimitive, + none_rprimitive, + object_rprimitive, + str_rprimitive, +) +from mypyc.irbuild.context import FuncInfo, ImplicitClass +from mypyc.irbuild.ll_builder import LowLevelIRBuilder +from mypyc.irbuild.mapper import Mapper +from mypyc.irbuild.nonlocalcontrol import ( + BaseNonlocalControl, + GeneratorNonlocalControl, + LoopNonlocalControl, + NonlocalControl, +) +from mypyc.irbuild.prebuildvisitor import PreBuildVisitor +from mypyc.irbuild.prepare import RegisterImplInfo +from mypyc.irbuild.targets import ( + AssignmentTarget, + AssignmentTargetAttr, + AssignmentTargetIndex, + AssignmentTargetRegister, + AssignmentTargetTuple, +) +from mypyc.irbuild.util import bytes_from_str, is_constant +from mypyc.options import CompilerOptions +from mypyc.primitives.dict_ops import dict_get_item_op, dict_set_item_op +from mypyc.primitives.generic_ops import iter_op, next_op, py_setattr_op +from mypyc.primitives.list_ops import list_get_item_unsafe_op, list_pop_last, to_list +from mypyc.primitives.misc_ops import check_unpack_count_op, get_module_dict_op, import_op +from mypyc.primitives.registry import CFunctionDescription, function_ops + +# These int binary operations can borrow their operands safely, since the +# primitives take this into consideration. +int_borrow_friendly_op: Final = {"+", "-", "==", "!=", "<", "<=", ">", ">="} + + +class IRVisitor(ExpressionVisitor[Value], StatementVisitor[None]): + pass + + +class UnsupportedException(Exception): + pass + + +SymbolTarget = Union[AssignmentTargetRegister, AssignmentTargetAttr] + + +class IRBuilder: + def __init__( + self, + current_module: str, + types: dict[Expression, Type], + graph: Graph, + errors: Errors, + mapper: Mapper, + pbv: PreBuildVisitor, + visitor: IRVisitor, + options: CompilerOptions, + singledispatch_impls: dict[FuncDef, list[RegisterImplInfo]], + ) -> None: + self.builder = LowLevelIRBuilder(errors, options) + self.builders = [self.builder] + self.symtables: list[dict[SymbolNode, SymbolTarget]] = [{}] + self.runtime_args: list[list[RuntimeArg]] = [[]] + self.function_name_stack: list[str] = [] + self.class_ir_stack: list[ClassIR] = [] + # Keep track of whether the next statement in a block is reachable + # or not, separately for each block nesting level + self.block_reachable_stack: list[bool] = [True] + + self.current_module = current_module + self.mapper = mapper + self.types = types + self.graph = graph + self.ret_types: list[RType] = [] + self.functions: list[FuncIR] = [] + self.function_names: set[tuple[str | None, str]] = set() + self.classes: list[ClassIR] = [] + self.final_names: list[tuple[str, RType]] = [] + self.type_var_names: list[str] = [] + self.callable_class_names: set[str] = set() + self.options = options + + # These variables keep track of the number of lambdas, implicit indices, and implicit + # iterators instantiated so we avoid name conflicts. The indices and iterators are + # instantiated from for-loops. + self.lambda_counter = 0 + self.temp_counter = 0 + + # These variables are populated from the first-pass PreBuildVisitor. + self.free_variables = pbv.free_variables + self.prop_setters = pbv.prop_setters + self.encapsulating_funcs = pbv.encapsulating_funcs + self.nested_fitems = pbv.nested_funcs.keys() + self.fdefs_to_decorators = pbv.funcs_to_decorators + self.module_import_groups = pbv.module_import_groups + + self.singledispatch_impls = singledispatch_impls + + self.visitor = visitor + + # This list operates similarly to a function call stack for nested functions. Whenever a + # function definition begins to be generated, a FuncInfo instance is added to the stack, + # and information about that function (e.g. whether it is nested, its environment class to + # be generated) is stored in that FuncInfo instance. When the function is done being + # generated, its corresponding FuncInfo is popped off the stack. + self.fn_info = FuncInfo(INVALID_FUNC_DEF, "", "") + self.fn_infos: list[FuncInfo] = [self.fn_info] + + # This list operates as a stack of constructs that modify the + # behavior of nonlocal control flow constructs. + self.nonlocal_control: list[NonlocalControl] = [] + + self.errors = errors + # Notionally a list of all of the modules imported by the + # module being compiled, but stored as an OrderedDict so we + # can also do quick lookups. + self.imports: dict[str, None] = {} + + self.can_borrow = False + + # High-level control + + def set_module(self, module_name: str, module_path: str) -> None: + """Set the name and path of the current module. + + This must be called before transforming any AST nodes. + """ + self.module_name = module_name + self.module_path = module_path + self.builder.set_module(module_name, module_path) + + @overload + def accept(self, node: Expression, *, can_borrow: bool = False) -> Value: ... + + @overload + def accept(self, node: Statement) -> None: ... + + def accept(self, node: Statement | Expression, *, can_borrow: bool = False) -> Value | None: + """Transform an expression or a statement. + + If can_borrow is true, prefer to generate a borrowed reference. + Borrowed references are faster since they don't require reference count + manipulation, but they are only safe to use in specific contexts. + """ + with self.catch_errors(node.line): + if isinstance(node, Expression): + old_can_borrow = self.can_borrow + self.can_borrow = can_borrow + try: + res = node.accept(self.visitor) + res = self.coerce(res, self.node_type(node), node.line) + # If we hit an error during compilation, we want to + # keep trying, so we can produce more error + # messages. Generate a temp of the right type to keep + # from causing more downstream trouble. + except UnsupportedException: + res = Register(self.node_type(node)) + self.can_borrow = old_can_borrow + if not can_borrow: + self.flush_keep_alives() + return res + else: + try: + node.accept(self.visitor) + except UnsupportedException: + pass + return None + + def flush_keep_alives(self) -> None: + self.builder.flush_keep_alives() + + # Pass through methods for the most common low-level builder ops, for convenience. + + def add(self, op: Op) -> Value: + return self.builder.add(op) + + def goto(self, target: BasicBlock) -> None: + self.builder.goto(target) + + def activate_block(self, block: BasicBlock) -> None: + self.builder.activate_block(block) + + def goto_and_activate(self, block: BasicBlock) -> None: + self.builder.goto_and_activate(block) + + def self(self) -> Register: + return self.builder.self() + + def py_get_attr(self, obj: Value, attr: str, line: int) -> Value: + return self.builder.py_get_attr(obj, attr, line) + + def load_str(self, value: str) -> Value: + return self.builder.load_str(value) + + def load_bytes_from_str_literal(self, value: str) -> Value: + """Load bytes object from a string literal. + + The literal characters of BytesExpr (the characters inside b'') + are stored in BytesExpr.value, whose type is 'str' not 'bytes'. + Thus we perform a special conversion here. + """ + return self.builder.load_bytes(bytes_from_str(value)) + + def load_int(self, value: int) -> Value: + return self.builder.load_int(value) + + def load_float(self, value: float) -> Value: + return self.builder.load_float(value) + + def unary_op(self, lreg: Value, expr_op: str, line: int) -> Value: + return self.builder.unary_op(lreg, expr_op, line) + + def binary_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value: + return self.builder.binary_op(lreg, rreg, expr_op, line) + + def coerce(self, src: Value, target_type: RType, line: int, force: bool = False) -> Value: + return self.builder.coerce(src, target_type, line, force, can_borrow=self.can_borrow) + + def none_object(self) -> Value: + return self.builder.none_object() + + def none(self) -> Value: + return self.builder.none() + + def true(self) -> Value: + return self.builder.true() + + def false(self) -> Value: + return self.builder.false() + + def new_list_op(self, values: list[Value], line: int) -> Value: + return self.builder.new_list_op(values, line) + + def new_set_op(self, values: list[Value], line: int) -> Value: + return self.builder.new_set_op(values, line) + + def translate_is_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value: + return self.builder.translate_is_op(lreg, rreg, expr_op, line) + + def py_call( + self, + function: Value, + arg_values: list[Value], + line: int, + arg_kinds: list[ArgKind] | None = None, + arg_names: Sequence[str | None] | None = None, + ) -> Value: + return self.builder.py_call(function, arg_values, line, arg_kinds, arg_names) + + def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) -> None: + self.builder.add_bool_branch(value, true, false) + + def load_native_type_object(self, fullname: str) -> Value: + return self.builder.load_native_type_object(fullname) + + def gen_method_call( + self, + base: Value, + name: str, + arg_values: list[Value], + result_type: RType | None, + line: int, + arg_kinds: list[ArgKind] | None = None, + arg_names: list[str | None] | None = None, + ) -> Value: + return self.builder.gen_method_call( + base, name, arg_values, result_type, line, arg_kinds, arg_names, self.can_borrow + ) + + def load_module(self, name: str) -> Value: + return self.builder.load_module(name) + + def call_c(self, desc: CFunctionDescription, args: list[Value], line: int) -> Value: + return self.builder.call_c(desc, args, line) + + def primitive_op(self, desc: PrimitiveDescription, args: list[Value], line: int) -> Value: + return self.builder.primitive_op(desc, args, line) + + def int_op(self, type: RType, lhs: Value, rhs: Value, op: int, line: int) -> Value: + return self.builder.int_op(type, lhs, rhs, op, line) + + def compare_tuples(self, lhs: Value, rhs: Value, op: str, line: int) -> Value: + return self.builder.compare_tuples(lhs, rhs, op, line) + + def builtin_len(self, val: Value, line: int) -> Value: + return self.builder.builtin_len(val, line) + + def new_tuple(self, items: list[Value], line: int) -> Value: + return self.builder.new_tuple(items, line) + + # Helpers for IR building + + def add_to_non_ext_dict( + self, non_ext: NonExtClassInfo, key: str, val: Value, line: int + ) -> None: + # Add an attribute entry into the class dict of a non-extension class. + key_unicode = self.load_str(key) + self.primitive_op(dict_set_item_op, [non_ext.dict, key_unicode, val], line) + + def gen_import(self, id: str, line: int) -> None: + self.imports[id] = None + + needs_import, out = BasicBlock(), BasicBlock() + self.check_if_module_loaded(id, line, needs_import, out) + + self.activate_block(needs_import) + value = self.call_c(import_op, [self.load_str(id)], line) + self.add(InitStatic(value, id, namespace=NAMESPACE_MODULE)) + self.goto_and_activate(out) + + def check_if_module_loaded( + self, id: str, line: int, needs_import: BasicBlock, out: BasicBlock + ) -> None: + """Generate code that checks if the module `id` has been loaded yet. + + Arguments: + id: name of module to check if imported + line: line number that the import occurs on + needs_import: the BasicBlock that is run if the module has not been loaded yet + out: the BasicBlock that is run if the module has already been loaded""" + first_load = self.load_module(id) + comparison = self.translate_is_op(first_load, self.none_object(), "is not", line) + self.add_bool_branch(comparison, out, needs_import) + + def get_module(self, module: str, line: int) -> Value: + # Python 3.7 has a nice 'PyImport_GetModule' function that we can't use :( + mod_dict = self.call_c(get_module_dict_op, [], line) + # Get module object from modules dict. + return self.primitive_op(dict_get_item_op, [mod_dict, self.load_str(module)], line) + + def get_module_attr(self, module: str, attr: str, line: int) -> Value: + """Look up an attribute of a module without storing it in the local namespace. + + For example, get_module_attr('typing', 'TypedDict', line) results in + the value of 'typing.TypedDict'. + + Import the module if needed. + """ + self.gen_import(module, line) + module_obj = self.get_module(module, line) + return self.py_get_attr(module_obj, attr, line) + + def assign_if_null(self, target: Register, get_val: Callable[[], Value], line: int) -> None: + """If target is NULL, assign value produced by get_val to it.""" + error_block, body_block = BasicBlock(), BasicBlock() + self.add(Branch(target, error_block, body_block, Branch.IS_ERROR)) + self.activate_block(error_block) + self.add(Assign(target, self.coerce(get_val(), target.type, line))) + self.goto(body_block) + self.activate_block(body_block) + + def assign_if_bitmap_unset( + self, target: Register, get_val: Callable[[], Value], index: int, line: int + ) -> None: + error_block, body_block = BasicBlock(), BasicBlock() + o = self.int_op( + bitmap_rprimitive, + self.builder.args[-1 - index // BITMAP_BITS], + Integer(1 << (index & (BITMAP_BITS - 1)), bitmap_rprimitive), + IntOp.AND, + line, + ) + b = self.add(ComparisonOp(o, Integer(0, bitmap_rprimitive), ComparisonOp.EQ)) + self.add(Branch(b, error_block, body_block, Branch.BOOL)) + self.activate_block(error_block) + self.add(Assign(target, self.coerce(get_val(), target.type, line))) + self.goto(body_block) + self.activate_block(body_block) + + def maybe_add_implicit_return(self) -> None: + if is_none_rprimitive(self.ret_types[-1]) or is_object_rprimitive(self.ret_types[-1]): + self.add_implicit_return() + else: + self.add_implicit_unreachable() + + def add_implicit_return(self) -> None: + block = self.builder.blocks[-1] + if not block.terminated: + retval = self.coerce(self.builder.none(), self.ret_types[-1], -1) + self.nonlocal_control[-1].gen_return(self, retval, self.fn_info.fitem.line) + + def add_implicit_unreachable(self) -> None: + block = self.builder.blocks[-1] + if not block.terminated: + self.add(Unreachable()) + + def disallow_class_assignments(self, lvalues: list[Lvalue], line: int) -> None: + # Some best-effort attempts to disallow assigning to class + # variables that aren't marked ClassVar, since we blatantly + # miscompile the interaction between instance and class + # variables. + for lvalue in lvalues: + if ( + isinstance(lvalue, MemberExpr) + and isinstance(lvalue.expr, RefExpr) + and isinstance(lvalue.expr.node, TypeInfo) + ): + var = lvalue.expr.node[lvalue.name].node + if isinstance(var, Var) and not var.is_classvar: + self.error("Only class variables defined as ClassVar can be assigned to", line) + + def non_function_scope(self) -> bool: + # Currently the stack always has at least two items: dummy and top-level. + return len(self.fn_infos) <= 2 + + def top_level_fn_info(self) -> FuncInfo | None: + if self.non_function_scope(): + return None + return self.fn_infos[2] + + def init_final_static( + self, + lvalue: Lvalue, + rvalue_reg: Value, + class_name: str | None = None, + *, + type_override: RType | None = None, + ) -> None: + assert isinstance(lvalue, NameExpr) + assert isinstance(lvalue.node, Var) + if lvalue.node.final_value is None: + if class_name is None: + name = lvalue.name + else: + name = f"{class_name}.{lvalue.name}" + assert name is not None, "Full name not set for variable" + coerced = self.coerce(rvalue_reg, type_override or self.node_type(lvalue), lvalue.line) + self.final_names.append((name, coerced.type)) + self.add(InitStatic(coerced, name, self.module_name)) + + def load_final_static( + self, fullname: str, typ: RType, line: int, error_name: str | None = None + ) -> Value: + split_name = split_target(self.graph, fullname) + assert split_name is not None + module, name = split_name + return self.builder.load_static_checked( + typ, + name, + module, + line=line, + error_msg=f'value for final name "{error_name}" was not set', + ) + + def init_type_var(self, value: Value, name: str, line: int) -> None: + unique_name = name + "___" + str(line) + self.type_var_names.append(unique_name) + self.add(InitStatic(value, unique_name, self.module_name, namespace=NAMESPACE_TYPE_VAR)) + + def load_type_var(self, name: str, line: int) -> Value: + return self.add( + LoadStatic( + object_rprimitive, + name + "___" + str(line), + self.module_name, + namespace=NAMESPACE_TYPE_VAR, + ) + ) + + def load_literal_value(self, val: int | str | bytes | float | complex | bool) -> Value: + """Load value of a final name, class-level attribute, or constant folded expression.""" + if isinstance(val, bool): + if val: + return self.true() + else: + return self.false() + elif isinstance(val, int): + return self.builder.load_int(val) + elif isinstance(val, float): + return self.builder.load_float(val) + elif isinstance(val, str): + return self.builder.load_str(val) + elif isinstance(val, bytes): + return self.builder.load_bytes(val) + elif isinstance(val, complex): + return self.builder.load_complex(val) + else: + assert False, "Unsupported literal value" + + def get_assignment_target( + self, lvalue: Lvalue, line: int = -1, *, for_read: bool = False + ) -> AssignmentTarget: + if line == -1: + line = lvalue.line + if isinstance(lvalue, NameExpr): + # If we are visiting a decorator, then the SymbolNode we really want to be looking at + # is the function that is decorated, not the entire Decorator node itself. + symbol = lvalue.node + if isinstance(symbol, Decorator): + symbol = symbol.func + if symbol is None: + # Semantic analyzer doesn't create ad-hoc Vars for special forms. + assert lvalue.is_special_form + symbol = Var(lvalue.name) + if not for_read and isinstance(symbol, Var) and symbol.is_cls: + self.error("Cannot assign to the first argument of classmethod", line) + if lvalue.kind == LDEF: + if symbol not in self.symtables[-1]: + if isinstance(symbol, Var) and not isinstance(symbol.type, DeletedType): + reg_type = self.type_to_rtype(symbol.type) + else: + reg_type = self.node_type(lvalue) + # If the function is a generator function, then first define a new variable + # in the current function's environment class. Next, define a target that + # refers to the newly defined variable in that environment class. Add the + # target to the table containing class environment variables, as well as the + # current environment. + if self.fn_info.is_generator: + return self.add_var_to_env_class( + symbol, reg_type, self.fn_info.generator_class, reassign=False + ) + + # Otherwise define a new local variable. + return self.add_local_reg(symbol, reg_type) + else: + # Assign to a previously defined variable. + return self.lookup(symbol) + elif lvalue.kind == GDEF: + globals_dict = self.load_globals_dict() + name = self.load_str(lvalue.name) + return AssignmentTargetIndex(globals_dict, name) + else: + assert False, lvalue.kind + elif isinstance(lvalue, IndexExpr): + # Indexed assignment x[y] = e + base = self.accept(lvalue.base) + index = self.accept(lvalue.index) + return AssignmentTargetIndex(base, index) + elif isinstance(lvalue, MemberExpr): + # Attribute assignment x.y = e + can_borrow = self.is_native_attr_ref(lvalue) + obj = self.accept(lvalue.expr, can_borrow=can_borrow) + return AssignmentTargetAttr(obj, lvalue.name, can_borrow=can_borrow) + elif isinstance(lvalue, TupleExpr): + # Multiple assignment a, ..., b = e + star_idx: int | None = None + lvalues = [] + for idx, item in enumerate(lvalue.items): + targ = self.get_assignment_target(item) + lvalues.append(targ) + if isinstance(item, StarExpr): + if star_idx is not None: + self.error("Two starred expressions in assignment", line) + star_idx = idx + + return AssignmentTargetTuple(lvalues, star_idx) + + elif isinstance(lvalue, StarExpr): + return self.get_assignment_target(lvalue.expr) + + assert False, "Unsupported lvalue: %r" % lvalue + + def read( + self, target: Value | AssignmentTarget, line: int = -1, can_borrow: bool = False + ) -> Value: + if isinstance(target, Value): + return target + if isinstance(target, AssignmentTargetRegister): + return target.register + if isinstance(target, AssignmentTargetIndex): + reg = self.gen_method_call( + target.base, "__getitem__", [target.index], target.type, line + ) + if reg is not None: + return reg + assert False, target.base.type + if isinstance(target, AssignmentTargetAttr): + if isinstance(target.obj.type, RInstance) and target.obj.type.class_ir.is_ext_class: + borrow = can_borrow and target.can_borrow + return self.add(GetAttr(target.obj, target.attr, line, borrow=borrow)) + else: + return self.py_get_attr(target.obj, target.attr, line) + + assert False, "Unsupported lvalue: %r" % target + + def assign(self, target: Register | AssignmentTarget, rvalue_reg: Value, line: int) -> None: + if isinstance(target, Register): + self.add(Assign(target, self.coerce_rvalue(rvalue_reg, target.type, line))) + elif isinstance(target, AssignmentTargetRegister): + rvalue_reg = self.coerce_rvalue(rvalue_reg, target.type, line) + self.add(Assign(target.register, rvalue_reg)) + elif isinstance(target, AssignmentTargetAttr): + if isinstance(target.obj_type, RInstance): + rvalue_reg = self.coerce_rvalue(rvalue_reg, target.type, line) + self.add(SetAttr(target.obj, target.attr, rvalue_reg, line)) + else: + key = self.load_str(target.attr) + boxed_reg = self.builder.box(rvalue_reg) + self.primitive_op(py_setattr_op, [target.obj, key, boxed_reg], line) + elif isinstance(target, AssignmentTargetIndex): + target_reg2 = self.gen_method_call( + target.base, "__setitem__", [target.index, rvalue_reg], None, line + ) + assert target_reg2 is not None, target.base.type + elif isinstance(target, AssignmentTargetTuple): + if isinstance(rvalue_reg.type, RTuple) and target.star_idx is None: + rtypes = rvalue_reg.type.types + assert len(rtypes) == len(target.items) + for i in range(len(rtypes)): + item_value = self.add(TupleGet(rvalue_reg, i, line)) + self.assign(target.items[i], item_value, line) + elif ( + is_list_rprimitive(rvalue_reg.type) or is_tuple_rprimitive(rvalue_reg.type) + ) and target.star_idx is None: + self.process_sequence_assignment(target, rvalue_reg, line) + else: + self.process_iterator_tuple_assignment(target, rvalue_reg, line) + else: + assert False, "Unsupported assignment target" + + def coerce_rvalue(self, rvalue: Value, rtype: RType, line: int) -> Value: + if is_float_rprimitive(rtype) and is_tagged(rvalue.type): + typename = rvalue.type.short_name() + if typename == "short_int": + typename = "int" + self.error( + "Incompatible value representations in assignment " + + f'(expression has type "{typename}", variable has type "float")', + line, + ) + return self.coerce(rvalue, rtype, line) + + def process_sequence_assignment( + self, target: AssignmentTargetTuple, rvalue: Value, line: int + ) -> None: + """Process assignment like 'x, y = s', where s is a variable-length list or tuple.""" + # Check the length of sequence. + expected_len = Integer(len(target.items), c_pyssize_t_rprimitive) + self.builder.call_c(check_unpack_count_op, [rvalue, expected_len], line) + + # Read sequence items. + values = [] + for i in range(len(target.items)): + item = target.items[i] + index = self.builder.load_int(i) + if is_list_rprimitive(rvalue.type): + item_value = self.call_c(list_get_item_unsafe_op, [rvalue, index], line) + else: + item_value = self.builder.gen_method_call( + rvalue, "__getitem__", [index], item.type, line + ) + values.append(item_value) + + # Assign sequence items to the target lvalues. + for lvalue, value in zip(target.items, values): + self.assign(lvalue, value, line) + + def process_iterator_tuple_assignment_helper( + self, litem: AssignmentTarget, ritem: Value, line: int + ) -> None: + error_block, ok_block = BasicBlock(), BasicBlock() + self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR)) + + self.activate_block(error_block) + self.add( + RaiseStandardError(RaiseStandardError.VALUE_ERROR, "not enough values to unpack", line) + ) + self.add(Unreachable()) + + self.activate_block(ok_block) + self.assign(litem, ritem, line) + + def process_iterator_tuple_assignment( + self, target: AssignmentTargetTuple, rvalue_reg: Value, line: int + ) -> None: + iterator = self.primitive_op(iter_op, [rvalue_reg], line) + + # This may be the whole lvalue list if there is no starred value + split_idx = target.star_idx if target.star_idx is not None else len(target.items) + + # Assign values before the first starred value + for litem in target.items[:split_idx]: + ritem = self.call_c(next_op, [iterator], line) + error_block, ok_block = BasicBlock(), BasicBlock() + self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR)) + + self.activate_block(error_block) + self.add( + RaiseStandardError( + RaiseStandardError.VALUE_ERROR, "not enough values to unpack", line + ) + ) + self.add(Unreachable()) + + self.activate_block(ok_block) + + self.assign(litem, ritem, line) + + # Assign the starred value and all values after it + if target.star_idx is not None: + post_star_vals = target.items[split_idx + 1 :] + iter_list = self.primitive_op(to_list, [iterator], line) + iter_list_len = self.builtin_len(iter_list, line) + post_star_len = Integer(len(post_star_vals)) + condition = self.binary_op(post_star_len, iter_list_len, "<=", line) + + error_block, ok_block = BasicBlock(), BasicBlock() + self.add(Branch(condition, ok_block, error_block, Branch.BOOL)) + + self.activate_block(error_block) + self.add( + RaiseStandardError( + RaiseStandardError.VALUE_ERROR, "not enough values to unpack", line + ) + ) + self.add(Unreachable()) + + self.activate_block(ok_block) + + for litem in reversed(post_star_vals): + ritem = self.primitive_op(list_pop_last, [iter_list], line) + self.assign(litem, ritem, line) + + # Assign the starred value + self.assign(target.items[target.star_idx], iter_list, line) + + # There is no starred value, so check if there are extra values in rhs that + # have not been assigned. + else: + extra = self.call_c(next_op, [iterator], line) + error_block, ok_block = BasicBlock(), BasicBlock() + self.add(Branch(extra, ok_block, error_block, Branch.IS_ERROR)) + + self.activate_block(error_block) + self.add( + RaiseStandardError( + RaiseStandardError.VALUE_ERROR, "too many values to unpack", line + ) + ) + self.add(Unreachable()) + + self.activate_block(ok_block) + + def push_loop_stack(self, continue_block: BasicBlock, break_block: BasicBlock) -> None: + self.nonlocal_control.append( + LoopNonlocalControl(self.nonlocal_control[-1], continue_block, break_block) + ) + + def pop_loop_stack(self) -> None: + self.nonlocal_control.pop() + + def make_spill_target(self, type: RType) -> AssignmentTarget: + """Moves a given Value instance into the generator class' environment class.""" + name = f"{TEMP_ATTR_NAME}{self.temp_counter}" + self.temp_counter += 1 + target = self.add_var_to_env_class(Var(name), type, self.fn_info.generator_class) + return target + + def spill(self, value: Value) -> AssignmentTarget: + """Moves a given Value instance into the generator class' environment class.""" + target = self.make_spill_target(value.type) + # Shouldn't be able to fail, so -1 for line + self.assign(target, value, -1) + return target + + def maybe_spill(self, value: Value) -> Value | AssignmentTarget: + """ + Moves a given Value instance into the environment class for generator functions. For + non-generator functions, leaves the Value instance as it is. + + Returns an AssignmentTarget associated with the Value for generator functions and the + original Value itself for non-generator functions. + """ + if self.fn_info.is_generator: + return self.spill(value) + return value + + def maybe_spill_assignable(self, value: Value) -> Register | AssignmentTarget: + """ + Moves a given Value instance into the environment class for generator functions. For + non-generator functions, allocate a temporary Register. + + Returns an AssignmentTarget associated with the Value for generator functions and an + assignable Register for non-generator functions. + """ + if self.fn_info.is_generator: + return self.spill(value) + + if isinstance(value, Register): + return value + + # Allocate a temporary register for the assignable value. + reg = Register(value.type) + self.assign(reg, value, -1) + return reg + + def extract_int(self, e: Expression) -> int | None: + if isinstance(e, IntExpr): + return e.value + elif isinstance(e, UnaryExpr) and e.op == "-" and isinstance(e.expr, IntExpr): + return -e.expr.value + else: + return None + + def get_sequence_type(self, expr: Expression) -> RType: + return self.get_sequence_type_from_type(self.types[expr]) + + def get_sequence_type_from_type(self, target_type: Type) -> RType: + target_type = get_proper_type(target_type) + if isinstance(target_type, UnionType): + return RUnion.make_simplified_union( + [self.get_sequence_type_from_type(item) for item in target_type.items] + ) + assert isinstance(target_type, Instance), target_type + if target_type.type.fullname == "builtins.str": + return str_rprimitive + else: + return self.type_to_rtype(target_type.args[0]) + + def get_dict_base_type(self, expr: Expression) -> list[Instance]: + """Find dict type of a dict-like expression. + + This is useful for dict subclasses like SymbolTable. + """ + target_type = get_proper_type(self.types[expr]) + if isinstance(target_type, UnionType): + types = [get_proper_type(item) for item in target_type.items] + else: + types = [target_type] + + dict_types = [] + for t in types: + if isinstance(t, TypedDictType): + t = t.fallback + dict_base = next(base for base in t.type.mro if base.fullname == "typing.Mapping") + else: + assert isinstance(t, Instance), t + dict_base = next(base for base in t.type.mro if base.fullname == "builtins.dict") + dict_types.append(map_instance_to_supertype(t, dict_base)) + return dict_types + + def get_dict_key_type(self, expr: Expression) -> RType: + dict_base_types = self.get_dict_base_type(expr) + if len(dict_base_types) == 1: + return self.type_to_rtype(dict_base_types[0].args[0]) + else: + rtypes = [self.type_to_rtype(t.args[0]) for t in dict_base_types] + return RUnion.make_simplified_union(rtypes) + + def get_dict_value_type(self, expr: Expression) -> RType: + dict_base_types = self.get_dict_base_type(expr) + if len(dict_base_types) == 1: + return self.type_to_rtype(dict_base_types[0].args[1]) + else: + rtypes = [self.type_to_rtype(t.args[1]) for t in dict_base_types] + return RUnion.make_simplified_union(rtypes) + + def get_dict_item_type(self, expr: Expression) -> RType: + key_type = self.get_dict_key_type(expr) + value_type = self.get_dict_value_type(expr) + return RTuple([key_type, value_type]) + + def _analyze_iterable_item_type(self, expr: Expression) -> Type: + """Return the item type given by 'expr' in an iterable context.""" + # This logic is copied from mypy's TypeChecker.analyze_iterable_item_type. + if expr not in self.types: + # Mypy thinks this is unreachable. + iterable: ProperType = AnyType(TypeOfAny.from_error) + else: + iterable = get_proper_type(self.types[expr]) + echk = self.graph[self.module_name].type_checker().expr_checker + iterator = echk.check_method_call_by_name("__iter__", iterable, [], [], expr)[0] + + from mypy.join import join_types + + if isinstance(iterable, TupleType): + joined: Type = UninhabitedType() + for item in iterable.items: + joined = join_types(joined, item) + return joined + else: + # Non-tuple iterable. + return echk.check_method_call_by_name("__next__", iterator, [], [], expr)[0] + + def is_native_module(self, module: str) -> bool: + """Is the given module one compiled by mypyc?""" + return self.mapper.is_native_module(module) + + def is_native_ref_expr(self, expr: RefExpr) -> bool: + return self.mapper.is_native_ref_expr(expr) + + def is_native_module_ref_expr(self, expr: RefExpr) -> bool: + return self.mapper.is_native_module_ref_expr(expr) + + def is_synthetic_type(self, typ: TypeInfo) -> bool: + """Is a type something other than just a class we've created?""" + return typ.is_named_tuple or typ.is_newtype or typ.typeddict_type is not None + + def get_final_ref(self, expr: MemberExpr) -> tuple[str, Var, bool] | None: + """Check if `expr` is a final attribute. + + This needs to be done differently for class and module attributes to + correctly determine fully qualified name. Return a tuple that consists of + the qualified name, the corresponding Var node, and a flag indicating whether + the final name was defined in a compiled module. Return None if `expr` does not + refer to a final attribute. + """ + final_var = None + if isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, TypeInfo): + # a class attribute + sym = expr.expr.node.get(expr.name) + if sym and isinstance(sym.node, Var): + # Enum attribute are treated as final since they are added to the global cache + expr_fullname = expr.expr.node.bases[0].type.fullname + is_final = sym.node.is_final or expr_fullname == "enum.Enum" + if is_final: + final_var = sym.node + fullname = f"{sym.node.info.fullname}.{final_var.name}" + native = self.is_native_module(expr.expr.node.module_name) + elif self.is_module_member_expr(expr): + # a module attribute + if isinstance(expr.node, Var) and expr.node.is_final: + final_var = expr.node + fullname = expr.node.fullname + native = self.is_native_ref_expr(expr) + if final_var is not None: + return fullname, final_var, native + return None + + def emit_load_final( + self, final_var: Var, fullname: str, name: str, native: bool, typ: Type, line: int + ) -> Value | None: + """Emit code for loading value of a final name (if possible). + + Args: + final_var: Var corresponding to the final name + fullname: its qualified name + name: shorter name to show in errors + native: whether the name was defined in a compiled module + typ: its type + line: line number where loading occurs + """ + if final_var.final_value is not None: # this is safe even for non-native names + return self.load_literal_value(final_var.final_value) + elif native and module_prefix(self.graph, fullname): + return self.load_final_static(fullname, self.mapper.type_to_rtype(typ), line, name) + else: + return None + + def is_module_member_expr(self, expr: MemberExpr) -> bool: + return isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, MypyFile) + + def call_refexpr_with_args( + self, expr: CallExpr, callee: RefExpr, arg_values: list[Value] + ) -> Value: + # Handle data-driven special-cased primitive call ops. + if callee.fullname and expr.arg_kinds == [ARG_POS] * len(arg_values): + fullname = get_call_target_fullname(callee) + primitive_candidates = function_ops.get(fullname, []) + target = self.builder.matching_primitive_op( + primitive_candidates, arg_values, expr.line, self.node_type(expr) + ) + if target: + return target + + # Standard native call if signature and fullname are good and all arguments are positional + # or named. + callee_node = callee.node + if isinstance(callee_node, OverloadedFuncDef): + callee_node = callee_node.impl + # TODO: use native calls for any decorated functions which have all their decorators + # removed, not just singledispatch functions (which we don't do now just in case those + # decorated functions are callable classes or cannot be called without the python API for + # some other reason) + if ( + isinstance(callee_node, Decorator) + and callee_node.func not in self.fdefs_to_decorators + and callee_node.func in self.singledispatch_impls + ): + callee_node = callee_node.func + if ( + callee_node is not None + and callee.fullname + and callee_node in self.mapper.func_to_decl + and all(kind in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds) + ): + decl = self.mapper.func_to_decl[callee_node] + return self.builder.call(decl, arg_values, expr.arg_kinds, expr.arg_names, expr.line) + + # Fall back to a Python call + function = self.accept(callee) + return self.py_call( + function, arg_values, expr.line, arg_kinds=expr.arg_kinds, arg_names=expr.arg_names + ) + + def shortcircuit_expr(self, expr: OpExpr) -> Value: + return self.builder.shortcircuit_helper( + expr.op, + self.node_type(expr), + lambda: self.accept(expr.left), + lambda: self.accept(expr.right), + expr.line, + ) + + # Basic helpers + + def flatten_classes(self, arg: RefExpr | TupleExpr) -> list[ClassIR] | None: + """Flatten classes in isinstance(obj, (A, (B, C))). + + If at least one item is not a reference to a native class, return None. + """ + if isinstance(arg, RefExpr): + if isinstance(arg.node, TypeInfo) and self.is_native_module_ref_expr(arg): + ir = self.mapper.type_to_ir.get(arg.node) + if ir: + return [ir] + return None + else: + res: list[ClassIR] = [] + for item in arg.items: + if isinstance(item, (RefExpr, TupleExpr)): + item_part = self.flatten_classes(item) + if item_part is None: + return None + res.extend(item_part) + else: + return None + return res + + def enter(self, fn_info: FuncInfo | str = "") -> None: + if isinstance(fn_info, str): + fn_info = FuncInfo(name=fn_info) + self.builder = LowLevelIRBuilder(self.errors, self.options) + self.builder.set_module(self.module_name, self.module_path) + self.builders.append(self.builder) + self.symtables.append({}) + self.runtime_args.append([]) + self.fn_info = fn_info + self.fn_infos.append(self.fn_info) + self.ret_types.append(none_rprimitive) + if fn_info.is_generator: + self.nonlocal_control.append(GeneratorNonlocalControl()) + else: + self.nonlocal_control.append(BaseNonlocalControl()) + self.activate_block(BasicBlock()) + + def leave(self) -> tuple[list[Register], list[RuntimeArg], list[BasicBlock], RType, FuncInfo]: + builder = self.builders.pop() + self.symtables.pop() + runtime_args = self.runtime_args.pop() + ret_type = self.ret_types.pop() + fn_info = self.fn_infos.pop() + self.nonlocal_control.pop() + self.builder = self.builders[-1] + self.fn_info = self.fn_infos[-1] + return builder.args, runtime_args, builder.blocks, ret_type, fn_info + + @contextmanager + def enter_method( + self, + class_ir: ClassIR, + name: str, + ret_type: RType, + fn_info: FuncInfo | str = "", + self_type: RType | None = None, + ) -> Iterator[None]: + """Generate IR for a method. + + If the method takes arguments, you should immediately afterwards call + add_argument() for each non-self argument (self is created implicitly). + + Args: + class_ir: Add method to this class + name: Short name of the method + ret_type: Return type of the method + fn_info: Optionally, additional information about the method + self_type: If not None, override default type of the implicit 'self' + argument (by default, derive type from class_ir) + """ + self.enter(fn_info) + self.function_name_stack.append(name) + self.class_ir_stack.append(class_ir) + self.ret_types[-1] = ret_type + if self_type is None: + self_type = RInstance(class_ir) + self.add_argument(SELF_NAME, self_type) + try: + yield + finally: + arg_regs, args, blocks, ret_type, fn_info = self.leave() + sig = FuncSignature(args, ret_type) + name = self.function_name_stack.pop() + class_ir = self.class_ir_stack.pop() + decl = FuncDecl(name, class_ir.name, self.module_name, sig) + ir = FuncIR(decl, arg_regs, blocks) + class_ir.methods[name] = ir + class_ir.method_decls[name] = ir.decl + self.functions.append(ir) + + def add_argument(self, var: str | Var, typ: RType, kind: ArgKind = ARG_POS) -> Register: + """Declare an argument in the current function. + + You should use this instead of directly calling add_local() in new code. + """ + if isinstance(var, str): + var = Var(var) + reg = self.add_local(var, typ, is_arg=True) + self.runtime_args[-1].append(RuntimeArg(var.name, typ, kind)) + return reg + + def lookup(self, symbol: SymbolNode) -> SymbolTarget: + return self.symtables[-1][symbol] + + def add_local(self, symbol: SymbolNode, typ: RType, is_arg: bool = False) -> Register: + """Add register that represents a symbol to the symbol table. + + Args: + is_arg: is this a function argument + """ + assert isinstance(symbol, SymbolNode) + reg = Register( + typ, remangle_redefinition_name(symbol.name), is_arg=is_arg, line=symbol.line + ) + self.symtables[-1][symbol] = AssignmentTargetRegister(reg) + if is_arg: + self.builder.args.append(reg) + return reg + + def add_local_reg( + self, symbol: SymbolNode, typ: RType, is_arg: bool = False + ) -> AssignmentTargetRegister: + """Like add_local, but return an assignment target instead of value.""" + self.add_local(symbol, typ, is_arg) + target = self.symtables[-1][symbol] + assert isinstance(target, AssignmentTargetRegister) + return target + + def add_self_to_env(self, cls: ClassIR) -> AssignmentTargetRegister: + """Low-level function that adds a 'self' argument. + + This is only useful if using enter() instead of enter_method(). + """ + return self.add_local_reg(Var(SELF_NAME), RInstance(cls), is_arg=True) + + def add_target(self, symbol: SymbolNode, target: SymbolTarget) -> SymbolTarget: + self.symtables[-1][symbol] = target + return target + + def type_to_rtype(self, typ: Type | None) -> RType: + return self.mapper.type_to_rtype(typ) + + def node_type(self, node: Expression) -> RType: + if isinstance(node, IntExpr): + # TODO: Don't special case IntExpr + return int_rprimitive + if node not in self.types: + return object_rprimitive + mypy_type = self.types[node] + return self.type_to_rtype(mypy_type) + + def add_var_to_env_class( + self, var: SymbolNode, rtype: RType, base: FuncInfo | ImplicitClass, reassign: bool = False + ) -> AssignmentTarget: + # First, define the variable name as an attribute of the environment class, and then + # construct a target for that attribute. + name = remangle_redefinition_name(var.name) + self.fn_info.env_class.attributes[name] = rtype + attr_target = AssignmentTargetAttr(base.curr_env_reg, name) + + if reassign: + # Read the local definition of the variable, and set the corresponding attribute of + # the environment class' variable to be that value. + reg = self.read(self.lookup(var), self.fn_info.fitem.line) + self.add(SetAttr(base.curr_env_reg, name, reg, self.fn_info.fitem.line)) + + # Override the local definition of the variable to instead point at the variable in + # the environment class. + return self.add_target(var, attr_target) + + def is_builtin_ref_expr(self, expr: RefExpr) -> bool: + assert expr.node, "RefExpr not resolved" + return "." in expr.node.fullname and expr.node.fullname.split(".")[0] == "builtins" + + def load_global(self, expr: NameExpr) -> Value: + """Loads a Python-level global. + + This takes a NameExpr and uses its name as a key to retrieve the corresponding PyObject * + from the _globals dictionary in the C-generated code. + """ + # If the global is from 'builtins', turn it into a module attr load instead + if self.is_builtin_ref_expr(expr): + assert expr.node, "RefExpr not resolved" + return self.load_module_attr_by_fullname(expr.node.fullname, expr.line) + if ( + self.is_native_module_ref_expr(expr) + and isinstance(expr.node, TypeInfo) + and not self.is_synthetic_type(expr.node) + ): + assert expr.fullname + return self.load_native_type_object(expr.fullname) + return self.load_global_str(expr.name, expr.line) + + def load_global_str(self, name: str, line: int) -> Value: + _globals = self.load_globals_dict() + reg = self.load_str(name) + return self.primitive_op(dict_get_item_op, [_globals, reg], line) + + def load_globals_dict(self) -> Value: + return self.add(LoadStatic(dict_rprimitive, "globals", self.module_name)) + + def load_module_attr_by_fullname(self, fullname: str, line: int) -> Value: + module, _, name = fullname.rpartition(".") + left = self.load_module(module) + return self.py_get_attr(left, name, line) + + def is_native_attr_ref(self, expr: MemberExpr) -> bool: + """Is expr a direct reference to a native (struct) attribute of an instance?""" + obj_rtype = self.node_type(expr.expr) + return ( + isinstance(obj_rtype, RInstance) + and obj_rtype.class_ir.is_ext_class + and obj_rtype.class_ir.has_attr(expr.name) + and not obj_rtype.class_ir.get_method(expr.name) + ) + + def mark_block_unreachable(self) -> None: + """Mark statements in the innermost block being processed as unreachable. + + This should be called after a statement that unconditionally leaves the + block, such as 'break' or 'return'. + """ + self.block_reachable_stack[-1] = False + + # Lacks a good type because there wasn't a reasonable type in 3.5 :( + def catch_errors(self, line: int) -> Any: + return catch_errors(self.module_path, line) + + def warning(self, msg: str, line: int) -> None: + self.errors.warning(msg, self.module_path, line) + + def error(self, msg: str, line: int) -> None: + self.errors.error(msg, self.module_path, line) + + def note(self, msg: str, line: int) -> None: + self.errors.note(msg, self.module_path, line) + + def add_function(self, func_ir: FuncIR, line: int) -> None: + name = (func_ir.class_name, func_ir.name) + if name in self.function_names: + self.error(f'Duplicate definition of "{name[1]}" not supported by mypyc', line) + return + self.function_names.add(name) + self.functions.append(func_ir) + + +def gen_arg_defaults(builder: IRBuilder) -> None: + """Generate blocks for arguments that have default values. + + If the passed value is an error value, then assign the default + value to the argument. + """ + fitem = builder.fn_info.fitem + nb = 0 + for arg in fitem.arguments: + if arg.initializer: + target = builder.lookup(arg.variable) + + def get_default() -> Value: + assert arg.initializer is not None + + # If it is constant, don't bother storing it + if is_constant(arg.initializer): + return builder.accept(arg.initializer) + + # Because gen_arg_defaults runs before calculate_arg_defaults, we + # add the static/attribute to final_names/the class here. + elif not builder.fn_info.is_nested: + name = fitem.fullname + "." + arg.variable.name + builder.final_names.append((name, target.type)) + return builder.add(LoadStatic(target.type, name, builder.module_name)) + else: + name = arg.variable.name + builder.fn_info.callable_class.ir.attributes[name] = target.type + return builder.add( + GetAttr(builder.fn_info.callable_class.self_reg, name, arg.line) + ) + + assert isinstance(target, AssignmentTargetRegister) + reg = target.register + if not reg.type.error_overlap: + builder.assign_if_null(target.register, get_default, arg.initializer.line) + else: + builder.assign_if_bitmap_unset( + target.register, get_default, nb, arg.initializer.line + ) + nb += 1 + + +def remangle_redefinition_name(name: str) -> str: + """Remangle names produced by mypy when allow-redefinition is used and a name + is used with multiple types within a single block. + + We only need to do this for locals, because the name is used as the name of the register; + for globals, the name itself is stored in a register for the purpose of doing dict + lookups. + """ + return name.replace("'", "__redef__") + + +def get_call_target_fullname(ref: RefExpr) -> str: + if isinstance(ref.node, TypeAlias): + # Resolve simple type aliases. In calls they evaluate to the type they point to. + target = get_proper_type(ref.node.target) + if isinstance(target, Instance): + return target.type.fullname + return ref.fullname + + +def create_type_params( + builder: IRBuilder, typing_mod: Value, type_args: list[TypeParam], line: int +) -> list[Value]: + """Create objects representing various kinds of Python 3.12 type parameters. + + The "typing_mod" argument is the "_typing" module object. The type objects + are looked up from it. + + The returned list has one item for each "type_args" item, in the same order. + Each item is either a TypeVar, TypeVarTuple or ParamSpec instance. + """ + tvs = [] + type_var_imported: Value | None = None + for type_param in type_args: + if type_param.kind == TYPE_VAR_KIND: + if type_var_imported: + # Reuse previously imported value as a minor optimization + tvt = type_var_imported + else: + tvt = builder.py_get_attr(typing_mod, "TypeVar", line) + type_var_imported = tvt + elif type_param.kind == TYPE_VAR_TUPLE_KIND: + tvt = builder.py_get_attr(typing_mod, "TypeVarTuple", line) + else: + assert type_param.kind == PARAM_SPEC_KIND + tvt = builder.py_get_attr(typing_mod, "ParamSpec", line) + if type_param.kind != TYPE_VAR_TUPLE_KIND: + # To match runtime semantics, pass infer_variance=True + tv = builder.py_call( + tvt, + [builder.load_str(type_param.name), builder.true()], + line, + arg_kinds=[ARG_POS, ARG_NAMED], + arg_names=[None, "infer_variance"], + ) + else: + tv = builder.py_call(tvt, [builder.load_str(type_param.name)], line) + builder.init_type_var(tv, type_param.name, line) + tvs.append(tv) + return tvs diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/ll_builder.py b/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/ll_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..556d753b89f891bd47b76126bb3240c3adc3dc76 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/ll_builder.py @@ -0,0 +1,2424 @@ +"""A "low-level" IR builder class. + +LowLevelIRBuilder provides core abstractions we use for constructing +IR as well as a number of higher-level ones (accessing attributes, +calling functions and methods, and coercing between types, for +example). The core principle of the low-level IR builder is that all +of its facilities operate solely on the IR level and not the AST +level---it has *no knowledge* of mypy types or expressions. +""" + +from __future__ import annotations + +from typing import Callable, Final, Optional, Sequence, Tuple + +from mypy.argmap import map_actuals_to_formals +from mypy.nodes import ARG_POS, ARG_STAR, ARG_STAR2, ArgKind +from mypy.operators import op_methods, unary_op_methods +from mypy.types import AnyType, TypeOfAny +from mypyc.common import ( + BITMAP_BITS, + FAST_ISINSTANCE_MAX_SUBCLASSES, + MAX_LITERAL_SHORT_INT, + MAX_SHORT_INT, + MIN_LITERAL_SHORT_INT, + MIN_SHORT_INT, + PLATFORM_SIZE, + use_method_vectorcall, + use_vectorcall, +) +from mypyc.errors import Errors +from mypyc.ir.class_ir import ClassIR, all_concrete_classes +from mypyc.ir.func_ir import FuncDecl, FuncSignature +from mypyc.ir.ops import ( + ERR_FALSE, + ERR_NEVER, + NAMESPACE_MODULE, + NAMESPACE_STATIC, + NAMESPACE_TYPE, + Assign, + AssignMulti, + BasicBlock, + Box, + Branch, + Call, + CallC, + Cast, + ComparisonOp, + Extend, + Float, + FloatComparisonOp, + FloatNeg, + FloatOp, + GetAttr, + GetElementPtr, + Goto, + Integer, + IntOp, + KeepAlive, + LoadAddress, + LoadErrorValue, + LoadLiteral, + LoadMem, + LoadStatic, + MethodCall, + Op, + PrimitiveDescription, + PrimitiveOp, + RaiseStandardError, + Register, + Truncate, + TupleGet, + TupleSet, + Unbox, + Unreachable, + Value, + float_comparison_op_to_id, + float_op_to_id, + int_op_to_id, +) +from mypyc.ir.rtypes import ( + PyObject, + PySetObject, + RArray, + RInstance, + RPrimitive, + RTuple, + RType, + RUnion, + bit_rprimitive, + bitmap_rprimitive, + bool_rprimitive, + bytes_rprimitive, + c_int_rprimitive, + c_pointer_rprimitive, + c_pyssize_t_rprimitive, + c_size_t_rprimitive, + check_native_int_range, + dict_rprimitive, + float_rprimitive, + int_rprimitive, + is_bit_rprimitive, + is_bool_rprimitive, + is_bytes_rprimitive, + is_dict_rprimitive, + is_fixed_width_rtype, + is_float_rprimitive, + is_int16_rprimitive, + is_int32_rprimitive, + is_int64_rprimitive, + is_int_rprimitive, + is_list_rprimitive, + is_none_rprimitive, + is_set_rprimitive, + is_short_int_rprimitive, + is_str_rprimitive, + is_tagged, + is_tuple_rprimitive, + is_uint8_rprimitive, + list_rprimitive, + none_rprimitive, + object_pointer_rprimitive, + object_rprimitive, + optional_value_type, + pointer_rprimitive, + short_int_rprimitive, + str_rprimitive, +) +from mypyc.irbuild.util import concrete_arg_kind +from mypyc.options import CompilerOptions +from mypyc.primitives.bytes_ops import bytes_compare +from mypyc.primitives.dict_ops import ( + dict_build_op, + dict_new_op, + dict_ssize_t_size_op, + dict_update_in_display_op, +) +from mypyc.primitives.exc_ops import err_occurred_op, keep_propagating_op +from mypyc.primitives.float_ops import copysign_op, int_to_float_op +from mypyc.primitives.generic_ops import ( + generic_len_op, + generic_ssize_t_len_op, + py_call_op, + py_call_with_kwargs_op, + py_getattr_op, + py_method_call_op, + py_vectorcall_method_op, + py_vectorcall_op, +) +from mypyc.primitives.int_ops import ( + int16_divide_op, + int16_mod_op, + int16_overflow, + int32_divide_op, + int32_mod_op, + int32_overflow, + int64_divide_op, + int64_mod_op, + int64_to_int_op, + int_to_int32_op, + int_to_int64_op, + ssize_t_to_int_op, + uint8_overflow, +) +from mypyc.primitives.list_ops import list_build_op, list_extend_op, list_items, new_list_op +from mypyc.primitives.misc_ops import ( + bool_op, + buf_init_item, + fast_isinstance_op, + none_object_op, + not_implemented_op, + var_object_size, +) +from mypyc.primitives.registry import ( + ERR_NEG_INT, + CFunctionDescription, + binary_ops, + method_call_ops, + unary_ops, +) +from mypyc.primitives.set_ops import new_set_op +from mypyc.primitives.str_ops import str_check_if_true, str_ssize_t_size_op, unicode_compare +from mypyc.primitives.tuple_ops import list_tuple_op, new_tuple_op, new_tuple_with_length_op +from mypyc.rt_subtype import is_runtime_subtype +from mypyc.sametype import is_same_type +from mypyc.subtype import is_subtype + +DictEntry = Tuple[Optional[Value], Value] + +# If the number of items is less than the threshold when initializing +# a list, we would inline the generate IR using SetMem and expanded +# for-loop. Otherwise, we would call `list_build_op` for larger lists. +# TODO: The threshold is a randomly chosen number which needs further +# study on real-world projects for a better balance. +LIST_BUILDING_EXPANSION_THRESHOLD = 10 + +# From CPython +PY_VECTORCALL_ARGUMENTS_OFFSET: Final = 1 << (PLATFORM_SIZE * 8 - 1) + +FIXED_WIDTH_INT_BINARY_OPS: Final = { + "+", + "-", + "*", + "//", + "%", + "&", + "|", + "^", + "<<", + ">>", + "+=", + "-=", + "*=", + "//=", + "%=", + "&=", + "|=", + "^=", + "<<=", + ">>=", +} + +# Binary operations on bools that are specialized and don't just promote operands to int +BOOL_BINARY_OPS: Final = {"&", "&=", "|", "|=", "^", "^=", "==", "!=", "<", "<=", ">", ">="} + + +class LowLevelIRBuilder: + def __init__(self, errors: Errors | None, options: CompilerOptions) -> None: + self.errors = errors + self.options = options + self.args: list[Register] = [] + self.blocks: list[BasicBlock] = [] + # Stack of except handler entry blocks + self.error_handlers: list[BasicBlock | None] = [None] + # Values that we need to keep alive as long as we have borrowed + # temporaries. Use flush_keep_alives() to mark the end of the live range. + self.keep_alives: list[Value] = [] + + def set_module(self, module_name: str, module_path: str) -> None: + """Set the name and path of the current module.""" + self.module_name = module_name + self.module_path = module_path + + # Basic operations + + def add(self, op: Op) -> Value: + """Add an op.""" + assert not self.blocks[-1].terminated, "Can't add to finished block" + self.blocks[-1].ops.append(op) + return op + + def goto(self, target: BasicBlock) -> None: + """Add goto to a basic block.""" + if not self.blocks[-1].terminated: + self.add(Goto(target)) + + def activate_block(self, block: BasicBlock) -> None: + """Add a basic block and make it the active one (target of adds).""" + if self.blocks: + assert self.blocks[-1].terminated + + block.error_handler = self.error_handlers[-1] + self.blocks.append(block) + + def goto_and_activate(self, block: BasicBlock) -> None: + """Add goto a block and make it the active block.""" + self.goto(block) + self.activate_block(block) + + def keep_alive(self, values: list[Value], *, steal: bool = False) -> None: + self.add(KeepAlive(values, steal=steal)) + + def push_error_handler(self, handler: BasicBlock | None) -> None: + self.error_handlers.append(handler) + + def pop_error_handler(self) -> BasicBlock | None: + return self.error_handlers.pop() + + def self(self) -> Register: + """Return reference to the 'self' argument. + + This only works in a method. + """ + return self.args[0] + + def flush_keep_alives(self) -> None: + if self.keep_alives: + self.add(KeepAlive(self.keep_alives.copy())) + self.keep_alives = [] + + # Type conversions + + def box(self, src: Value) -> Value: + if src.type.is_unboxed: + if isinstance(src, Integer) and is_tagged(src.type): + return self.add(LoadLiteral(src.value >> 1, rtype=object_rprimitive)) + return self.add(Box(src)) + else: + return src + + def unbox_or_cast( + self, src: Value, target_type: RType, line: int, *, can_borrow: bool = False + ) -> Value: + if target_type.is_unboxed: + return self.add(Unbox(src, target_type, line)) + else: + if can_borrow: + self.keep_alives.append(src) + return self.add(Cast(src, target_type, line, borrow=can_borrow)) + + def coerce( + self, + src: Value, + target_type: RType, + line: int, + force: bool = False, + *, + can_borrow: bool = False, + ) -> Value: + """Generate a coercion/cast from one type to other (only if needed). + + For example, int -> object boxes the source int; int -> int emits nothing; + object -> int unboxes the object. All conversions preserve object value. + + If force is true, always generate an op (even if it is just an assignment) so + that the result will have exactly target_type as the type. + + Returns the register with the converted value (may be same as src). + """ + src_type = src.type + if src_type.is_unboxed and not target_type.is_unboxed: + # Unboxed -> boxed + return self.box(src) + if (src_type.is_unboxed and target_type.is_unboxed) and not is_runtime_subtype( + src_type, target_type + ): + if ( + isinstance(src, Integer) + and is_short_int_rprimitive(src_type) + and is_fixed_width_rtype(target_type) + ): + value = src.numeric_value() + if not check_native_int_range(target_type, value): + self.error(f'Value {value} is out of range for "{target_type}"', line) + return Integer(src.value >> 1, target_type) + elif is_int_rprimitive(src_type) and is_fixed_width_rtype(target_type): + return self.coerce_int_to_fixed_width(src, target_type, line) + elif is_fixed_width_rtype(src_type) and is_int_rprimitive(target_type): + return self.coerce_fixed_width_to_int(src, line) + elif is_short_int_rprimitive(src_type) and is_fixed_width_rtype(target_type): + return self.coerce_short_int_to_fixed_width(src, target_type, line) + elif ( + isinstance(src_type, RPrimitive) + and isinstance(target_type, RPrimitive) + and src_type.is_native_int + and target_type.is_native_int + and src_type.size == target_type.size + and src_type.is_signed == target_type.is_signed + ): + # Equivalent types + return src + elif (is_bool_rprimitive(src_type) or is_bit_rprimitive(src_type)) and is_tagged( + target_type + ): + shifted = self.int_op( + bool_rprimitive, src, Integer(1, bool_rprimitive), IntOp.LEFT_SHIFT + ) + return self.add(Extend(shifted, target_type, signed=False)) + elif ( + is_bool_rprimitive(src_type) or is_bit_rprimitive(src_type) + ) and is_fixed_width_rtype(target_type): + return self.add(Extend(src, target_type, signed=False)) + elif isinstance(src, Integer) and is_float_rprimitive(target_type): + if is_tagged(src_type): + return Float(float(src.value // 2)) + return Float(float(src.value)) + elif is_tagged(src_type) and is_float_rprimitive(target_type): + return self.int_to_float(src, line) + elif ( + isinstance(src_type, RTuple) + and isinstance(target_type, RTuple) + and len(src_type.types) == len(target_type.types) + ): + # Coerce between two tuple types by coercing each item separately + values = [] + for i in range(len(src_type.types)): + v = None + if isinstance(src, TupleSet): + item = src.items[i] + # We can't reuse register values, since they can be modified. + if not isinstance(item, Register): + v = item + if v is None: + v = TupleGet(src, i) + self.add(v) + values.append(v) + return self.add( + TupleSet( + [self.coerce(v, t, line) for v, t in zip(values, target_type.types)], line + ) + ) + # To go between any other unboxed types, we go through a boxed + # in-between value, for simplicity. + tmp = self.box(src) + return self.unbox_or_cast(tmp, target_type, line) + if (not src_type.is_unboxed and target_type.is_unboxed) or not is_subtype( + src_type, target_type + ): + return self.unbox_or_cast(src, target_type, line, can_borrow=can_borrow) + elif force: + tmp = Register(target_type) + self.add(Assign(tmp, src)) + return tmp + return src + + def coerce_int_to_fixed_width(self, src: Value, target_type: RType, line: int) -> Value: + assert is_fixed_width_rtype(target_type), target_type + assert isinstance(target_type, RPrimitive) + + res = Register(target_type) + + fast, slow, end = BasicBlock(), BasicBlock(), BasicBlock() + + check = self.check_tagged_short_int(src, line) + self.add(Branch(check, fast, slow, Branch.BOOL)) + + self.activate_block(fast) + + size = target_type.size + if size < int_rprimitive.size: + # Add a range check when the target type is smaller than the source tyoe + fast2, fast3 = BasicBlock(), BasicBlock() + upper_bound = 1 << (size * 8 - 1) + if not target_type.is_signed: + upper_bound *= 2 + check2 = self.add(ComparisonOp(src, Integer(upper_bound, src.type), ComparisonOp.SLT)) + self.add(Branch(check2, fast2, slow, Branch.BOOL)) + self.activate_block(fast2) + if target_type.is_signed: + lower_bound = -upper_bound + else: + lower_bound = 0 + check3 = self.add(ComparisonOp(src, Integer(lower_bound, src.type), ComparisonOp.SGE)) + self.add(Branch(check3, fast3, slow, Branch.BOOL)) + self.activate_block(fast3) + tmp = self.int_op( + c_pyssize_t_rprimitive, + src, + Integer(1, c_pyssize_t_rprimitive), + IntOp.RIGHT_SHIFT, + line, + ) + tmp = self.add(Truncate(tmp, target_type)) + else: + if size > int_rprimitive.size: + tmp = self.add(Extend(src, target_type, signed=True)) + else: + tmp = src + tmp = self.int_op(target_type, tmp, Integer(1, target_type), IntOp.RIGHT_SHIFT, line) + + self.add(Assign(res, tmp)) + self.goto(end) + + self.activate_block(slow) + if is_int64_rprimitive(target_type) or ( + is_int32_rprimitive(target_type) and size == int_rprimitive.size + ): + # Slow path calls a library function that handles more complex logic + ptr = self.int_op( + pointer_rprimitive, src, Integer(1, pointer_rprimitive), IntOp.XOR, line + ) + ptr2 = Register(c_pointer_rprimitive) + self.add(Assign(ptr2, ptr)) + if is_int64_rprimitive(target_type): + conv_op = int_to_int64_op + else: + conv_op = int_to_int32_op + tmp = self.call_c(conv_op, [ptr2], line) + self.add(Assign(res, tmp)) + self.add(KeepAlive([src])) + self.goto(end) + elif is_int32_rprimitive(target_type): + # Slow path just always generates an OverflowError + self.call_c(int32_overflow, [], line) + self.add(Unreachable()) + elif is_int16_rprimitive(target_type): + # Slow path just always generates an OverflowError + self.call_c(int16_overflow, [], line) + self.add(Unreachable()) + elif is_uint8_rprimitive(target_type): + # Slow path just always generates an OverflowError + self.call_c(uint8_overflow, [], line) + self.add(Unreachable()) + else: + assert False, target_type + + self.activate_block(end) + return res + + def coerce_short_int_to_fixed_width(self, src: Value, target_type: RType, line: int) -> Value: + if is_int64_rprimitive(target_type): + return self.int_op(target_type, src, Integer(1, target_type), IntOp.RIGHT_SHIFT, line) + # TODO: i32 + assert False, (src.type, target_type) + + def coerce_fixed_width_to_int(self, src: Value, line: int) -> Value: + if ( + (is_int32_rprimitive(src.type) and PLATFORM_SIZE == 8) + or is_int16_rprimitive(src.type) + or is_uint8_rprimitive(src.type) + ): + # Simple case -- just sign extend and shift. + extended = self.add(Extend(src, c_pyssize_t_rprimitive, signed=src.type.is_signed)) + return self.int_op( + int_rprimitive, + extended, + Integer(1, c_pyssize_t_rprimitive), + IntOp.LEFT_SHIFT, + line, + ) + + assert is_fixed_width_rtype(src.type) + assert isinstance(src.type, RPrimitive) + src_type = src.type + + res = Register(int_rprimitive) + + fast, fast2, slow, end = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock() + + c1 = self.add(ComparisonOp(src, Integer(MAX_SHORT_INT, src_type), ComparisonOp.SLE)) + self.add(Branch(c1, fast, slow, Branch.BOOL)) + + self.activate_block(fast) + c2 = self.add(ComparisonOp(src, Integer(MIN_SHORT_INT, src_type), ComparisonOp.SGE)) + self.add(Branch(c2, fast2, slow, Branch.BOOL)) + + self.activate_block(slow) + if is_int64_rprimitive(src_type): + conv_op = int64_to_int_op + elif is_int32_rprimitive(src_type): + assert PLATFORM_SIZE == 4 + conv_op = ssize_t_to_int_op + else: + assert False, src_type + x = self.call_c(conv_op, [src], line) + self.add(Assign(res, x)) + self.goto(end) + + self.activate_block(fast2) + if int_rprimitive.size < src_type.size: + tmp = self.add(Truncate(src, c_pyssize_t_rprimitive)) + else: + tmp = src + s = self.int_op(int_rprimitive, tmp, Integer(1, tmp.type), IntOp.LEFT_SHIFT, line) + self.add(Assign(res, s)) + self.goto(end) + + self.activate_block(end) + return res + + def coerce_nullable(self, src: Value, target_type: RType, line: int) -> Value: + """Generate a coercion from a potentially null value.""" + if src.type.is_unboxed == target_type.is_unboxed and ( + (target_type.is_unboxed and is_runtime_subtype(src.type, target_type)) + or (not target_type.is_unboxed and is_subtype(src.type, target_type)) + ): + return src + + target = Register(target_type) + + valid, invalid, out = BasicBlock(), BasicBlock(), BasicBlock() + self.add(Branch(src, invalid, valid, Branch.IS_ERROR)) + + self.activate_block(valid) + coerced = self.coerce(src, target_type, line) + self.add(Assign(target, coerced, line)) + self.goto(out) + + self.activate_block(invalid) + error = self.add(LoadErrorValue(target_type)) + self.add(Assign(target, error, line)) + + self.goto_and_activate(out) + return target + + # Attribute access + + def get_attr( + self, obj: Value, attr: str, result_type: RType, line: int, *, borrow: bool = False + ) -> Value: + """Get a native or Python attribute of an object.""" + if ( + isinstance(obj.type, RInstance) + and obj.type.class_ir.is_ext_class + and obj.type.class_ir.has_attr(attr) + ): + op = GetAttr(obj, attr, line, borrow=borrow) + # For non-refcounted attribute types, the borrow might be + # disabled even if requested, so don't check 'borrow'. + if op.is_borrowed: + self.keep_alives.append(obj) + return self.add(op) + elif isinstance(obj.type, RUnion): + return self.union_get_attr(obj, obj.type, attr, result_type, line) + else: + return self.py_get_attr(obj, attr, line) + + def union_get_attr( + self, obj: Value, rtype: RUnion, attr: str, result_type: RType, line: int + ) -> Value: + """Get an attribute of an object with a union type.""" + + def get_item_attr(value: Value) -> Value: + return self.get_attr(value, attr, result_type, line) + + return self.decompose_union_helper(obj, rtype, result_type, get_item_attr, line) + + def py_get_attr(self, obj: Value, attr: str, line: int) -> Value: + """Get a Python attribute (slow). + + Prefer get_attr() which generates optimized code for native classes. + """ + key = self.load_str(attr) + return self.primitive_op(py_getattr_op, [obj, key], line) + + # isinstance() checks + + def isinstance_helper(self, obj: Value, class_irs: list[ClassIR], line: int) -> Value: + """Fast path for isinstance() that checks against a list of native classes.""" + if not class_irs: + return self.false() + ret = self.isinstance_native(obj, class_irs[0], line) + for class_ir in class_irs[1:]: + + def other() -> Value: + return self.isinstance_native(obj, class_ir, line) + + ret = self.shortcircuit_helper("or", bool_rprimitive, lambda: ret, other, line) + return ret + + def get_type_of_obj(self, obj: Value, line: int) -> Value: + ob_type_address = self.add(GetElementPtr(obj, PyObject, "ob_type", line)) + ob_type = self.add(LoadMem(object_rprimitive, ob_type_address)) + self.add(KeepAlive([obj])) + return ob_type + + def type_is_op(self, obj: Value, type_obj: Value, line: int) -> Value: + typ = self.get_type_of_obj(obj, line) + return self.add(ComparisonOp(typ, type_obj, ComparisonOp.EQ, line)) + + def isinstance_native(self, obj: Value, class_ir: ClassIR, line: int) -> Value: + """Fast isinstance() check for a native class. + + If there are three or fewer concrete (non-trait) classes among the class + and all its children, use even faster type comparison checks `type(obj) + is typ`. + """ + concrete = all_concrete_classes(class_ir) + if concrete is None or len(concrete) > FAST_ISINSTANCE_MAX_SUBCLASSES + 1: + return self.primitive_op( + fast_isinstance_op, [obj, self.get_native_type(class_ir)], line + ) + if not concrete: + # There can't be any concrete instance that matches this. + return self.false() + type_obj = self.get_native_type(concrete[0]) + ret = self.type_is_op(obj, type_obj, line) + for c in concrete[1:]: + + def other() -> Value: + return self.type_is_op(obj, self.get_native_type(c), line) + + ret = self.shortcircuit_helper("or", bool_rprimitive, lambda: ret, other, line) + return ret + + # Calls + + def _construct_varargs( + self, + args: Sequence[tuple[Value, ArgKind, str | None]], + line: int, + *, + has_star: bool, + has_star2: bool, + ) -> tuple[Value | None, Value | None]: + """Construct *args and **kwargs from a collection of arguments + + This is pretty complicated, and almost all of the complication here stems from + one of two things (but mostly the second): + * The handling of ARG_STAR/ARG_STAR2. We want to create as much of the args/kwargs + values in one go as we can, so we collect values until our hand is forced, and + then we emit creation of the list/tuple, and expand it from there if needed. + + * Support potentially nullable argument values. This has very narrow applicability, + as this will never be done by our compiled Python code, but is critically used + by gen_glue_method when generating glue methods to mediate between the function + signature of a parent class and its subclasses. + + For named-only arguments, this is quite simple: if it is + null, don't put it in the dict. + + For positional-or-named arguments, things are much more complicated. + * First, anything that was passed as a positional arg + must be forwarded along as a positional arg. It *must + not* be converted to a named arg. This is because mypy + does not enforce that positional-or-named arguments + have the same name in subclasses, and it is not + uncommon for code to have different names in + subclasses (a bunch of mypy's visitors do this, for + example!). This is arguably a bug in both mypy and code doing + this, and they ought to be using positional-only arguments, but + positional-only arguments are new and ugly. + + * On the flip side, we're willing to accept the + infelicity of sometimes turning an argument that was + passed by keyword into a positional argument. It's wrong, + but it's very marginal, and avoiding it would require passing + a bitmask of which arguments were named with every function call, + or something similar. + (See some discussion of this in testComplicatedArgs) + + Thus, our strategy for positional-or-named arguments is to + always pass them as positional, except in the one + situation where we can not, and where we can be absolutely + sure they were passed by name: when an *earlier* + positional argument was missing its value. + + This means that if we have a method `f(self, x: int=..., y: object=...)`: + * x and y present: args=(x, y), kwargs={} + * x present, y missing: args=(x,), kwargs={} + * x missing, y present: args=(), kwargs={'y': y} + + To implement this, when we have multiple optional + positional arguments, we maintain a flag in a register + that tracks whether an argument has been missing, and for + each such optional argument (except the first), we check + the flag to determine whether to append the argument to + the *args list or add it to the **kwargs dict. What a + mess! + + This is what really makes everything here such a tangle; + otherwise the *args and **kwargs code could be separated. + + The arguments has_star and has_star2 indicate whether the target function + takes an ARG_STAR and ARG_STAR2 argument, respectively. + (These will always be true when making a pycall, and be based + on the actual target signature for a native call.) + """ + + star_result: Value | None = None + star2_result: Value | None = None + # We aggregate values that need to go into *args and **kwargs + # in these lists. Once all arguments are processed (in the + # happiest case), or we encounter an ARG_STAR/ARG_STAR2 or a + # nullable arg, then we create the list and/or dict. + star_values: list[Value] = [] + star2_keys: list[Value] = [] + star2_values: list[Value] = [] + + seen_empty_reg: Register | None = None + + for value, kind, name in args: + if kind == ARG_STAR: + if star_result is None: + star_result = self.new_list_op(star_values, line) + self.primitive_op(list_extend_op, [star_result, value], line) + elif kind == ARG_STAR2: + if star2_result is None: + star2_result = self._create_dict(star2_keys, star2_values, line) + + self.call_c(dict_update_in_display_op, [star2_result, value], line=line) + else: + nullable = kind.is_optional() + maybe_pos = kind.is_positional() and has_star + maybe_named = kind.is_named() or (kind.is_optional() and name and has_star2) + + # If the argument is nullable, we need to create the + # relevant args/kwargs objects so that we can + # conditionally modify them. + if nullable: + if maybe_pos and star_result is None: + star_result = self.new_list_op(star_values, line) + if maybe_named and star2_result is None: + star2_result = self._create_dict(star2_keys, star2_values, line) + + # Easy cases: just collect the argument. + if maybe_pos and star_result is None: + star_values.append(value) + continue + + if maybe_named and star2_result is None: + assert name is not None + key = self.load_str(name) + star2_keys.append(key) + star2_values.append(value) + continue + + # OK, anything that is nullable or *after* a nullable arg needs to be here + # TODO: We could try harder to avoid creating basic blocks in the common case + new_seen_empty_reg = seen_empty_reg + + out = BasicBlock() + if nullable: + # If this is the first nullable positional arg we've seen, create + # a register to track whether anything has been null. + # (We won't *check* the register until the next argument, though.) + if maybe_pos and not seen_empty_reg: + new_seen_empty_reg = Register(bool_rprimitive) + self.add(Assign(new_seen_empty_reg, self.false(), line)) + + skip = BasicBlock() if maybe_pos else out + keep = BasicBlock() + self.add(Branch(value, skip, keep, Branch.IS_ERROR)) + self.activate_block(keep) + + # If this could be positional or named and we /might/ have seen a missing + # positional arg, then we need to compile *both* a positional and named + # version! What a pain! + if maybe_pos and maybe_named and seen_empty_reg: + pos_block, named_block = BasicBlock(), BasicBlock() + self.add(Branch(seen_empty_reg, named_block, pos_block, Branch.BOOL)) + else: + pos_block = named_block = BasicBlock() + self.goto(pos_block) + + if maybe_pos: + self.activate_block(pos_block) + assert star_result + self.translate_special_method_call( + star_result, "append", [value], result_type=None, line=line + ) + self.goto(out) + + if maybe_named and (not maybe_pos or seen_empty_reg): + self.activate_block(named_block) + assert name is not None + key = self.load_str(name) + assert star2_result + self.translate_special_method_call( + star2_result, "__setitem__", [key, value], result_type=None, line=line + ) + self.goto(out) + + if nullable and maybe_pos and new_seen_empty_reg: + assert skip is not out + self.activate_block(skip) + self.add(Assign(new_seen_empty_reg, self.true(), line)) + self.goto(out) + + self.activate_block(out) + + seen_empty_reg = new_seen_empty_reg + + assert not (star_result or star_values) or has_star + assert not (star2_result or star2_values) or has_star2 + if has_star: + # If we managed to make it this far without creating a + # *args list, then we can directly create a + # tuple. Otherwise create the tuple from the list. + if star_result is None: + star_result = self.new_tuple(star_values, line) + else: + star_result = self.primitive_op(list_tuple_op, [star_result], line) + if has_star2 and star2_result is None: + star2_result = self._create_dict(star2_keys, star2_values, line) + + return star_result, star2_result + + def py_call( + self, + function: Value, + arg_values: list[Value], + line: int, + arg_kinds: list[ArgKind] | None = None, + arg_names: Sequence[str | None] | None = None, + ) -> Value: + """Call a Python function (non-native and slow). + + Use py_call_op or py_call_with_kwargs_op for Python function call. + """ + if use_vectorcall(self.options.capi_version): + # More recent Python versions support faster vectorcalls. + result = self._py_vector_call(function, arg_values, line, arg_kinds, arg_names) + if result is not None: + return result + + # If all arguments are positional, we can use py_call_op. + if arg_kinds is None or all(kind == ARG_POS for kind in arg_kinds): + return self.call_c(py_call_op, [function] + arg_values, line) + + # Otherwise fallback to py_call_with_kwargs_op. + assert arg_names is not None + + pos_args_tuple, kw_args_dict = self._construct_varargs( + list(zip(arg_values, arg_kinds, arg_names)), line, has_star=True, has_star2=True + ) + assert pos_args_tuple and kw_args_dict + + return self.call_c(py_call_with_kwargs_op, [function, pos_args_tuple, kw_args_dict], line) + + def _py_vector_call( + self, + function: Value, + arg_values: list[Value], + line: int, + arg_kinds: list[ArgKind] | None = None, + arg_names: Sequence[str | None] | None = None, + ) -> Value | None: + """Call function using the vectorcall API if possible. + + Return the return value if successful. Return None if a non-vectorcall + API should be used instead. + """ + # We can do this if all args are positional or named (no *args or **kwargs, not optional). + if arg_kinds is None or all( + not kind.is_star() and not kind.is_optional() for kind in arg_kinds + ): + if arg_values: + # Create a C array containing all arguments as boxed values. + coerced_args = [self.coerce(arg, object_rprimitive, line) for arg in arg_values] + arg_ptr = self.setup_rarray(object_rprimitive, coerced_args, object_ptr=True) + else: + arg_ptr = Integer(0, object_pointer_rprimitive) + num_pos = num_positional_args(arg_values, arg_kinds) + keywords = self._vectorcall_keywords(arg_names) + value = self.call_c( + py_vectorcall_op, + [function, arg_ptr, Integer(num_pos, c_size_t_rprimitive), keywords], + line, + ) + if arg_values: + # Make sure arguments won't be freed until after the call. + # We need this because RArray doesn't support automatic + # memory management. + self.add(KeepAlive(coerced_args)) + return value + return None + + def _vectorcall_keywords(self, arg_names: Sequence[str | None] | None) -> Value: + """Return a reference to a tuple literal with keyword argument names. + + Return null pointer if there are no keyword arguments. + """ + if arg_names: + kw_list = [name for name in arg_names if name is not None] + if kw_list: + return self.add(LoadLiteral(tuple(kw_list), object_rprimitive)) + return Integer(0, object_rprimitive) + + def py_method_call( + self, + obj: Value, + method_name: str, + arg_values: list[Value], + line: int, + arg_kinds: list[ArgKind] | None, + arg_names: Sequence[str | None] | None, + ) -> Value: + """Call a Python method (non-native and slow).""" + if use_method_vectorcall(self.options.capi_version): + # More recent Python versions support faster vectorcalls. + result = self._py_vector_method_call( + obj, method_name, arg_values, line, arg_kinds, arg_names + ) + if result is not None: + return result + + if arg_kinds is None or all(kind == ARG_POS for kind in arg_kinds): + # Use legacy method call API + method_name_reg = self.load_str(method_name) + return self.call_c(py_method_call_op, [obj, method_name_reg] + arg_values, line) + else: + # Use py_call since it supports keyword arguments (and vectorcalls). + method = self.py_get_attr(obj, method_name, line) + return self.py_call(method, arg_values, line, arg_kinds=arg_kinds, arg_names=arg_names) + + def _py_vector_method_call( + self, + obj: Value, + method_name: str, + arg_values: list[Value], + line: int, + arg_kinds: list[ArgKind] | None, + arg_names: Sequence[str | None] | None, + ) -> Value | None: + """Call method using the vectorcall API if possible. + + Return the return value if successful. Return None if a non-vectorcall + API should be used instead. + """ + if arg_kinds is None or all( + not kind.is_star() and not kind.is_optional() for kind in arg_kinds + ): + method_name_reg = self.load_str(method_name) + coerced_args = [ + self.coerce(arg, object_rprimitive, line) for arg in [obj] + arg_values + ] + arg_ptr = self.setup_rarray(object_rprimitive, coerced_args, object_ptr=True) + num_pos = num_positional_args(arg_values, arg_kinds) + keywords = self._vectorcall_keywords(arg_names) + value = self.call_c( + py_vectorcall_method_op, + [ + method_name_reg, + arg_ptr, + Integer((num_pos + 1) | PY_VECTORCALL_ARGUMENTS_OFFSET, c_size_t_rprimitive), + keywords, + ], + line, + ) + # Make sure arguments won't be freed until after the call. + # We need this because RArray doesn't support automatic + # memory management. + self.add(KeepAlive(coerced_args)) + return value + return None + + def call( + self, + decl: FuncDecl, + args: Sequence[Value], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None], + line: int, + *, + bitmap_args: list[Register] | None = None, + ) -> Value: + """Call a native function. + + If bitmap_args is given, they override the values of (some) of the bitmap + arguments used to track the presence of values for certain arguments. By + default, the values of the bitmap arguments are inferred from args. + """ + # Normalize args to positionals. + args = self.native_args_to_positional( + args, arg_kinds, arg_names, decl.sig, line, bitmap_args=bitmap_args + ) + return self.add(Call(decl, args, line)) + + def native_args_to_positional( + self, + args: Sequence[Value], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None], + sig: FuncSignature, + line: int, + *, + bitmap_args: list[Register] | None = None, + ) -> list[Value]: + """Prepare arguments for a native call. + + Given args/kinds/names and a target signature for a native call, map + keyword arguments to their appropriate place in the argument list, + fill in error values for unspecified default arguments, + package arguments that will go into *args/**kwargs into a tuple/dict, + and coerce arguments to the appropriate type. + """ + + sig_args = sig.args + n = sig.num_bitmap_args + if n: + sig_args = sig_args[:-n] + + sig_arg_kinds = [arg.kind for arg in sig_args] + sig_arg_names = [arg.name for arg in sig_args] + + concrete_kinds = [concrete_arg_kind(arg_kind) for arg_kind in arg_kinds] + formal_to_actual = map_actuals_to_formals( + concrete_kinds, + arg_names, + sig_arg_kinds, + sig_arg_names, + lambda n: AnyType(TypeOfAny.special_form), + ) + + # First scan for */** and construct those + has_star = has_star2 = False + star_arg_entries = [] + for lst, arg in zip(formal_to_actual, sig_args): + if arg.kind.is_star(): + star_arg_entries.extend([(args[i], arg_kinds[i], arg_names[i]) for i in lst]) + has_star = has_star or arg.kind == ARG_STAR + has_star2 = has_star2 or arg.kind == ARG_STAR2 + + star_arg, star2_arg = self._construct_varargs( + star_arg_entries, line, has_star=has_star, has_star2=has_star2 + ) + + # Flatten out the arguments, loading error values for default + # arguments, constructing tuples/dicts for star args, and + # coercing everything to the expected type. + output_args: list[Value] = [] + for lst, arg in zip(formal_to_actual, sig_args): + if arg.kind == ARG_STAR: + assert star_arg + output_arg = star_arg + elif arg.kind == ARG_STAR2: + assert star2_arg + output_arg = star2_arg + elif not lst: + if is_fixed_width_rtype(arg.type): + output_arg = Integer(0, arg.type) + elif is_float_rprimitive(arg.type): + output_arg = Float(0.0) + else: + output_arg = self.add(LoadErrorValue(arg.type, is_borrowed=True)) + else: + base_arg = args[lst[0]] + + if arg_kinds[lst[0]].is_optional(): + output_arg = self.coerce_nullable(base_arg, arg.type, line) + else: + output_arg = self.coerce(base_arg, arg.type, line) + + output_args.append(output_arg) + + for i in reversed(range(n)): + if bitmap_args and i < len(bitmap_args): + # Use override provided by caller + output_args.append(bitmap_args[i]) + continue + # Infer values of bitmap args + bitmap = 0 + c = 0 + for lst, arg in zip(formal_to_actual, sig_args): + if arg.kind.is_optional() and arg.type.error_overlap: + if i * BITMAP_BITS <= c < (i + 1) * BITMAP_BITS: + if lst: + bitmap |= 1 << (c & (BITMAP_BITS - 1)) + c += 1 + output_args.append(Integer(bitmap, bitmap_rprimitive)) + + return output_args + + def gen_method_call( + self, + base: Value, + name: str, + arg_values: list[Value], + result_type: RType | None, + line: int, + arg_kinds: list[ArgKind] | None = None, + arg_names: list[str | None] | None = None, + can_borrow: bool = False, + ) -> Value: + """Generate either a native or Python method call.""" + # If we have *args, then fallback to Python method call. + if arg_kinds is not None and any(kind.is_star() for kind in arg_kinds): + return self.py_method_call(base, name, arg_values, base.line, arg_kinds, arg_names) + + # If the base type is one of ours, do a MethodCall + if ( + isinstance(base.type, RInstance) + and base.type.class_ir.is_ext_class + and not base.type.class_ir.builtin_base + ): + if base.type.class_ir.has_method(name): + decl = base.type.class_ir.method_decl(name) + if arg_kinds is None: + assert arg_names is None, "arg_kinds not present but arg_names is" + arg_kinds = [ARG_POS for _ in arg_values] + arg_names = [None for _ in arg_values] + else: + assert arg_names is not None, "arg_kinds present but arg_names is not" + + # Normalize args to positionals. + assert decl.bound_sig + arg_values = self.native_args_to_positional( + arg_values, arg_kinds, arg_names, decl.bound_sig, line + ) + return self.add(MethodCall(base, name, arg_values, line)) + elif base.type.class_ir.has_attr(name): + function = self.add(GetAttr(base, name, line)) + return self.py_call( + function, arg_values, line, arg_kinds=arg_kinds, arg_names=arg_names + ) + + elif isinstance(base.type, RUnion): + return self.union_method_call( + base, base.type, name, arg_values, result_type, line, arg_kinds, arg_names + ) + + # Try to do a special-cased method call + if not arg_kinds or arg_kinds == [ARG_POS] * len(arg_values): + target = self.translate_special_method_call( + base, name, arg_values, result_type, line, can_borrow=can_borrow + ) + if target: + return target + + # Fall back to Python method call + return self.py_method_call(base, name, arg_values, line, arg_kinds, arg_names) + + def union_method_call( + self, + base: Value, + obj_type: RUnion, + name: str, + arg_values: list[Value], + return_rtype: RType | None, + line: int, + arg_kinds: list[ArgKind] | None, + arg_names: list[str | None] | None, + ) -> Value: + """Generate a method call with a union type for the object.""" + # Union method call needs a return_rtype for the type of the output register. + # If we don't have one, use object_rprimitive. + return_rtype = return_rtype or object_rprimitive + + def call_union_item(value: Value) -> Value: + return self.gen_method_call( + value, name, arg_values, return_rtype, line, arg_kinds, arg_names + ) + + return self.decompose_union_helper(base, obj_type, return_rtype, call_union_item, line) + + # Loading various values + + def none(self) -> Value: + """Load unboxed None value (type: none_rprimitive).""" + return Integer(1, none_rprimitive) + + def true(self) -> Value: + """Load unboxed True value (type: bool_rprimitive).""" + return Integer(1, bool_rprimitive) + + def false(self) -> Value: + """Load unboxed False value (type: bool_rprimitive).""" + return Integer(0, bool_rprimitive) + + def none_object(self) -> Value: + """Load Python None value (type: object_rprimitive).""" + return self.add(LoadAddress(none_object_op.type, none_object_op.src, line=-1)) + + def load_int(self, value: int) -> Value: + """Load a tagged (Python) integer literal value.""" + if value > MAX_LITERAL_SHORT_INT or value < MIN_LITERAL_SHORT_INT: + return self.add(LoadLiteral(value, int_rprimitive)) + else: + return Integer(value) + + def load_float(self, value: float) -> Value: + """Load a float literal value.""" + return Float(value) + + def load_str(self, value: str) -> Value: + """Load a str literal value. + + This is useful for more than just str literals; for example, method calls + also require a PyObject * form for the name of the method. + """ + return self.add(LoadLiteral(value, str_rprimitive)) + + def load_bytes(self, value: bytes) -> Value: + """Load a bytes literal value.""" + return self.add(LoadLiteral(value, bytes_rprimitive)) + + def load_complex(self, value: complex) -> Value: + """Load a complex literal value.""" + return self.add(LoadLiteral(value, object_rprimitive)) + + def load_static_checked( + self, + typ: RType, + identifier: str, + module_name: str | None = None, + namespace: str = NAMESPACE_STATIC, + line: int = -1, + error_msg: str | None = None, + ) -> Value: + if error_msg is None: + error_msg = f'name "{identifier}" is not defined' + ok_block, error_block = BasicBlock(), BasicBlock() + value = self.add(LoadStatic(typ, identifier, module_name, namespace, line=line)) + self.add(Branch(value, error_block, ok_block, Branch.IS_ERROR, rare=True)) + self.activate_block(error_block) + self.add(RaiseStandardError(RaiseStandardError.NAME_ERROR, error_msg, line)) + self.add(Unreachable()) + self.activate_block(ok_block) + return value + + def load_module(self, name: str) -> Value: + return self.add(LoadStatic(object_rprimitive, name, namespace=NAMESPACE_MODULE)) + + def get_native_type(self, cls: ClassIR) -> Value: + """Load native type object.""" + fullname = f"{cls.module_name}.{cls.name}" + return self.load_native_type_object(fullname) + + def load_native_type_object(self, fullname: str) -> Value: + module, name = fullname.rsplit(".", 1) + return self.add(LoadStatic(object_rprimitive, name, module, NAMESPACE_TYPE)) + + # Other primitive operations + + def binary_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value: + """Perform a binary operation. + + Generate specialized operations based on operand types, with a fallback + to generic operations. + """ + ltype = lreg.type + rtype = rreg.type + + # Special case tuple comparison here so that nested tuples can be supported + if isinstance(ltype, RTuple) and isinstance(rtype, RTuple) and op in ("==", "!="): + return self.compare_tuples(lreg, rreg, op, line) + + # Special case == and != when we can resolve the method call statically + if op in ("==", "!="): + value = self.translate_eq_cmp(lreg, rreg, op, line) + if value is not None: + return value + + # Special case various ops + if op in ("is", "is not"): + return self.translate_is_op(lreg, rreg, op, line) + # TODO: modify 'str' to use same interface as 'compare_bytes' as it avoids + # call to PyErr_Occurred() + if is_str_rprimitive(ltype) and is_str_rprimitive(rtype) and op in ("==", "!="): + return self.compare_strings(lreg, rreg, op, line) + if is_bytes_rprimitive(ltype) and is_bytes_rprimitive(rtype) and op in ("==", "!="): + return self.compare_bytes(lreg, rreg, op, line) + if is_bool_rprimitive(ltype) and is_bool_rprimitive(rtype) and op in BOOL_BINARY_OPS: + if op in ComparisonOp.signed_ops: + return self.bool_comparison_op(lreg, rreg, op, line) + else: + return self.bool_bitwise_op(lreg, rreg, op[0], line) + if isinstance(rtype, RInstance) and op in ("in", "not in"): + return self.translate_instance_contains(rreg, lreg, op, line) + if is_fixed_width_rtype(ltype): + if op in FIXED_WIDTH_INT_BINARY_OPS: + if op.endswith("="): + op = op[:-1] + if op != "//": + op_id = int_op_to_id[op] + else: + op_id = IntOp.DIV + if is_bool_rprimitive(rtype) or is_bit_rprimitive(rtype): + rreg = self.coerce(rreg, ltype, line) + rtype = ltype + if is_fixed_width_rtype(rtype) or is_tagged(rtype): + return self.fixed_width_int_op(ltype, lreg, rreg, op_id, line) + if isinstance(rreg, Integer): + return self.fixed_width_int_op( + ltype, lreg, self.coerce(rreg, ltype, line), op_id, line + ) + elif op in ComparisonOp.signed_ops: + if is_int_rprimitive(rtype): + rreg = self.coerce_int_to_fixed_width(rreg, ltype, line) + elif is_bool_rprimitive(rtype) or is_bit_rprimitive(rtype): + rreg = self.coerce(rreg, ltype, line) + op_id = ComparisonOp.signed_ops[op] + if is_fixed_width_rtype(rreg.type): + return self.comparison_op(lreg, rreg, op_id, line) + if isinstance(rreg, Integer): + return self.comparison_op(lreg, self.coerce(rreg, ltype, line), op_id, line) + elif is_fixed_width_rtype(rtype): + if op in FIXED_WIDTH_INT_BINARY_OPS: + if op.endswith("="): + op = op[:-1] + if op != "//": + op_id = int_op_to_id[op] + else: + op_id = IntOp.DIV + if isinstance(lreg, Integer): + return self.fixed_width_int_op( + rtype, self.coerce(lreg, rtype, line), rreg, op_id, line + ) + if is_tagged(ltype): + return self.fixed_width_int_op(rtype, lreg, rreg, op_id, line) + if is_bool_rprimitive(ltype) or is_bit_rprimitive(ltype): + lreg = self.coerce(lreg, rtype, line) + return self.fixed_width_int_op(rtype, lreg, rreg, op_id, line) + elif op in ComparisonOp.signed_ops: + if is_int_rprimitive(ltype): + lreg = self.coerce_int_to_fixed_width(lreg, rtype, line) + elif is_bool_rprimitive(ltype) or is_bit_rprimitive(ltype): + lreg = self.coerce(lreg, rtype, line) + op_id = ComparisonOp.signed_ops[op] + if isinstance(lreg, Integer): + return self.comparison_op(self.coerce(lreg, rtype, line), rreg, op_id, line) + if is_fixed_width_rtype(lreg.type): + return self.comparison_op(lreg, rreg, op_id, line) + + if is_float_rprimitive(ltype) or is_float_rprimitive(rtype): + if isinstance(lreg, Integer): + lreg = Float(float(lreg.numeric_value())) + elif isinstance(rreg, Integer): + rreg = Float(float(rreg.numeric_value())) + elif is_int_rprimitive(lreg.type): + lreg = self.int_to_float(lreg, line) + elif is_int_rprimitive(rreg.type): + rreg = self.int_to_float(rreg, line) + if is_float_rprimitive(lreg.type) and is_float_rprimitive(rreg.type): + if op in float_comparison_op_to_id: + return self.compare_floats(lreg, rreg, float_comparison_op_to_id[op], line) + if op.endswith("="): + base_op = op[:-1] + else: + base_op = op + if base_op in float_op_to_id: + return self.float_op(lreg, rreg, base_op, line) + + dunder_op = self.dunder_op(lreg, rreg, op, line) + if dunder_op: + return dunder_op + + primitive_ops_candidates = binary_ops.get(op, []) + target = self.matching_primitive_op(primitive_ops_candidates, [lreg, rreg], line) + assert target, "Unsupported binary operation: %s" % op + return target + + def dunder_op(self, lreg: Value, rreg: Value | None, op: str, line: int) -> Value | None: + """ + Dispatch a dunder method if applicable. + For example for `a + b` it will use `a.__add__(b)` which can lead to higher performance + due to the fact that the method could be already compiled and optimized instead of going + all the way through `PyNumber_Add(a, b)` python api (making a jump into the python DL). + """ + ltype = lreg.type + if not isinstance(ltype, RInstance): + return None + + method_name = op_methods.get(op) if rreg else unary_op_methods.get(op) + if method_name is None: + return None + + if not ltype.class_ir.has_method(method_name): + return None + + decl = ltype.class_ir.method_decl(method_name) + if not rreg and len(decl.sig.args) != 1: + return None + + if rreg and (len(decl.sig.args) != 2 or not is_subtype(rreg.type, decl.sig.args[1].type)): + return None + + if rreg and is_subtype(not_implemented_op.type, decl.sig.ret_type): + # If the method is able to return NotImplemented, we should not optimize it. + # We can just let go so it will be handled through the python api. + return None + + args = [rreg] if rreg else [] + return self.gen_method_call(lreg, method_name, args, decl.sig.ret_type, line) + + def check_tagged_short_int(self, val: Value, line: int, negated: bool = False) -> Value: + """Check if a tagged integer is a short integer. + + Return the result of the check (value of type 'bit'). + """ + int_tag = Integer(1, c_pyssize_t_rprimitive, line) + bitwise_and = self.int_op(c_pyssize_t_rprimitive, val, int_tag, IntOp.AND, line) + zero = Integer(0, c_pyssize_t_rprimitive, line) + op = ComparisonOp.NEQ if negated else ComparisonOp.EQ + check = self.comparison_op(bitwise_and, zero, op, line) + return check + + def compare_strings(self, lhs: Value, rhs: Value, op: str, line: int) -> Value: + """Compare two strings""" + compare_result = self.call_c(unicode_compare, [lhs, rhs], line) + error_constant = Integer(-1, c_int_rprimitive, line) + compare_error_check = self.add( + ComparisonOp(compare_result, error_constant, ComparisonOp.EQ, line) + ) + exception_check, propagate, final_compare = BasicBlock(), BasicBlock(), BasicBlock() + branch = Branch(compare_error_check, exception_check, final_compare, Branch.BOOL) + branch.negated = False + self.add(branch) + self.activate_block(exception_check) + check_error_result = self.call_c(err_occurred_op, [], line) + null = Integer(0, pointer_rprimitive, line) + compare_error_check = self.add( + ComparisonOp(check_error_result, null, ComparisonOp.NEQ, line) + ) + branch = Branch(compare_error_check, propagate, final_compare, Branch.BOOL) + branch.negated = False + self.add(branch) + self.activate_block(propagate) + self.call_c(keep_propagating_op, [], line) + self.goto(final_compare) + self.activate_block(final_compare) + op_type = ComparisonOp.EQ if op == "==" else ComparisonOp.NEQ + return self.add(ComparisonOp(compare_result, Integer(0, c_int_rprimitive), op_type, line)) + + def compare_bytes(self, lhs: Value, rhs: Value, op: str, line: int) -> Value: + compare_result = self.call_c(bytes_compare, [lhs, rhs], line) + op_type = ComparisonOp.EQ if op == "==" else ComparisonOp.NEQ + return self.add(ComparisonOp(compare_result, Integer(1, c_int_rprimitive), op_type, line)) + + def compare_tuples(self, lhs: Value, rhs: Value, op: str, line: int = -1) -> Value: + """Compare two tuples item by item""" + # type cast to pass mypy check + assert isinstance(lhs.type, RTuple) and isinstance(rhs.type, RTuple) + equal = True if op == "==" else False + result = Register(bool_rprimitive) + # empty tuples + if len(lhs.type.types) == 0 and len(rhs.type.types) == 0: + self.add(Assign(result, self.true() if equal else self.false(), line)) + return result + length = len(lhs.type.types) + false_assign, true_assign, out = BasicBlock(), BasicBlock(), BasicBlock() + check_blocks = [BasicBlock() for _ in range(length)] + lhs_items = [self.add(TupleGet(lhs, i, line)) for i in range(length)] + rhs_items = [self.add(TupleGet(rhs, i, line)) for i in range(length)] + + if equal: + early_stop, final = false_assign, true_assign + else: + early_stop, final = true_assign, false_assign + + for i in range(len(lhs.type.types)): + if i != 0: + self.activate_block(check_blocks[i]) + lhs_item = lhs_items[i] + rhs_item = rhs_items[i] + compare = self.binary_op(lhs_item, rhs_item, op, line) + # Cast to bool if necessary since most types uses comparison returning a object type + # See generic_ops.py for more information + if not is_bool_rprimitive(compare.type): + compare = self.primitive_op(bool_op, [compare], line) + if i < len(lhs.type.types) - 1: + branch = Branch(compare, early_stop, check_blocks[i + 1], Branch.BOOL) + else: + branch = Branch(compare, early_stop, final, Branch.BOOL) + # if op is ==, we branch on false, else branch on true + branch.negated = equal + self.add(branch) + self.activate_block(false_assign) + self.add(Assign(result, self.false(), line)) + self.goto(out) + self.activate_block(true_assign) + self.add(Assign(result, self.true(), line)) + self.goto_and_activate(out) + return result + + def translate_instance_contains(self, inst: Value, item: Value, op: str, line: int) -> Value: + res = self.gen_method_call(inst, "__contains__", [item], None, line) + if not is_bool_rprimitive(res.type): + res = self.primitive_op(bool_op, [res], line) + if op == "not in": + res = self.bool_bitwise_op(res, Integer(1, rtype=bool_rprimitive), "^", line) + return res + + def bool_bitwise_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value: + if op == "&": + code = IntOp.AND + elif op == "|": + code = IntOp.OR + elif op == "^": + code = IntOp.XOR + else: + assert False, op + return self.add(IntOp(bool_rprimitive, lreg, rreg, code, line)) + + def bool_comparison_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value: + op_id = ComparisonOp.signed_ops[op] + return self.comparison_op(lreg, rreg, op_id, line) + + def unary_not(self, value: Value, line: int) -> Value: + mask = Integer(1, value.type, line) + return self.int_op(value.type, value, mask, IntOp.XOR, line) + + def unary_op(self, value: Value, expr_op: str, line: int) -> Value: + typ = value.type + if is_bool_rprimitive(typ) or is_bit_rprimitive(typ): + if expr_op == "not": + return self.unary_not(value, line) + if expr_op == "+": + return value + if is_fixed_width_rtype(typ): + if expr_op == "-": + # Translate to '0 - x' + return self.int_op(typ, Integer(0, typ), value, IntOp.SUB, line) + elif expr_op == "~": + if typ.is_signed: + # Translate to 'x ^ -1' + return self.int_op(typ, value, Integer(-1, typ), IntOp.XOR, line) + else: + # Translate to 'x ^ 0xff...' + mask = (1 << (typ.size * 8)) - 1 + return self.int_op(typ, value, Integer(mask, typ), IntOp.XOR, line) + elif expr_op == "+": + return value + if is_float_rprimitive(typ): + if expr_op == "-": + return self.add(FloatNeg(value, line)) + elif expr_op == "+": + return value + + if isinstance(value, Integer): + # TODO: Overflow? Unsigned? + num = value.value + if is_short_int_rprimitive(typ): + num >>= 1 + return Integer(-num, typ, value.line) + if is_tagged(typ) and expr_op == "+": + return value + if isinstance(value, Float): + return Float(-value.value, value.line) + if isinstance(typ, RInstance): + result = self.dunder_op(value, None, expr_op, line) + if result is not None: + return result + primitive_ops_candidates = unary_ops.get(expr_op, []) + target = self.matching_primitive_op(primitive_ops_candidates, [value], line) + assert target, "Unsupported unary operation: %s" % expr_op + return target + + def make_dict(self, key_value_pairs: Sequence[DictEntry], line: int) -> Value: + result: Value | None = None + keys: list[Value] = [] + values: list[Value] = [] + for key, value in key_value_pairs: + if key is not None: + # key:value + if result is None: + keys.append(key) + values.append(value) + continue + + self.translate_special_method_call( + result, "__setitem__", [key, value], result_type=None, line=line + ) + else: + # **value + if result is None: + result = self._create_dict(keys, values, line) + + self.call_c(dict_update_in_display_op, [result, value], line=line) + + if result is None: + result = self._create_dict(keys, values, line) + + return result + + def new_list_op_with_length(self, length: Value, line: int) -> Value: + """This function returns an uninitialized list. + + If the length is non-zero, the caller must initialize the list, before + it can be made visible to user code -- otherwise the list object is broken. + You might need further initialization with `new_list_set_item_op` op. + + Args: + length: desired length of the new list. The rtype should be + c_pyssize_t_rprimitive + line: line number + """ + return self.call_c(new_list_op, [length], line) + + def new_list_op(self, values: list[Value], line: int) -> Value: + length: list[Value] = [Integer(len(values), c_pyssize_t_rprimitive, line)] + if len(values) >= LIST_BUILDING_EXPANSION_THRESHOLD: + return self.call_c(list_build_op, length + values, line) + + # If the length of the list is less than the threshold, + # LIST_BUILDING_EXPANSION_THRESHOLD, we directly expand the + # for-loop and inline the SetMem operation, which is faster + # than list_build_op, however generates more code. + result_list = self.call_c(new_list_op, length, line) + if not values: + return result_list + args = [self.coerce(item, object_rprimitive, line) for item in values] + ob_item_base = self.add(PrimitiveOp([result_list], list_items, line)) + for i in range(len(values)): + self.primitive_op( + buf_init_item, [ob_item_base, Integer(i, c_pyssize_t_rprimitive), args[i]], line + ) + self.add(KeepAlive([result_list])) + return result_list + + def new_set_op(self, values: list[Value], line: int) -> Value: + return self.primitive_op(new_set_op, values, line) + + def setup_rarray( + self, item_type: RType, values: Sequence[Value], *, object_ptr: bool = False + ) -> Value: + """Declare and initialize a new RArray, returning its address.""" + array = Register(RArray(item_type, len(values))) + self.add(AssignMulti(array, list(values))) + return self.add( + LoadAddress(object_pointer_rprimitive if object_ptr else c_pointer_rprimitive, array) + ) + + def shortcircuit_helper( + self, + op: str, + expr_type: RType, + left: Callable[[], Value], + right: Callable[[], Value], + line: int, + ) -> Value: + # Having actual Phi nodes would be really nice here! + target = Register(expr_type) + # left_body takes the value of the left side, right_body the right + left_body, right_body, next_block = BasicBlock(), BasicBlock(), BasicBlock() + # true_body is taken if the left is true, false_body if it is false. + # For 'and' the value is the right side if the left is true, and for 'or' + # it is the right side if the left is false. + true_body, false_body = (right_body, left_body) if op == "and" else (left_body, right_body) + + left_value = left() + self.add_bool_branch(left_value, true_body, false_body) + + self.activate_block(left_body) + left_coerced = self.coerce(left_value, expr_type, line) + self.add(Assign(target, left_coerced)) + self.goto(next_block) + + self.activate_block(right_body) + right_value = right() + right_coerced = self.coerce(right_value, expr_type, line) + self.add(Assign(target, right_coerced)) + self.goto(next_block) + + self.activate_block(next_block) + return target + + def bool_value(self, value: Value) -> Value: + """Return bool(value). + + The result type can be bit_rprimitive or bool_rprimitive. + """ + if is_bool_rprimitive(value.type) or is_bit_rprimitive(value.type): + result = value + elif is_runtime_subtype(value.type, int_rprimitive): + zero = Integer(0, short_int_rprimitive) + result = self.comparison_op(value, zero, ComparisonOp.NEQ, value.line) + elif is_fixed_width_rtype(value.type): + zero = Integer(0, value.type) + result = self.add(ComparisonOp(value, zero, ComparisonOp.NEQ)) + elif is_same_type(value.type, str_rprimitive): + result = self.call_c(str_check_if_true, [value], value.line) + elif is_same_type(value.type, list_rprimitive) or is_same_type( + value.type, dict_rprimitive + ): + length = self.builtin_len(value, value.line) + zero = Integer(0) + result = self.binary_op(length, zero, "!=", value.line) + elif ( + isinstance(value.type, RInstance) + and value.type.class_ir.is_ext_class + and value.type.class_ir.has_method("__bool__") + ): + # Directly call the __bool__ method on classes that have it. + result = self.gen_method_call(value, "__bool__", [], bool_rprimitive, value.line) + elif is_float_rprimitive(value.type): + result = self.compare_floats(value, Float(0.0), FloatComparisonOp.NEQ, value.line) + else: + value_type = optional_value_type(value.type) + if value_type is not None: + not_none = self.translate_is_op(value, self.none_object(), "is not", value.line) + always_truthy = False + if isinstance(value_type, RInstance): + # check whether X.__bool__ is always just the default (object.__bool__) + if not value_type.class_ir.has_method( + "__bool__" + ) and value_type.class_ir.is_method_final("__bool__"): + always_truthy = True + + if always_truthy: + result = not_none + else: + # "X | None" where X may be falsey and requires a check + result = Register(bit_rprimitive) + true, false, end = BasicBlock(), BasicBlock(), BasicBlock() + branch = Branch(not_none, true, false, Branch.BOOL) + self.add(branch) + self.activate_block(true) + # unbox_or_cast instead of coerce because we want the + # type to change even if it is a subtype. + remaining = self.unbox_or_cast(value, value_type, value.line) + as_bool = self.bool_value(remaining) + self.add(Assign(result, as_bool)) + self.goto(end) + self.activate_block(false) + self.add(Assign(result, Integer(0, bit_rprimitive))) + self.goto(end) + self.activate_block(end) + else: + result = self.primitive_op(bool_op, [value], value.line) + return result + + def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) -> None: + opt_value_type = optional_value_type(value.type) + if opt_value_type is None: + bool_value = self.bool_value(value) + self.add(Branch(bool_value, true, false, Branch.BOOL)) + else: + # Special-case optional types + is_none = self.translate_is_op(value, self.none_object(), "is not", value.line) + branch = Branch(is_none, true, false, Branch.BOOL) + self.add(branch) + always_truthy = False + if isinstance(opt_value_type, RInstance): + # check whether X.__bool__ is always just the default (object.__bool__) + if not opt_value_type.class_ir.has_method( + "__bool__" + ) and opt_value_type.class_ir.is_method_final("__bool__"): + always_truthy = True + + if not always_truthy: + # Optional[X] where X may be falsey and requires a check + branch.true = BasicBlock() + self.activate_block(branch.true) + # unbox_or_cast instead of coerce because we want the + # type to change even if it is a subtype. + remaining = self.unbox_or_cast(value, opt_value_type, value.line) + self.add_bool_branch(remaining, true, false) + + def call_c( + self, + desc: CFunctionDescription, + args: list[Value], + line: int, + result_type: RType | None = None, + ) -> Value: + """Call function using C/native calling convention (not a Python callable).""" + # Handle void function via singleton RVoid instance + coerced = [] + # Coerce fixed number arguments + for i in range(min(len(args), len(desc.arg_types))): + formal_type = desc.arg_types[i] + arg = args[i] + arg = self.coerce(arg, formal_type, line) + coerced.append(arg) + # Reorder args if necessary + if desc.ordering is not None: + assert desc.var_arg_type is None + coerced = [coerced[i] for i in desc.ordering] + # Coerce any var_arg + var_arg_idx = -1 + if desc.var_arg_type is not None: + var_arg_idx = len(desc.arg_types) + for i in range(len(desc.arg_types), len(args)): + arg = args[i] + arg = self.coerce(arg, desc.var_arg_type, line) + coerced.append(arg) + # Add extra integer constant if any + for item in desc.extra_int_constants: + val, typ = item + extra_int_constant = Integer(val, typ, line) + coerced.append(extra_int_constant) + error_kind = desc.error_kind + if error_kind == ERR_NEG_INT: + # Handled with an explicit comparison + error_kind = ERR_NEVER + target = self.add( + CallC( + desc.c_function_name, + coerced, + desc.return_type, + desc.steals, + desc.is_borrowed, + error_kind, + line, + var_arg_idx, + is_pure=desc.is_pure, + ) + ) + if desc.is_borrowed: + # If the result is borrowed, force the arguments to be + # kept alive afterwards, as otherwise the result might be + # immediately freed, at the risk of a dangling pointer. + for arg in coerced: + if not isinstance(arg, (Integer, LoadLiteral)): + self.keep_alives.append(arg) + if desc.error_kind == ERR_NEG_INT: + comp = ComparisonOp(target, Integer(0, desc.return_type, line), ComparisonOp.SGE, line) + comp.error_kind = ERR_FALSE + self.add(comp) + + if desc.truncated_type is None: + result = target + else: + truncate = self.add(Truncate(target, desc.truncated_type)) + result = truncate + if result_type and not is_runtime_subtype(result.type, result_type): + if is_none_rprimitive(result_type): + # Special case None return. The actual result may actually be a bool + # and so we can't just coerce it. + result = self.none() + else: + result = self.coerce(target, result_type, line, can_borrow=desc.is_borrowed) + return result + + def matching_call_c( + self, + candidates: list[CFunctionDescription], + args: list[Value], + line: int, + result_type: RType | None = None, + can_borrow: bool = False, + ) -> Value | None: + matching: CFunctionDescription | None = None + for desc in candidates: + if len(desc.arg_types) != len(args): + continue + if all( + is_subtype(actual.type, formal) for actual, formal in zip(args, desc.arg_types) + ) and (not desc.is_borrowed or can_borrow): + if matching: + assert matching.priority != desc.priority, "Ambiguous:\n1) {}\n2) {}".format( + matching, desc + ) + if desc.priority > matching.priority: + matching = desc + else: + matching = desc + if matching: + target = self.call_c(matching, args, line, result_type) + return target + return None + + def primitive_op( + self, + desc: PrimitiveDescription, + args: list[Value], + line: int, + result_type: RType | None = None, + ) -> Value: + """Add a primitive op.""" + # Does this primitive map into calling a Python C API + # or an internal mypyc C API function? + if desc.c_function_name: + # TODO: Generate PrimitiveOps here and transform them into CallC + # ops only later in the lowering pass + c_desc = CFunctionDescription( + desc.name, + desc.arg_types, + desc.return_type, + desc.var_arg_type, + desc.truncated_type, + desc.c_function_name, + desc.error_kind, + desc.steals, + desc.is_borrowed, + desc.ordering, + desc.extra_int_constants, + desc.priority, + is_pure=desc.is_pure, + ) + return self.call_c(c_desc, args, line, result_type=result_type) + + # This primitive gets transformed in a lowering pass to + # lower-level IR ops using a custom transform function. + + coerced = [] + # Coerce fixed number arguments + for i in range(min(len(args), len(desc.arg_types))): + formal_type = desc.arg_types[i] + arg = args[i] + assert formal_type is not None # TODO + arg = self.coerce(arg, formal_type, line) + coerced.append(arg) + assert desc.ordering is None + assert desc.var_arg_type is None + assert not desc.extra_int_constants + target = self.add(PrimitiveOp(coerced, desc, line=line)) + if desc.is_borrowed: + # If the result is borrowed, force the arguments to be + # kept alive afterwards, as otherwise the result might be + # immediately freed, at the risk of a dangling pointer. + for arg in coerced: + if not isinstance(arg, (Integer, LoadLiteral)): + self.keep_alives.append(arg) + if desc.error_kind == ERR_NEG_INT: + comp = ComparisonOp(target, Integer(0, desc.return_type, line), ComparisonOp.SGE, line) + comp.error_kind = ERR_FALSE + self.add(comp) + + assert desc.truncated_type is None + result = target + if result_type and not is_runtime_subtype(result.type, result_type): + if is_none_rprimitive(result_type): + # Special case None return. The actual result may actually be a bool + # and so we can't just coerce it. + result = self.none() + else: + result = self.coerce(result, result_type, line, can_borrow=desc.is_borrowed) + return result + + def matching_primitive_op( + self, + candidates: list[PrimitiveDescription], + args: list[Value], + line: int, + result_type: RType | None = None, + can_borrow: bool = False, + ) -> Value | None: + matching: PrimitiveDescription | None = None + for desc in candidates: + if len(desc.arg_types) != len(args): + continue + if all( + # formal is not None and # TODO + is_subtype(actual.type, formal) + for actual, formal in zip(args, desc.arg_types) + ) and (not desc.is_borrowed or can_borrow): + if matching: + assert matching.priority != desc.priority, "Ambiguous:\n1) {}\n2) {}".format( + matching, desc + ) + if desc.priority > matching.priority: + matching = desc + else: + matching = desc + if matching: + return self.primitive_op(matching, args, line=line, result_type=result_type) + return None + + def int_op(self, type: RType, lhs: Value, rhs: Value, op: int, line: int = -1) -> Value: + """Generate a native integer binary op. + + Use native/C semantics, which sometimes differ from Python + semantics. + + Args: + type: Either int64_rprimitive or int32_rprimitive + op: IntOp.* constant (e.g. IntOp.ADD) + """ + return self.add(IntOp(type, lhs, rhs, op, line)) + + def float_op(self, lhs: Value, rhs: Value, op: str, line: int) -> Value: + """Generate a native float binary arithmetic operation. + + This follows Python semantics (e.g. raise exception on division by zero). + Add a FloatOp directly if you want low-level semantics. + + Args: + op: Binary operator (e.g. '+' or '*') + """ + op_id = float_op_to_id[op] + if op_id in (FloatOp.DIV, FloatOp.MOD): + if not (isinstance(rhs, Float) and rhs.value != 0.0): + c = self.compare_floats(rhs, Float(0.0), FloatComparisonOp.EQ, line) + err, ok = BasicBlock(), BasicBlock() + self.add(Branch(c, err, ok, Branch.BOOL, rare=True)) + self.activate_block(err) + if op_id == FloatOp.DIV: + msg = "float division by zero" + else: + msg = "float modulo" + self.add(RaiseStandardError(RaiseStandardError.ZERO_DIVISION_ERROR, msg, line)) + self.add(Unreachable()) + self.activate_block(ok) + if op_id == FloatOp.MOD: + # Adjust the result to match Python semantics (FloatOp follows C semantics). + return self.float_mod(lhs, rhs, line) + else: + return self.add(FloatOp(lhs, rhs, op_id, line)) + + def float_mod(self, lhs: Value, rhs: Value, line: int) -> Value: + """Perform x % y on floats using Python semantics.""" + mod = self.add(FloatOp(lhs, rhs, FloatOp.MOD, line)) + res = Register(float_rprimitive) + self.add(Assign(res, mod)) + tricky, adjust, copysign, done = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock() + is_zero = self.add(FloatComparisonOp(res, Float(0.0), FloatComparisonOp.EQ, line)) + self.add(Branch(is_zero, copysign, tricky, Branch.BOOL)) + self.activate_block(tricky) + same_signs = self.is_same_float_signs(lhs, rhs, line) + self.add(Branch(same_signs, done, adjust, Branch.BOOL)) + self.activate_block(adjust) + adj = self.float_op(res, rhs, "+", line) + self.add(Assign(res, adj)) + self.add(Goto(done)) + self.activate_block(copysign) + # If the remainder is zero, CPython ensures the result has the + # same sign as the denominator. + adj = self.primitive_op(copysign_op, [Float(0.0), rhs], line) + self.add(Assign(res, adj)) + self.add(Goto(done)) + self.activate_block(done) + return res + + def compare_floats(self, lhs: Value, rhs: Value, op: int, line: int) -> Value: + return self.add(FloatComparisonOp(lhs, rhs, op, line)) + + def fixed_width_int_op( + self, type: RPrimitive, lhs: Value, rhs: Value, op: int, line: int + ) -> Value: + """Generate a binary op using Python fixed-width integer semantics. + + These may differ in overflow/rounding behavior from native/C ops. + + Args: + type: Either int64_rprimitive or int32_rprimitive + op: IntOp.* constant (e.g. IntOp.ADD) + """ + lhs = self.coerce(lhs, type, line) + rhs = self.coerce(rhs, type, line) + if op == IntOp.DIV: + if isinstance(rhs, Integer) and rhs.value not in (-1, 0): + if not type.is_signed: + return self.int_op(type, lhs, rhs, IntOp.DIV, line) + else: + # Inline simple division by a constant, so that C + # compilers can optimize more + return self.inline_fixed_width_divide(type, lhs, rhs, line) + if is_int64_rprimitive(type): + prim = int64_divide_op + elif is_int32_rprimitive(type): + prim = int32_divide_op + elif is_int16_rprimitive(type): + prim = int16_divide_op + elif is_uint8_rprimitive(type): + self.check_for_zero_division(rhs, type, line) + return self.int_op(type, lhs, rhs, op, line) + else: + assert False, type + return self.call_c(prim, [lhs, rhs], line) + if op == IntOp.MOD: + if isinstance(rhs, Integer) and rhs.value not in (-1, 0): + if not type.is_signed: + return self.int_op(type, lhs, rhs, IntOp.MOD, line) + else: + # Inline simple % by a constant, so that C + # compilers can optimize more + return self.inline_fixed_width_mod(type, lhs, rhs, line) + if is_int64_rprimitive(type): + prim = int64_mod_op + elif is_int32_rprimitive(type): + prim = int32_mod_op + elif is_int16_rprimitive(type): + prim = int16_mod_op + elif is_uint8_rprimitive(type): + self.check_for_zero_division(rhs, type, line) + return self.int_op(type, lhs, rhs, op, line) + else: + assert False, type + return self.call_c(prim, [lhs, rhs], line) + return self.int_op(type, lhs, rhs, op, line) + + def check_for_zero_division(self, rhs: Value, type: RType, line: int) -> None: + err, ok = BasicBlock(), BasicBlock() + is_zero = self.binary_op(rhs, Integer(0, type), "==", line) + self.add(Branch(is_zero, err, ok, Branch.BOOL)) + self.activate_block(err) + self.add( + RaiseStandardError( + RaiseStandardError.ZERO_DIVISION_ERROR, "integer division or modulo by zero", line + ) + ) + self.add(Unreachable()) + self.activate_block(ok) + + def inline_fixed_width_divide(self, type: RType, lhs: Value, rhs: Value, line: int) -> Value: + # Perform floor division (native division truncates) + res = Register(type) + div = self.int_op(type, lhs, rhs, IntOp.DIV, line) + self.add(Assign(res, div)) + same_signs = self.is_same_native_int_signs(type, lhs, rhs, line) + tricky, adjust, done = BasicBlock(), BasicBlock(), BasicBlock() + self.add(Branch(same_signs, done, tricky, Branch.BOOL)) + self.activate_block(tricky) + mul = self.int_op(type, res, rhs, IntOp.MUL, line) + mul_eq = self.add(ComparisonOp(mul, lhs, ComparisonOp.EQ, line)) + self.add(Branch(mul_eq, done, adjust, Branch.BOOL)) + self.activate_block(adjust) + adj = self.int_op(type, res, Integer(1, type), IntOp.SUB, line) + self.add(Assign(res, adj)) + self.add(Goto(done)) + self.activate_block(done) + return res + + def inline_fixed_width_mod(self, type: RType, lhs: Value, rhs: Value, line: int) -> Value: + # Perform floor modulus + res = Register(type) + mod = self.int_op(type, lhs, rhs, IntOp.MOD, line) + self.add(Assign(res, mod)) + same_signs = self.is_same_native_int_signs(type, lhs, rhs, line) + tricky, adjust, done = BasicBlock(), BasicBlock(), BasicBlock() + self.add(Branch(same_signs, done, tricky, Branch.BOOL)) + self.activate_block(tricky) + is_zero = self.add(ComparisonOp(res, Integer(0, type), ComparisonOp.EQ, line)) + self.add(Branch(is_zero, done, adjust, Branch.BOOL)) + self.activate_block(adjust) + adj = self.int_op(type, res, rhs, IntOp.ADD, line) + self.add(Assign(res, adj)) + self.add(Goto(done)) + self.activate_block(done) + return res + + def is_same_native_int_signs(self, type: RType, a: Value, b: Value, line: int) -> Value: + neg1 = self.add(ComparisonOp(a, Integer(0, type), ComparisonOp.SLT, line)) + neg2 = self.add(ComparisonOp(b, Integer(0, type), ComparisonOp.SLT, line)) + return self.add(ComparisonOp(neg1, neg2, ComparisonOp.EQ, line)) + + def is_same_float_signs(self, a: Value, b: Value, line: int) -> Value: + neg1 = self.add(FloatComparisonOp(a, Float(0.0), FloatComparisonOp.LT, line)) + neg2 = self.add(FloatComparisonOp(b, Float(0.0), FloatComparisonOp.LT, line)) + return self.add(ComparisonOp(neg1, neg2, ComparisonOp.EQ, line)) + + def comparison_op(self, lhs: Value, rhs: Value, op: int, line: int) -> Value: + return self.add(ComparisonOp(lhs, rhs, op, line)) + + def builtin_len(self, val: Value, line: int, use_pyssize_t: bool = False) -> Value: + """Generate len(val). + + Return short_int_rprimitive by default. + Return c_pyssize_t if use_pyssize_t is true (unshifted). + """ + typ = val.type + size_value = None + if is_list_rprimitive(typ) or is_tuple_rprimitive(typ) or is_bytes_rprimitive(typ): + size_value = self.primitive_op(var_object_size, [val], line) + elif is_set_rprimitive(typ): + elem_address = self.add(GetElementPtr(val, PySetObject, "used")) + size_value = self.add(LoadMem(c_pyssize_t_rprimitive, elem_address)) + self.add(KeepAlive([val])) + elif is_dict_rprimitive(typ): + size_value = self.call_c(dict_ssize_t_size_op, [val], line) + elif is_str_rprimitive(typ): + size_value = self.call_c(str_ssize_t_size_op, [val], line) + + if size_value is not None: + if use_pyssize_t: + return size_value + offset = Integer(1, c_pyssize_t_rprimitive, line) + return self.int_op(short_int_rprimitive, size_value, offset, IntOp.LEFT_SHIFT, line) + + if isinstance(typ, RInstance): + # TODO: Support use_pyssize_t + assert not use_pyssize_t + length = self.gen_method_call(val, "__len__", [], int_rprimitive, line) + length = self.coerce(length, int_rprimitive, line) + ok, fail = BasicBlock(), BasicBlock() + cond = self.binary_op(length, Integer(0), ">=", line) + self.add_bool_branch(cond, ok, fail) + self.activate_block(fail) + self.add( + RaiseStandardError( + RaiseStandardError.VALUE_ERROR, "__len__() should return >= 0", line + ) + ) + self.add(Unreachable()) + self.activate_block(ok) + return length + + # generic case + if use_pyssize_t: + return self.call_c(generic_ssize_t_len_op, [val], line) + else: + return self.call_c(generic_len_op, [val], line) + + def new_tuple(self, items: list[Value], line: int) -> Value: + size: Value = Integer(len(items), c_pyssize_t_rprimitive) + return self.call_c(new_tuple_op, [size] + items, line) + + def new_tuple_with_length(self, length: Value, line: int) -> Value: + """This function returns an uninitialized tuple. + + If the length is non-zero, the caller must initialize the tuple, before + it can be made visible to user code -- otherwise the tuple object is broken. + You might need further initialization with `new_tuple_set_item_op` op. + + Args: + length: desired length of the new tuple. The rtype should be + c_pyssize_t_rprimitive + line: line number + """ + return self.call_c(new_tuple_with_length_op, [length], line) + + def int_to_float(self, n: Value, line: int) -> Value: + return self.primitive_op(int_to_float_op, [n], line) + + # Internal helpers + + def decompose_union_helper( + self, + obj: Value, + rtype: RUnion, + result_type: RType, + process_item: Callable[[Value], Value], + line: int, + ) -> Value: + """Generate isinstance() + specialized operations for union items. + + Say, for Union[A, B] generate ops resembling this (pseudocode): + + if isinstance(obj, A): + result = + else: + result = + + Args: + obj: value with a union type + rtype: the union type + result_type: result of the operation + process_item: callback to generate op for a single union item (arg is coerced + to union item type) + line: line number + """ + # TODO: Optimize cases where a single operation can handle multiple union items + # (say a method is implemented in a common base class) + fast_items = [] + rest_items = [] + for item in rtype.items: + if isinstance(item, RInstance): + fast_items.append(item) + else: + # For everything but RInstance we fall back to C API + rest_items.append(item) + exit_block = BasicBlock() + result = Register(result_type) + for i, item in enumerate(fast_items): + more_types = i < len(fast_items) - 1 or rest_items + if more_types: + # We are not at the final item so we need one more branch + op = self.isinstance_native(obj, item.class_ir, line) + true_block, false_block = BasicBlock(), BasicBlock() + self.add_bool_branch(op, true_block, false_block) + self.activate_block(true_block) + coerced = self.coerce(obj, item, line) + temp = process_item(coerced) + temp2 = self.coerce(temp, result_type, line) + self.add(Assign(result, temp2)) + self.goto(exit_block) + if more_types: + self.activate_block(false_block) + if rest_items: + # For everything else we use generic operation. Use force=True to drop the + # union type. + coerced = self.coerce(obj, object_rprimitive, line, force=True) + temp = process_item(coerced) + temp2 = self.coerce(temp, result_type, line) + self.add(Assign(result, temp2)) + self.goto(exit_block) + self.activate_block(exit_block) + return result + + def translate_special_method_call( + self, + base_reg: Value, + name: str, + args: list[Value], + result_type: RType | None, + line: int, + can_borrow: bool = False, + ) -> Value | None: + """Translate a method call which is handled nongenerically. + + These are special in the sense that we have code generated specifically for them. + They tend to be method calls which have equivalents in C that are more direct + than calling with the PyObject api. + + Return None if no translation found; otherwise return the target register. + """ + primitive_ops_candidates = method_call_ops.get(name, []) + primitive_op = self.matching_primitive_op( + primitive_ops_candidates, [base_reg] + args, line, result_type, can_borrow=can_borrow + ) + return primitive_op + + def translate_eq_cmp(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value | None: + """Add a equality comparison operation. + + Args: + expr_op: either '==' or '!=' + """ + ltype = lreg.type + rtype = rreg.type + if not (isinstance(ltype, RInstance) and ltype == rtype): + return None + + class_ir = ltype.class_ir + # Check whether any subclasses of the operand redefines __eq__ + # or it might be redefined in a Python parent class or by + # dataclasses + cmp_varies_at_runtime = ( + not class_ir.is_method_final("__eq__") + or not class_ir.is_method_final("__ne__") + or class_ir.inherits_python + or class_ir.is_augmented + ) + + if cmp_varies_at_runtime: + # We might need to call left.__eq__(right) or right.__eq__(left) + # depending on which is the more specific type. + return None + + if not class_ir.has_method("__eq__"): + # There's no __eq__ defined, so just use object identity. + identity_ref_op = "is" if expr_op == "==" else "is not" + return self.translate_is_op(lreg, rreg, identity_ref_op, line) + + return self.gen_method_call(lreg, op_methods[expr_op], [rreg], ltype, line) + + def translate_is_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value: + """Create equality comparison operation between object identities + + Args: + expr_op: either 'is' or 'is not' + """ + op = ComparisonOp.EQ if expr_op == "is" else ComparisonOp.NEQ + lhs = self.coerce(lreg, object_rprimitive, line) + rhs = self.coerce(rreg, object_rprimitive, line) + return self.add(ComparisonOp(lhs, rhs, op, line)) + + def _create_dict(self, keys: list[Value], values: list[Value], line: int) -> Value: + """Create a dictionary(possibly empty) using keys and values""" + # keys and values should have the same number of items + size = len(keys) + if size > 0: + size_value: Value = Integer(size, c_pyssize_t_rprimitive) + # merge keys and values + items = [i for t in list(zip(keys, values)) for i in t] + return self.call_c(dict_build_op, [size_value] + items, line) + else: + return self.call_c(dict_new_op, [], line) + + def error(self, msg: str, line: int) -> None: + assert self.errors is not None, "cannot generate errors in this compiler phase" + self.errors.error(msg, self.module_path, line) + + +def num_positional_args(arg_values: list[Value], arg_kinds: list[ArgKind] | None) -> int: + if arg_kinds is None: + return len(arg_values) + num_pos = 0 + for kind in arg_kinds: + if kind == ARG_POS: + num_pos += 1 + return num_pos diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/mapper.cpython-310-x86_64-linux-gnu.so b/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/mapper.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..bf6a1c088dc28b72ed2938ee303184eb4391ef3a Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/mapper.cpython-310-x86_64-linux-gnu.so differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/prepare.cpython-310-x86_64-linux-gnu.so b/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/prepare.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9504e97cae311fd0c14d683278b0d2bbc421155f Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/irbuild/prepare.cpython-310-x86_64-linux-gnu.so differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__init__.cpython-310-x86_64-linux-gnu.so b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__init__.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..303d32468ed9aa0cbca3b5ea0a33d6b7d6deb822 Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__init__.cpython-310-x86_64-linux-gnu.so differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__init__.py b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/__init__.cpython-310.pyc b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd996e81f9294431a51267acc5bfdf8e5300c8af Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/__init__.cpython-310.pyc differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/dict_ops.cpython-310.pyc b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/dict_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85dd80e9d4372f2e97338a71005d9864db269ed1 Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/dict_ops.cpython-310.pyc differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/exc_ops.cpython-310.pyc b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/exc_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a053fa32fc458f4a8c1b19c0d8421893265f814b Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/exc_ops.cpython-310.pyc differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/float_ops.cpython-310.pyc b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/float_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a639a35160ea500275df0639d691dae8e5e3f9ba Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/float_ops.cpython-310.pyc differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/generic_ops.cpython-310.pyc b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/generic_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3225250f604a90c5587b18d1dbb0c8ea2235e3b0 Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/generic_ops.cpython-310.pyc differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/int_ops.cpython-310.pyc b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/int_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..241d8d599d2599753ec7c231e3c3ad56028c7e9d Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/int_ops.cpython-310.pyc differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/list_ops.cpython-310.pyc b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/list_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e14d9839fedb0b372b8521064cb6166298f3d77d Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/list_ops.cpython-310.pyc differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/misc_ops.cpython-310.pyc b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/misc_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d98de0bfffa9ae4e4590b9614972ca7d6bc5c808 Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/misc_ops.cpython-310.pyc differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/set_ops.cpython-310.pyc b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/set_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfd203c7e7ded6a96eddf4678f55f43fa4e2b476 Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/set_ops.cpython-310.pyc differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/str_ops.cpython-310.pyc b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/str_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d751f99690788d3786011461d74df002c2377f2 Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/str_ops.cpython-310.pyc differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/tuple_ops.cpython-310.pyc b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/tuple_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfdaf45e94a0977beca834a217f72f30cca6bf59 Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/tuple_ops.cpython-310.pyc differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/bytes_ops.py b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/bytes_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..1afd196cff846746cb1404490a7aa3f846b3805c --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/bytes_ops.py @@ -0,0 +1,109 @@ +"""Primitive bytes ops.""" + +from __future__ import annotations + +from mypyc.ir.ops import ERR_MAGIC +from mypyc.ir.rtypes import ( + RUnion, + bytes_rprimitive, + c_int_rprimitive, + c_pyssize_t_rprimitive, + dict_rprimitive, + int_rprimitive, + list_rprimitive, + object_rprimitive, + str_rprimitive, +) +from mypyc.primitives.registry import ( + ERR_NEG_INT, + binary_op, + custom_op, + function_op, + load_address_op, + method_op, +) + +# Get the 'bytes' type object. +load_address_op(name="builtins.bytes", type=object_rprimitive, src="PyBytes_Type") + +# bytes(obj) +function_op( + name="builtins.bytes", + arg_types=[RUnion([list_rprimitive, dict_rprimitive, str_rprimitive])], + return_type=bytes_rprimitive, + c_function_name="PyBytes_FromObject", + error_kind=ERR_MAGIC, +) + +# bytearray(obj) +function_op( + name="builtins.bytearray", + arg_types=[object_rprimitive], + return_type=bytes_rprimitive, + c_function_name="PyByteArray_FromObject", + error_kind=ERR_MAGIC, +) + +# bytes ==/!= (return -1/0/1) +bytes_compare = custom_op( + arg_types=[bytes_rprimitive, bytes_rprimitive], + return_type=c_int_rprimitive, + c_function_name="CPyBytes_Compare", + error_kind=ERR_NEG_INT, +) + +# bytes + bytes +# bytearray + bytearray +binary_op( + name="+", + arg_types=[bytes_rprimitive, bytes_rprimitive], + return_type=bytes_rprimitive, + c_function_name="CPyBytes_Concat", + error_kind=ERR_MAGIC, + steals=[True, False], +) + +# bytes[begin:end] +bytes_slice_op = custom_op( + arg_types=[bytes_rprimitive, int_rprimitive, int_rprimitive], + return_type=bytes_rprimitive, + c_function_name="CPyBytes_GetSlice", + error_kind=ERR_MAGIC, +) + +# bytes[index] +# bytearray[index] +method_op( + name="__getitem__", + arg_types=[bytes_rprimitive, int_rprimitive], + return_type=int_rprimitive, + c_function_name="CPyBytes_GetItem", + error_kind=ERR_MAGIC, +) + +# bytes.join(obj) +method_op( + name="join", + arg_types=[bytes_rprimitive, object_rprimitive], + return_type=bytes_rprimitive, + c_function_name="CPyBytes_Join", + error_kind=ERR_MAGIC, +) + +# Join bytes objects and return a new bytes. +# The first argument is the total number of the following bytes. +bytes_build_op = custom_op( + arg_types=[c_pyssize_t_rprimitive], + return_type=bytes_rprimitive, + c_function_name="CPyBytes_Build", + error_kind=ERR_MAGIC, + var_arg_type=bytes_rprimitive, +) + +function_op( + name="builtins.ord", + arg_types=[bytes_rprimitive], + return_type=int_rprimitive, + c_function_name="CPyBytes_Ord", + error_kind=ERR_MAGIC, +) diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/dict_ops.py b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/dict_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..ce7b9bb8d70e11ee3bd5d25ab50937616e332aa7 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/dict_ops.py @@ -0,0 +1,325 @@ +"""Primitive dict ops.""" + +from __future__ import annotations + +from mypyc.ir.ops import ERR_FALSE, ERR_MAGIC, ERR_NEVER +from mypyc.ir.rtypes import ( + bit_rprimitive, + bool_rprimitive, + c_int_rprimitive, + c_pyssize_t_rprimitive, + dict_next_rtuple_pair, + dict_next_rtuple_single, + dict_rprimitive, + int_rprimitive, + list_rprimitive, + object_rprimitive, +) +from mypyc.primitives.registry import ( + ERR_NEG_INT, + binary_op, + custom_op, + function_op, + load_address_op, + method_op, +) + +# Get the 'dict' type object. +load_address_op(name="builtins.dict", type=object_rprimitive, src="PyDict_Type") + +# Construct an empty dictionary via dict(). +function_op( + name="builtins.dict", + arg_types=[], + return_type=dict_rprimitive, + c_function_name="PyDict_New", + error_kind=ERR_MAGIC, +) + +# Construct an empty dictionary. +dict_new_op = custom_op( + arg_types=[], return_type=dict_rprimitive, c_function_name="PyDict_New", error_kind=ERR_MAGIC +) + +# Construct a dictionary from keys and values. +# Positional argument is the number of key-value pairs +# Variable arguments are (key1, value1, ..., keyN, valueN). +dict_build_op = custom_op( + arg_types=[c_pyssize_t_rprimitive], + return_type=dict_rprimitive, + c_function_name="CPyDict_Build", + error_kind=ERR_MAGIC, + var_arg_type=object_rprimitive, +) + +# Construct a dictionary from another dictionary. +function_op( + name="builtins.dict", + arg_types=[dict_rprimitive], + return_type=dict_rprimitive, + c_function_name="PyDict_Copy", + error_kind=ERR_MAGIC, + priority=2, +) + +# Generic one-argument dict constructor: dict(obj) +dict_copy = function_op( + name="builtins.dict", + arg_types=[object_rprimitive], + return_type=dict_rprimitive, + c_function_name="CPyDict_FromAny", + error_kind=ERR_MAGIC, +) + +# dict[key] +dict_get_item_op = method_op( + name="__getitem__", + arg_types=[dict_rprimitive, object_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyDict_GetItem", + error_kind=ERR_MAGIC, +) + +# dict[key] = value +dict_set_item_op = method_op( + name="__setitem__", + arg_types=[dict_rprimitive, object_rprimitive, object_rprimitive], + return_type=c_int_rprimitive, + c_function_name="CPyDict_SetItem", + error_kind=ERR_NEG_INT, +) + +# key in dict +binary_op( + name="in", + arg_types=[object_rprimitive, dict_rprimitive], + return_type=c_int_rprimitive, + c_function_name="PyDict_Contains", + error_kind=ERR_NEG_INT, + truncated_type=bool_rprimitive, + ordering=[1, 0], +) + +# dict1.update(dict2) +dict_update_op = method_op( + name="update", + arg_types=[dict_rprimitive, dict_rprimitive], + return_type=c_int_rprimitive, + c_function_name="CPyDict_Update", + error_kind=ERR_NEG_INT, + priority=2, +) + +# Operation used for **value in dict displays. +# This is mostly like dict.update(obj), but has customized error handling. +dict_update_in_display_op = custom_op( + arg_types=[dict_rprimitive, object_rprimitive], + return_type=c_int_rprimitive, + c_function_name="CPyDict_UpdateInDisplay", + error_kind=ERR_NEG_INT, +) + +# dict.update(obj) +method_op( + name="update", + arg_types=[dict_rprimitive, object_rprimitive], + return_type=c_int_rprimitive, + c_function_name="CPyDict_UpdateFromAny", + error_kind=ERR_NEG_INT, +) + +# dict.get(key, default) +method_op( + name="get", + arg_types=[dict_rprimitive, object_rprimitive, object_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyDict_Get", + error_kind=ERR_MAGIC, +) + +# dict.get(key) +dict_get_method_with_none = method_op( + name="get", + arg_types=[dict_rprimitive, object_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyDict_GetWithNone", + error_kind=ERR_MAGIC, +) + +# dict.setdefault(key, default) +dict_setdefault_op = method_op( + name="setdefault", + arg_types=[dict_rprimitive, object_rprimitive, object_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyDict_SetDefault", + error_kind=ERR_MAGIC, +) + +# dict.setdefault(key) +method_op( + name="setdefault", + arg_types=[dict_rprimitive, object_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyDict_SetDefaultWithNone", + error_kind=ERR_MAGIC, +) + +# dict.setdefault(key, empty tuple/list/set) +# The third argument marks the data type of the second argument. +# 1: list 2: dict 3: set +# Other number would lead to an error. +dict_setdefault_spec_init_op = custom_op( + arg_types=[dict_rprimitive, object_rprimitive, c_int_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyDict_SetDefaultWithEmptyDatatype", + error_kind=ERR_MAGIC, +) + +# dict.keys() +method_op( + name="keys", + arg_types=[dict_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyDict_KeysView", + error_kind=ERR_MAGIC, +) + +# dict.values() +method_op( + name="values", + arg_types=[dict_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyDict_ValuesView", + error_kind=ERR_MAGIC, +) + +# dict.items() +method_op( + name="items", + arg_types=[dict_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyDict_ItemsView", + error_kind=ERR_MAGIC, +) + +# dict.clear() +method_op( + name="clear", + arg_types=[dict_rprimitive], + return_type=bit_rprimitive, + c_function_name="CPyDict_Clear", + error_kind=ERR_FALSE, +) + +# dict.copy() +method_op( + name="copy", + arg_types=[dict_rprimitive], + return_type=dict_rprimitive, + c_function_name="CPyDict_Copy", + error_kind=ERR_MAGIC, +) + +# list(dict.keys()) +dict_keys_op = custom_op( + arg_types=[dict_rprimitive], + return_type=list_rprimitive, + c_function_name="CPyDict_Keys", + error_kind=ERR_MAGIC, +) + +# list(dict.values()) +dict_values_op = custom_op( + arg_types=[dict_rprimitive], + return_type=list_rprimitive, + c_function_name="CPyDict_Values", + error_kind=ERR_MAGIC, +) + +# list(dict.items()) +dict_items_op = custom_op( + arg_types=[dict_rprimitive], + return_type=list_rprimitive, + c_function_name="CPyDict_Items", + error_kind=ERR_MAGIC, +) + +# PyDict_Next() fast iteration +dict_key_iter_op = custom_op( + arg_types=[dict_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyDict_GetKeysIter", + error_kind=ERR_MAGIC, +) + +dict_value_iter_op = custom_op( + arg_types=[dict_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyDict_GetValuesIter", + error_kind=ERR_MAGIC, +) + +dict_item_iter_op = custom_op( + arg_types=[dict_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyDict_GetItemsIter", + error_kind=ERR_MAGIC, +) + +dict_next_key_op = custom_op( + arg_types=[object_rprimitive, int_rprimitive], + return_type=dict_next_rtuple_single, + c_function_name="CPyDict_NextKey", + error_kind=ERR_NEVER, +) + +dict_next_value_op = custom_op( + arg_types=[object_rprimitive, int_rprimitive], + return_type=dict_next_rtuple_single, + c_function_name="CPyDict_NextValue", + error_kind=ERR_NEVER, +) + +dict_next_item_op = custom_op( + arg_types=[object_rprimitive, int_rprimitive], + return_type=dict_next_rtuple_pair, + c_function_name="CPyDict_NextItem", + error_kind=ERR_NEVER, +) + +# check that len(dict) == const during iteration +dict_check_size_op = custom_op( + arg_types=[dict_rprimitive, int_rprimitive], + return_type=bit_rprimitive, + c_function_name="CPyDict_CheckSize", + error_kind=ERR_FALSE, +) + +dict_ssize_t_size_op = custom_op( + arg_types=[dict_rprimitive], + return_type=c_pyssize_t_rprimitive, + c_function_name="PyDict_Size", + error_kind=ERR_NEVER, +) + +# Delete an item from a dict +dict_del_item = custom_op( + arg_types=[object_rprimitive, object_rprimitive], + return_type=c_int_rprimitive, + c_function_name="PyDict_DelItem", + error_kind=ERR_NEG_INT, +) + +supports_mapping_protocol = custom_op( + arg_types=[object_rprimitive], + return_type=c_int_rprimitive, + c_function_name="CPyMapping_Check", + error_kind=ERR_NEVER, +) + +mapping_has_key = custom_op( + arg_types=[object_rprimitive, object_rprimitive], + return_type=c_int_rprimitive, + c_function_name="PyMapping_HasKey", + error_kind=ERR_NEVER, +) diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.cpython-310-x86_64-linux-gnu.so b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..71d60061fec896af5bf7e4f9ead33ba43e12bb3d Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.cpython-310-x86_64-linux-gnu.so differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.py b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..ad105056158a81fe8cde62e35eb85b82886cb5c1 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.py @@ -0,0 +1,101 @@ +"""Exception-related primitive ops.""" + +from __future__ import annotations + +from mypyc.ir.ops import ERR_ALWAYS, ERR_FALSE, ERR_NEVER +from mypyc.ir.rtypes import bit_rprimitive, exc_rtuple, object_rprimitive, void_rtype +from mypyc.primitives.registry import custom_op + +# If the argument is a class, raise an instance of the class. Otherwise, assume +# that the argument is an exception object, and raise it. +raise_exception_op = custom_op( + arg_types=[object_rprimitive], + return_type=void_rtype, + c_function_name="CPy_Raise", + error_kind=ERR_ALWAYS, +) + +# Raise StopIteration exception with the specified value (which can be NULL). +set_stop_iteration_value = custom_op( + arg_types=[object_rprimitive], + return_type=void_rtype, + c_function_name="CPyGen_SetStopIterationValue", + error_kind=ERR_ALWAYS, +) + +# Raise exception with traceback. +# Arguments are (exception type, exception value, traceback). +raise_exception_with_tb_op = custom_op( + arg_types=[object_rprimitive, object_rprimitive, object_rprimitive], + return_type=void_rtype, + c_function_name="CPyErr_SetObjectAndTraceback", + error_kind=ERR_ALWAYS, +) + +# Reraise the currently raised exception. +reraise_exception_op = custom_op( + arg_types=[], return_type=void_rtype, c_function_name="CPy_Reraise", error_kind=ERR_ALWAYS +) + +# Propagate exception if the CPython error indicator is set (an exception was raised). +no_err_occurred_op = custom_op( + arg_types=[], + return_type=bit_rprimitive, + c_function_name="CPy_NoErrOccured", + error_kind=ERR_FALSE, +) + +err_occurred_op = custom_op( + arg_types=[], + return_type=object_rprimitive, + c_function_name="PyErr_Occurred", + error_kind=ERR_NEVER, + is_borrowed=True, +) + +# Keep propagating a raised exception by unconditionally giving an error value. +# This doesn't actually raise an exception. +keep_propagating_op = custom_op( + arg_types=[], + return_type=bit_rprimitive, + c_function_name="CPy_KeepPropagating", + error_kind=ERR_FALSE, +) + +# Catches a propagating exception and makes it the "currently +# handled exception" (by sticking it into sys.exc_info()). Returns the +# exception that was previously being handled, which must be restored +# later. +error_catch_op = custom_op( + arg_types=[], return_type=exc_rtuple, c_function_name="CPy_CatchError", error_kind=ERR_NEVER +) + +# Restore an old "currently handled exception" returned from. +# error_catch (by sticking it into sys.exc_info()) +restore_exc_info_op = custom_op( + arg_types=[exc_rtuple], + return_type=void_rtype, + c_function_name="CPy_RestoreExcInfo", + error_kind=ERR_NEVER, +) + +# Checks whether the exception currently being handled matches a particular type. +exc_matches_op = custom_op( + arg_types=[object_rprimitive], + return_type=bit_rprimitive, + c_function_name="CPy_ExceptionMatches", + error_kind=ERR_NEVER, +) + +# Get the value of the exception currently being handled. +get_exc_value_op = custom_op( + arg_types=[], + return_type=object_rprimitive, + c_function_name="CPy_GetExcValue", + error_kind=ERR_NEVER, +) + +# Get exception info (exception type, exception instance, traceback object). +get_exc_info_op = custom_op( + arg_types=[], return_type=exc_rtuple, c_function_name="CPy_GetExcInfo", error_kind=ERR_NEVER +) diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/int_ops.cpython-310-x86_64-linux-gnu.so b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/int_ops.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..462f8f8f29ffcef1d49305c49b00d69eba6434ca Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/int_ops.cpython-310-x86_64-linux-gnu.so differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/int_ops.py b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/int_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..657578d200460e8e5a7a8a7b8cd75194e818dd05 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/int_ops.py @@ -0,0 +1,298 @@ +"""Arbitrary-precision integer primitive ops. + +These mostly operate on (usually) unboxed integers that use a tagged pointer +representation (CPyTagged) and correspond to the Python 'int' type. + +See also the documentation for mypyc.rtypes.int_rprimitive. + +Use mypyc.ir.ops.IntOp for operations on fixed-width/C integers. +""" + +from __future__ import annotations + +from mypyc.ir.ops import ( + ERR_ALWAYS, + ERR_MAGIC, + ERR_MAGIC_OVERLAPPING, + ERR_NEVER, + PrimitiveDescription, +) +from mypyc.ir.rtypes import ( + RType, + bit_rprimitive, + bool_rprimitive, + c_pyssize_t_rprimitive, + float_rprimitive, + int16_rprimitive, + int32_rprimitive, + int64_rprimitive, + int_rprimitive, + object_rprimitive, + str_rprimitive, + void_rtype, +) +from mypyc.primitives.registry import binary_op, custom_op, function_op, load_address_op, unary_op + +# Constructors for builtins.int and native int types have the same behavior. In +# interpreted mode, native int types are just aliases to 'int'. +for int_name in ( + "builtins.int", + "mypy_extensions.i64", + "mypy_extensions.i32", + "mypy_extensions.i16", + "mypy_extensions.u8", +): + # These int constructors produce object_rprimitives that then need to be unboxed + # I guess unboxing ourselves would save a check and branch though? + + # Get the type object for 'builtins.int' or a native int type. + # For ordinary calls to int() we use a load_address to the type. + # Native ints don't have a separate type object -- we just use 'builtins.int'. + load_address_op(name=int_name, type=object_rprimitive, src="PyLong_Type") + + # int(float). We could do a bit better directly. + function_op( + name=int_name, + arg_types=[float_rprimitive], + return_type=int_rprimitive, + c_function_name="CPyTagged_FromFloat", + error_kind=ERR_MAGIC, + ) + + # int(string) + function_op( + name=int_name, + arg_types=[str_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyLong_FromStr", + error_kind=ERR_MAGIC, + ) + + # int(string, base) + function_op( + name=int_name, + arg_types=[str_rprimitive, int_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyLong_FromStrWithBase", + error_kind=ERR_MAGIC, + ) + +# str(int) +int_to_str_op = function_op( + name="builtins.str", + arg_types=[int_rprimitive], + return_type=str_rprimitive, + c_function_name="CPyTagged_Str", + error_kind=ERR_MAGIC, + priority=2, +) + +# We need a specialization for str on bools also since the int one is wrong... +function_op( + name="builtins.str", + arg_types=[bool_rprimitive], + return_type=str_rprimitive, + c_function_name="CPyBool_Str", + error_kind=ERR_MAGIC, + priority=3, +) + + +def int_binary_primitive( + op: str, primitive_name: str, return_type: RType = int_rprimitive, error_kind: int = ERR_NEVER +) -> PrimitiveDescription: + return binary_op( + name=op, + arg_types=[int_rprimitive, int_rprimitive], + return_type=return_type, + primitive_name=primitive_name, + error_kind=error_kind, + ) + + +int_eq = int_binary_primitive(op="==", primitive_name="int_eq", return_type=bit_rprimitive) +int_ne = int_binary_primitive(op="!=", primitive_name="int_ne", return_type=bit_rprimitive) +int_lt = int_binary_primitive(op="<", primitive_name="int_lt", return_type=bit_rprimitive) +int_le = int_binary_primitive(op="<=", primitive_name="int_le", return_type=bit_rprimitive) +int_gt = int_binary_primitive(op=">", primitive_name="int_gt", return_type=bit_rprimitive) +int_ge = int_binary_primitive(op=">=", primitive_name="int_ge", return_type=bit_rprimitive) + + +def int_binary_op( + name: str, + c_function_name: str, + return_type: RType = int_rprimitive, + error_kind: int = ERR_NEVER, +) -> None: + binary_op( + name=name, + arg_types=[int_rprimitive, int_rprimitive], + return_type=return_type, + c_function_name=c_function_name, + error_kind=error_kind, + ) + + +# Binary, unary and augmented assignment operations that operate on CPyTagged ints +# are implemented as C functions. + +int_binary_op("+", "CPyTagged_Add") +int_binary_op("-", "CPyTagged_Subtract") +int_binary_op("*", "CPyTagged_Multiply") +int_binary_op("&", "CPyTagged_And") +int_binary_op("|", "CPyTagged_Or") +int_binary_op("^", "CPyTagged_Xor") +# Divide and remainder we honestly propagate errors from because they +# can raise ZeroDivisionError +int_binary_op("//", "CPyTagged_FloorDivide", error_kind=ERR_MAGIC) +int_binary_op("%", "CPyTagged_Remainder", error_kind=ERR_MAGIC) +# Negative shift counts raise an exception +int_binary_op(">>", "CPyTagged_Rshift", error_kind=ERR_MAGIC) +int_binary_op("<<", "CPyTagged_Lshift", error_kind=ERR_MAGIC) + +int_binary_op( + "/", "CPyTagged_TrueDivide", return_type=float_rprimitive, error_kind=ERR_MAGIC_OVERLAPPING +) + +# This should work because assignment operators are parsed differently +# and the code in irbuild that handles it does the assignment +# regardless of whether or not the operator works in place anyway. +int_binary_op("+=", "CPyTagged_Add") +int_binary_op("-=", "CPyTagged_Subtract") +int_binary_op("*=", "CPyTagged_Multiply") +int_binary_op("&=", "CPyTagged_And") +int_binary_op("|=", "CPyTagged_Or") +int_binary_op("^=", "CPyTagged_Xor") +int_binary_op("//=", "CPyTagged_FloorDivide", error_kind=ERR_MAGIC) +int_binary_op("%=", "CPyTagged_Remainder", error_kind=ERR_MAGIC) +int_binary_op(">>=", "CPyTagged_Rshift", error_kind=ERR_MAGIC) +int_binary_op("<<=", "CPyTagged_Lshift", error_kind=ERR_MAGIC) + + +def int_unary_op(name: str, c_function_name: str) -> PrimitiveDescription: + return unary_op( + name=name, + arg_type=int_rprimitive, + return_type=int_rprimitive, + c_function_name=c_function_name, + error_kind=ERR_NEVER, + ) + + +int_neg_op = int_unary_op("-", "CPyTagged_Negate") +int_invert_op = int_unary_op("~", "CPyTagged_Invert") + + +# Primitives related to integer comparison operations: + + +# Equals operation on two boxed tagged integers +int_equal_ = custom_op( + arg_types=[int_rprimitive, int_rprimitive], + return_type=bit_rprimitive, + c_function_name="CPyTagged_IsEq_", + error_kind=ERR_NEVER, + is_pure=True, +) + +# Less than operation on two boxed tagged integers +int_less_than_ = custom_op( + arg_types=[int_rprimitive, int_rprimitive], + return_type=bit_rprimitive, + c_function_name="CPyTagged_IsLt_", + error_kind=ERR_NEVER, + is_pure=True, +) + +int64_divide_op = custom_op( + arg_types=[int64_rprimitive, int64_rprimitive], + return_type=int64_rprimitive, + c_function_name="CPyInt64_Divide", + error_kind=ERR_MAGIC_OVERLAPPING, +) + +int64_mod_op = custom_op( + arg_types=[int64_rprimitive, int64_rprimitive], + return_type=int64_rprimitive, + c_function_name="CPyInt64_Remainder", + error_kind=ERR_MAGIC_OVERLAPPING, +) + +int32_divide_op = custom_op( + arg_types=[int32_rprimitive, int32_rprimitive], + return_type=int32_rprimitive, + c_function_name="CPyInt32_Divide", + error_kind=ERR_MAGIC_OVERLAPPING, +) + +int32_mod_op = custom_op( + arg_types=[int32_rprimitive, int32_rprimitive], + return_type=int32_rprimitive, + c_function_name="CPyInt32_Remainder", + error_kind=ERR_MAGIC_OVERLAPPING, +) + +int16_divide_op = custom_op( + arg_types=[int16_rprimitive, int16_rprimitive], + return_type=int16_rprimitive, + c_function_name="CPyInt16_Divide", + error_kind=ERR_MAGIC_OVERLAPPING, +) + +int16_mod_op = custom_op( + arg_types=[int16_rprimitive, int16_rprimitive], + return_type=int16_rprimitive, + c_function_name="CPyInt16_Remainder", + error_kind=ERR_MAGIC_OVERLAPPING, +) + +# Convert tagged int (as PyObject *) to i64 +int_to_int64_op = custom_op( + arg_types=[object_rprimitive], + return_type=int64_rprimitive, + c_function_name="CPyLong_AsInt64", + error_kind=ERR_MAGIC_OVERLAPPING, +) + +ssize_t_to_int_op = custom_op( + arg_types=[c_pyssize_t_rprimitive], + return_type=int_rprimitive, + c_function_name="CPyTagged_FromSsize_t", + error_kind=ERR_MAGIC, +) + +int64_to_int_op = custom_op( + arg_types=[int64_rprimitive], + return_type=int_rprimitive, + c_function_name="CPyTagged_FromInt64", + error_kind=ERR_MAGIC, +) + +# Convert tagged int (as PyObject *) to i32 +int_to_int32_op = custom_op( + arg_types=[object_rprimitive], + return_type=int32_rprimitive, + c_function_name="CPyLong_AsInt32", + error_kind=ERR_MAGIC_OVERLAPPING, +) + +int32_overflow = custom_op( + arg_types=[], + return_type=void_rtype, + c_function_name="CPyInt32_Overflow", + error_kind=ERR_ALWAYS, +) + +int16_overflow = custom_op( + arg_types=[], + return_type=void_rtype, + c_function_name="CPyInt16_Overflow", + error_kind=ERR_ALWAYS, +) + +uint8_overflow = custom_op( + arg_types=[], + return_type=void_rtype, + c_function_name="CPyUInt8_Overflow", + error_kind=ERR_ALWAYS, +) diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/set_ops.cpython-310-x86_64-linux-gnu.so b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/set_ops.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4b28d428945674f3e11b770e83fb88b2d167e6c1 Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/set_ops.cpython-310-x86_64-linux-gnu.so differ diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/set_ops.py b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/set_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..fcfb7847dc7d58f495bcf515774d5e6cb20fb861 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/set_ops.py @@ -0,0 +1,121 @@ +"""Primitive set (and frozenset) ops.""" + +from __future__ import annotations + +from mypyc.ir.ops import ERR_FALSE, ERR_MAGIC +from mypyc.ir.rtypes import ( + bit_rprimitive, + bool_rprimitive, + c_int_rprimitive, + object_rprimitive, + pointer_rprimitive, + set_rprimitive, +) +from mypyc.primitives.registry import ( + ERR_NEG_INT, + binary_op, + function_op, + load_address_op, + method_op, +) + +# Get the 'builtins.set' type object. +load_address_op(name="builtins.set", type=object_rprimitive, src="PySet_Type") + +# Get the 'builtins.frozenset' tyoe object. +load_address_op(name="builtins.frozenset", type=object_rprimitive, src="PyFrozenSet_Type") + +# Construct an empty set. +new_set_op = function_op( + name="builtins.set", + arg_types=[], + return_type=set_rprimitive, + c_function_name="PySet_New", + error_kind=ERR_MAGIC, + extra_int_constants=[(0, pointer_rprimitive)], +) + +# set(obj) +function_op( + name="builtins.set", + arg_types=[object_rprimitive], + return_type=set_rprimitive, + c_function_name="PySet_New", + error_kind=ERR_MAGIC, +) + +# frozenset(obj) +function_op( + name="builtins.frozenset", + arg_types=[object_rprimitive], + return_type=object_rprimitive, + c_function_name="PyFrozenSet_New", + error_kind=ERR_MAGIC, +) + +# item in set +set_in_op = binary_op( + name="in", + arg_types=[object_rprimitive, set_rprimitive], + return_type=c_int_rprimitive, + c_function_name="PySet_Contains", + error_kind=ERR_NEG_INT, + truncated_type=bool_rprimitive, + ordering=[1, 0], +) + +# set.remove(obj) +method_op( + name="remove", + arg_types=[set_rprimitive, object_rprimitive], + return_type=bit_rprimitive, + c_function_name="CPySet_Remove", + error_kind=ERR_FALSE, +) + +# set.discard(obj) +method_op( + name="discard", + arg_types=[set_rprimitive, object_rprimitive], + return_type=c_int_rprimitive, + c_function_name="PySet_Discard", + error_kind=ERR_NEG_INT, +) + +# set.add(obj) +set_add_op = method_op( + name="add", + arg_types=[set_rprimitive, object_rprimitive], + return_type=c_int_rprimitive, + c_function_name="PySet_Add", + error_kind=ERR_NEG_INT, +) + +# set.update(obj) +# +# This is not a public API but looks like it should be fine. +set_update_op = method_op( + name="update", + arg_types=[set_rprimitive, object_rprimitive], + return_type=c_int_rprimitive, + c_function_name="_PySet_Update", + error_kind=ERR_NEG_INT, +) + +# set.clear() +method_op( + name="clear", + arg_types=[set_rprimitive], + return_type=c_int_rprimitive, + c_function_name="PySet_Clear", + error_kind=ERR_NEG_INT, +) + +# set.pop() +method_op( + name="pop", + arg_types=[set_rprimitive], + return_type=object_rprimitive, + c_function_name="PySet_Pop", + error_kind=ERR_MAGIC, +) diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/str_ops.py b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/str_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..0accffd86a17023ed027162d6978022e59f6323e --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/str_ops.py @@ -0,0 +1,261 @@ +"""Primitive str ops.""" + +from __future__ import annotations + +from mypyc.ir.ops import ERR_MAGIC, ERR_NEVER +from mypyc.ir.rtypes import ( + RType, + bit_rprimitive, + bool_rprimitive, + bytes_rprimitive, + c_int_rprimitive, + c_pyssize_t_rprimitive, + int_rprimitive, + list_rprimitive, + object_rprimitive, + pointer_rprimitive, + str_rprimitive, +) +from mypyc.primitives.registry import ( + ERR_NEG_INT, + binary_op, + custom_op, + function_op, + load_address_op, + method_op, +) + +# Get the 'str' type object. +load_address_op(name="builtins.str", type=object_rprimitive, src="PyUnicode_Type") + +# str(obj) +str_op = function_op( + name="builtins.str", + arg_types=[object_rprimitive], + return_type=str_rprimitive, + c_function_name="PyObject_Str", + error_kind=ERR_MAGIC, +) + +# str1 + str2 +binary_op( + name="+", + arg_types=[str_rprimitive, str_rprimitive], + return_type=str_rprimitive, + c_function_name="PyUnicode_Concat", + error_kind=ERR_MAGIC, +) + +# str1 += str2 +# +# PyUnicode_Append makes an effort to reuse the LHS when the refcount +# is 1. This is super dodgy but oh well, the interpreter does it. +binary_op( + name="+=", + arg_types=[str_rprimitive, str_rprimitive], + return_type=str_rprimitive, + c_function_name="CPyStr_Append", + error_kind=ERR_MAGIC, + steals=[True, False], +) + +unicode_compare = custom_op( + arg_types=[str_rprimitive, str_rprimitive], + return_type=c_int_rprimitive, + c_function_name="PyUnicode_Compare", + error_kind=ERR_NEVER, +) + +# str[index] (for an int index) +method_op( + name="__getitem__", + arg_types=[str_rprimitive, int_rprimitive], + return_type=str_rprimitive, + c_function_name="CPyStr_GetItem", + error_kind=ERR_MAGIC, +) + +# str[begin:end] +str_slice_op = custom_op( + arg_types=[str_rprimitive, int_rprimitive, int_rprimitive], + return_type=object_rprimitive, + c_function_name="CPyStr_GetSlice", + error_kind=ERR_MAGIC, +) + +# str.join(obj) +method_op( + name="join", + arg_types=[str_rprimitive, object_rprimitive], + return_type=str_rprimitive, + c_function_name="PyUnicode_Join", + error_kind=ERR_MAGIC, +) + +str_build_op = custom_op( + arg_types=[c_pyssize_t_rprimitive], + return_type=str_rprimitive, + c_function_name="CPyStr_Build", + error_kind=ERR_MAGIC, + var_arg_type=str_rprimitive, +) + +# str.startswith(str) +method_op( + name="startswith", + arg_types=[str_rprimitive, str_rprimitive], + return_type=bool_rprimitive, + c_function_name="CPyStr_Startswith", + error_kind=ERR_NEVER, +) + +# str.endswith(str) +method_op( + name="endswith", + arg_types=[str_rprimitive, str_rprimitive], + return_type=bool_rprimitive, + c_function_name="CPyStr_Endswith", + error_kind=ERR_NEVER, +) + +# str.split(...) +str_split_types: list[RType] = [str_rprimitive, str_rprimitive, int_rprimitive] +str_split_functions = ["PyUnicode_Split", "PyUnicode_Split", "CPyStr_Split"] +str_split_constants: list[list[tuple[int, RType]]] = [ + [(0, pointer_rprimitive), (-1, c_int_rprimitive)], + [(-1, c_int_rprimitive)], + [], +] +for i in range(len(str_split_types)): + method_op( + name="split", + arg_types=str_split_types[0 : i + 1], + return_type=list_rprimitive, + c_function_name=str_split_functions[i], + extra_int_constants=str_split_constants[i], + error_kind=ERR_MAGIC, + ) + +# str.replace(old, new) +method_op( + name="replace", + arg_types=[str_rprimitive, str_rprimitive, str_rprimitive], + return_type=str_rprimitive, + c_function_name="PyUnicode_Replace", + error_kind=ERR_MAGIC, + extra_int_constants=[(-1, c_int_rprimitive)], +) + +# str.replace(old, new, count) +method_op( + name="replace", + arg_types=[str_rprimitive, str_rprimitive, str_rprimitive, int_rprimitive], + return_type=str_rprimitive, + c_function_name="CPyStr_Replace", + error_kind=ERR_MAGIC, +) + +# check if a string is true (isn't an empty string) +str_check_if_true = custom_op( + arg_types=[str_rprimitive], + return_type=bit_rprimitive, + c_function_name="CPyStr_IsTrue", + error_kind=ERR_NEVER, +) + +str_ssize_t_size_op = custom_op( + arg_types=[str_rprimitive], + return_type=c_pyssize_t_rprimitive, + c_function_name="CPyStr_Size_size_t", + error_kind=ERR_NEG_INT, +) + +# obj.decode() +method_op( + name="decode", + arg_types=[bytes_rprimitive], + return_type=str_rprimitive, + c_function_name="CPy_Decode", + error_kind=ERR_MAGIC, + extra_int_constants=[(0, pointer_rprimitive), (0, pointer_rprimitive)], +) + +# obj.decode(encoding) +method_op( + name="decode", + arg_types=[bytes_rprimitive, str_rprimitive], + return_type=str_rprimitive, + c_function_name="CPy_Decode", + error_kind=ERR_MAGIC, + extra_int_constants=[(0, pointer_rprimitive)], +) + +# obj.decode(encoding, errors) +method_op( + name="decode", + arg_types=[bytes_rprimitive, str_rprimitive, str_rprimitive], + return_type=str_rprimitive, + c_function_name="CPy_Decode", + error_kind=ERR_MAGIC, +) + +# str.encode() +method_op( + name="encode", + arg_types=[str_rprimitive], + return_type=bytes_rprimitive, + c_function_name="CPy_Encode", + error_kind=ERR_MAGIC, + extra_int_constants=[(0, pointer_rprimitive), (0, pointer_rprimitive)], +) + +# str.encode(encoding) +method_op( + name="encode", + arg_types=[str_rprimitive, str_rprimitive], + return_type=bytes_rprimitive, + c_function_name="CPy_Encode", + error_kind=ERR_MAGIC, + extra_int_constants=[(0, pointer_rprimitive)], +) + +# str.encode(encoding) - utf8 strict specialization +str_encode_utf8_strict = custom_op( + arg_types=[str_rprimitive], + return_type=bytes_rprimitive, + c_function_name="PyUnicode_AsUTF8String", + error_kind=ERR_MAGIC, +) + +# str.encode(encoding) - ascii strict specialization +str_encode_ascii_strict = custom_op( + arg_types=[str_rprimitive], + return_type=bytes_rprimitive, + c_function_name="PyUnicode_AsASCIIString", + error_kind=ERR_MAGIC, +) + +# str.encode(encoding) - latin1 strict specialization +str_encode_latin1_strict = custom_op( + arg_types=[str_rprimitive], + return_type=bytes_rprimitive, + c_function_name="PyUnicode_AsLatin1String", + error_kind=ERR_MAGIC, +) + +# str.encode(encoding, errors) +method_op( + name="encode", + arg_types=[str_rprimitive, str_rprimitive, str_rprimitive], + return_type=bytes_rprimitive, + c_function_name="CPy_Encode", + error_kind=ERR_MAGIC, +) + +function_op( + name="builtins.ord", + arg_types=[str_rprimitive], + return_type=int_rprimitive, + c_function_name="CPyStr_Ord", + error_kind=ERR_MAGIC, +) diff --git a/openflamingo/lib/python3.10/site-packages/mypyc/primitives/tuple_ops.cpython-310-x86_64-linux-gnu.so b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/tuple_ops.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b568fac3a2ffb54630a7e3326f8954ab216e9e29 Binary files /dev/null and b/openflamingo/lib/python3.10/site-packages/mypyc/primitives/tuple_ops.cpython-310-x86_64-linux-gnu.so differ diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/detail/TensorDataContainer.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/detail/TensorDataContainer.h new file mode 100644 index 0000000000000000000000000000000000000000..d5e8f0f9234b4753b773de891cef344c3eebf440 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/detail/TensorDataContainer.h @@ -0,0 +1,351 @@ +#pragma once + +#include +#include +#include +#include + +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +#include + +namespace torch::detail { + +enum class TensorDataContainerType { Scalar, InitList, Tensor }; + +struct TensorDataContainer; + +inline std::ostream& operator<<( + std::ostream& stream, + const TensorDataContainer& tensor_data_container); + +inline c10::ScalarType compute_desired_dtype(c10::ScalarType scalar_type) { + if (scalar_type == at::kInt || scalar_type == at::kLong) { + // C++ `torch::tensor` with an integer type or an `at::ArrayRef` / + // `std::vector` / (nested) braced-init-list of integer types always + // produces a tensor of dtype `at::kLong` (aka. int64_t), matching Python + // `torch.tensor` behavior. + return at::kLong; + } else if (scalar_type == at::kFloat || scalar_type == at::kDouble) { + // C++ `torch::tensor` with a floating-point type or an `at::ArrayRef` / + // `std::vector` / (nested) braced-init-list of floating-point types always + // produces a tensor of dtype `torch::get_default_dtype()`, matching Python + // `torch.tensor` behavior. + return at::typeMetaToScalarType(at::get_default_dtype()); + } else { + return scalar_type; + } +} + +// We use `TensorDataContainer` to support converting the following data +// container types into the equivalent Tensor: +// +// 1. Arbitrarily nested braced-init-list (e.g. `{{1, 2}, {3, 4}}`). +// 2. `at::ArrayRef` of supported tensor data types. +// 3. `std::vector` of supported tensor data types. +// +// At any time, a `TensorDataContainer` object represents one of the following: +// +// 1. A scalar with value `scalar()` and type `scalar_type()`. +// 2. A Tensor represented in `std::initializer_list` form, +// with value `init_list()`, Tensor scalar type `scalar_type()`, and Tensor +// sizes `sizes()`. +// 3. A Tensor represented in `at::Tensor` form, with value `tensor()`, scalar +// type `scalar_type()`, +// and Tensor sizes `sizes()`. +// +// All the infrastructure here is mostly to support converting an arbitrarily +// nested braced-init-list to the equivalent Tensor successfully. Consider the +// following example: +// +// `torch::tensor({{1}, {2}})` +// +// this will call into the `torch::tensor` function: +// +// `at::Tensor tensor(detail::TensorDataContainer tensor_data_container, const +// at::TensorOptions& options = {})` +// +// the compiler will first try to convert `{{1}, {2}}` to `TensorDataContainer` +// type: +// +// `TensorDataContainer({{1}, {2}})` +// +// which matches to the +// `TensorDataContainer(std::initializer_list)` +// constructor, and in an attempt to convert `{1}` and `{2}` to +// `TensorDataContainer`, it calls the following: +// +// `TensorDataContainer({1})` (same call path happens for `{2}`, and we'll just +// focus on `{1}` here) +// +// At this point, theoretically there are two plausible ways for `{1}` to be +// matched to one of the constructors of `TensorDataContainer`: +// +// 1. It can be a list-initialization of a scalar value, thus matching +// `TensorDataContainer(int value)`. +// 2. It can be converted to `std::initializer_list`, thus +// matching +// `TensorDataContainer(std::initializer_list)`. +// +// How does the compiler decide which one to choose? According to +// `https://en.cppreference.com/w/cpp/language/list_initialization`, +// braced-init-list always prefers the constructor that takes +// `std::initializer_list`. Hence we happily move forward with constructor #2, +// and it calls the following: +// +// `TensorDataContainer(1)` +// +// Now it matches `TensorDataContainer(int value)`, which stores `1` as a scalar +// value. All is good. +struct TensorDataContainer { + // NOTE: For tensors with zero-size dimensions (e.g. `torch::tensor({{}, + // {}})`), the innermost empty braced-init-list `{}` matches the default + // constructor of the innermost `TensorDataContainer`. + TensorDataContainer() + : sizes_({0}), + // NOTE: In Python, the dtype of tensors with zero-size dimensions (e.g. + // `torch.tensor([[], []])`) depends on the value of + // `torch.get_default_dtype()`, and we should do the same for the C++ + // equivalent. + scalar_type_(at::typeMetaToScalarType(at::get_default_dtype())), + type_(TensorDataContainerType::InitList) {} +#define TENSOR(T, S) \ + TensorDataContainer(T value) \ + : sizes_(), \ + scalar_type_(at::k##S), \ + type_(TensorDataContainerType::Scalar), \ + scalar_(value) {} + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TENSOR) + AT_FORALL_COMPLEX_TYPES(TENSOR) +#undef TENSOR + TensorDataContainer(std::initializer_list init_list) + : sizes_(), + scalar_type_(init_list.begin()->scalar_type()), + type_(TensorDataContainerType::InitList), + init_list_(init_list) { + const TensorDataContainer& first_elem = *(init_list.begin()); + for (const auto& elem : init_list) { + TORCH_CHECK( + elem.sizes() == first_elem.sizes(), + "Expected all sub-lists to have sizes: ", + first_elem.sizes(), + " (e.g. ", + first_elem, + "), ", + "but got sub-list ", + elem, + " with sizes: ", + elem.sizes()); + TORCH_CHECK( + elem.scalar_type() == first_elem.scalar_type(), + "Expected all elements of the tensor to have the same scalar type: ", + first_elem.scalar_type(), + ", but got element of scalar type: ", + elem.scalar_type()); + } + sizes_.reserve(first_elem.sizes().size() + 1); + sizes_.push_back(static_cast(init_list.size())); + sizes_.insert( + sizes_.end(), first_elem.sizes().begin(), first_elem.sizes().end()); + } + +#define TENSOR(T, S) \ + TensorDataContainer(at::ArrayRef values) \ + : sizes_({(int64_t)values.size()}), \ + scalar_type_(at::k##S), \ + type_(TensorDataContainerType::Tensor) { \ + at::AutoDispatchBelowAutograd mode; \ + if (scalar_type_ == at::kBool) { \ + tensor_ = at::tensor(values, at::TensorOptions().device(at::kCPU)); \ + } else { \ + tensor_ = at::tensor(values, at::dtype(scalar_type_).device(at::kCPU)); \ + } \ + } + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TENSOR) + AT_FORALL_COMPLEX_TYPES(TENSOR) +#undef TENSOR + + // NOTE: We need to handle `std::vector` explicitly instead of relying on an + // implicit conversion to `at::ArrayRef`, otherwise the following error can be + // thrown when calling `torch::tensor(std::vector({1, 2}))`: + // ``` + // error: no matching function for call to 'tensor(const std::vector&)' + // no known conversion for argument 1 from 'const std::vector' to + // 'torch::detail::TensorDataContainer' + // ``` + // + // NOTE: `torch::tensor(std::vector)` is not supported for now, because + // ArrayRef cannot be constructed from a std::vector bitfield. +#define TENSOR(T, S) \ + TensorDataContainer(const std::vector& values) \ + : TensorDataContainer(at::ArrayRef(values)) {} + AT_FORALL_SCALAR_TYPES_AND2(Half, BFloat16, TENSOR) + AT_FORALL_COMPLEX_TYPES(TENSOR) +#undef TENSOR + + bool is_scalar() const { + return type_ == TensorDataContainerType::Scalar; + } + + const c10::Scalar& scalar() const { + TORCH_CHECK( + is_scalar(), + "Can only call `scalar()` on a TensorDataContainer that has `is_scalar() == true`"); + return scalar_; + } + + bool is_init_list() const { + return type_ == TensorDataContainerType::InitList; + } + + const std::initializer_list& init_list() const { + TORCH_CHECK( + is_init_list(), + "Can only call `init_list()` on a TensorDataContainer that has `is_init_list() == true`"); + return init_list_; + } + + bool is_tensor() const { + return type_ == TensorDataContainerType::Tensor; + } + + const at::Tensor& tensor() const { + TORCH_CHECK( + is_tensor(), + "Can only call `tensor()` on a TensorDataContainer that has `is_tensor() == true`"); + return tensor_; + } + + const std::vector& sizes() const { + return sizes_; + } + + const c10::ScalarType& scalar_type() const { + return scalar_type_; + } + + at::Tensor convert_to_tensor(at::TensorOptions options) const { + if (!options.has_dtype()) { + options = options.dtype(compute_desired_dtype(scalar_type_)); + } + + if (is_scalar()) { + at::AutoDispatchBelowAutograd mode; + return at::scalar_tensor(scalar_, options); + } else if (is_init_list()) { + // NOTE: Here we explicitly choose to initialize the tensor on CPU first, + // fill each element of the tensor, and then move the tensor to the + // desired device. For CUDA device, this approach only involves 1 CUDA + // kernel launch, and is much faster than initializing the tensor on CUDA + // first and then filling each element of it (which involves `N` CUDA + // kernel launches where `N` is the number of the elements in the tensor). + at::Tensor tensor = ([&]() { + at::AutoDispatchBelowAutograd mode; + return at::empty(sizes_, options.device(at::kCPU)); + })(); + fill_tensor(tensor); + return tensor.to(options.device()); + } else if (is_tensor()) { + auto output = tensor_.to(options); + TORCH_CHECK( + !tensor_.is_complex() || output.is_complex(), + "can not do torch::tensor(complex, dtype=non-complex) because complex can not be casted to real number without loss of information"); + return output; + } else { + TORCH_INTERNAL_ASSERT(false, "Invalid TensorDataContainer type"); + } + } + + void pretty_print_recursive(std::ostream& stream) const { + if (is_scalar()) { + AT_DISPATCH_ALL_TYPES_AND3( + at::kBool, + at::kHalf, + at::kBFloat16, + scalar_type_, + "TensorDataContainer_pretty_print_scalar", + [&] { stream << scalar_.to(); }); + } else if (is_init_list()) { + stream << "{"; + for (const TensorDataContainer* it = init_list_.begin(); + it != init_list_.end(); + it++) { + stream << *it; + if (std::next(it) != init_list_.end()) + stream << ", "; + } + stream << "}"; + } else if (is_tensor()) { + stream << "{"; + for (const auto i : c10::irange(tensor_.sizes()[0])) { + AT_DISPATCH_ALL_TYPES_AND3( + at::kBool, + at::kHalf, + at::kBFloat16, + scalar_type_, + "TensorDataContainer_pretty_print_tensor_item", + [&] { stream << tensor_[i].item(); }); + if (i != tensor_.sizes()[0] - 1) + stream << ", "; + } + stream << "}"; + } else { + TORCH_INTERNAL_ASSERT(false, "Invalid TensorDataContainer type"); + } + } + + private: + void fill_tensor(at::Tensor& tensor) const { + if (is_scalar()) { + TORCH_INTERNAL_ASSERT( + tensor.dim() == 0, + "Expected a 0-dim Tensor, but got Tensor with dimensions: ", + tensor.dim()); + at::NoGradGuard guard; + tensor.fill_(scalar_); + } else if (is_init_list()) { + TORCH_INTERNAL_ASSERT( + tensor.sizes()[0] == (int64_t)init_list_.size(), + "Expected a Tensor with size ", + init_list_.size(), + " in its first dimension, but got Tensor with size ", + tensor.sizes()[0], + " in its first dimension"); + int64_t index = 0; + for (const auto& elem : init_list_) { + at::Tensor slice = tensor[index]; + elem.fill_tensor(slice); + index++; + } + } else if (is_tensor()) { + TORCH_INTERNAL_ASSERT( + false, + "TensorDataContainer is already a Tensor type, `fill_tensor` should not be called"); + } else { + TORCH_INTERNAL_ASSERT(false, "Invalid TensorDataContainer type"); + } + } + + std::vector sizes_; + c10::ScalarType scalar_type_; + TensorDataContainerType type_; + c10::Scalar scalar_; + std::initializer_list init_list_; + at::Tensor tensor_; +}; + +inline std::ostream& operator<<( + std::ostream& stream, + const TensorDataContainer& tensor_data_container) { + tensor_data_container.pretty_print_recursive(stream); + return stream; +} + +} // namespace torch::detail diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/detail/static.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/detail/static.h new file mode 100644 index 0000000000000000000000000000000000000000..d855f0007498cbb8707efb3f4fca6220165d868f --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/detail/static.h @@ -0,0 +1,60 @@ +#pragma once + +#include +#include + +#include +#include + +namespace torch::nn { +class Module; +} // namespace torch::nn + +namespace torch::detail { +/// Detects if a type T has a forward() method. +template +struct has_forward { + // Declare two types with differing size. + using yes = int8_t; + using no = int16_t; + + // Here we declare two functions. The first is only enabled if `&U::forward` + // is well-formed and returns the `yes` type. In C++, the ellipsis parameter + // type (`...`) always puts the function at the bottom of overload resolution. + // This is specified in the standard as: 1) A standard conversion sequence is + // always better than a user-defined conversion sequence or an ellipsis + // conversion sequence. 2) A user-defined conversion sequence is always better + // than an ellipsis conversion sequence This means that if the first overload + // is viable, it will be preferred over the second as long as we pass any + // convertible type. The type of `&U::forward` is a pointer type, so we can + // pass e.g. 0. + template + static yes test(decltype(&U::forward)); + template + static no test(...); + + // Finally we test statically whether the size of the type returned by the + // selected overload is the size of the `yes` type. + static constexpr bool value = (sizeof(test(nullptr)) == sizeof(yes)); +}; + +template +constexpr bool check_not_lvalue_references() { + return ( + !std::is_lvalue_reference_v || + std::is_const_v>)&&check_not_lvalue_references(); +} + +template <> +inline constexpr bool check_not_lvalue_references() { + return true; +} + +/// A type trait whose `value` member is true if `M` derives from `Module`. +template +using is_module = std::is_base_of>; + +template +using enable_if_module_t = std::enable_if_t::value, T>; +} // namespace torch::detail diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h new file mode 100644 index 0000000000000000000000000000000000000000..9a582435815169cb62e795967434bb5d3a89fa0f --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h @@ -0,0 +1,94 @@ +#pragma once + +#include +#include +#include + +#include +#include + +#include +#include + +namespace torch::nn { +/// The `clone()` method in the base `Module` class does not have knowledge of +/// the concrete runtime type of its subclasses. Therefore, `clone()` must +/// either be called from within the subclass, or from a base class that has +/// knowledge of the concrete type. `Cloneable` uses the CRTP to gain +/// knowledge of the subclass' static type and provide an implementation of the +/// `clone()` method. We do not want to use this pattern in the base class, +/// because then storing a module would always require templatizing it. +template +// NOLINTNEXTLINE(bugprone-exception-escape) +class Cloneable : public Module { + public: + using Module::Module; + + /// `reset()` must perform initialization of all members with reference + /// semantics, most importantly parameters, buffers and submodules. + virtual void reset() = 0; + + /// Performs a recursive "deep copy" of the `Module`, such that all parameters + /// and submodules in the cloned module are different from those in the + /// original module. + std::shared_ptr clone( + const std::optional& device = std::nullopt) const override { + NoGradGuard no_grad; + + const auto& self = static_cast(*this); + auto copy = std::make_shared(self); + copy->parameters_.clear(); + copy->buffers_.clear(); + copy->children_.clear(); + copy->reset(); + TORCH_CHECK( + copy->parameters_.size() == parameters_.size(), + "The cloned module does not have the same number of " + "parameters as the original module after calling reset(). " + "Are you sure you called register_parameter() inside reset() " + "and not the constructor?"); + for (const auto& parameter : named_parameters(/*recurse=*/false)) { + auto& tensor = *parameter; + auto data = device && tensor.device() != *device ? tensor.to(*device) + : tensor.clone(); + copy->parameters_[parameter.key()].set_data(data); + } + TORCH_CHECK( + copy->buffers_.size() == buffers_.size(), + "The cloned module does not have the same number of " + "buffers as the original module after calling reset(). " + "Are you sure you called register_buffer() inside reset() " + "and not the constructor?"); + for (const auto& buffer : named_buffers(/*recurse=*/false)) { + auto& tensor = *buffer; + auto data = device && tensor.device() != *device ? tensor.to(*device) + : tensor.clone(); + copy->buffers_[buffer.key()].set_data(data); + } + TORCH_CHECK( + copy->children_.size() == children_.size(), + "The cloned module does not have the same number of " + "child modules as the original module after calling reset(). " + "Are you sure you called register_module() inside reset() " + "and not the constructor?"); + for (const auto& child : children_) { + copy->children_[child.key()]->clone_(*child.value(), device); + } + return copy; + } + + private: + void clone_(Module& other, const std::optional& device) final { + // Here we are *pretty* certain that `other's` type is `Derived` (because it + // was registered under the same name as `this`), but you never know what + // crazy things `reset()` does, so `dynamic_cast` just to be safe. + auto clone = std::dynamic_pointer_cast(other.clone(device)); + TORCH_CHECK( + clone != nullptr, + "Attempted to clone submodule, but it is of a " + "different type than the submodule it was to be cloned into"); + static_cast(*this) = *clone; + } +}; + +} // namespace torch::nn diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional.h new file mode 100644 index 0000000000000000000000000000000000000000..b148edc68173f4d11cf58e042902edf3c508afff --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/functional.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/init.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/init.h new file mode 100644 index 0000000000000000000000000000000000000000..d7a5476653c70dc19671bc7b9a4507b1a75f04e0 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/init.h @@ -0,0 +1,122 @@ +#pragma once + +#include +#include +#include + +namespace torch { + +namespace nn::init { + +using NonlinearityType = std::variant< + enumtype::kLinear, + enumtype::kConv1D, + enumtype::kConv2D, + enumtype::kConv3D, + enumtype::kConvTranspose1D, + enumtype::kConvTranspose2D, + enumtype::kConvTranspose3D, + enumtype::kSigmoid, + enumtype::kTanh, + enumtype::kReLU, + enumtype::kLeakyReLU>; + +using FanModeType = std::variant; + +} // namespace nn::init + +namespace nn::init { + +/// Return the recommended gain value for the given nonlinearity function. +TORCH_API double calculate_gain( + NonlinearityType nonlinearity, + double param = 0.01); + +/// Fills the given `tensor` with the provided `value` in-place, and returns it. +/// No gradient will be recorded for this operation. +TORCH_API Tensor constant_(Tensor tensor, Scalar value); + +/// Fills the given `tensor` with the Dirac delta function in-place, and returns +/// it. No gradient will be recorded for this operation. +TORCH_API Tensor dirac_(Tensor tensor); + +/// Fills the given 2-dimensional `matrix` with an identity matrix. +/// No gradient will be recorded for this operation. +TORCH_API Tensor eye_(Tensor matrix); + +/// Fills the given 2-dimensional `matrix` with values drawn from a normal +/// distribution parameterized by `mean` and `std`. +/// No gradient will be recorded for this operation. +TORCH_API Tensor normal_(Tensor tensor, double mean = 0, double std = 1); + +/// Fills the given `tensor` with ones. +/// No gradient will be recorded for this operation. +TORCH_API Tensor ones_(Tensor tensor); + +/// Fills the input `Tensor` with a (semi) orthogonal matrix, as described in +/// "Exact solutions to the nonlinear dynamics of learning in deep linear neural +/// networks" - Saxe, A. et al. (2013). The input tensor must have at least 2 +/// dimensions, and for tensors with more than 2 dimensions the trailing +/// dimensions are flattened. +/// No gradient will be recorded for this operation. +TORCH_API Tensor orthogonal_(Tensor tensor, double gain = 1.0); + +/// Fills the 2D input `Tensor` as a sparse matrix, where the +/// non-zero elements will be drawn from a centered normal distribution +/// with the given standard deviation `std`, as described in "Deep learning via +/// Hessian-free optimization" - Martens, J. (2010). The `sparsity` is a real +/// value between 0 and 1 that controls the fraction of elements in each column +/// to be set to zero. +/// No gradient will be recorded for this operation. +TORCH_API Tensor sparse_(Tensor tensor, double sparsity, double std = 0.01); + +/// Fills the given 2-dimensional `matrix` with values drawn from a uniform +/// distribution parameterized by `low` and `high`. +/// No gradient will be recorded for this operation. +TORCH_API Tensor uniform_(Tensor tensor, double low = 0, double high = 1); + +/// Fills the input `Tensor` with values according to the method +/// described in "Delving deep into rectifiers: Surpassing human-level +/// performance on ImageNet classification" - He, K. et al. (2015), using a +/// normal distribution. Also known as He initialization. +/// No gradient will be recorded for this operation. +TORCH_API Tensor kaiming_normal_( + Tensor tensor, + double a = 0, + FanModeType mode = torch::kFanIn, + NonlinearityType nonlinearity = torch::kLeakyReLU); + +/// Fills the input `Tensor` with values according to the method +/// described in "Delving deep into rectifiers: Surpassing human-level +/// performance on ImageNet classification" - He, K. et al. (2015), using a +/// uniform distribution. Also known as He initialization. +/// No gradient will be recorded for this operation. +TORCH_API Tensor kaiming_uniform_( + Tensor tensor, + double a = 0, + FanModeType mode = torch::kFanIn, + NonlinearityType nonlinearity = torch::kLeakyReLU); + +/// Fills the input `Tensor` with values according to the method +/// described in "Understanding the difficulty of training deep feedforward +/// neural networks" - Glorot, X. & Bengio, Y. (2010). Values are scaled by the +/// `gain` parameter. No gradient will be recorded for this operation. +TORCH_API Tensor xavier_normal_(Tensor tensor, double gain = 1.0); + +/// Fills the input `Tensor` with values according to the method +/// described in "Understanding the difficulty of training deep feedforward +/// neural networks" - Glorot, X. & Bengio, Y. (2010), using a uniform +/// distribution. Values are scaled by the `gain` parameter +/// No gradient will be recorded for this operation. +TORCH_API Tensor xavier_uniform_(Tensor tensor, double gain = 1.0); + +/// Fills the given `tensor` with zeros. +/// No gradient will be recorded for this operation. +TORCH_API Tensor zeros_(Tensor tensor); + +TORCH_API std::tuple _calculate_fan_in_and_fan_out( + const Tensor& tensor); + +} // namespace nn::init + +} // namespace torch diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules.h new file mode 100644 index 0000000000000000000000000000000000000000..e037d52a8535490ff5ecb17e578df5b4101ee9a3 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/modules.h @@ -0,0 +1,36 @@ +#pragma once + +// Common +#include + +// Containers +#include +#include +#include +#include +#include +#include +#include +#include + +// Layers +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/options.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/options.h new file mode 100644 index 0000000000000000000000000000000000000000..4a5224a478e1b650e393dcb3f95adc13ab36d65f --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/options.h @@ -0,0 +1,18 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/linear.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/linear.h new file mode 100644 index 0000000000000000000000000000000000000000..6c045910b848c909d0d6727709cb4aa1a4932ad3 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/options/linear.h @@ -0,0 +1,93 @@ +#pragma once + +#include +#include +#include + +namespace torch::nn { + +/// Options for the `Linear` module. +/// +/// Example: +/// ``` +/// Linear model(LinearOptions(5, 2).bias(false)); +/// ``` +struct TORCH_API LinearOptions { + LinearOptions(int64_t in_features, int64_t out_features); + /// size of each input sample + TORCH_ARG(int64_t, in_features); + + /// size of each output sample + TORCH_ARG(int64_t, out_features); + + /// If set to false, the layer will not learn an additive bias. Default: true + TORCH_ARG(bool, bias) = true; +}; + +// ============================================================================ + +/// Options for the `Flatten` module. +/// +/// Example: +/// ``` +/// Flatten model(FlattenOptions().start_dim(2).end_dim(4)); +/// ``` +struct TORCH_API FlattenOptions { + /// first dim to flatten + TORCH_ARG(int64_t, start_dim) = 1; + /// last dim to flatten + TORCH_ARG(int64_t, end_dim) = -1; +}; + +// ============================================================================ + +/// Options for the `Unflatten` module. +/// +/// Note: If input tensor is named, use dimname and namedshape arguments. +/// +/// Example: +/// ``` +/// Unflatten unnamed_model(UnflattenOptions(0, {2, 2})); +/// Unflatten named_model(UnflattenOptions("B", {{"B1", 2}, {"B2", 2}})); +/// ``` +struct TORCH_API UnflattenOptions { + typedef std::vector> namedshape_t; + + UnflattenOptions(int64_t dim, std::vector sizes); + UnflattenOptions(const char* dimname, namedshape_t namedshape); + UnflattenOptions(std::string dimname, namedshape_t namedshape); + + /// dim to unflatten + TORCH_ARG(int64_t, dim); + /// name of dim to unflatten, for use with named tensors + TORCH_ARG(std::string, dimname); + /// new shape of unflattened dim + TORCH_ARG(std::vector, sizes); + /// new shape of unflattened dim with names, for use with named tensors + TORCH_ARG(namedshape_t, namedshape); +}; + +// ============================================================================ + +/// Options for the `Bilinear` module. +/// +/// Example: +/// ``` +/// Bilinear model(BilinearOptions(3, 2, 4).bias(false)); +/// ``` +struct TORCH_API BilinearOptions { + BilinearOptions( + int64_t in1_features, + int64_t in2_features, + int64_t out_features); + /// The number of features in input 1 (columns of the input1 matrix). + TORCH_ARG(int64_t, in1_features); + /// The number of features in input 2 (columns of the input2 matrix). + TORCH_ARG(int64_t, in2_features); + /// The number of output features to produce (columns of the output matrix). + TORCH_ARG(int64_t, out_features); + /// Whether to learn and add a bias after the bilinear transformation. + TORCH_ARG(bool, bias) = true; +}; + +} // namespace torch::nn diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/pimpl-inl.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/pimpl-inl.h new file mode 100644 index 0000000000000000000000000000000000000000..cea53b6562bd1d1cec21a7d6ed520fd271ae4c50 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/pimpl-inl.h @@ -0,0 +1,76 @@ +// This class exists only to do SFINAE on abstract types `T` that are really +// `ModuleHolder`, because there's no good way to say that `T` is a +// `ModuleHolder` over some unknown type `ModuleType`. With this, you can do +// `enable_if_t>`. +struct ModuleHolderIndicator {}; + +// A type trait that is true for types that are `ModuleHolder`s. +template +using is_module_holder = + std::is_base_of>; + +template +using disable_if_module_holder_t = + std::enable_if_t::value>; + +// A collection of templates that answer the question whether a type `T` is a +// `ModuleHolder`, and if so whether its contained type is of type `C`. This is +// tricky because it is hard to short circuit in template metaprogramming. A +// naive and incorrect solution to this problem would be something like +// `disable_if::value && typename T::ContainedType == C>`. +// This would disable all types that are not `ModuleHolder`s, because even +// though the `is_module_holder::value` may be `false` for such types the +// `T::ContainedType` access would be ill-formed and thus fail the whole +// expression by the rules of SFINAE. Instead we have to use template +// specialization to statically branch on the first condition +// (`is_module_holder`) and are only then allowed to query +// `T::ContainedType` in the branch for which the condition was true. + +// Base template. +template +struct is_module_holder_of_impl; + +// False branch. `T` is not a `ModuleHolder` and thus not a `ModuleHolder` with +// contained type `C`. +template +struct is_module_holder_of_impl : std::false_type {}; + +// True branch. `T` is a `ModuleHolder` and thus we can legit access its +// `ContainedType` and compare it against `C`. +template +struct is_module_holder_of_impl + : std::is_same {}; + +// Helper template. +template +struct is_module_holder_of : is_module_holder_of_impl< + is_module_holder::value, + std::decay_t, + std::decay_t> {}; + +// A collection of templates that allow deducing the return type of the +// `forward()` method, but only if a module actually has a `forward()` method, +// and otherwise deduces to the type `void`. + +template +struct return_type_of_forward_impl; + +template +struct return_type_of_forward_impl { + using type = decltype(::std::declval().forward(::std::declval()...)); +}; + +template +struct return_type_of_forward_impl { + using type = void; +}; + +template +using return_type_of_forward = return_type_of_forward_impl< + torch::detail::has_forward::value, + C, + Args...>; + +template +using return_type_of_forward_t = + typename return_type_of_forward::type; diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/pimpl.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/pimpl.h new file mode 100644 index 0000000000000000000000000000000000000000..3c1206e4edb82150929d41a57c91902e360321ad --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/pimpl.h @@ -0,0 +1,200 @@ +#pragma once + +#include +#include +#include +#include + +#include + +#include +#include +#include + +namespace torch { +namespace detail { +// Dump all the template metaprogramming in this file. +#include +} // namespace detail + +namespace nn { + +/// A `ModuleHolder` is essentially a wrapper around `std::shared_ptr` where +/// `M` is an `nn::Module` subclass, with convenient constructors defined for +/// the kind of constructions we want to allow for our modules. +template +class ModuleHolder : torch::detail::ModuleHolderIndicator { + protected: + /// The module pointer this class wraps. + /// NOTE: Must be placed at the top of the class so that we can use it with + /// trailing return types below. + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::shared_ptr impl_; + + public: + using ContainedType = Contained; + + /// Default constructs the contained module if if has a default constructor, + /// else produces a static error. + /// + /// NOTE: This uses the behavior of template + /// classes in C++ that constructors (or any methods) are only compiled when + /// actually used. + ModuleHolder() : impl_(default_construct()) { + static_assert( + std::is_default_constructible_v, + "You are trying to default construct a module which has " + "no default constructor. Use = nullptr to give it the empty state " + "(e.g. `Linear linear = nullptr;` instead of `Linear linear;`)."); + } + + /// Constructs the `ModuleHolder` with an empty contained value. Access to + /// the underlying module is not permitted and will throw an exception, until + /// a value is assigned. + /* implicit */ ModuleHolder(std::nullptr_t) : impl_(nullptr) {} + + /// Constructs the `ModuleHolder` with a contained module, forwarding all + /// arguments to its constructor. + template < + typename Head, + typename... Tail, + typename = std::enable_if_t< + !(torch::detail::is_module_holder_of::value && + (sizeof...(Tail) == 0))>> + explicit ModuleHolder(Head&& head, Tail&&... tail) + : impl_(new Contained( + std::forward(head), + std::forward(tail)...)) {} + + /// Constructs the `ModuleHolder` from a pointer to the contained type. + /// Example: `Linear(std::make_shared(...))`. + /* implicit */ ModuleHolder(std::shared_ptr module) + : impl_(std::move(module)) {} + + /// Returns true if the `ModuleHolder` contains a module, or false if it is + /// `nullptr`. + explicit operator bool() const noexcept { + return !is_empty(); + } + + /// Forwards to the contained module. + Contained* operator->() { + return get(); + } + + /// Forwards to the contained module. + const Contained* operator->() const { + return get(); + } + + /// Returns a reference to the contained module. + Contained& operator*() { + return *get(); + } + + /// Returns a const reference to the contained module. + const Contained& operator*() const { + return *get(); + } + + /// Returns a shared pointer to the underlying module. + const std::shared_ptr& ptr() const { + TORCH_CHECK(!is_empty(), "Accessing empty ModuleHolder"); + return impl_; + } + + /// Returns a pointer to the underlying module. + Contained* get() { + TORCH_CHECK(!is_empty(), "Accessing empty ModuleHolder"); + return impl_.get(); + } + + /// Returns a const pointer to the underlying module. + const Contained* get() const { + TORCH_CHECK(!is_empty(), "Accessing empty ModuleHolder"); + return impl_.get(); + } + + /// Calls the `forward()` method of the contained module. + template + auto operator()(Args&&... args) + -> torch::detail::return_type_of_forward_t { + // This will not compile if the module does not have a `forward()` method + // (as expected). + // NOTE: `std::forward` is qualified to prevent VS2017 emitting + // error C2872: 'std': ambiguous symbol + return impl_->forward(::std::forward(args)...); + } + + /// Forwards to the subscript operator of the contained module. + /// NOTE: std::forward is qualified to prevent VS2017 emitting + /// error C2872: 'std': ambiguous symbol + template + decltype(auto) operator[](Arg&& arg) { + return (*impl_)[::std::forward(arg)]; + } + + /// Returns true if the `ModuleHolder` does not contain a module. + bool is_empty() const noexcept { + return impl_ == nullptr; + } + + private: + template + std::shared_ptr default_construct() { + if constexpr (std::is_default_constructible_v) { + return std::make_shared(); + } else { + return nullptr; + } + } +}; + +/// Pretty prints the given `Module` into the `ostream`. +template +std::ostream& operator<<( + std::ostream& stream, + const nn::ModuleHolder& module) { + return stream << *module; +} + +/// Serializes a `ModuleHolder` into an `OutputArchive`. +template +serialize::OutputArchive& operator<<( + serialize::OutputArchive& archive, + const nn::ModuleHolder& module) { + return archive << module.ptr(); +} + +/// Deserializes a `ModuleHolder` from an `InputArchive`. +template +serialize::InputArchive& operator>>( + serialize::InputArchive& archive, + nn::ModuleHolder& module) { + return archive >> module.ptr(); +} + +} // namespace nn +} // namespace torch + +// Workaround for CUDA 10.2 and below not allowing attribute unused on +// using declarations. +#ifdef __CUDACC__ +#define TORCH_UNUSED_EXCEPT_CUDA +#else +#define TORCH_UNUSED_EXCEPT_CUDA [[maybe_unused]] +#endif + +/// Defines a class `Name` which inherits from `nn::ModuleHolder` to provide a +/// wrapper over a `std::shared_ptr`. +/// `Impl` is a type alias for `ImplType` which provides a way to call static +/// method of `ImplType`. +#define TORCH_MODULE_IMPL(Name, ImplType) \ + class Name : public torch::nn::ModuleHolder { /* NOLINT */ \ + public: \ + using torch::nn::ModuleHolder::ModuleHolder; \ + using Impl TORCH_UNUSED_EXCEPT_CUDA = ImplType; \ + } + +/// Like `TORCH_MODULE_IMPL`, but defaults the `ImplType` name to `Impl`. +#define TORCH_MODULE(Name) TORCH_MODULE_IMPL(Name, Name##Impl) diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..8dbfaf5126e4f3db94174937432ea4b017354ab7 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/nn/utils.h @@ -0,0 +1,5 @@ +#pragma once + +#include +#include +#include diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adagrad.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adagrad.h new file mode 100644 index 0000000000000000000000000000000000000000..80e85dc0dfcd1f6ce476d9a3f9f41c037df90552 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adagrad.h @@ -0,0 +1,104 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +namespace torch::serialize { +class OutputArchive; +class InputArchive; +} // namespace torch::serialize + +namespace torch::optim { + +struct TORCH_API AdagradOptions + : public OptimizerCloneableOptions { + AdagradOptions(double lr = 1e-2); + TORCH_ARG(double, lr) = 1e-2; + TORCH_ARG(double, lr_decay) = 0; + TORCH_ARG(double, weight_decay) = 0; + TORCH_ARG(double, initial_accumulator_value) = 0; + TORCH_ARG(double, eps) = 1e-10; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const AdagradOptions& lhs, + const AdagradOptions& rhs); + double get_lr() const override; + void set_lr(const double lr) override; +}; + +struct TORCH_API AdagradParamState + : public OptimizerCloneableParamState { + TORCH_ARG(torch::Tensor, sum); + TORCH_ARG(int64_t, step) = 0; + + public: + AdagradParamState() = default; + AdagradParamState(const AdagradParamState&) = default; + AdagradParamState& operator=(const AdagradParamState&) = default; + AdagradParamState(AdagradParamState&&) noexcept = default; + AdagradParamState& operator=(AdagradParamState&&) noexcept = default; + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const AdagradParamState& lhs, + const AdagradParamState& rhs); +}; + +class TORCH_API Adagrad : public Optimizer { + public: + explicit Adagrad( + const std::vector& param_groups, + AdagradOptions defaults = {}) + : Optimizer(param_groups, std::make_unique(defaults)) { + TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr()); + TORCH_CHECK( + defaults.lr_decay() >= 0, + "Invalid lr_decay value: ", + defaults.lr_decay()); + TORCH_CHECK( + defaults.weight_decay() >= 0, + "Invalid weight_decay value: ", + defaults.weight_decay()); + TORCH_CHECK( + defaults.initial_accumulator_value() >= 0, + "Invalid initial_accumulator_value value: ", + defaults.initial_accumulator_value()); + TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps()); + + for (const auto& group : param_groups_) { + for (const auto& p : group.params()) { + auto state = std::make_unique(); + state->step(0); + state->sum(torch::full_like( + p.data(), + defaults.initial_accumulator_value(), + at::MemoryFormat::Preserve)); + state_[p.unsafeGetTensorImpl()] = std::move(state); + } + } + } + + explicit Adagrad(std::vector params, AdagradOptions defaults = {}) + : Adagrad({OptimizerParamGroup(std::move(params))}, std::move(defaults)) { + } + + torch::Tensor step(LossClosure closure = nullptr) override; + void save(serialize::OutputArchive& archive) const override; + void load(serialize::InputArchive& archive) override; + + private: + template + static void serialize(Self& self, Archive& archive) { + _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(Adagrad); + } +}; +} // namespace torch::optim diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adam.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adam.h new file mode 100644 index 0000000000000000000000000000000000000000..6c06e4030cf4cbd43684481e24aad002444e7797 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adam.h @@ -0,0 +1,86 @@ +#pragma once + +#include +#include +#include + +#include +#include + +namespace torch::serialize { +class OutputArchive; +class InputArchive; +} // namespace torch::serialize + +namespace torch::optim { + +struct TORCH_API AdamOptions : public OptimizerCloneableOptions { + AdamOptions(double lr = 1e-3); + TORCH_ARG(double, lr) = 1e-3; + typedef std::tuple betas_t; + TORCH_ARG(betas_t, betas) = std::make_tuple(0.9, 0.999); + TORCH_ARG(double, eps) = 1e-8; + TORCH_ARG(double, weight_decay) = 0; + TORCH_ARG(bool, amsgrad) = false; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const AdamOptions& lhs, + const AdamOptions& rhs); + double get_lr() const override; + void set_lr(const double lr) override; +}; + +struct TORCH_API AdamParamState + : public OptimizerCloneableParamState { + TORCH_ARG(int64_t, step) = 0; + TORCH_ARG(torch::Tensor, exp_avg); + TORCH_ARG(torch::Tensor, exp_avg_sq); + TORCH_ARG(torch::Tensor, max_exp_avg_sq) = {}; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const AdamParamState& lhs, + const AdamParamState& rhs); +}; + +class TORCH_API Adam : public Optimizer { + public: + explicit Adam( + const std::vector& param_groups, + AdamOptions defaults = {}) + : Optimizer(param_groups, std::make_unique(defaults)) { + TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr()); + TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps()); + auto betas = defaults.betas(); + TORCH_CHECK( + 0 <= std::get<0>(betas) && std::get<0>(betas) < 1.0, + "Invalid beta parameter at index 0: ", + std::get<0>(betas)); + TORCH_CHECK( + 0 <= std::get<1>(betas) && std::get<1>(betas) < 1.0, + "Invalid beta parameter at index 1: ", + std::get<1>(betas)); + TORCH_CHECK( + defaults.weight_decay() >= 0, + "Invalid weight_decay value: ", + defaults.weight_decay()); + } + explicit Adam(std::vector params, AdamOptions defaults = {}) + : Adam({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {} + + torch::Tensor step(LossClosure closure = nullptr) override; + void save(serialize::OutputArchive& archive) const override; + void load(serialize::InputArchive& archive) override; + + private: + template + static void serialize(Self& self, Archive& archive) { + _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(Adam); + } +}; +} // namespace torch::optim diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adamw.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adamw.h new file mode 100644 index 0000000000000000000000000000000000000000..d656921a719d0cfab6c992bab7f73f509c2c8b97 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adamw.h @@ -0,0 +1,86 @@ +#pragma once + +#include +#include +#include + +#include +#include + +namespace torch::serialize { +class OutputArchive; +class InputArchive; +} // namespace torch::serialize + +namespace torch::optim { + +struct TORCH_API AdamWOptions : public OptimizerCloneableOptions { + AdamWOptions(double lr = 1e-3); + TORCH_ARG(double, lr) = 1e-3; + typedef std::tuple betas_t; + TORCH_ARG(betas_t, betas) = std::make_tuple(0.9, 0.999); + TORCH_ARG(double, eps) = 1e-8; + TORCH_ARG(double, weight_decay) = 1e-2; + TORCH_ARG(bool, amsgrad) = false; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const AdamWOptions& lhs, + const AdamWOptions& rhs); + double get_lr() const override; + void set_lr(const double lr) override; +}; + +struct TORCH_API AdamWParamState + : public OptimizerCloneableParamState { + TORCH_ARG(int64_t, step) = 0; + TORCH_ARG(torch::Tensor, exp_avg); + TORCH_ARG(torch::Tensor, exp_avg_sq); + TORCH_ARG(torch::Tensor, max_exp_avg_sq) = {}; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const AdamWParamState& lhs, + const AdamWParamState& rhs); +}; + +class TORCH_API AdamW : public Optimizer { + public: + explicit AdamW( + const std::vector& param_groups, + AdamWOptions defaults = {}) + : Optimizer(param_groups, std::make_unique(defaults)) { + TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr()); + TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps()); + auto betas = defaults.betas(); + TORCH_CHECK( + 0 <= std::get<0>(betas) && std::get<0>(betas) < 1.0, + "Invalid beta parameter at index 0: ", + std::get<0>(betas)); + TORCH_CHECK( + 0 <= std::get<1>(betas) && std::get<1>(betas) < 1.0, + "Invalid beta parameter at index 1: ", + std::get<1>(betas)); + TORCH_CHECK( + defaults.weight_decay() >= 0, + "Invalid weight_decay value: ", + defaults.weight_decay()); + } + explicit AdamW(std::vector params, AdamWOptions defaults = {}) + : AdamW({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {} + + torch::Tensor step(LossClosure closure = nullptr) override; + void save(serialize::OutputArchive& archive) const override; + void load(serialize::InputArchive& archive) override; + + private: + template + static void serialize(Self& self, Archive& archive) { + _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(AdamW); + } +}; +} // namespace torch::optim diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/lbfgs.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/lbfgs.h new file mode 100644 index 0000000000000000000000000000000000000000..3d5f1832cf600d2705687efc5f295ff07e64e0a2 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/lbfgs.h @@ -0,0 +1,100 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::optim { + +struct TORCH_API LBFGSOptions : public OptimizerCloneableOptions { + LBFGSOptions(double lr = 1); + TORCH_ARG(double, lr) = 1; + TORCH_ARG(int64_t, max_iter) = 20; + TORCH_ARG(std::optional, max_eval) = std::nullopt; + TORCH_ARG(double, tolerance_grad) = 1e-7; + TORCH_ARG(double, tolerance_change) = 1e-9; + TORCH_ARG(int64_t, history_size) = 100; + TORCH_ARG(std::optional, line_search_fn) = std::nullopt; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const LBFGSOptions& lhs, + const LBFGSOptions& rhs); + double get_lr() const override; + void set_lr(const double lr) override; +}; + +struct TORCH_API LBFGSParamState + : public OptimizerCloneableParamState { + TORCH_ARG(int64_t, func_evals) = 0; + TORCH_ARG(int64_t, n_iter) = 0; + TORCH_ARG(double, t) = 0; + TORCH_ARG(double, prev_loss) = 0; + TORCH_ARG(Tensor, d) = {}; + TORCH_ARG(Tensor, H_diag) = {}; + TORCH_ARG(Tensor, prev_flat_grad) = {}; + TORCH_ARG(std::deque, old_dirs); + TORCH_ARG(std::deque, old_stps); + TORCH_ARG(std::deque, ro); + TORCH_ARG(std::optional>, al) = std::nullopt; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const LBFGSParamState& lhs, + const LBFGSParamState& rhs); +}; + +class TORCH_API LBFGS : public Optimizer { + public: + explicit LBFGS( + const std::vector& param_groups, + LBFGSOptions defaults = {}) + : Optimizer(param_groups, std::make_unique(defaults)) { + TORCH_CHECK( + param_groups_.size() == 1, + "LBFGS doesn't support per-parameter options (parameter groups)"); + if (defaults.max_eval() == std::nullopt) { + auto max_eval_val = (defaults.max_iter() * 5) / 4; + static_cast(param_groups_[0].options()) + .max_eval(max_eval_val); + static_cast(*defaults_).max_eval(max_eval_val); + } + _numel_cache = std::nullopt; + } + explicit LBFGS(std::vector params, LBFGSOptions defaults = {}) + : LBFGS({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {} + + Tensor step(LossClosure closure) override; + void save(serialize::OutputArchive& archive) const override; + void load(serialize::InputArchive& archive) override; + + private: + std::optional _numel_cache; + int64_t _numel(); + Tensor _gather_flat_grad(); + void _add_grad(const double step_size, const Tensor& update); + std::tuple _directional_evaluate( + const LossClosure& closure, + const std::vector& x, + double t, + const Tensor& d); + void _set_param(const std::vector& params_data); + std::vector _clone_param(); + + template + static void serialize(Self& self, Archive& archive) { + _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(LBFGS); + } +}; +} // namespace torch::optim diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/optimizer.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/optimizer.h new file mode 100644 index 0000000000000000000000000000000000000000..fd81153db1c67bc27a466af0200ff79a001b640f --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/optimizer.h @@ -0,0 +1,217 @@ +#pragma once + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +// Forward declarations confuse Doxygen +#ifndef DOXYGEN_SHOULD_SKIP_THIS +namespace at { +class Tensor; +} // namespace at + +namespace torch { +using at::Tensor; +namespace serialize { +class OutputArchive; +class InputArchive; +} // namespace serialize +} // namespace torch +#endif // DOXYGEN_SHOULD_SKIP_THIS + +namespace torch::optim { + +class TORCH_API OptimizerParamState { + public: + OptimizerParamState() = default; + OptimizerParamState(const OptimizerParamState&) = default; + OptimizerParamState& operator=(const OptimizerParamState&) = default; + OptimizerParamState(OptimizerParamState&&) noexcept = default; + OptimizerParamState& operator=(OptimizerParamState&&) noexcept = default; + virtual std::unique_ptr clone() const; + virtual void serialize(torch::serialize::InputArchive& archive); + virtual void serialize(torch::serialize::OutputArchive& archive) const; + virtual ~OptimizerParamState() = default; +}; + +template +class OptimizerCloneableParamState : public OptimizerParamState { + std::unique_ptr clone() const override { + return std::make_unique(static_cast(*this)); + } +}; + +class TORCH_API OptimizerOptions { + public: + OptimizerOptions() = default; + OptimizerOptions(const OptimizerOptions&) = default; + OptimizerOptions& operator=(const OptimizerOptions&) = default; + OptimizerOptions(OptimizerOptions&&) noexcept = default; + OptimizerOptions& operator=(OptimizerOptions&&) noexcept = default; + virtual std::unique_ptr clone() const; + virtual void serialize(torch::serialize::InputArchive& archive); + virtual void serialize(torch::serialize::OutputArchive& archive) const; + virtual ~OptimizerOptions() = default; + virtual double get_lr() const; + virtual void set_lr(const double lr); +}; + +template +class OptimizerCloneableOptions : public OptimizerOptions { + private: + std::unique_ptr clone() const override { + return std::make_unique(static_cast(*this)); + } +}; + +/// Stores parameters in the param_group and stores a pointer to the +/// OptimizerOptions +class TORCH_API OptimizerParamGroup { + public: + // NOTE: In order to store `OptimizerParamGroup` in a `std::vector`, it has to + // be copy-constructible. + OptimizerParamGroup(const OptimizerParamGroup& param_group) + : params_(param_group.params()), + options_( + param_group.has_options() ? param_group.options().clone() + : nullptr) {} + OptimizerParamGroup(std::vector params) + : params_(std::move(params)) {} + OptimizerParamGroup( + std::vector params, + std::unique_ptr options) + : params_(std::move(params)), options_(std::move(options)) {} + + OptimizerParamGroup& operator=(const OptimizerParamGroup& param_group) = + delete; + bool has_options() const; + OptimizerOptions& options(); + const OptimizerOptions& options() const; + void set_options(std::unique_ptr options); + std::vector& params(); + const std::vector& params() const; + + protected: + std::vector params_; + std::unique_ptr options_; +}; + +class TORCH_API Optimizer { + public: + // The copy constructor is deleted, because the user should use the + // `state_dict` / `load_state_dict` API to copy an optimizer instead. + Optimizer(const Optimizer& optimizer) = delete; + Optimizer(Optimizer&& optimizer) = default; + + explicit Optimizer( + const std::vector& param_groups, + std::unique_ptr defaults) + : defaults_(std::move(defaults)) { + for (const auto& param_group : param_groups) { + add_param_group(param_group); + } + } + + /// Constructs the `Optimizer` from a vector of parameters. + explicit Optimizer( + std::vector parameters, + std::unique_ptr defaults) + : Optimizer( + {OptimizerParamGroup(std::move(parameters))}, + std::move(defaults)) {} + + /// Adds the given param_group to the optimizer's param_group list. + void add_param_group(const OptimizerParamGroup& param_group); + + virtual ~Optimizer() = default; + + using LossClosure = std::function; + /// A loss function closure, which is expected to return the loss value. + virtual Tensor step(LossClosure closure = nullptr) = 0; + + /// Adds the given vector of parameters to the optimizer's parameter list. + void add_parameters(const std::vector& parameters); + + /// Zeros out the gradients of all parameters. + void zero_grad(bool set_to_none = true); + + /// Provides a const reference to the parameters in the first param_group this + /// optimizer holds. + const std::vector& parameters() const noexcept; + + /// Provides a reference to the parameters in the first param_group this + /// optimizer holds. + std::vector& parameters() noexcept; + + /// Returns the number of parameters referenced by the optimizer. + size_t size() const noexcept; + + OptimizerOptions& defaults() noexcept; + + const OptimizerOptions& defaults() const noexcept; + + /// Provides a reference to the param_groups this optimizer holds. + std::vector& param_groups() noexcept; + + /// Provides a const reference to the param_groups this optimizer holds. + const std::vector& param_groups() const noexcept; + + /// Provides a reference to the state this optimizer holds + ska::flat_hash_map>& + state() noexcept; + + /// Provides a const reference to the state this optimizer holds + const ska::flat_hash_map>& state() + const noexcept; + + /// Serializes the optimizer state into the given `archive`. + virtual void save(serialize::OutputArchive& archive) const; + + /// Deserializes the optimizer state from the given `archive`. + virtual void load(serialize::InputArchive& archive); + + protected: + std::vector param_groups_; + ska::flat_hash_map> state_; + std::unique_ptr defaults_; +}; + +/* How do we decide whether to serialize undefined tensors or + std::nullopt values into the output archive? +Answer: we strictly follow the behavior of Python API. To be more specific: + +For optimizer options: +a) For undefined tensor: currently no tensor is used as an options argument in +Python API, so we don't need to worry about it now. b) For std::nullopt value: +we serialize std::nullopt values into the output archive, to follow the exact +same behavior as Python API. + +For optimizer param state: +a) For undefined tensor: in param state, undefined tensor in C++ impl is +equivalent to missing key in Python impl. Since we don't serialize missing keys +in Python API, we skip undefined tensors when serializing the param state. b) +For std::nullopt value: in param state, std::nullopt value in C++ impl is +equivalent to missing key in Python impl. Since we don't serialize missing keys +in Python API, we skip std::nullopt values when serializing the param state. */ + +/// Serializes an `Optimizer` into an `OutputArchive`. +TORCH_API serialize::OutputArchive& operator<<( + serialize::OutputArchive& archive, + const Optimizer& optimizer); + +/// Deserializes a `Tensor` from an `InputArchive`. +TORCH_API serialize::InputArchive& operator>>( + serialize::InputArchive& archive, + Optimizer& optimizer); + +} // namespace torch::optim diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/lr_scheduler.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/lr_scheduler.h new file mode 100644 index 0000000000000000000000000000000000000000..fdab69d3615c4cd66298ff1809e337cd6ee9502f --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/lr_scheduler.h @@ -0,0 +1,37 @@ +#pragma once + +#include + +#include + +namespace torch::optim { + +class TORCH_API LRScheduler { + public: + // This class needs to take a reference of an optimizer from outside such that + // it can modify its learning rates; due to this the lifetime of said + // optimizer must be maintained + LRScheduler(torch::optim::Optimizer& optimizer); + + virtual ~LRScheduler() = default; + + void step(); + + protected: + // A vector of learning rates is calculated and returned from the specific + // subclass. A vector is returned with each element being a separate learning + // rate for each param group - although the normal use case would be to return + // a vector of identical elements. + virtual std::vector get_lrs() = 0; + + // Get current learning rates from the optimizer + std::vector get_current_lrs() const; + + unsigned step_count_{}; + + private: + void set_optimizer_lrs(const std::vector& learning_rates); + + torch::optim::Optimizer& optimizer_; +}; +} // namespace torch::optim diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/reduce_on_plateau_scheduler.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/reduce_on_plateau_scheduler.h new file mode 100644 index 0000000000000000000000000000000000000000..17c89816d79d3ab3a73b54614d9f248874de2f56 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/reduce_on_plateau_scheduler.h @@ -0,0 +1,59 @@ +#pragma once + +#include +#include + +#include + +#include + +namespace torch::optim { + +class TORCH_API ReduceLROnPlateauScheduler { + public: + enum SchedulerMode { min, max }; + enum ThresholdMode { rel, abs }; + ReduceLROnPlateauScheduler( + Optimizer& optimizer, + SchedulerMode mode = min, + float factor = 0.1, + int patience = 10, + double threshold = 1e-4, + ThresholdMode threshold_mode = rel, + int cooldown = 0, + const std::vector& min_lr = std::vector(), + double eps = 1e-8, + bool verbose = false); + + virtual ~ReduceLROnPlateauScheduler() = default; + + void step(float metric); + + private: + void reset(); + void reduce_lr(int epoch); + bool in_cooldown() const; + bool is_better(float a); + void init_is_better( + SchedulerMode mode, + double threshold, + ThresholdMode threshold_mode); + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + Optimizer& optimizer; + SchedulerMode mode{}; + float mode_worse{}; + float factor; + int patience; + double threshold{}; + ThresholdMode threshold_mode{}; + int cooldown{}; + int cooldown_counter{}; + std::vector min_lrs; + double eps; + float best{}; + bool verbose; + int last_epoch{}; + int num_bad_epochs{}; +}; +} // namespace torch::optim diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/step_lr.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/step_lr.h new file mode 100644 index 0000000000000000000000000000000000000000..f46b274f518bd5f116c3616341e8e1a9c070715c --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/step_lr.h @@ -0,0 +1,20 @@ +#pragma once + +#include + +namespace torch::optim { + +class TORCH_API StepLR : public LRScheduler { + public: + StepLR( + torch::optim::Optimizer& optimizer, + const unsigned step_size, + const double gamma = 0.1); + + private: + std::vector get_lrs() override; + + const unsigned step_size_; + const double gamma_; +}; +} // namespace torch::optim diff --git a/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/sgd.h b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/sgd.h new file mode 100644 index 0000000000000000000000000000000000000000..34896fb15653d2b6fae7e88f0fd8dfe6be4a2c4f --- /dev/null +++ b/phi4/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/sgd.h @@ -0,0 +1,85 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::serialize { +class OutputArchive; +class InputArchive; +} // namespace torch::serialize + +namespace torch::optim { + +struct TORCH_API SGDOptions : public OptimizerCloneableOptions { + SGDOptions(double lr); + TORCH_ARG(double, lr); + TORCH_ARG(double, momentum) = 0; + TORCH_ARG(double, dampening) = 0; + TORCH_ARG(double, weight_decay) = 0; + TORCH_ARG(bool, nesterov) = false; + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const SGDOptions& lhs, + const SGDOptions& rhs); + double get_lr() const override; + void set_lr(const double lr) override; +}; + +struct TORCH_API SGDParamState + : public OptimizerCloneableParamState { + TORCH_ARG(torch::Tensor, momentum_buffer); + + public: + void serialize(torch::serialize::InputArchive& archive) override; + void serialize(torch::serialize::OutputArchive& archive) const override; + TORCH_API friend bool operator==( + const SGDParamState& lhs, + const SGDParamState& rhs); +}; + +class TORCH_API SGD : public Optimizer { + public: + explicit SGD( + const std::vector& param_groups, + SGDOptions defaults) + : Optimizer(param_groups, std::make_unique(defaults)) { + TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr()); + TORCH_CHECK( + defaults.momentum() >= 0, + "Invalid momentum value: ", + defaults.momentum()); + TORCH_CHECK( + defaults.weight_decay() >= 0, + "Invalid weight_decay value: ", + defaults.weight_decay()); + TORCH_CHECK( + !defaults.nesterov() || + (defaults.momentum() > 0 && defaults.dampening() == 0), + "Nesterov momentum requires a momentum and zero dampening"); + } + + explicit SGD(std::vector params, SGDOptions defaults) + : SGD({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {} + + torch::Tensor step(LossClosure closure = nullptr) override; + + void save(serialize::OutputArchive& archive) const override; + void load(serialize::InputArchive& archive) override; + + private: + template + static void serialize(Self& self, Archive& archive) { + _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(SGD); + } +}; +} // namespace torch::optim