Skip to content

C API fast paths that keep the object representation - #21

Draft
Ivo Horák (horakivo) wants to merge 7 commits into
developfrom
perf/capi-fast-paths
Draft

Ivo Horák (horakivo) wants to merge 7 commits into
developfrom
perf/capi-fast-paths

Conversation

@horakivo

@horakivo Ivo Horák (horakivo) commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Draft, do not merge yet. C API fast paths that do not change how Python objects are represented. They are the base for #22, which adds native copies of value types; keeping them separate lets the benchmarks show each part on its own.

What this changes

Commit Change
Build C extensions with -O3 Extensions were compiled without optimisation. Also keeps JIT-compiled code near libpythonvm on macOS/aarch64, where calls across a large distance are slow; that part does nothing on Linux.
Allocate zeroed native memory lazily calloc-style allocation instead of allocate-then-clear, large zeroed blocks mapped directly, and the native-memory collection trigger looks at the resident footprint.
Mirror dict entry tables in C PyDict_Next reads a native copy of the entry table instead of calling into Java for every entry. The copy is checked against a counter that changes whenever Java code ran.
Compiled roots for C calls of builtins and simple slots One compiled entry point per wrapped builtin method and per slot kind, with cached argument conversion. Also fixes C calls of ml_meth for builtins with keyword-only arguments such as sorted, min and max.
Answer frequent C API queries without entering Java Py_TYPE, Py_REFCNT, type checks and the thread identifier for common cases.
Keep list size and items readable from C PyList_GET_SIZE, PyList_GET_ITEM and the list length slots read native data for lists that C has seen.
Iterate big ranges with Java longs A range whose values fit 64 bits no longer produces big integers.

Known limits

  • Built and tested on macOS/aarch64 only before this pull request; the CI run here is the first build on Linux x86-64. -O3 can expose undefined behaviour in extensions that -O0 hid.
  • On Linux the footprint check reads /proc/self/statm, which counts file-backed pages, unlike the macOS figure.
  • The inline Py_TYPE/Py_REFCNT paths assume that native pointers have the top bit clear.
  • Each commit compiles, but only the tip of Native copies of int, float, complex and str for C extensions #22 was built natively and run locally.

Testing

The C API test suite passed on a native standalone built from the tip of #22 (macOS/aarch64): 765 run, 756 passed, 9 skipped, 0 failures. No performance numbers here; the benchmark run of this pull request is the measurement.

🤖 Generated with Claude Code

…OS/aarch64

GraalPy's sysconfig set OPT to "-DNDEBUG" only, so C extensions built
through it were compiled without optimisation (CPython uses "-DNDEBUG -g
-O3 -Wall"). Use "-DNDEBUG -O3" on all platforms except Windows.

On darwin-aarch64, build libpythonvm with -H:-RandomizeRuntimeCodeCache.
macOS ignores address hints for MAP_JIT mappings, so with the randomisation
every runtime-compiled method lands far (hundreds of GB) away from
libpythonvm and the C extensions, and Apple cores predict indirect calls
across that distance poorly. Without a hint the code cache is mapped next
to the (ASLR-slid) libraries. The trade-off is that the code cache loses
its own address randomisation on this platform; the flag is not added if
the user sets either form of it.
…rint

- _PyType_AllocNoTrack allocates with PyObject_Calloc instead of malloc
  plus memset, and _GraalPyMem_RawCalloc uses calloc for the whole block,
  so pages of a large object that are never written stay non-resident.
- On macOS and Linux, zeroed blocks of 256 KB or more are mapped with mmap
  and unmapped on free: the system allocator keeps freed large blocks in a
  cache, and calloc of a reused block zeroes (and so touches) all of it.
- The native-memory barrier counts requested bytes. Before forcing a full
  Java collection, check the resident footprint of the process: if it
  grew by less than half a barrier since the last collection, allow
  another barrier's worth of requests (up to the configured maximum).
- After a forced collection, wait for the reference handler in short steps
  (100 us, draining the reference queue) instead of collecting again after
  fixed delays.
PyDict_Next was an upcall per step. C now keeps a mirror of a dict's entry
table: borrowed (key, value) pointers indexed by the storage's iteration
position, the same position space as _PyDict_Next. The mirror is built on
the second step of a pass and lives in a small direct-mapped cache keyed
by the dict pointer.

Validity rests on a "Java ran" epoch (CApiEpoch): one native word that Java
bumps on entry of every downcall, on exit of every upcall (generated C API
wrappers and the closures that go through GilNode.UncachedAcquire) and
whenever a thread acquires the GIL. A dict can only change while Java runs,
so an unchanged epoch means an unchanged dict. A mirror is refused if the
epoch moved while it was filled, and a stale mirror falls back to
_PyDict_Next. Entries are promoted before a mirror is built, so the
borrowed pointers live as long as the dict holds the entries.

GRAALPY_DICT_MIRROR=0 disables the mirror, GRAALPY_DICT_MIRROR=2 checks
every mirror hit against _PyDict_Next and reports counts at exit.
C code that calls the ml_meth of a GraalPy builtin (PyCFunctionWrapper) and
the lenfunc/hashfunc/inquiry slot wrappers ran uncached nodes on every
call. Each wrapper now forwards to one root node of its own (cached
argument conversion, argument creation with the builtin's positional and
keyword-only defaults, direct call, exception transfer, epoch bump), which
the JIT compiles per wrapper so the target is a constant.

This also fixes calls through ml_meth of builtins that have keyword-only
defaults (e.g. sorted, min, max), which raised "missing keyword-only
argument".
- Py_TYPE and Py_REFCNT are inline: a native object or a stub is read
  directly, tagged ints and floats have fixed types and are immortal. The
  exported functions stay for the ABI. PyFloat_AS_DOUBLE reads a native
  float object directly.
- PyType_IsSubtype answers PyFloat_Check, and subtype tests against a type
  whose instance layout differs from its base's, from the tp_base chain
  instead of the MRO tuple; the MRO walk is kept out of line.
- PyThread_get_thread_ident reads the thread id from the thread's native
  PyThreadState.
- Reading the current exception after a downcall does not store anything
  when C set no exception (the common case).
- _PyObject_GetDictPtr is not called for a native object whose type has
  neither a managed dict nor a tp_dictoffset.
A list's native stub is now a GraalPyVarObject like a tuple's. Its ob_size
and ob_item are valid while the list's storage is empty or is native
storage attached to that list; otherwise ob_size is -1 and C asks Java.
Java keeps the fields current in two places only: PTupleListBase's storage
replacement (out of line, only for lists that have a stub) and the length
and pointer setters of the attached native storage.

With that, PyList_GetItem, PyList_Size, Py_SIZE of a list and PyList_Type's
sq_length/mp_length are answered in C, and list.clear's ml_meth is a C
function that returns at once for an empty list and calls PyList_Clear
otherwise. Every stub now has at least the GraalPyVarObject fields,
zeroed. Compiled list append of a list without a stub keeps the code path
without the stub sync, so pure-Python appends compile as before.
A range whose bounds are outside the int range but whose values all fit a
Java long (e.g. range(2**32, 2**32 + n)) is iterated with longs instead of
BigInteger values wrapped in PInt, in the iterator builtins and in the
bytecode interpreter's for-loop iteration.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

perf:bench Runs walltime bench on our infra

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant