From e7c3c9b443d8b733cb0f9989233e6c7e12568d1b Mon Sep 17 00:00:00 2001 From: Andrew Svetlov Date: Fri, 20 Nov 2026 19:33:31 +0100 Subject: [PATCH 01/10] gh-161170: Lazily materialize coroutine objects for awaited calls `await f()` on an async def, and async def __aenter__() and __aexit__() of async with, no longer create a coroutine object unless the body suspends. The compiler pushes a NULL lazy_outcome below the callable and follows the call with the new END_AWAITED_CALL instruction, which continues with GET_AWAITABLE, skips the SEND loop if the body returned, or creates the coroutine and jumps to YIELD_VALUE if it suspended. Co-Authored-By: Claude Opus 5.5 --- Doc/c-api/frame.rst | 4 + Doc/library/dis.rst | 21 + Doc/library/inspect.rst | 4 +- Doc/reference/datamodel.rst | 14 +- Doc/whatsnew/3.16.rst | 46 + Include/internal/pycore_ceval.h | 7 + Include/internal/pycore_interpframe.h | 3 + Include/internal/pycore_interpframe_structs.h | 6 +- Include/internal/pycore_magic_number.h | 3 +- Include/internal/pycore_opcode_metadata.h | 76 +- Include/internal/pycore_uop_ids.h | 31 +- Include/internal/pycore_uop_metadata.h | 42 + Include/opcode_ids.h | 259 ++-- InternalDocs/generators.md | 38 +- Lib/_opcode_metadata.py | 265 ++-- Lib/asyncio/graph.py | 61 +- Lib/test/test__opcode.py | 4 + Lib/test/test_asyncio/test_graph.py | 46 +- Lib/test/test_capi/test_opt.py | 38 + Lib/test/test_coroutines.py | 851 +++++++++++++ Lib/test/test_dis.py | 36 +- Lib/test/test_opcache.py | 102 ++ Lib/test/test_sys_settrace.py | 17 + ...-10-27-12-00-00.gh-issue-161170.lazyCo.rst | 5 + Modules/_testinternalcapi/test_cases.c.h | 1125 +++++++++++++++-- Modules/_testinternalcapi/test_targets.h | 63 +- Objects/frameobject.c | 15 + Objects/genobject.c | 73 +- Programs/test_frozenmain.h | 20 +- Python/bytecodes.c | 258 +++- Python/ceval.c | 113 +- Python/ceval.h | 2 + Python/ceval_macros.h | 22 + Python/codegen.c | 77 +- Python/executor_cases.c.h | 267 +++- Python/flowgraph.c | 20 +- Python/generated_cases.c.h | 1125 +++++++++++++++-- Python/instrumentation.c | 21 +- Python/intrinsics.c | 5 +- Python/opcode_targets.h | 63 +- Python/optimizer.c | 17 +- Python/optimizer_cases.c.h | 22 + Python/record_functions.c.h | 12 + Python/specialize.c | 28 +- 44 files changed, 4638 insertions(+), 689 deletions(-) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-10-27-12-00-00.gh-issue-161170.lazyCo.rst diff --git a/Doc/c-api/frame.rst b/Doc/c-api/frame.rst index a086c60905402e..bfd39507461d03 100644 --- a/Doc/c-api/frame.rst +++ b/Doc/c-api/frame.rst @@ -85,6 +85,10 @@ See also :ref:`Reflection `. .. versionadded:: 3.11 + .. versionchanged:: 3.16 + May return ``NULL`` for a coroutine frame before its first suspension; + see :attr:`frame.f_generator`. + .. c:function:: PyObject* PyFrame_GetGlobals(PyFrameObject *frame) diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst index 1b5f0c92faf02c..f46d793b60ffe6 100644 --- a/Doc/library/dis.rst +++ b/Doc/library/dis.rst @@ -839,6 +839,27 @@ not have to be) the original ``STACK[-2]``. separate instructions. +.. opcode:: END_AWAITED_CALL (delta) + + Follows a call whose result is awaited right away (``await f()``, and the + calls of :meth:`~object.__aenter__` and :meth:`~object.__aexit__` in + :keyword:`async with`). + The compiler pushes an extra ``NULL``, the *lazy outcome*, below the + callable of such a call, and the call may run the body of a coroutine + function without creating the coroutine object, reporting in the lazy + outcome how the body ended. + + If the lazy outcome is ``NULL``, it is removed and execution continues with + :opcode:`GET_AWAITABLE`. If the body returned, it is removed and + execution continues after the :opcode:`END_SEND` of the following + :opcode:`SEND` loop. If the body suspended, the coroutine object is + created and the bytecode counter is incremented by *delta*, to the + :opcode:`YIELD_VALUE` of that loop, with ``STACK[-3:]`` set to the + coroutine, ``NULL`` and the yielded value. + + .. versionadded:: 3.16 + + .. opcode:: GET_AITER Implements ``STACK[-1] = STACK[-1].__aiter__()``. diff --git a/Doc/library/inspect.rst b/Doc/library/inspect.rst index 51c465e8f00b5e..328bfea8a372ab 100644 --- a/Doc/library/inspect.rst +++ b/Doc/library/inspect.rst @@ -151,7 +151,9 @@ attributes (see :ref:`import-mod-attrs` for module attributes): | | | coroutine object that | | | | owns this frame, or | | | | ``None`` if the frame is | -| | | of a regular function | +| | | of a regular function or | +| | | the generator is not | +| | | materialized yet | +-----------------+-------------------+---------------------------+ | | f_trace | tracing function for this | | | | frame, or ``None`` | diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index 02663ed465f424..07fa9cf5441e64 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -1736,10 +1736,22 @@ Special read-only attributes * - .. attribute:: frame.f_generator - The :term:`generator` or :term:`coroutine` object that owns this frame, - or ``None`` if the frame is a normal function. + or ``None`` if the frame is a normal function or if the generator + is not materialized yet. + + .. impl-detail:: + + A coroutine that is awaited as soon as it is called + (``await coro_func()``) may run without a coroutine object until + it first suspends, so this attribute is ``None`` before that. + Use :attr:`~codeobject.co_flags` of :attr:`frame.f_code` to tell + coroutine frames apart from normal function frames. .. versionadded:: 3.14 + .. versionchanged:: 3.16 + May be ``None`` for a coroutine frame before its first suspension. + .. index:: single: f_trace (frame attribute) single: f_trace_lines (frame attribute) diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index 33328b2ee00521..f7e1d9922cd3da 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -1147,6 +1147,26 @@ datetime and time (Contributed by Paul Ganssle in :gh:`158252`, based on work by Stan Ulbrych.) +Interpreter +----------- + +* A coroutine that is awaited as soon as it is called + (``await coro_func()``), and an ``async def`` :meth:`~object.__aenter__` + or :meth:`~object.__aexit__` of an :keyword:`async with` statement, now + runs without creating a coroutine object unless it suspends, making awaits + that complete immediately about twice as fast in a micro-benchmark + (``await noop()``: 52 ns to 27 ns on x86-64). + :meth:`~object.__aexit__` still runs with a coroutine object when the body + of the :keyword:`async with` statement raised an exception. + This does not apply while coroutine origin tracking is enabled, while a + profiler or :mod:`sys.monitoring` tool receives call events (for example + :func:`sys.setprofile` or :mod:`profiling.tracing`), while a :pep:`523` frame + evaluation function is set, or inside code compiled by the experimental JIT. + Until it first suspends, :attr:`frame.f_generator` is ``None`` for such a + coroutine, so its value may differ when one of these is active; + see :ref:`whatsnew316-porting`. + (Contributed by Andrew Svetlov in :gh:`161170`.) + re -- @@ -1405,12 +1425,26 @@ New deprecations .. include:: ../deprecations/pending-removal-in-future.rst +.. _whatsnew316-porting: + Porting to Python 3.16 ====================== This section lists previously described changes and other bugfixes that may require changes to your code. +* :attr:`frame.f_generator` and :c:func:`PyFrame_GetGenerator` may now + return ``None``/``NULL`` for a coroutine frame before its first + suspension, because a coroutine that is awaited as soon as it is called + (``await coro_func()``) runs without a coroutine object until then. + Code that used ``frame.f_generator is None`` to detect frames of normal + functions should check ``frame.f_code.co_flags`` for + :data:`~inspect.CO_COROUTINE` instead. + For the same reason, such a coroutine takes its ``__name__`` and + ``__qualname__`` from its function when it first suspends, not when it + is called. + (Contributed by Andrew Svetlov in :gh:`161170`.) + * In :mod:`tkinter`, the *name* parameter of the :meth:`~tkinter.Misc.wait_variable`, :meth:`~tkinter.Misc.setvar` and :meth:`~tkinter.Misc.getvar` methods and the *value* parameter of @@ -1488,6 +1522,18 @@ that may require changes to your code. (Contributed by An Long in :gh:`86768`.) +CPython bytecode changes +======================== + +* ``await `` and the calls of :meth:`~object.__aenter__` and + :meth:`~object.__aexit__` in :keyword:`async with` now push an extra + ``NULL`` below the callable and + follow the call with the new :opcode:`END_AWAITED_CALL` instruction, + which either goes on to :opcode:`GET_AWAITABLE`, skips the + :opcode:`SEND` loop, or jumps to its :opcode:`YIELD_VALUE`. + (Contributed by Andrew Svetlov in :gh:`161170`.) + + Build changes ============= diff --git a/Include/internal/pycore_ceval.h b/Include/internal/pycore_ceval.h index c404fc6e67d193..d25afac268becd 100644 --- a/Include/internal/pycore_ceval.h +++ b/Include/internal/pycore_ceval.h @@ -267,6 +267,13 @@ extern int _PyEval_EnsureBuiltinsWithModule( PyObject **p_builtins); PyAPI_FUNC(PyObject *)_Py_MakeCoro(PyFunctionObject *func); +PyAPI_FUNC(PyObject *) _PyCoro_MaterializeLazy(_PyInterpreterFrame *frame); +PyAPI_FUNC(_PyInterpreterFrame *) _PyEval_SuspendLazyCoro( + PyThreadState *tstate, _PyInterpreterFrame *frame); +PyAPI_FUNC(PyGenObject *) _PyEval_MaterializeLazyCoro(PyThreadState *tstate, + _PyInterpreterFrame *frame); +PyAPI_FUNC(_PyInterpreterFrame *) _PyEval_ThrowIntoLazyCoro( + PyThreadState *tstate, _PyInterpreterFrame *frame, _PyStackRef value); /* Handle signals, pending calls, GIL drop request and asynchronous exception */ diff --git a/Include/internal/pycore_interpframe.h b/Include/internal/pycore_interpframe.h index a85fa9bd32853c..8b90f3d9b0e9fe 100644 --- a/Include/internal/pycore_interpframe.h +++ b/Include/internal/pycore_interpframe.h @@ -152,6 +152,7 @@ static inline void _PyFrame_Copy(_PyInterpreterFrame *src, _PyInterpreterFrame * dest->stackpointer = dest->localsplus + stacktop; // visited is GC bookkeeping for the current stack walk, not frame state. dest->visited = 0; + dest->lazy_coro = 0; #ifdef Py_DEBUG dest->stackpointer_valid = src->stackpointer_valid; dest->lltrace = src->lltrace; @@ -208,6 +209,7 @@ _PyFrame_Initialize( frame->return_offset = 0; frame->owner = FRAME_OWNED_BY_THREAD; frame->visited = 0; + frame->lazy_coro = 0; #ifdef Py_DEBUG frame->stackpointer_valid = 1; frame->lltrace = 0; @@ -441,6 +443,7 @@ _PyFrame_PushTrampolineUnchecked(PyThreadState *tstate, PyCodeObject *code, int #endif frame->owner = FRAME_OWNED_BY_THREAD; frame->visited = 0; + frame->lazy_coro = 0; #ifdef Py_DEBUG frame->stackpointer_valid = 1; frame->lltrace = 0; diff --git a/Include/internal/pycore_interpframe_structs.h b/Include/internal/pycore_interpframe_structs.h index 0d6a37cc2c1a17..03726ff0a45750 100644 --- a/Include/internal/pycore_interpframe_structs.h +++ b/Include/internal/pycore_interpframe_structs.h @@ -44,14 +44,18 @@ struct _PyInterpreterFrame { char owner; uint8_t visited:1; uint8_t external:1; /* Set when the frame was pushed by something other than the VM */ + uint8_t lazy_coro:2; /* LAZY_CORO_REQUESTED or LAZY_CORO_RUNNING */ #ifdef Py_DEBUG uint8_t stackpointer_valid:1; - uint8_t lltrace:5; + uint8_t lltrace:3; #endif /* Locals and stack */ _PyStackRef localsplus[1]; }; +#define LAZY_CORO_REQUESTED 1 +#define LAZY_CORO_RUNNING 2 + /* _PyGenObject_HEAD defines the initial segment of generator and coroutine objects. */ diff --git a/Include/internal/pycore_magic_number.h b/Include/internal/pycore_magic_number.h index 041256df56b493..364e6ed20608b4 100644 --- a/Include/internal/pycore_magic_number.h +++ b/Include/internal/pycore_magic_number.h @@ -306,6 +306,7 @@ Known values: Python 3.16a1 3706 (Add INTRINSIC_MATCH_CLASS_ISINSTANCE) Python 3.16a1 3707 (GET_AWAITABLE also pushes NULL and None for SEND) Python 3.16a1 3708 (GET_ANEXT also pushes NULL and None for SEND) + Python 3.16a1 3709 (Lazily materialize coroutine objects for awaited calls) Python 3.17 will start with 3750 @@ -315,7 +316,7 @@ Known values: */ -#define PYC_MAGIC_NUMBER 3708 +#define PYC_MAGIC_NUMBER 3709 /* This is equivalent to converting PYC_MAGIC_NUMBER to 2 bytes (little-endian) and then appending b'\r\n'. */ #define PYC_MAGIC_NUMBER_TOKEN \ diff --git a/Include/internal/pycore_opcode_metadata.h b/Include/internal/pycore_opcode_metadata.h index f1e6f1beae644a..d81ad35d1fe754 100644 --- a/Include/internal/pycore_opcode_metadata.h +++ b/Include/internal/pycore_opcode_metadata.h @@ -98,8 +98,12 @@ int _PyOpcode_num_popped(int opcode, int oparg) { return 2 + oparg; case CALL_BOUND_METHOD_EXACT_ARGS: return 2 + oparg; + case CALL_BOUND_METHOD_EXACT_ARGS_AWAITED: + return 2 + oparg; case CALL_BOUND_METHOD_GENERAL: return 2 + oparg; + case CALL_BOUND_METHOD_GENERAL_AWAITED: + return 2 + oparg; case CALL_BUILTIN_CLASS: return 2 + oparg; case CALL_BUILTIN_FAST: @@ -124,10 +128,14 @@ int _PyOpcode_num_popped(int opcode, int oparg) { return 3 + oparg; case CALL_KW_BOUND_METHOD: return 3 + oparg; + case CALL_KW_BOUND_METHOD_AWAITED: + return 3 + oparg; case CALL_KW_NON_PY: return 3 + oparg; case CALL_KW_PY: return 3 + oparg; + case CALL_KW_PY_AWAITED: + return 3 + oparg; case CALL_LEN: return 3; case CALL_LIST_APPEND: @@ -144,8 +152,12 @@ int _PyOpcode_num_popped(int opcode, int oparg) { return 2 + oparg; case CALL_PY_EXACT_ARGS: return 2 + oparg; + case CALL_PY_EXACT_ARGS_AWAITED: + return 2 + oparg; case CALL_PY_GENERAL: return 2 + oparg; + case CALL_PY_GENERAL_AWAITED: + return 2 + oparg; case CALL_STR_1: return 3; case CALL_TUPLE_1: @@ -190,6 +202,8 @@ int _PyOpcode_num_popped(int opcode, int oparg) { return 2 + (oparg - 1); case END_ASYNC_FOR: return 2; + case END_AWAITED_CALL: + return 2; case END_FOR: return 1; case END_SEND: @@ -593,8 +607,12 @@ int _PyOpcode_num_pushed(int opcode, int oparg) { return 0; case CALL_BOUND_METHOD_EXACT_ARGS: return 0; + case CALL_BOUND_METHOD_EXACT_ARGS_AWAITED: + return 0; case CALL_BOUND_METHOD_GENERAL: return 0; + case CALL_BOUND_METHOD_GENERAL_AWAITED: + return 0; case CALL_BUILTIN_CLASS: return 1; case CALL_BUILTIN_FAST: @@ -619,10 +637,14 @@ int _PyOpcode_num_pushed(int opcode, int oparg) { return 1; case CALL_KW_BOUND_METHOD: return 0; + case CALL_KW_BOUND_METHOD_AWAITED: + return 0; case CALL_KW_NON_PY: return 1; case CALL_KW_PY: return 0; + case CALL_KW_PY_AWAITED: + return 0; case CALL_LEN: return 1; case CALL_LIST_APPEND: @@ -639,8 +661,12 @@ int _PyOpcode_num_pushed(int opcode, int oparg) { return 1; case CALL_PY_EXACT_ARGS: return 0; + case CALL_PY_EXACT_ARGS_AWAITED: + return 0; case CALL_PY_GENERAL: return 0; + case CALL_PY_GENERAL_AWAITED: + return 0; case CALL_STR_1: return 1; case CALL_TUPLE_1: @@ -685,6 +711,8 @@ int _PyOpcode_num_pushed(int opcode, int oparg) { return 1 + (oparg - 1); case END_ASYNC_FOR: return 0; + case END_AWAITED_CALL: + return 1; case END_FOR: return 0; case END_SEND: @@ -1130,7 +1158,9 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = { [CALL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG }, [CALL_ALLOC_AND_ENTER_INIT] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_BOUND_METHOD_EXACT_ARGS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_BOUND_METHOD_GENERAL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_BUILTIN_CLASS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_BUILTIN_FAST] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_RECORDS_VALUE_FLAG }, @@ -1143,8 +1173,10 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = { [CALL_ISINSTANCE] = { true, INSTR_FMT_IXC00, HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, [CALL_KW] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG }, [CALL_KW_BOUND_METHOD] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, + [CALL_KW_BOUND_METHOD_AWAITED] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_KW_NON_PY] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG }, [CALL_KW_PY] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, + [CALL_KW_PY_AWAITED] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_LEN] = { true, INSTR_FMT_IXC00, HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, [CALL_LIST_APPEND] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG }, [CALL_METHOD_DESCRIPTOR_FAST] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, @@ -1153,7 +1185,9 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = { [CALL_METHOD_DESCRIPTOR_O] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_NON_PY_GENERAL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_PY_EXACT_ARGS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, + [CALL_PY_EXACT_ARGS_AWAITED] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_PY_GENERAL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, + [CALL_PY_GENERAL_AWAITED] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_STR_1] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, [CALL_TUPLE_1] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, [CALL_TYPE_1] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG }, @@ -1176,6 +1210,7 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = { [DICT_MERGE] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, [DICT_UPDATE] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, [END_ASYNC_FOR] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_UNPREDICTABLE_JUMP_FLAG | HAS_NEEDS_GUARD_IP_FLAG }, + [END_AWAITED_CALL] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG }, [END_FOR] = { true, INSTR_FMT_IX, HAS_ESCAPES_FLAG | HAS_NO_SAVE_IP_FLAG }, [END_SEND] = { true, INSTR_FMT_IX, HAS_ESCAPES_FLAG | HAS_PURE_FLAG }, [ENTER_EXECUTOR] = { true, INSTR_FMT_IB, HAS_ARG_FLAG }, @@ -1345,7 +1380,7 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = { }; #endif -#define MAX_UOP_PER_EXPANSION 11 +#define MAX_UOP_PER_EXPANSION 12 struct opcode_macro_expansion { int nuops; struct { int16_t uop; int8_t size; int8_t offset; } uops[MAX_UOP_PER_EXPANSION]; @@ -1383,19 +1418,23 @@ _PyOpcode_macro_expansion[256] = { [BUILD_TUPLE] = { .nuops = 1, .uops = { { _BUILD_TUPLE, OPARG_SIMPLE, 0 } } }, [CALL_ALLOC_AND_ENTER_INIT] = { .nuops = 7, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_OBJECT, 2, 1 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _ALLOCATE_OBJECT, OPARG_SIMPLE, 3 }, { _CREATE_INIT_FRAME, OPARG_SIMPLE, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_BOUND_METHOD_EXACT_ARGS] = { .nuops = 11, .uops = { { _RECORD_BOUND_METHOD, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_CALL_BOUND_METHOD_EXACT_ARGS, OPARG_SIMPLE, 1 }, { _INIT_CALL_BOUND_METHOD_EXACT_ARGS, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION, 2, 1 }, { _CHECK_FUNCTION_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _CHECK_STACK_SPACE, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _INIT_CALL_PY_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = { .nuops = 12, .uops = { { _RECORD_BOUND_METHOD, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_CALL_BOUND_METHOD_EXACT_ARGS, OPARG_SIMPLE, 1 }, { _INIT_CALL_BOUND_METHOD_EXACT_ARGS, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION, 2, 1 }, { _CHECK_FUNCTION_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _CHECK_STACK_SPACE, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _INIT_CALL_PY_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _START_LAZY_CORO, OPARG_REPLACED, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_BOUND_METHOD_GENERAL] = { .nuops = 8, .uops = { { _RECORD_BOUND_METHOD, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_METHOD_VERSION, 2, 1 }, { _EXPAND_METHOD, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _PY_FRAME_GENERAL, OPARG_SIMPLE, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = { .nuops = 9, .uops = { { _RECORD_BOUND_METHOD, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_METHOD_VERSION, 2, 1 }, { _EXPAND_METHOD, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _PY_FRAME_GENERAL, OPARG_SIMPLE, 3 }, { _START_LAZY_CORO, OPARG_REPLACED, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_BUILTIN_CLASS] = { .nuops = 6, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _GUARD_CALLABLE_BUILTIN_CLASS, OPARG_SIMPLE, 3 }, { _CALL_BUILTIN_CLASS, OPARG_SIMPLE, 3 }, { _POP_TOP_OPARG, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_BUILTIN_FAST] = { .nuops = 6, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _GUARD_CALLABLE_BUILTIN_FAST, OPARG_SIMPLE, 3 }, { _CALL_BUILTIN_FAST, OPARG_SIMPLE, 3 }, { _POP_TOP_OPARG, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = { .nuops = 6, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _GUARD_CALLABLE_BUILTIN_FAST_WITH_KEYWORDS, OPARG_SIMPLE, 3 }, { _CALL_BUILTIN_FAST_WITH_KEYWORDS, OPARG_SIMPLE, 3 }, { _POP_TOP_OPARG, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_BUILTIN_O] = { .nuops = 7, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _GUARD_CALLABLE_BUILTIN_O, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_LIMIT, OPARG_SIMPLE, 3 }, { _CALL_BUILTIN_O, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_EX_NON_PY_GENERAL] = { .nuops = 4, .uops = { { _CHECK_IS_NOT_PY_CALLABLE_EX, OPARG_SIMPLE, 1 }, { _MAKE_CALLARGS_A_TUPLE, OPARG_SIMPLE, 1 }, { _CALL_FUNCTION_EX_NON_PY_GENERAL, OPARG_SIMPLE, 1 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 1 } } }, - [CALL_EX_PY] = { .nuops = 7, .uops = { { _RECORD_4OS, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _MAKE_CALLARGS_A_TUPLE, OPARG_SIMPLE, 1 }, { _CHECK_IS_PY_CALLABLE_EX, OPARG_SIMPLE, 1 }, { _PY_FRAME_EX, OPARG_SIMPLE, 1 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 1 }, { _PUSH_FRAME, OPARG_SIMPLE, 1 } } }, + [CALL_EX_PY] = { .nuops = 8, .uops = { { _RECORD_4OS, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _MAKE_CALLARGS_A_TUPLE, OPARG_SIMPLE, 1 }, { _CHECK_IS_PY_CALLABLE_EX, OPARG_SIMPLE, 1 }, { _PY_FRAME_EX, OPARG_SIMPLE, 1 }, { _MAYBE_LAZY_CORO, OPARG_REPLACED, 1 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 1 }, { _PUSH_FRAME, OPARG_SIMPLE, 1 } } }, [CALL_INTRINSIC_1] = { .nuops = 2, .uops = { { _CALL_INTRINSIC_1, OPARG_SIMPLE, 0 }, { _POP_TOP, OPARG_SIMPLE, 0 } } }, [CALL_INTRINSIC_2] = { .nuops = 3, .uops = { { _CALL_INTRINSIC_2, OPARG_SIMPLE, 0 }, { _POP_TOP, OPARG_SIMPLE, 0 }, { _POP_TOP, OPARG_SIMPLE, 0 } } }, [CALL_ISINSTANCE] = { .nuops = 3, .uops = { { _GUARD_THIRD_NULL, OPARG_SIMPLE, 3 }, { _GUARD_CALLABLE_ISINSTANCE, OPARG_SIMPLE, 3 }, { _CALL_ISINSTANCE, OPARG_SIMPLE, 3 } } }, [CALL_KW_BOUND_METHOD] = { .nuops = 7, .uops = { { _RECORD_CALLABLE_KW, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_METHOD_VERSION_KW, 2, 1 }, { _EXPAND_METHOD_KW, OPARG_SIMPLE, 3 }, { _PY_FRAME_KW, OPARG_SIMPLE, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, + [CALL_KW_BOUND_METHOD_AWAITED] = { .nuops = 8, .uops = { { _RECORD_CALLABLE_KW, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_METHOD_VERSION_KW, 2, 1 }, { _EXPAND_METHOD_KW, OPARG_SIMPLE, 3 }, { _PY_FRAME_KW, OPARG_SIMPLE, 3 }, { _START_LAZY_CORO, OPARG_REPLACED, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_KW_NON_PY] = { .nuops = 3, .uops = { { _CHECK_IS_NOT_PY_CALLABLE_KW, OPARG_SIMPLE, 3 }, { _CALL_KW_NON_PY, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_KW_PY] = { .nuops = 7, .uops = { { _RECORD_CALLABLE_KW, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION_KW, 2, 1 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _PY_FRAME_KW, OPARG_SIMPLE, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, + [CALL_KW_PY_AWAITED] = { .nuops = 8, .uops = { { _RECORD_CALLABLE_KW, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION_KW, 2, 1 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _PY_FRAME_KW, OPARG_SIMPLE, 3 }, { _START_LAZY_CORO, OPARG_REPLACED, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_LEN] = { .nuops = 5, .uops = { { _GUARD_NOS_NULL, OPARG_SIMPLE, 3 }, { _GUARD_CALLABLE_LEN, OPARG_SIMPLE, 3 }, { _CALL_LEN, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 } } }, [CALL_LIST_APPEND] = { .nuops = 6, .uops = { { _GUARD_CALLABLE_LIST_APPEND, OPARG_SIMPLE, 3 }, { _GUARD_NOS_NOT_NULL, OPARG_SIMPLE, 3 }, { _GUARD_NOS_LIST, OPARG_SIMPLE, 3 }, { _CALL_LIST_APPEND, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 } } }, [CALL_METHOD_DESCRIPTOR_FAST] = { .nuops = 5, .uops = { { _GUARD_CALLABLE_METHOD_DESCRIPTOR_FAST, OPARG_SIMPLE, 3 }, { _CALL_METHOD_DESCRIPTOR_FAST, OPARG_SIMPLE, 3 }, { _POP_TOP_OPARG, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, @@ -1404,7 +1443,9 @@ _PyOpcode_macro_expansion[256] = { [CALL_METHOD_DESCRIPTOR_O] = { .nuops = 8, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _GUARD_CALLABLE_METHOD_DESCRIPTOR_O, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_LIMIT, OPARG_SIMPLE, 3 }, { _CALL_METHOD_DESCRIPTOR_O, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_NON_PY_GENERAL] = { .nuops = 4, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _CHECK_IS_NOT_PY_CALLABLE, OPARG_SIMPLE, 3 }, { _CALL_NON_PY_GENERAL, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_PY_EXACT_ARGS] = { .nuops = 9, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION, 2, 1 }, { _CHECK_FUNCTION_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _CHECK_STACK_SPACE, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _INIT_CALL_PY_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, + [CALL_PY_EXACT_ARGS_AWAITED] = { .nuops = 10, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION, 2, 1 }, { _CHECK_FUNCTION_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _CHECK_STACK_SPACE, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _INIT_CALL_PY_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _START_LAZY_CORO, OPARG_REPLACED, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_PY_GENERAL] = { .nuops = 7, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION, 2, 1 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _PY_FRAME_GENERAL, OPARG_SIMPLE, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, + [CALL_PY_GENERAL_AWAITED] = { .nuops = 8, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION, 2, 1 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _PY_FRAME_GENERAL, OPARG_SIMPLE, 3 }, { _START_LAZY_CORO, OPARG_REPLACED, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_STR_1] = { .nuops = 5, .uops = { { _GUARD_NOS_NULL, OPARG_SIMPLE, 3 }, { _GUARD_CALLABLE_STR_1, OPARG_SIMPLE, 3 }, { _CALL_STR_1, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_TUPLE_1] = { .nuops = 5, .uops = { { _GUARD_NOS_NULL, OPARG_SIMPLE, 3 }, { _GUARD_CALLABLE_TUPLE_1, OPARG_SIMPLE, 3 }, { _CALL_TUPLE_1, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_TYPE_1] = { .nuops = 4, .uops = { { _GUARD_NOS_NULL, OPARG_SIMPLE, 3 }, { _GUARD_CALLABLE_TYPE_1, OPARG_SIMPLE, 3 }, { _CALL_TYPE_1, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 } } }, @@ -1425,6 +1466,7 @@ _PyOpcode_macro_expansion[256] = { [DELETE_SUBSCR] = { .nuops = 1, .uops = { { _DELETE_SUBSCR, OPARG_SIMPLE, 0 } } }, [DICT_MERGE] = { .nuops = 2, .uops = { { _DICT_MERGE, OPARG_SIMPLE, 0 }, { _POP_TOP, OPARG_SIMPLE, 0 } } }, [DICT_UPDATE] = { .nuops = 2, .uops = { { _DICT_UPDATE, OPARG_SIMPLE, 0 }, { _POP_TOP, OPARG_SIMPLE, 0 } } }, + [END_AWAITED_CALL] = { .nuops = 2, .uops = { { _END_AWAITED_CALL, OPARG_REPLACED, 0 }, { _POP_LAZY_OUTCOME, OPARG_SIMPLE, 0 } } }, [END_FOR] = { .nuops = 1, .uops = { { _END_FOR, OPARG_SIMPLE, 0 } } }, [END_SEND] = { .nuops = 1, .uops = { { _END_SEND, OPARG_SIMPLE, 0 } } }, [EXIT_INIT_CHECK] = { .nuops = 1, .uops = { { _EXIT_INIT_CHECK, OPARG_SIMPLE, 0 } } }, @@ -1545,7 +1587,7 @@ _PyOpcode_macro_expansion[256] = { [UNPACK_SEQUENCE_TUPLE] = { .nuops = 2, .uops = { { _GUARD_TOS_TUPLE, OPARG_SIMPLE, 0 }, { _UNPACK_SEQUENCE_TUPLE, OPARG_SIMPLE, 1 } } }, [UNPACK_SEQUENCE_TWO_TUPLE] = { .nuops = 2, .uops = { { _GUARD_TOS_TUPLE, OPARG_SIMPLE, 0 }, { _UNPACK_SEQUENCE_TWO_TUPLE, OPARG_SIMPLE, 1 } } }, [WITH_EXCEPT_START] = { .nuops = 1, .uops = { { _WITH_EXCEPT_START, OPARG_SIMPLE, 0 } } }, - [YIELD_VALUE] = { .nuops = 2, .uops = { { _MAKE_HEAP_SAFE, OPARG_SIMPLE, 0 }, { _YIELD_VALUE, OPARG_SIMPLE, 0 } } }, + [YIELD_VALUE] = { .nuops = 3, .uops = { { _CHECK_LAZY_CORO, OPARG_REPLACED, 0 }, { _MAKE_HEAP_SAFE, OPARG_SIMPLE, 0 }, { _YIELD_VALUE, OPARG_SIMPLE, 0 } } }, }; #endif // NEED_OPCODE_METADATA @@ -1583,7 +1625,9 @@ const char *_PyOpcode_OpName[267] = { [CALL] = "CALL", [CALL_ALLOC_AND_ENTER_INIT] = "CALL_ALLOC_AND_ENTER_INIT", [CALL_BOUND_METHOD_EXACT_ARGS] = "CALL_BOUND_METHOD_EXACT_ARGS", + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = "CALL_BOUND_METHOD_EXACT_ARGS_AWAITED", [CALL_BOUND_METHOD_GENERAL] = "CALL_BOUND_METHOD_GENERAL", + [CALL_BOUND_METHOD_GENERAL_AWAITED] = "CALL_BOUND_METHOD_GENERAL_AWAITED", [CALL_BUILTIN_CLASS] = "CALL_BUILTIN_CLASS", [CALL_BUILTIN_FAST] = "CALL_BUILTIN_FAST", [CALL_BUILTIN_FAST_WITH_KEYWORDS] = "CALL_BUILTIN_FAST_WITH_KEYWORDS", @@ -1596,8 +1640,10 @@ const char *_PyOpcode_OpName[267] = { [CALL_ISINSTANCE] = "CALL_ISINSTANCE", [CALL_KW] = "CALL_KW", [CALL_KW_BOUND_METHOD] = "CALL_KW_BOUND_METHOD", + [CALL_KW_BOUND_METHOD_AWAITED] = "CALL_KW_BOUND_METHOD_AWAITED", [CALL_KW_NON_PY] = "CALL_KW_NON_PY", [CALL_KW_PY] = "CALL_KW_PY", + [CALL_KW_PY_AWAITED] = "CALL_KW_PY_AWAITED", [CALL_LEN] = "CALL_LEN", [CALL_LIST_APPEND] = "CALL_LIST_APPEND", [CALL_METHOD_DESCRIPTOR_FAST] = "CALL_METHOD_DESCRIPTOR_FAST", @@ -1606,7 +1652,9 @@ const char *_PyOpcode_OpName[267] = { [CALL_METHOD_DESCRIPTOR_O] = "CALL_METHOD_DESCRIPTOR_O", [CALL_NON_PY_GENERAL] = "CALL_NON_PY_GENERAL", [CALL_PY_EXACT_ARGS] = "CALL_PY_EXACT_ARGS", + [CALL_PY_EXACT_ARGS_AWAITED] = "CALL_PY_EXACT_ARGS_AWAITED", [CALL_PY_GENERAL] = "CALL_PY_GENERAL", + [CALL_PY_GENERAL_AWAITED] = "CALL_PY_GENERAL_AWAITED", [CALL_STR_1] = "CALL_STR_1", [CALL_TUPLE_1] = "CALL_TUPLE_1", [CALL_TYPE_1] = "CALL_TYPE_1", @@ -1629,6 +1677,7 @@ const char *_PyOpcode_OpName[267] = { [DICT_MERGE] = "DICT_MERGE", [DICT_UPDATE] = "DICT_UPDATE", [END_ASYNC_FOR] = "END_ASYNC_FOR", + [END_AWAITED_CALL] = "END_AWAITED_CALL", [END_FOR] = "END_FOR", [END_SEND] = "END_SEND", [ENTER_EXECUTOR] = "ENTER_EXECUTOR", @@ -1828,7 +1877,6 @@ const uint8_t _PyOpcode_Caches[256] = { PyAPI_DATA(const uint8_t) _PyOpcode_Deopt[256]; #ifdef NEED_OPCODE_METADATA const uint8_t _PyOpcode_Deopt[256] = { - [117] = 117, [118] = 118, [119] = 119, [120] = 120, @@ -1839,12 +1887,6 @@ const uint8_t _PyOpcode_Deopt[256] = { [125] = 125, [126] = 126, [127] = 127, - [219] = 219, - [220] = 220, - [221] = 221, - [222] = 222, - [223] = 223, - [224] = 224, [225] = 225, [226] = 226, [227] = 227, @@ -1883,7 +1925,9 @@ const uint8_t _PyOpcode_Deopt[256] = { [CALL] = CALL, [CALL_ALLOC_AND_ENTER_INIT] = CALL, [CALL_BOUND_METHOD_EXACT_ARGS] = CALL, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = CALL, [CALL_BOUND_METHOD_GENERAL] = CALL, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = CALL, [CALL_BUILTIN_CLASS] = CALL, [CALL_BUILTIN_FAST] = CALL, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = CALL, @@ -1896,8 +1940,10 @@ const uint8_t _PyOpcode_Deopt[256] = { [CALL_ISINSTANCE] = CALL, [CALL_KW] = CALL_KW, [CALL_KW_BOUND_METHOD] = CALL_KW, + [CALL_KW_BOUND_METHOD_AWAITED] = CALL_KW, [CALL_KW_NON_PY] = CALL_KW, [CALL_KW_PY] = CALL_KW, + [CALL_KW_PY_AWAITED] = CALL_KW, [CALL_LEN] = CALL, [CALL_LIST_APPEND] = CALL, [CALL_METHOD_DESCRIPTOR_FAST] = CALL, @@ -1906,7 +1952,9 @@ const uint8_t _PyOpcode_Deopt[256] = { [CALL_METHOD_DESCRIPTOR_O] = CALL, [CALL_NON_PY_GENERAL] = CALL, [CALL_PY_EXACT_ARGS] = CALL, + [CALL_PY_EXACT_ARGS_AWAITED] = CALL, [CALL_PY_GENERAL] = CALL, + [CALL_PY_GENERAL_AWAITED] = CALL, [CALL_STR_1] = CALL, [CALL_TUPLE_1] = CALL, [CALL_TYPE_1] = CALL, @@ -1929,6 +1977,7 @@ const uint8_t _PyOpcode_Deopt[256] = { [DICT_MERGE] = DICT_MERGE, [DICT_UPDATE] = DICT_UPDATE, [END_ASYNC_FOR] = END_ASYNC_FOR, + [END_AWAITED_CALL] = END_AWAITED_CALL, [END_FOR] = END_FOR, [END_SEND] = END_SEND, [ENTER_EXECUTOR] = ENTER_EXECUTOR, @@ -2089,7 +2138,6 @@ const uint8_t _PyOpcode_Deopt[256] = { #endif // NEED_OPCODE_METADATA #define EXTRA_CASES \ - case 117: \ case 118: \ case 119: \ case 120: \ @@ -2100,12 +2148,6 @@ const uint8_t _PyOpcode_Deopt[256] = { case 125: \ case 126: \ case 127: \ - case 219: \ - case 220: \ - case 221: \ - case 222: \ - case 223: \ - case 224: \ case 225: \ case 226: \ case 227: \ diff --git a/Include/internal/pycore_uop_ids.h b/Include/internal/pycore_uop_ids.h index 31a8e60259f4ba..93d7c8fcfdcc48 100644 --- a/Include/internal/pycore_uop_ids.h +++ b/Include/internal/pycore_uop_ids.h @@ -82,6 +82,7 @@ enum { _CHECK_IS_NOT_PY_CALLABLE_EX, _CHECK_IS_NOT_PY_CALLABLE_KW, _CHECK_IS_PY_CALLABLE_EX, + _CHECK_LAZY_CORO, _CHECK_MANAGED_OBJECT_HAS_VALUES, _CHECK_METHOD_VERSION, _CHECK_METHOD_VERSION_KW, @@ -116,6 +117,7 @@ enum { _DO_CALL_FUNCTION_EX, _DO_CALL_KW, _DYNAMIC_EXIT, + _END_AWAITED_CALL, _ERROR_POP_N, _EXPAND_METHOD, _EXPAND_METHOD_KW, @@ -191,6 +193,7 @@ enum { _GUARD_NOT_EXHAUSTED_LIST, _GUARD_NOT_EXHAUSTED_RANGE, _GUARD_NOT_EXHAUSTED_TUPLE, + _GUARD_NOT_LAZY_CORO, _GUARD_THIRD_NULL, _GUARD_TOS_ANY_DICT, _GUARD_TOS_ANY_SET, @@ -287,12 +290,14 @@ enum { _MATCH_CLASS, _MAYBE_EXPAND_METHOD, _MAYBE_EXPAND_METHOD_KW, + _MAYBE_LAZY_CORO, _MONITOR_CALL, _MONITOR_CALL_KW, _MONITOR_JUMP_BACKWARD, _MONITOR_RESUME, _POP_JUMP_IF_FALSE, _POP_JUMP_IF_TRUE, + _POP_LAZY_OUTCOME, _POP_TOP_FLOAT, _POP_TOP_INT, _POP_TOP_NOP, @@ -328,6 +333,7 @@ enum { _SET_UPDATE, _SPILL_OR_RELOAD, _START_EXECUTOR, + _START_LAZY_CORO, _STORE_ATTR, _STORE_ATTR_INSTANCE_VALUE, _STORE_ATTR_SLOT, @@ -366,7 +372,7 @@ enum { _UNPACK_SEQUENCE_UNIQUE_TWO_TUPLE, _YIELD_VALUE, }; -#define MAX_UOP_ID 654 +#define MAX_UOP_ID 660 #define _BUILD_INTERPOLATION BUILD_INTERPOLATION #define _BUILD_LIST BUILD_LIST @@ -590,6 +596,10 @@ enum { _CHECK_IS_PY_CALLABLE_EX_r13, _CHECK_IS_PY_CALLABLE_EX_r23, _CHECK_IS_PY_CALLABLE_EX_r33, + _CHECK_LAZY_CORO_r00, + _CHECK_LAZY_CORO_r11, + _CHECK_LAZY_CORO_r22, + _CHECK_LAZY_CORO_r33, _CHECK_MANAGED_OBJECT_HAS_VALUES_r01, _CHECK_MANAGED_OBJECT_HAS_VALUES_r11, _CHECK_MANAGED_OBJECT_HAS_VALUES_r22, @@ -665,6 +675,7 @@ enum { _DYNAMIC_EXIT_r10, _DYNAMIC_EXIT_r20, _DYNAMIC_EXIT_r30, + _END_AWAITED_CALL_r22, _END_FOR_r10, _END_SEND_r31, _ERROR_POP_N_r00, @@ -920,6 +931,10 @@ enum { _GUARD_NOT_EXHAUSTED_TUPLE_r12, _GUARD_NOT_EXHAUSTED_TUPLE_r22, _GUARD_NOT_EXHAUSTED_TUPLE_r33, + _GUARD_NOT_LAZY_CORO_r00, + _GUARD_NOT_LAZY_CORO_r11, + _GUARD_NOT_LAZY_CORO_r22, + _GUARD_NOT_LAZY_CORO_r33, _GUARD_THIRD_NULL_r03, _GUARD_THIRD_NULL_r13, _GUARD_THIRD_NULL_r23, @@ -1237,6 +1252,10 @@ enum { _MATCH_SEQUENCE_r23, _MAYBE_EXPAND_METHOD_r00, _MAYBE_EXPAND_METHOD_KW_r11, + _MAYBE_LAZY_CORO_r01, + _MAYBE_LAZY_CORO_r11, + _MAYBE_LAZY_CORO_r22, + _MAYBE_LAZY_CORO_r33, _MONITOR_CALL_r00, _MONITOR_CALL_KW_r11, _MONITOR_JUMP_BACKWARD_r00, @@ -1258,6 +1277,10 @@ enum { _POP_JUMP_IF_TRUE_r10, _POP_JUMP_IF_TRUE_r21, _POP_JUMP_IF_TRUE_r32, + _POP_LAZY_OUTCOME_r01, + _POP_LAZY_OUTCOME_r11, + _POP_LAZY_OUTCOME_r21, + _POP_LAZY_OUTCOME_r32, _POP_TOP_r10, _POP_TOP_FLOAT_r00, _POP_TOP_FLOAT_r10, @@ -1339,6 +1362,10 @@ enum { _SPILL_OR_RELOAD_r31, _SPILL_OR_RELOAD_r32, _START_EXECUTOR_r00, + _START_LAZY_CORO_r01, + _START_LAZY_CORO_r11, + _START_LAZY_CORO_r22, + _START_LAZY_CORO_r33, _STORE_ATTR_r20, _STORE_ATTR_INSTANCE_VALUE_r21, _STORE_ATTR_SLOT_r21, @@ -1444,7 +1471,7 @@ enum { _WITH_EXCEPT_START_r33, _YIELD_VALUE_r11, }; -#define MAX_UOP_REGS_ID 1655 +#define MAX_UOP_REGS_ID 1682 #ifdef __cplusplus } diff --git a/Include/internal/pycore_uop_metadata.h b/Include/internal/pycore_uop_metadata.h index a264ad3f7848b7..a7c440bc0db24d 100644 --- a/Include/internal/pycore_uop_metadata.h +++ b/Include/internal/pycore_uop_metadata.h @@ -168,12 +168,14 @@ const uint32_t _PyUop_Flags[MAX_UOP_ID+1] = { [_GET_AITER] = HAS_ERROR_FLAG | HAS_ESCAPES_FLAG, [_GET_ANEXT] = HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG, [_GET_AWAITABLE] = HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG, + [_POP_LAZY_OUTCOME] = 0, [_SEND_GEN_FRAME] = HAS_ARG_FLAG | HAS_EXIT_FLAG, [_GUARD_TOS_IS_NONE] = HAS_EXIT_FLAG, [_GUARD_NOS_NOT_NULL] = HAS_EXIT_FLAG, [_SEND_VIRTUAL_TIER_TWO] = HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG, [_GUARD_3OS_ASYNC_GEN_ASEND] = HAS_EXIT_FLAG, [_SEND_ASYNC_GEN_TIER_TWO] = HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG, + [_GUARD_NOT_LAZY_CORO] = HAS_EXIT_FLAG, [_YIELD_VALUE] = HAS_ARG_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG, [_POP_EXCEPT] = HAS_ESCAPES_FLAG, [_LOAD_COMMON_CONSTANT] = HAS_ARG_FLAG, @@ -1644,6 +1646,15 @@ const _PyUopCachingInfo _PyUop_Caching[MAX_UOP_ID+1] = { { -1, -1, -1 }, }, }, + [_POP_LAZY_OUTCOME] = { + .best = { 0, 1, 2, 3 }, + .entries = { + { 1, 0, _POP_LAZY_OUTCOME_r01 }, + { 1, 1, _POP_LAZY_OUTCOME_r11 }, + { 1, 2, _POP_LAZY_OUTCOME_r21 }, + { 2, 3, _POP_LAZY_OUTCOME_r32 }, + }, + }, [_SEND_GEN_FRAME] = { .best = { 3, 3, 3, 3 }, .entries = { @@ -1698,6 +1709,15 @@ const _PyUopCachingInfo _PyUop_Caching[MAX_UOP_ID+1] = { { 3, 3, _SEND_ASYNC_GEN_TIER_TWO_r33 }, }, }, + [_GUARD_NOT_LAZY_CORO] = { + .best = { 0, 1, 2, 3 }, + .entries = { + { 0, 0, _GUARD_NOT_LAZY_CORO_r00 }, + { 1, 1, _GUARD_NOT_LAZY_CORO_r11 }, + { 2, 2, _GUARD_NOT_LAZY_CORO_r22 }, + { 3, 3, _GUARD_NOT_LAZY_CORO_r33 }, + }, + }, [_YIELD_VALUE] = { .best = { 1, 1, 1, 1 }, .entries = { @@ -4285,6 +4305,10 @@ const uint16_t _PyUop_Uncached[MAX_UOP_REGS_ID+1] = { [_GET_AITER_r11] = _GET_AITER, [_GET_ANEXT_r13] = _GET_ANEXT, [_GET_AWAITABLE_r13] = _GET_AWAITABLE, + [_POP_LAZY_OUTCOME_r01] = _POP_LAZY_OUTCOME, + [_POP_LAZY_OUTCOME_r11] = _POP_LAZY_OUTCOME, + [_POP_LAZY_OUTCOME_r21] = _POP_LAZY_OUTCOME, + [_POP_LAZY_OUTCOME_r32] = _POP_LAZY_OUTCOME, [_SEND_GEN_FRAME_r33] = _SEND_GEN_FRAME, [_GUARD_TOS_IS_NONE_r01] = _GUARD_TOS_IS_NONE, [_GUARD_TOS_IS_NONE_r11] = _GUARD_TOS_IS_NONE, @@ -4303,6 +4327,10 @@ const uint16_t _PyUop_Uncached[MAX_UOP_REGS_ID+1] = { [_GUARD_3OS_ASYNC_GEN_ASEND_r23] = _GUARD_3OS_ASYNC_GEN_ASEND, [_GUARD_3OS_ASYNC_GEN_ASEND_r33] = _GUARD_3OS_ASYNC_GEN_ASEND, [_SEND_ASYNC_GEN_TIER_TWO_r33] = _SEND_ASYNC_GEN_TIER_TWO, + [_GUARD_NOT_LAZY_CORO_r00] = _GUARD_NOT_LAZY_CORO, + [_GUARD_NOT_LAZY_CORO_r11] = _GUARD_NOT_LAZY_CORO, + [_GUARD_NOT_LAZY_CORO_r22] = _GUARD_NOT_LAZY_CORO, + [_GUARD_NOT_LAZY_CORO_r33] = _GUARD_NOT_LAZY_CORO, [_YIELD_VALUE_r11] = _YIELD_VALUE, [_POP_EXCEPT_r10] = _POP_EXCEPT, [_LOAD_COMMON_CONSTANT_r01] = _LOAD_COMMON_CONSTANT, @@ -5535,6 +5563,11 @@ const char *const _PyOpcode_uop_name[MAX_UOP_REGS_ID+1] = { [_GUARD_NOT_EXHAUSTED_TUPLE_r12] = "_GUARD_NOT_EXHAUSTED_TUPLE_r12", [_GUARD_NOT_EXHAUSTED_TUPLE_r22] = "_GUARD_NOT_EXHAUSTED_TUPLE_r22", [_GUARD_NOT_EXHAUSTED_TUPLE_r33] = "_GUARD_NOT_EXHAUSTED_TUPLE_r33", + [_GUARD_NOT_LAZY_CORO] = "_GUARD_NOT_LAZY_CORO", + [_GUARD_NOT_LAZY_CORO_r00] = "_GUARD_NOT_LAZY_CORO_r00", + [_GUARD_NOT_LAZY_CORO_r11] = "_GUARD_NOT_LAZY_CORO_r11", + [_GUARD_NOT_LAZY_CORO_r22] = "_GUARD_NOT_LAZY_CORO_r22", + [_GUARD_NOT_LAZY_CORO_r33] = "_GUARD_NOT_LAZY_CORO_r33", [_GUARD_THIRD_NULL] = "_GUARD_THIRD_NULL", [_GUARD_THIRD_NULL_r03] = "_GUARD_THIRD_NULL_r03", [_GUARD_THIRD_NULL_r13] = "_GUARD_THIRD_NULL_r13", @@ -5928,6 +5961,11 @@ const char *const _PyOpcode_uop_name[MAX_UOP_REGS_ID+1] = { [_POP_EXCEPT_r10] = "_POP_EXCEPT_r10", [_POP_ITER] = "_POP_ITER", [_POP_ITER_r20] = "_POP_ITER_r20", + [_POP_LAZY_OUTCOME] = "_POP_LAZY_OUTCOME", + [_POP_LAZY_OUTCOME_r01] = "_POP_LAZY_OUTCOME_r01", + [_POP_LAZY_OUTCOME_r11] = "_POP_LAZY_OUTCOME_r11", + [_POP_LAZY_OUTCOME_r21] = "_POP_LAZY_OUTCOME_r21", + [_POP_LAZY_OUTCOME_r32] = "_POP_LAZY_OUTCOME_r32", [_POP_TOP] = "_POP_TOP", [_POP_TOP_r10] = "_POP_TOP_r10", [_POP_TOP_FLOAT] = "_POP_TOP_FLOAT", @@ -6464,6 +6502,8 @@ int _PyUop_num_popped(int opcode, int oparg) return 0; case _GET_AWAITABLE: return 1; + case _POP_LAZY_OUTCOME: + return 2; case _SEND_GEN_FRAME: return 1; case _GUARD_TOS_IS_NONE: @@ -6476,6 +6516,8 @@ int _PyUop_num_popped(int opcode, int oparg) return 0; case _SEND_ASYNC_GEN_TIER_TWO: return 3; + case _GUARD_NOT_LAZY_CORO: + return 0; case _YIELD_VALUE: return 1; case _POP_EXCEPT: diff --git a/Include/opcode_ids.h b/Include/opcode_ids.h index 11342ae451b9f6..5d1d741a609650 100644 --- a/Include/opcode_ids.h +++ b/Include/opcode_ids.h @@ -74,59 +74,60 @@ extern "C" { #define DICT_MERGE 61 #define DICT_UPDATE 62 #define END_ASYNC_FOR 63 -#define EXTENDED_ARG 64 -#define FOR_ITER 65 -#define GET_AWAITABLE 66 -#define GET_ITER 67 -#define IMPORT_FROM 68 -#define IMPORT_NAME 69 -#define IS_OP 70 -#define JUMP_BACKWARD 71 -#define JUMP_BACKWARD_NO_INTERRUPT 72 -#define JUMP_FORWARD 73 -#define LIST_APPEND 74 -#define LIST_EXTEND 75 -#define LOAD_ATTR 76 -#define LOAD_COMMON_CONSTANT 77 -#define LOAD_CONST 78 -#define LOAD_DEREF 79 -#define LOAD_FAST 80 -#define LOAD_FAST_AND_CLEAR 81 -#define LOAD_FAST_BORROW 82 -#define LOAD_FAST_BORROW_LOAD_FAST_BORROW 83 -#define LOAD_FAST_CHECK 84 -#define LOAD_FAST_LOAD_FAST 85 -#define LOAD_FROM_DICT_OR_DEREF 86 -#define LOAD_FROM_DICT_OR_GLOBALS 87 -#define LOAD_GLOBAL 88 -#define LOAD_NAME 89 -#define LOAD_SMALL_INT 90 -#define LOAD_SPECIAL 91 -#define LOAD_SUPER_ATTR 92 -#define MAKE_CELL 93 -#define MAP_ADD 94 -#define MATCH_CLASS 95 -#define POP_JUMP_IF_FALSE 96 -#define POP_JUMP_IF_NONE 97 -#define POP_JUMP_IF_NOT_NONE 98 -#define POP_JUMP_IF_TRUE 99 -#define RAISE_VARARGS 100 -#define RERAISE 101 -#define SEND 102 -#define SET_ADD 103 -#define SET_FUNCTION_ATTRIBUTE 104 -#define SET_UPDATE 105 -#define STORE_ATTR 106 -#define STORE_DEREF 107 -#define STORE_FAST 108 -#define STORE_FAST_LOAD_FAST 109 -#define STORE_FAST_STORE_FAST 110 -#define STORE_GLOBAL 111 -#define STORE_NAME 112 -#define SWAP 113 -#define UNPACK_EX 114 -#define UNPACK_SEQUENCE 115 -#define YIELD_VALUE 116 +#define END_AWAITED_CALL 64 +#define EXTENDED_ARG 65 +#define FOR_ITER 66 +#define GET_AWAITABLE 67 +#define GET_ITER 68 +#define IMPORT_FROM 69 +#define IMPORT_NAME 70 +#define IS_OP 71 +#define JUMP_BACKWARD 72 +#define JUMP_BACKWARD_NO_INTERRUPT 73 +#define JUMP_FORWARD 74 +#define LIST_APPEND 75 +#define LIST_EXTEND 76 +#define LOAD_ATTR 77 +#define LOAD_COMMON_CONSTANT 78 +#define LOAD_CONST 79 +#define LOAD_DEREF 80 +#define LOAD_FAST 81 +#define LOAD_FAST_AND_CLEAR 82 +#define LOAD_FAST_BORROW 83 +#define LOAD_FAST_BORROW_LOAD_FAST_BORROW 84 +#define LOAD_FAST_CHECK 85 +#define LOAD_FAST_LOAD_FAST 86 +#define LOAD_FROM_DICT_OR_DEREF 87 +#define LOAD_FROM_DICT_OR_GLOBALS 88 +#define LOAD_GLOBAL 89 +#define LOAD_NAME 90 +#define LOAD_SMALL_INT 91 +#define LOAD_SPECIAL 92 +#define LOAD_SUPER_ATTR 93 +#define MAKE_CELL 94 +#define MAP_ADD 95 +#define MATCH_CLASS 96 +#define POP_JUMP_IF_FALSE 97 +#define POP_JUMP_IF_NONE 98 +#define POP_JUMP_IF_NOT_NONE 99 +#define POP_JUMP_IF_TRUE 100 +#define RAISE_VARARGS 101 +#define RERAISE 102 +#define SEND 103 +#define SET_ADD 104 +#define SET_FUNCTION_ATTRIBUTE 105 +#define SET_UPDATE 106 +#define STORE_ATTR 107 +#define STORE_DEREF 108 +#define STORE_FAST 109 +#define STORE_FAST_LOAD_FAST 110 +#define STORE_FAST_STORE_FAST 111 +#define STORE_GLOBAL 112 +#define STORE_NAME 113 +#define SWAP 114 +#define UNPACK_EX 115 +#define UNPACK_SEQUENCE 116 +#define YIELD_VALUE 117 #define RESUME 128 #define BINARY_OP_ADD_FLOAT 129 #define BINARY_OP_ADD_INT 130 @@ -145,79 +146,85 @@ extern "C" { #define BINARY_OP_SUBTRACT_INT 143 #define CALL_ALLOC_AND_ENTER_INIT 144 #define CALL_BOUND_METHOD_EXACT_ARGS 145 -#define CALL_BOUND_METHOD_GENERAL 146 -#define CALL_BUILTIN_CLASS 147 -#define CALL_BUILTIN_FAST 148 -#define CALL_BUILTIN_FAST_WITH_KEYWORDS 149 -#define CALL_BUILTIN_O 150 -#define CALL_EX_NON_PY_GENERAL 151 -#define CALL_EX_PY 152 -#define CALL_ISINSTANCE 153 -#define CALL_KW_BOUND_METHOD 154 -#define CALL_KW_NON_PY 155 -#define CALL_KW_PY 156 -#define CALL_LEN 157 -#define CALL_LIST_APPEND 158 -#define CALL_METHOD_DESCRIPTOR_FAST 159 -#define CALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS 160 -#define CALL_METHOD_DESCRIPTOR_NOARGS 161 -#define CALL_METHOD_DESCRIPTOR_O 162 -#define CALL_NON_PY_GENERAL 163 -#define CALL_PY_EXACT_ARGS 164 -#define CALL_PY_GENERAL 165 -#define CALL_STR_1 166 -#define CALL_TUPLE_1 167 -#define CALL_TYPE_1 168 -#define COMPARE_OP_FLOAT 169 -#define COMPARE_OP_INT 170 -#define COMPARE_OP_STR 171 -#define CONTAINS_OP_DICT 172 -#define CONTAINS_OP_SET 173 -#define FOR_ITER_GEN 174 -#define FOR_ITER_LIST 175 -#define FOR_ITER_RANGE 176 -#define FOR_ITER_TUPLE 177 -#define FOR_ITER_VIRTUAL 178 -#define GET_ITER_SELF 179 -#define GET_ITER_VIRTUAL 180 -#define JUMP_BACKWARD_JIT 181 -#define JUMP_BACKWARD_NO_JIT 182 -#define LOAD_ATTR_CLASS 183 -#define LOAD_ATTR_CLASS_WITH_METACLASS_CHECK 184 -#define LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN 185 -#define LOAD_ATTR_INSTANCE_VALUE 186 -#define LOAD_ATTR_METHOD_LAZY_DICT 187 -#define LOAD_ATTR_METHOD_NO_DICT 188 -#define LOAD_ATTR_METHOD_WITH_VALUES 189 -#define LOAD_ATTR_MODULE 190 -#define LOAD_ATTR_NONDESCRIPTOR_NO_DICT 191 -#define LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES 192 -#define LOAD_ATTR_PROPERTY 193 -#define LOAD_ATTR_SLOT 194 -#define LOAD_ATTR_WITH_HINT 195 -#define LOAD_GLOBAL_BUILTIN 196 -#define LOAD_GLOBAL_MODULE 197 -#define LOAD_SUPER_ATTR_ATTR 198 -#define LOAD_SUPER_ATTR_METHOD 199 -#define RESUME_CHECK 200 -#define RESUME_CHECK_JIT 201 -#define SEND_ASYNC_GEN 202 -#define SEND_GEN 203 -#define SEND_VIRTUAL 204 -#define STORE_ATTR_INSTANCE_VALUE 205 -#define STORE_ATTR_SLOT 206 -#define STORE_ATTR_WITH_HINT 207 -#define STORE_SUBSCR_DICT 208 -#define STORE_SUBSCR_LIST_INT 209 -#define TO_BOOL_ALWAYS_TRUE 210 -#define TO_BOOL_BOOL 211 -#define TO_BOOL_INT 212 -#define TO_BOOL_LIST 213 -#define TO_BOOL_NONE 214 -#define TO_BOOL_STR 215 -#define UNPACK_SEQUENCE_LIST 216 -#define UNPACK_SEQUENCE_TUPLE 217 -#define UNPACK_SEQUENCE_TWO_TUPLE 218 +#define CALL_BOUND_METHOD_EXACT_ARGS_AWAITED 146 +#define CALL_BOUND_METHOD_GENERAL 147 +#define CALL_BOUND_METHOD_GENERAL_AWAITED 148 +#define CALL_BUILTIN_CLASS 149 +#define CALL_BUILTIN_FAST 150 +#define CALL_BUILTIN_FAST_WITH_KEYWORDS 151 +#define CALL_BUILTIN_O 152 +#define CALL_EX_NON_PY_GENERAL 153 +#define CALL_EX_PY 154 +#define CALL_ISINSTANCE 155 +#define CALL_KW_BOUND_METHOD 156 +#define CALL_KW_BOUND_METHOD_AWAITED 157 +#define CALL_KW_NON_PY 158 +#define CALL_KW_PY 159 +#define CALL_KW_PY_AWAITED 160 +#define CALL_LEN 161 +#define CALL_LIST_APPEND 162 +#define CALL_METHOD_DESCRIPTOR_FAST 163 +#define CALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS 164 +#define CALL_METHOD_DESCRIPTOR_NOARGS 165 +#define CALL_METHOD_DESCRIPTOR_O 166 +#define CALL_NON_PY_GENERAL 167 +#define CALL_PY_EXACT_ARGS 168 +#define CALL_PY_EXACT_ARGS_AWAITED 169 +#define CALL_PY_GENERAL 170 +#define CALL_PY_GENERAL_AWAITED 171 +#define CALL_STR_1 172 +#define CALL_TUPLE_1 173 +#define CALL_TYPE_1 174 +#define COMPARE_OP_FLOAT 175 +#define COMPARE_OP_INT 176 +#define COMPARE_OP_STR 177 +#define CONTAINS_OP_DICT 178 +#define CONTAINS_OP_SET 179 +#define FOR_ITER_GEN 180 +#define FOR_ITER_LIST 181 +#define FOR_ITER_RANGE 182 +#define FOR_ITER_TUPLE 183 +#define FOR_ITER_VIRTUAL 184 +#define GET_ITER_SELF 185 +#define GET_ITER_VIRTUAL 186 +#define JUMP_BACKWARD_JIT 187 +#define JUMP_BACKWARD_NO_JIT 188 +#define LOAD_ATTR_CLASS 189 +#define LOAD_ATTR_CLASS_WITH_METACLASS_CHECK 190 +#define LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN 191 +#define LOAD_ATTR_INSTANCE_VALUE 192 +#define LOAD_ATTR_METHOD_LAZY_DICT 193 +#define LOAD_ATTR_METHOD_NO_DICT 194 +#define LOAD_ATTR_METHOD_WITH_VALUES 195 +#define LOAD_ATTR_MODULE 196 +#define LOAD_ATTR_NONDESCRIPTOR_NO_DICT 197 +#define LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES 198 +#define LOAD_ATTR_PROPERTY 199 +#define LOAD_ATTR_SLOT 200 +#define LOAD_ATTR_WITH_HINT 201 +#define LOAD_GLOBAL_BUILTIN 202 +#define LOAD_GLOBAL_MODULE 203 +#define LOAD_SUPER_ATTR_ATTR 204 +#define LOAD_SUPER_ATTR_METHOD 205 +#define RESUME_CHECK 206 +#define RESUME_CHECK_JIT 207 +#define SEND_ASYNC_GEN 208 +#define SEND_GEN 209 +#define SEND_VIRTUAL 210 +#define STORE_ATTR_INSTANCE_VALUE 211 +#define STORE_ATTR_SLOT 212 +#define STORE_ATTR_WITH_HINT 213 +#define STORE_SUBSCR_DICT 214 +#define STORE_SUBSCR_LIST_INT 215 +#define TO_BOOL_ALWAYS_TRUE 216 +#define TO_BOOL_BOOL 217 +#define TO_BOOL_INT 218 +#define TO_BOOL_LIST 219 +#define TO_BOOL_NONE 220 +#define TO_BOOL_STR 221 +#define UNPACK_SEQUENCE_LIST 222 +#define UNPACK_SEQUENCE_TUPLE 223 +#define UNPACK_SEQUENCE_TWO_TUPLE 224 #define INSTRUMENTED_END_FOR 233 #define INSTRUMENTED_POP_ITER 234 #define INSTRUMENTED_END_SEND 235 diff --git a/InternalDocs/generators.md b/InternalDocs/generators.md index fa652cd231cfa9..da2f7c6acc85cb 100644 --- a/InternalDocs/generators.md +++ b/InternalDocs/generators.md @@ -45,7 +45,43 @@ The generator's frame is initialized as a copy of the frame in which `RETURN_GENERATOR` is executing, but its `owner` field is overwritten to indicate that it is owned by a generator. Finally, `RETURN_GENERATOR` pushes the new generator object to the stack and returns to the caller of the generator function (at -which time its frame is destroyed). When the generator is next resumed by +which time its frame is destroyed). + +There is one exception: a coroutine function called by an awaited call +(`await f()` or the calls of `__aenter__` and `__aexit__` in `async with`: a +`CALL`, `CALL_KW` or `CALL_FUNCTION_EX` followed by `END_AWAITED_CALL`, see +`IS_AWAITED_CALL()`) sets `lazy_coro` to +`LAZY_CORO_REQUESTED` on its frame (see `MAYBE_START_LAZY_CORO()`). The +specializer gives such a call of a coroutine function an `*_AWAITED` form, +which does the same. `RETURN_GENERATOR` then pushes the body's own +`_PyErr_StackItem` on the data stack right after the frame, sets `lazy_coro` +to `LAZY_CORO_RUNNING`, moves the caller to its `END_AWAITED_CALL` (which has +the location of the `await`, like `SEND`) and keeps running the body in that +frame, so that a +body that returns or raises without suspending never creates a coroutine +object. A frame that unwinds before `RETURN_GENERATOR` (for example on +`RecursionError`) is cleared like any other. + +The compiler pushes an extra `NULL`, the `lazy_outcome`, below the callable of +an awaited call and follows the call with `END_AWAITED_CALL`, whose oparg jumps +to the `YIELD_VALUE` of the `SEND` loop for the await. A lazily run body reports +in `lazy_outcome` how it ended: + +- It returned: `clear_thread_frame()` stores a tagged int, and + `END_AWAITED_CALL` skips the `SEND` loop, jumping past the `END_SEND` that + the `SEND` right before `YIELD_VALUE` jumps to. +- It suspended: `YIELD_VALUE` leaves the frame and its `_PyErr_StackItem` on the + data stack and stores a pointer to the frame. `END_AWAITED_CALL` creates the + coroutine object, moves the frame and the exception state into it (see + `_PyEval_MaterializeLazyCoro()`) and jumps to `YIELD_VALUE` with the + coroutine, `NULL` and the yielded value on the stack, as `SEND` would have + left them. +- It raised: the exception is raised from the caller's `END_AWAITED_CALL`. + +Otherwise `lazy_outcome` stays `NULL`, and `END_AWAITED_CALL` pops it and goes +on to `GET_AWAITABLE`. + +When the generator is next resumed by [`gen_send_ex2()`](../Objects/genobject.c), `_PyEval_EvalFrame()` is called to continue executing the generator function, in the frame that is embedded in the generator object. diff --git a/Lib/_opcode_metadata.py b/Lib/_opcode_metadata.py index df92eae151d248..5584815a777cfe 100644 --- a/Lib/_opcode_metadata.py +++ b/Lib/_opcode_metadata.py @@ -120,11 +120,17 @@ "CALL_PY_GENERAL", "CALL_BOUND_METHOD_GENERAL", "CALL_NON_PY_GENERAL", + "CALL_PY_EXACT_ARGS_AWAITED", + "CALL_BOUND_METHOD_EXACT_ARGS_AWAITED", + "CALL_PY_GENERAL_AWAITED", + "CALL_BOUND_METHOD_GENERAL_AWAITED", ), CALL_KW=( "CALL_KW_BOUND_METHOD", "CALL_KW_PY", "CALL_KW_NON_PY", + "CALL_KW_PY_AWAITED", + "CALL_KW_BOUND_METHOD_AWAITED", ), CALL_FUNCTION_EX=( "CALL_EX_PY", @@ -151,79 +157,85 @@ BINARY_OP_SUBTRACT_INT=143, CALL_ALLOC_AND_ENTER_INIT=144, CALL_BOUND_METHOD_EXACT_ARGS=145, - CALL_BOUND_METHOD_GENERAL=146, - CALL_BUILTIN_CLASS=147, - CALL_BUILTIN_FAST=148, - CALL_BUILTIN_FAST_WITH_KEYWORDS=149, - CALL_BUILTIN_O=150, - CALL_EX_NON_PY_GENERAL=151, - CALL_EX_PY=152, - CALL_ISINSTANCE=153, - CALL_KW_BOUND_METHOD=154, - CALL_KW_NON_PY=155, - CALL_KW_PY=156, - CALL_LEN=157, - CALL_LIST_APPEND=158, - CALL_METHOD_DESCRIPTOR_FAST=159, - CALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS=160, - CALL_METHOD_DESCRIPTOR_NOARGS=161, - CALL_METHOD_DESCRIPTOR_O=162, - CALL_NON_PY_GENERAL=163, - CALL_PY_EXACT_ARGS=164, - CALL_PY_GENERAL=165, - CALL_STR_1=166, - CALL_TUPLE_1=167, - CALL_TYPE_1=168, - COMPARE_OP_FLOAT=169, - COMPARE_OP_INT=170, - COMPARE_OP_STR=171, - CONTAINS_OP_DICT=172, - CONTAINS_OP_SET=173, - FOR_ITER_GEN=174, - FOR_ITER_LIST=175, - FOR_ITER_RANGE=176, - FOR_ITER_TUPLE=177, - FOR_ITER_VIRTUAL=178, - GET_ITER_SELF=179, - GET_ITER_VIRTUAL=180, - JUMP_BACKWARD_JIT=181, - JUMP_BACKWARD_NO_JIT=182, - LOAD_ATTR_CLASS=183, - LOAD_ATTR_CLASS_WITH_METACLASS_CHECK=184, - LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN=185, - LOAD_ATTR_INSTANCE_VALUE=186, - LOAD_ATTR_METHOD_LAZY_DICT=187, - LOAD_ATTR_METHOD_NO_DICT=188, - LOAD_ATTR_METHOD_WITH_VALUES=189, - LOAD_ATTR_MODULE=190, - LOAD_ATTR_NONDESCRIPTOR_NO_DICT=191, - LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES=192, - LOAD_ATTR_PROPERTY=193, - LOAD_ATTR_SLOT=194, - LOAD_ATTR_WITH_HINT=195, - LOAD_GLOBAL_BUILTIN=196, - LOAD_GLOBAL_MODULE=197, - LOAD_SUPER_ATTR_ATTR=198, - LOAD_SUPER_ATTR_METHOD=199, - RESUME_CHECK=200, - RESUME_CHECK_JIT=201, - SEND_ASYNC_GEN=202, - SEND_GEN=203, - SEND_VIRTUAL=204, - STORE_ATTR_INSTANCE_VALUE=205, - STORE_ATTR_SLOT=206, - STORE_ATTR_WITH_HINT=207, - STORE_SUBSCR_DICT=208, - STORE_SUBSCR_LIST_INT=209, - TO_BOOL_ALWAYS_TRUE=210, - TO_BOOL_BOOL=211, - TO_BOOL_INT=212, - TO_BOOL_LIST=213, - TO_BOOL_NONE=214, - TO_BOOL_STR=215, - UNPACK_SEQUENCE_LIST=216, - UNPACK_SEQUENCE_TUPLE=217, - UNPACK_SEQUENCE_TWO_TUPLE=218, + CALL_BOUND_METHOD_EXACT_ARGS_AWAITED=146, + CALL_BOUND_METHOD_GENERAL=147, + CALL_BOUND_METHOD_GENERAL_AWAITED=148, + CALL_BUILTIN_CLASS=149, + CALL_BUILTIN_FAST=150, + CALL_BUILTIN_FAST_WITH_KEYWORDS=151, + CALL_BUILTIN_O=152, + CALL_EX_NON_PY_GENERAL=153, + CALL_EX_PY=154, + CALL_ISINSTANCE=155, + CALL_KW_BOUND_METHOD=156, + CALL_KW_BOUND_METHOD_AWAITED=157, + CALL_KW_NON_PY=158, + CALL_KW_PY=159, + CALL_KW_PY_AWAITED=160, + CALL_LEN=161, + CALL_LIST_APPEND=162, + CALL_METHOD_DESCRIPTOR_FAST=163, + CALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS=164, + CALL_METHOD_DESCRIPTOR_NOARGS=165, + CALL_METHOD_DESCRIPTOR_O=166, + CALL_NON_PY_GENERAL=167, + CALL_PY_EXACT_ARGS=168, + CALL_PY_EXACT_ARGS_AWAITED=169, + CALL_PY_GENERAL=170, + CALL_PY_GENERAL_AWAITED=171, + CALL_STR_1=172, + CALL_TUPLE_1=173, + CALL_TYPE_1=174, + COMPARE_OP_FLOAT=175, + COMPARE_OP_INT=176, + COMPARE_OP_STR=177, + CONTAINS_OP_DICT=178, + CONTAINS_OP_SET=179, + FOR_ITER_GEN=180, + FOR_ITER_LIST=181, + FOR_ITER_RANGE=182, + FOR_ITER_TUPLE=183, + FOR_ITER_VIRTUAL=184, + GET_ITER_SELF=185, + GET_ITER_VIRTUAL=186, + JUMP_BACKWARD_JIT=187, + JUMP_BACKWARD_NO_JIT=188, + LOAD_ATTR_CLASS=189, + LOAD_ATTR_CLASS_WITH_METACLASS_CHECK=190, + LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN=191, + LOAD_ATTR_INSTANCE_VALUE=192, + LOAD_ATTR_METHOD_LAZY_DICT=193, + LOAD_ATTR_METHOD_NO_DICT=194, + LOAD_ATTR_METHOD_WITH_VALUES=195, + LOAD_ATTR_MODULE=196, + LOAD_ATTR_NONDESCRIPTOR_NO_DICT=197, + LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES=198, + LOAD_ATTR_PROPERTY=199, + LOAD_ATTR_SLOT=200, + LOAD_ATTR_WITH_HINT=201, + LOAD_GLOBAL_BUILTIN=202, + LOAD_GLOBAL_MODULE=203, + LOAD_SUPER_ATTR_ATTR=204, + LOAD_SUPER_ATTR_METHOD=205, + RESUME_CHECK=206, + RESUME_CHECK_JIT=207, + SEND_ASYNC_GEN=208, + SEND_GEN=209, + SEND_VIRTUAL=210, + STORE_ATTR_INSTANCE_VALUE=211, + STORE_ATTR_SLOT=212, + STORE_ATTR_WITH_HINT=213, + STORE_SUBSCR_DICT=214, + STORE_SUBSCR_LIST_INT=215, + TO_BOOL_ALWAYS_TRUE=216, + TO_BOOL_BOOL=217, + TO_BOOL_INT=218, + TO_BOOL_LIST=219, + TO_BOOL_NONE=220, + TO_BOOL_STR=221, + UNPACK_SEQUENCE_LIST=222, + UNPACK_SEQUENCE_TUPLE=223, + UNPACK_SEQUENCE_TWO_TUPLE=224, ) opmap = frozendict( @@ -294,59 +306,60 @@ DICT_MERGE=61, DICT_UPDATE=62, END_ASYNC_FOR=63, - EXTENDED_ARG=64, - FOR_ITER=65, - GET_AWAITABLE=66, - GET_ITER=67, - IMPORT_FROM=68, - IMPORT_NAME=69, - IS_OP=70, - JUMP_BACKWARD=71, - JUMP_BACKWARD_NO_INTERRUPT=72, - JUMP_FORWARD=73, - LIST_APPEND=74, - LIST_EXTEND=75, - LOAD_ATTR=76, - LOAD_COMMON_CONSTANT=77, - LOAD_CONST=78, - LOAD_DEREF=79, - LOAD_FAST=80, - LOAD_FAST_AND_CLEAR=81, - LOAD_FAST_BORROW=82, - LOAD_FAST_BORROW_LOAD_FAST_BORROW=83, - LOAD_FAST_CHECK=84, - LOAD_FAST_LOAD_FAST=85, - LOAD_FROM_DICT_OR_DEREF=86, - LOAD_FROM_DICT_OR_GLOBALS=87, - LOAD_GLOBAL=88, - LOAD_NAME=89, - LOAD_SMALL_INT=90, - LOAD_SPECIAL=91, - LOAD_SUPER_ATTR=92, - MAKE_CELL=93, - MAP_ADD=94, - MATCH_CLASS=95, - POP_JUMP_IF_FALSE=96, - POP_JUMP_IF_NONE=97, - POP_JUMP_IF_NOT_NONE=98, - POP_JUMP_IF_TRUE=99, - RAISE_VARARGS=100, - RERAISE=101, - SEND=102, - SET_ADD=103, - SET_FUNCTION_ATTRIBUTE=104, - SET_UPDATE=105, - STORE_ATTR=106, - STORE_DEREF=107, - STORE_FAST=108, - STORE_FAST_LOAD_FAST=109, - STORE_FAST_STORE_FAST=110, - STORE_GLOBAL=111, - STORE_NAME=112, - SWAP=113, - UNPACK_EX=114, - UNPACK_SEQUENCE=115, - YIELD_VALUE=116, + END_AWAITED_CALL=64, + EXTENDED_ARG=65, + FOR_ITER=66, + GET_AWAITABLE=67, + GET_ITER=68, + IMPORT_FROM=69, + IMPORT_NAME=70, + IS_OP=71, + JUMP_BACKWARD=72, + JUMP_BACKWARD_NO_INTERRUPT=73, + JUMP_FORWARD=74, + LIST_APPEND=75, + LIST_EXTEND=76, + LOAD_ATTR=77, + LOAD_COMMON_CONSTANT=78, + LOAD_CONST=79, + LOAD_DEREF=80, + LOAD_FAST=81, + LOAD_FAST_AND_CLEAR=82, + LOAD_FAST_BORROW=83, + LOAD_FAST_BORROW_LOAD_FAST_BORROW=84, + LOAD_FAST_CHECK=85, + LOAD_FAST_LOAD_FAST=86, + LOAD_FROM_DICT_OR_DEREF=87, + LOAD_FROM_DICT_OR_GLOBALS=88, + LOAD_GLOBAL=89, + LOAD_NAME=90, + LOAD_SMALL_INT=91, + LOAD_SPECIAL=92, + LOAD_SUPER_ATTR=93, + MAKE_CELL=94, + MAP_ADD=95, + MATCH_CLASS=96, + POP_JUMP_IF_FALSE=97, + POP_JUMP_IF_NONE=98, + POP_JUMP_IF_NOT_NONE=99, + POP_JUMP_IF_TRUE=100, + RAISE_VARARGS=101, + RERAISE=102, + SEND=103, + SET_ADD=104, + SET_FUNCTION_ATTRIBUTE=105, + SET_UPDATE=106, + STORE_ATTR=107, + STORE_DEREF=108, + STORE_FAST=109, + STORE_FAST_LOAD_FAST=110, + STORE_FAST_STORE_FAST=111, + STORE_GLOBAL=112, + STORE_NAME=113, + SWAP=114, + UNPACK_EX=115, + UNPACK_SEQUENCE=116, + YIELD_VALUE=117, INSTRUMENTED_END_FOR=233, INSTRUMENTED_POP_ITER=234, INSTRUMENTED_END_SEND=235, diff --git a/Lib/asyncio/graph.py b/Lib/asyncio/graph.py index d76d2f6383343d..f18bb7611d85dd 100644 --- a/Lib/asyncio/graph.py +++ b/Lib/asyncio/graph.py @@ -1,6 +1,7 @@ """Introspection utils for tasks call graphs.""" import dataclasses +import inspect import io import operator import sys @@ -38,6 +39,24 @@ class FutureCallGraph: awaited_by: tuple["FutureCallGraph", ...] +# f_generator is None until a lazily started coroutine first suspends. +_CO_ASYNC_FLAGS = inspect.CO_COROUTINE | inspect.CO_ASYNC_GENERATOR +_CO_GEN_FLAGS = _CO_ASYNC_FLAGS | inspect.CO_GENERATOR +_FRAME_TAGS = { + inspect.CO_COROUTINE: 'async ', + inspect.CO_ASYNC_GENERATOR: 'async generator ', + inspect.CO_GENERATOR: 'generator ', +} + + +def _is_async_frame(f): + return bool(f.f_code.co_flags & _CO_ASYNC_FLAGS) + + +def _is_sync_frame(f): + return not (f.f_code.co_flags & _CO_GEN_FLAGS) + + def _build_graph_for_future( future: futures.Future, *, @@ -166,12 +185,10 @@ def capture_call_graph( try: while f is not None: # gh-156988: sync gen should not clear the call chain - is_async = isinstance( - f.f_generator, (types.CoroutineType, types.AsyncGeneratorType)) call_stack.append(FrameCallGraphEntry(f)) - if is_async: - if f.f_back is not None and f.f_back.f_generator is None: + if _is_async_frame(f): + if f.f_back is not None and _is_sync_frame(f.f_back): # We've reached the bottom of the coroutine stack, which # must be the Task that runs it. break @@ -228,36 +245,12 @@ def add_line(line: str) -> None: ) for ste in st.call_stack: f = ste.frame - - if f.f_generator is None: - f = ste.frame - add_line( - f' | File {f.f_code.co_filename!r},' - f' line {f.f_lineno}, in' - f' {f.f_code.co_qualname}()' - ) - else: - c = f.f_generator - - try: - f = c.cr_frame - code = c.cr_code - tag = 'async' - except AttributeError: - try: - f = c.ag_frame - code = c.ag_code - tag = 'async generator' - except AttributeError: - f = c.gi_frame - code = c.gi_code - tag = 'generator' - - add_line( - f' | File {f.f_code.co_filename!r},' - f' line {f.f_lineno}, in' - f' {tag} {code.co_qualname}()' - ) + tag = _FRAME_TAGS.get(f.f_code.co_flags & _CO_GEN_FLAGS, '') + add_line( + f' | File {f.f_code.co_filename!r},' + f' line {f.f_lineno}, in' + f' {tag}{f.f_code.co_qualname}()' + ) if st.awaited_by: add_line( diff --git a/Lib/test/test__opcode.py b/Lib/test/test__opcode.py index c253bc2be025a0..3a689d5e7010b4 100644 --- a/Lib/test/test__opcode.py +++ b/Lib/test/test__opcode.py @@ -91,6 +91,10 @@ def test_stack_effect_jump(self): self.assertEqual(stack_effect(JUMP_FORWARD, 0), 0) self.assertEqual(stack_effect(JUMP_FORWARD, 0, jump=True), 0) self.assertEqual(stack_effect(JUMP_FORWARD, 0, jump=False), 0) + END_AWAITED_CALL = dis.opmap['END_AWAITED_CALL'] + self.assertEqual(stack_effect(END_AWAITED_CALL, 0), 1) + self.assertEqual(stack_effect(END_AWAITED_CALL, 0, jump=True), 1) + self.assertEqual(stack_effect(END_AWAITED_CALL, 0, jump=False), -1) # All defined opcodes has_arg = dis.hasarg has_exc = dis.hasexc diff --git a/Lib/test/test_asyncio/test_graph.py b/Lib/test/test_asyncio/test_graph.py index 1f1c76e4aef69f..8df17a2a87de3c 100644 --- a/Lib/test/test_asyncio/test_graph.py +++ b/Lib/test/test_asyncio/test_graph.py @@ -1,4 +1,5 @@ import asyncio +import inspect import io import sys import types @@ -20,19 +21,22 @@ def walk(s): if isinstance(s.future, asyncio.Task) else 'F' ] + def tag(frame): + # f_generator is None until a lazily started coroutine + # first suspends. + flags = frame.f_code.co_flags + if flags & inspect.CO_COROUTINE: + return "a" + if flags & inspect.CO_ASYNC_GENERATOR: + return "ag" + if flags & inspect.CO_GENERATOR: + return "g" + return "s" + ret.append( [ - ( - f"s {entry.frame.f_code.co_name}" - if entry.frame.f_generator is None else - ( - f"a {entry.frame.f_generator.cr_code.co_name}" - if hasattr(entry.frame.f_generator, 'cr_code') else - f"ag {entry.frame.f_generator.ag_code.co_name}" - if hasattr(entry.frame.f_generator, 'ag_code') else - f"g {entry.frame.f_generator.gi_code.co_name}" - ) - ) for entry in s.call_stack + f"{tag(entry.frame)} {entry.frame.f_code.co_name}" + for entry in s.call_stack # Skip the pure Python Future.__await__ generator frame if entry.frame.f_code is not future_await_code ] @@ -986,6 +990,26 @@ async def child(): self.assertEqual(stack[0][2], [['T', ['a test_stack_eager_task'], []]]) + async def test_capture_call_graph_through_generator_based_coroutine(self): + # A native coroutine driven by a generator-based coroutine + # (yield from) keeps the frames of its callers. + stack = None + + async def native(): + nonlocal stack + graph = asyncio.capture_call_graph() + stack = [entry.frame.f_code.co_name for entry in graph.call_stack] + + @types.coroutine + def legacy(): + return (yield from native()) + + async def main(): + await legacy() + + await main() + self.assertEqual(stack[:3], ['native', 'legacy', 'main']) + @unittest.skipIf( not hasattr(asyncio.futures, "_c_future_add_to_awaited_by"), diff --git a/Lib/test/test_capi/test_opt.py b/Lib/test/test_capi/test_opt.py index 88077aacecbf5b..174d8c7e71aebe 100644 --- a/Lib/test/test_capi/test_opt.py +++ b/Lib/test/test_capi/test_opt.py @@ -188,6 +188,44 @@ class TestUops(unittest.TestCase): def setUp(self): self.guard_is_false, self.guard_is_true = get_bool_guard_ops() + def test_awaited_call_jump_not_traced(self): + # Tier two runs only END_AWAITED_CALL's fall-through: no trace may + # continue past END_SEND after a lazily started coroutine returned. + async def body(): + t = 0 + for i in range(2): + t += i + return t + + async def main(): + x = await body() + return x + 1 + + def run(): + coro = main() + try: + coro.send(None) + except StopIteration as exc: + return exc.value + return "suspended" + + offset = next(i.offset for i in dis.get_instructions(main) + if i.opname == "END_AWAITED_CALL") + enter_executor = dis.opmap["ENTER_EXECUTOR"] + for _ in range(30_000): # Long enough to chain side exits. + self.assertEqual(run(), 2) + if main.__code__._co_code_adaptive[offset] == enter_executor: + break + # Origin tracking makes the coroutine start eagerly. + old_depth = sys.get_coroutine_origin_tracking_depth() + sys.set_coroutine_origin_tracking_depth(1) + try: + self.assertEqual(run(), 2) + finally: + sys.set_coroutine_origin_tracking_depth(old_depth) + self.assertNotEqual(main.__code__._co_code_adaptive[offset], + enter_executor) + def test_basic_loop(self): def testfunc(x): i = 0 diff --git a/Lib/test/test_coroutines.py b/Lib/test/test_coroutines.py index c5900da09501b3..865b0db28f554e 100644 --- a/Lib/test/test_coroutines.py +++ b/Lib/test/test_coroutines.py @@ -1,6 +1,8 @@ import ast import contextlib import copy +import builtins +import gc import inspect import pickle import sys @@ -2594,6 +2596,855 @@ def test_unawaited_warning_during_shutdown(self): assert_python_ok("-c", code) +@support.cpython_only +class LazyCoroutineTest(unittest.TestCase): + """A coroutine that is awaited right away (``await f()``) runs in + the calling thread's frame and only gets a coroutine object when + it first suspends. This must not be observable, except that no + coroutine object exists before the first suspension.""" + + @staticmethod + def coroutines_for(code): + return [o for o in gc.get_objects() + if type(o) is types.CoroutineType and o.cr_code is code] + + def test_no_object_before_first_suspension(self): + seen = [] + + async def inner(): + seen.append(len(self.coroutines_for(inner.__code__))) + await AsyncYield(1) + seen.append(len(self.coroutines_for(inner.__code__))) + return 42 + + async def outer(): + return await inner() + + self.assertEqual(run_async(outer()), ([1], 42)) + self.assertEqual(seen, [0, 1]) + + def test_return_without_suspending(self): + async def inner(x): + return x + 1 + + async def outer(): + total = 0 + for i in range(100): + total += await inner(i) + return total + + self.assertEqual(run_async(outer()), ([], sum(range(1, 101)))) + + def test_nested_chain(self): + async def chain(n): + if n == 0: + await AsyncYield("bottom") + return 0 + return 1 + await chain(n - 1) + + self.assertEqual(run_async(chain(20)), (["bottom"], 20)) + + def test_exception_before_first_suspension(self): + async def inner(): + raise ValueError("boom") + + async def outer(): + try: + await inner() + except ValueError as exc: + tb = exc.__traceback__ + names = [] + while tb is not None: + names.append(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + return names + + self.assertEqual(run_async(outer()), ([], ["outer", "inner"])) + + def test_stopiteration_before_first_suspension(self): + async def inner(): + raise StopIteration + + async def outer(): + await inner() + + with self.assertRaisesRegex(RuntimeError, + "coroutine raised StopIteration"): + run_async(outer()) + + def test_frame_object(self): + async def inner(): + x = 1 + frame = sys._getframe() + self.assertIsNone(frame.f_generator) + self.assertEqual(frame.f_locals["x"], 1) + self.assertEqual(frame.f_back.f_code.co_name, "outer") + await AsyncYield(1) + coro = frame.f_generator + self.assertIsInstance(coro, types.CoroutineType) + self.assertIs(coro.cr_frame, frame) + self.assertIs(coro.cr_code, inner.__code__) + self.assertEqual(frame.f_locals["x"], 1) + self.assertEqual(frame.f_back.f_code.co_name, "outer") + x = 2 + return frame + + async def outer(): + return await inner() + + _, frame = run_async(outer()) + self.assertIsNone(frame.f_generator) # finished + self.assertEqual(frame.f_locals["x"], 2) + + def test_exc_info_suspend_inside_handler(self): + async def inner(): + try: + raise KeyError + except KeyError: + await AsyncYield(1) + self.assertIsInstance(sys.exc_info()[1], KeyError) + await AsyncYield(2) + self.assertIsInstance(sys.exc_info()[1], KeyError) + # The caller's context is visible after the handler. + self.assertIsInstance(sys.exc_info()[1], TypeError) + await AsyncYield(3) + self.assertIsInstance(sys.exc_info()[1], TypeError) + return "ok" + + async def outer(): + try: + raise TypeError + except TypeError: + result = await inner() + self.assertIsInstance(sys.exc_info()[1], TypeError) + self.assertIsNone(sys.exc_info()[1]) + return result + + self.assertEqual(run_async(outer()), ([1, 2, 3], "ok")) + + def test_exc_info_handler_without_suspending(self): + async def inner(): + try: + raise KeyError + except KeyError: + self.assertIsInstance(sys.exc_info()[1], KeyError) + self.assertIsInstance(sys.exc_info()[1], TypeError) + return "ok" + + async def outer(): + try: + raise TypeError + except TypeError: + result = await inner() + self.assertIsInstance(sys.exc_info()[1], TypeError) + self.assertIsNone(sys.exc_info()[1]) + return result + + self.assertEqual(run_async(outer()), ([], "ok")) + + def test_throw_into_materialized_coroutine(self): + async def inner(): + try: + await AsyncYield(1) + except ZeroDivisionError: + return "caught" + return "not caught" + + async def outer(): + return await inner() + + coro = outer() + self.assertEqual(coro.send(None), 1) + with self.assertRaises(StopIteration) as cm: + coro.throw(ZeroDivisionError) + self.assertEqual(cm.exception.value, "caught") + + def test_close_materialized_coroutine(self): + closed = [] + + async def inner(): + try: + await AsyncYield(1) + finally: + closed.append(True) + + async def outer(): + await inner() + + coro = outer() + self.assertEqual(coro.send(None), 1) + coro.close() + self.assertEqual(closed, [True]) + + def test_async_with(self): + log = [] + + class CM: + async def __aenter__(self): + log.append("enter") + return self + + async def __aexit__(self, *args): + log.append("exit") + return False + + async def outer(): + async with CM() as cm: + log.append(type(cm).__name__) + await AsyncYield(1) + return "done" + + self.assertEqual(run_async(outer()), ([1], "done")) + self.assertEqual(log, ["enter", "CM", "exit"]) + + def test_async_with_lazy(self): + log = [] + + class CM: + def __init__(self, suspend=False, suppress=False): + self.suspend = suspend + self.suppress = suppress + + async def __aenter__(self): + log.append(("enter", sys._getframe().f_generator is None)) + if self.suspend: + await AsyncYield("enter") + return self + + async def __aexit__(self, typ, *args): + log.append(("exit", typ, sys._getframe().f_generator is None)) + if self.suspend: + await AsyncYield("exit") + return self.suppress + + async def body(cm): + async with cm: + return "returned" + + async def loop(cm): + for i in range(2): + async with cm: + if i == 0: + continue + break + return "looped" + + async def nested(cm): + async with cm, cm as x: + pass + return x + + async def raises(cm): + async with cm: + raise ValueError + return "suppressed" + + for suspend in False, True: + with self.subTest(suspend=suspend): + y = ["enter", "exit"] if suspend else [] + lazy = [("enter", True), ("exit", None, True)] + log.clear() + self.assertEqual(run_async(body(CM(suspend))), (y, "returned")) + self.assertEqual(log, lazy) + log.clear() + self.assertEqual(run_async(loop(CM(suspend))), (y * 2, "looped")) + self.assertEqual(log, lazy * 2) + log.clear() + cm = CM(suspend) + self.assertEqual(run_async(nested(cm)), (y[:1] * 2 + y[1:] * 2, cm)) + self.assertEqual(log, [lazy[0], lazy[0], lazy[1], lazy[1]]) + # WITH_EXCEPT_START calls __aexit__() eagerly. + log.clear() + self.assertEqual(run_async(raises(CM(suspend, True))), + (y, "suppressed")) + self.assertEqual(log, [("enter", True), ("exit", ValueError, False)]) + log.clear() + with self.assertRaises(ValueError): + run_async(raises(CM(suspend))) + + def test_async_comprehension(self): + async def inner(x): + return x * 2 + + async def outer(): + return [await inner(x) for x in range(5)] + + self.assertEqual(run_async(outer()), ([], [0, 2, 4, 6, 8])) + + def test_origin_tracking(self): + orig_depth = sys.get_coroutine_origin_tracking_depth() + + async def inner(): + await AsyncYield(1) + return sys._getframe().f_generator.cr_origin + + async def outer(): + coro = inner() + eager = (await coro)[0] + lazy = (await inner())[0] + return eager, lazy + + sys.set_coroutine_origin_tracking_depth(2) + try: + _, (eager, lazy) = run_async(outer()) + finally: + sys.set_coroutine_origin_tracking_depth(orig_depth) + # Origin tracking disables the lazy path: the origin is the + # call, not the await, and is captured at creation. + self.assertEqual(eager[0], __file__) + self.assertEqual(eager[2], "outer") + self.assertEqual(lazy[0], __file__) + self.assertEqual(lazy[2], "outer") + self.assertEqual(lazy[1], eager[1] + 2) + + def test_origin_tracking_multiline_await(self): + orig_depth = sys.get_coroutine_origin_tracking_depth() + + async def inner(): + await AsyncYield(1) + return sys._getframe().f_generator.cr_origin + + async def outer(): + origin = await ( + inner() + ) + return origin[0][1] - outer.__code__.co_firstlineno + + sys.set_coroutine_origin_tracking_depth(1) + try: + _, line = run_async(outer()) + finally: + sys.set_coroutine_origin_tracking_depth(orig_depth) + # The line of the call, not of the await. + self.assertEqual(line, 2) + + def test_settrace_events(self): + async def inner(): + await AsyncYield(1) + return 1 + + async def eager(): + coro = inner() + return await coro + + async def lazy(): + return await inner() + + def trace(coro_fn): + events = [] + + def tracer(frame, event, arg): + if frame.f_code is inner.__code__: + events.append((event, frame.f_lineno - frame.f_code.co_firstlineno)) + return tracer + + sys.settrace(tracer) + try: + result = run_async(coro_fn()) + finally: + sys.settrace(None) + return events, result + + self.assertEqual(trace(lazy), trace(eager)) + + def test_monitoring_events(self): + async def inner(): + await AsyncYield(1) + return 1 + + async def eager(): + coro = inner() + return await coro + + async def lazy(): + return await inner() + + E = sys.monitoring.events + # No LINE events: eager() has one more line. + names = {E.PY_START: "start", E.PY_RESUME: "resume", + E.PY_RETURN: "return", E.PY_YIELD: "yield", + E.STOP_ITERATION: "stop_iteration"} + codes = {inner.__code__: "inner", eager.__code__: "outer", + lazy.__code__: "outer"} + + def monitor(coro_fn): + events = [] + tool = sys.monitoring.DEBUGGER_ID + sys.monitoring.use_tool_id(tool, "test") + try: + for event, name in names.items(): + def callback(code, offset, *args, name=name): + if code in codes: + events.append( + (codes[code], name, type(args[-1]) if args else None)) + sys.monitoring.register_callback(tool, event, callback) + sys.monitoring.set_events(tool, sum(names)) + result = run_async(coro_fn()) + finally: + sys.monitoring.set_events(tool, 0) + sys.monitoring.free_tool_id(tool) + return events, result + + self.assertEqual(monitor(lazy), monitor(eager)) + self.assertIn(("outer", "stop_iteration", StopIteration), + monitor(lazy)[0]) + + def test_stop_iteration_event_without_suspending(self): + async def inner(): + return 42 + + async def outer(): + return await inner() + + E = sys.monitoring.events + events = [] + tool = sys.monitoring.DEBUGGER_ID + sys.monitoring.use_tool_id(tool, "test") + try: + def callback(code, offset, exc): + if code is outer.__code__: + events.append(exc.value) + sys.monitoring.register_callback(tool, E.STOP_ITERATION, callback) + sys.monitoring.set_events(tool, E.STOP_ITERATION) + self.assertEqual(run_async(outer()), ([], 42)) + finally: + sys.monitoring.set_events(tool, 0) + sys.monitoring.free_tool_id(tool) + self.assertEqual(events, [42]) + + def test_exc_state_after_suspending_inside_handler(self): + # The coroutine's own exception state must not keep the + # caller's exception once its handler is done. + async def inner(): + try: + raise KeyError + except KeyError: + await AsyncYield(1) + await AsyncYield(2) + return sys.exc_info()[1] + + async def outer(): + try: + raise TypeError + except TypeError: + return await inner() + + coro = outer() + coro.send(None) + inner_coro = coro.cr_await + inner_coro.send(None) + self.assertNotIn(TypeError, + map(type, gc.get_referents(inner_coro))) + # Resumed directly, not through outer: no handled exception. + with self.assertRaises(StopIteration) as cm: + inner_coro.send(None) + self.assertIsNone(cm.exception.value) + coro.close() + + def test_throw_into_coroutine_suspended_inside_handler(self): + async def inner(): + try: + raise KeyError + except KeyError: + try: + await AsyncYield(1) + except ZeroDivisionError: + pass + return sys.exception() + + async def outer(): + try: + raise TypeError + except TypeError: + result = await inner() + self.assertIsInstance(sys.exception(), TypeError) + return result + + coro = outer() + self.assertEqual(coro.send(None), 1) + with self.assertRaises(StopIteration) as cm: + coro.throw(ZeroDivisionError) + self.assertIsNone(cm.exception.value) + + def test_import_hook_locals(self): + seen = [] + orig_import = builtins.__import__ + + def hook(name, globals=None, locals=None, fromlist=(), level=0): + seen.append(locals) + return orig_import(name, globals, locals, fromlist, level) + + async def inner(): + import sys as _sys + return _sys + + async def outer(): + try: + raise TypeError + except TypeError: + return await inner() + + with support.swap_attr(builtins, "__import__", hook): + self.assertEqual(run_async(outer()), ([], sys)) + self.assertEqual(seen, [None]) + + def test_traceback_frame_keeps_no_caller_exception(self): + async def inner(): + raise ValueError + + async def outer(): + try: + raise TypeError + except TypeError: + try: + await inner() + except ValueError as exc: + return exc.__traceback__.tb_next.tb_frame + + _, frame = run_async(outer()) + self.assertIs(frame.f_code, inner.__code__) + self.assertNotIn(TypeError, map(type, gc.get_referents(frame))) + + def test_code_replaced_before_first_suspension(self): + # The coroutine object is created at the first suspension, so it + # must be sized for the code the frame runs, not func.__code__. + async def small(): + big, small # same free variables as big() + await AsyncYield(1) + + async def big(): + a = b = c = d = e = f = g = h = i = j = k = m = n = o = p = 1 + big.__code__ = small.__code__ + await AsyncYield(1) + return (a, b, c, d, e, f, g, h, i, j, k, m, n, o, p) + + async def outer(): + return await big() + + self.assertEqual(run_async(outer()), ([1], (1,) * 15)) + + def test_finished_frame_has_no_f_back(self): + async def inner(): + return sys._getframe() + + async def outer(): + return await inner() + + _, frame = run_async(outer()) + self.assertIs(frame.f_code, inner.__code__) + self.assertIsNone(frame.f_back) + + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_memory_error_at_first_suspension(self): + @types.coroutine + def suspend(): + yield 1 + + class CM: + async def __aenter__(self): + log.append("enter") + async def __aexit__(self, typ, *args): + log.append(("exit", typ)) + + log = [] + awaitable = suspend() + + async def inner(): + async with CM(): + _testcapi.set_nomemory(0, 1) + try: + await awaitable + finally: + _testcapi.remove_mem_hooks() + log.append("finally") + return "resumed" + + async def outer(): + return await inner() + + coro = outer() + try: + with self.assertRaises(MemoryError): + coro.send(None) + finally: + _testcapi.remove_mem_hooks() + awaitable.close() + self.assertEqual(log, ["enter", "finally", ("exit", MemoryError)]) + + def test_recursion_error_before_body_runs(self): + async def f(): + return await f() + + coro = f() + with support.infinite_recursion(50): + with self.assertRaises(RecursionError): + coro.send(None) + + def test_memory_error_before_body_runs(self): + # MAKE_CELL runs before RETURN_GENERATOR. + async def inner(x): + def g(): + return x + return g + + async def outer(): + _testcapi.set_nomemory(0, 1) + try: + await inner(1) + except MemoryError: + return "MemoryError" + finally: + _testcapi.remove_mem_hooks() + + self.assertEqual(run_async(outer()), ([], "MemoryError")) + + def test_caller_location_while_body_runs(self): + positions = [] + + async def inner(): + caller = sys._getframe(1) + positions.append( + list(caller.f_code.co_positions())[caller.f_lasti // 2]) + + async def outer(): + x = (await + inner()) + + run_async(outer()) + line = outer.__code__.co_firstlineno + 1 + self.assertEqual(positions, [(line, line + 1, 17, 24)]) + + def test_origin_tracking_enabled_in_body(self): + @types.coroutine + def suspend(): + yield + + async def inner(): + sys.set_coroutine_origin_tracking_depth(5) + await suspend() + + async def outer(): + await inner() + + coro = outer() + try: + coro.send(None) + self.assertIsNone(coro.cr_await.cr_origin) + finally: + sys.set_coroutine_origin_tracking_depth(0) + coro.close() + + def test_coroutine_flag_without_coroutine_body(self): + def f(): + return 42 + code = f.__code__.replace(co_flags=f.__code__.co_flags | inspect.CO_COROUTINE) + g = types.FunctionType(code, globals()) + + async def outer(): + return await g() + + with self.assertRaisesRegex(TypeError, "can't be awaited"): + run_async(outer()) + + def test_line_events_at_awaited_call_jump_target(self): + # The list(genexpr) fast path jumps to END_AWAITED_CALL. + async def list(arg): + await AsyncYield("suspended") + return "done" + + async def outer(): + x = (await + list(i for i in range(3))) + return x + + def tracer(frame, event, arg): + if event == "line" and frame.f_code is outer.__code__: + gc.collect() + return tracer + + for _ in range(100): # Specialize the call. + run_async(outer()) + old_trace = sys.gettrace() + sys.settrace(tracer) + try: + self.assertEqual(run_async(outer()), (["suspended"], "done")) + finally: + sys.settrace(old_trace) + + def test_line_events_on_await_line(self): + async def returns(): + return "done" + + async def suspends(): + await AsyncYield("suspended") + return "done" + + async def outer(f): + x = (await + f()) + return x + + mon = sys.monitoring + tool = mon.DEBUGGER_ID + for f in returns, suspends: + with self.subTest(f=f.__name__): + lines = [] + def line(code, lineno): + if code is outer.__code__: + lines.append(lineno - code.co_firstlineno) + mon.use_tool_id(tool, "test") + try: + mon.register_callback(tool, mon.events.LINE, line) + mon.set_events(tool, mon.events.LINE) + run_async(outer(f)) + finally: + mon.set_events(tool, 0) + mon.register_callback(tool, mon.events.LINE, None) + mon.free_tool_id(tool) + self.assertEqual(lines, [2, 1, 3]) + + def test_call_forms(self): + class C: + async def meth(self, x, *, y=0): + if y: + await AsyncYield(y) + return ("meth", x, y) + + async def func(*args, **kwargs): + if kwargs.get("suspend"): + await AsyncYield("f") + return (args, kwargs) + + obj = C() + bound = obj.meth + + async def outer(): + return [ + await obj.meth(1), + await obj.meth(2, y=3), + await bound(4), + await bound(5, y=6), + await func(7), + await func(*[8, 9]), + await func(**{"a": 10}), + await func(11, suspend=True), + ] + + for _ in range(3): # also with specialized calls + self.assertEqual(run_async(outer()), ( + [3, 6, "f"], + [("meth", 1, 0), ("meth", 2, 3), ("meth", 4, 0), + ("meth", 5, 6), ((7,), {}), ((8, 9), {}), + ((), {"a": 10}), ((11,), {"suspend": True})], + )) + + def test_send_specialized_for_other_awaitables(self): + # The SEND of an await site may have been specialized for another + # kind of awaitable before a coroutine function is awaited there. + async def agen(): + yield 1 + + class Iterator: + async def __anext__(self): + return 2 + + class SuspendingIterator: + async def __anext__(self): + await AsyncYield("s") + return 3 + + async def outer(it): + return await type(it).__anext__(it) + + def check(it, expected): + self.assertEqual(run_async(outer(it)), expected) + + for _ in range(3): + for _ in range(20): + check(agen(), ([], 1)) + check(Iterator(), ([], 2)) + check(SuspendingIterator(), (["s"], 3)) + + def test_traceback_like_eager_coroutine(self): + async def inner(): + raise ValueError + + async def outer(): + await inner() + + def format_tb(): + try: + run_async(outer()) + except ValueError: + return traceback.format_exc() + + lazy = format_tb() + # Origin tracking makes awaited calls create the coroutine eagerly. + old_depth = sys.get_coroutine_origin_tracking_depth() + sys.set_coroutine_origin_tracking_depth(1) + try: + eager = format_tb() + finally: + sys.set_coroutine_origin_tracking_depth(old_depth) + # The whole `await inner()` line, not just `inner()` with carets. + self.assertIn(" await inner()\n File", lazy) + self.assertEqual(lazy, eager) + + def test_traceback_multiline_await(self): + async def inner(): + raise ValueError + + async def outer(): + x = (await + inner()) + return x + + def format_tb(): + try: + run_async(outer()) + except ValueError: + return traceback.format_exc() + + lazy = format_tb() + old_depth = sys.get_coroutine_origin_tracking_depth() + sys.set_coroutine_origin_tracking_depth(1) + try: + eager = format_tb() + finally: + sys.set_coroutine_origin_tracking_depth(old_depth) + self.assertEqual(lazy, eager) + + def test_instrumentation_enabled_before_first_suspension(self): + # END_AWAITED_CALL must run right after the body suspends, before + # anything else, even if LINE or INSTRUCTION events get enabled + # while the body runs. + E = sys.monitoring.events + tool = sys.monitoring.DEBUGGER_ID + + async def inner(events): + sys.monitoring.set_events(tool, events) + await AsyncYield("suspended") + return "done" + + async def outer(events): + x = (await + inner(events)) + return x + + for events in (E.LINE, E.INSTRUCTION, E.LINE | E.INSTRUCTION): + with self.subTest(events=events): + sys.monitoring.use_tool_id(tool, "test") + try: + for event in (E.LINE, E.INSTRUCTION): + sys.monitoring.register_callback( + tool, event, lambda *args: gc.collect()) + self.assertEqual(run_async(outer(events)), + (["suspended"], "done")) + finally: + sys.monitoring.set_events(tool, 0) + sys.monitoring.free_tool_id(tool) + + @support.cpython_only @unittest.skipIf(_testcapi is None, "requires _testcapi") class CAPITest(unittest.TestCase): diff --git a/Lib/test/test_dis.py b/Lib/test/test_dis.py index 2c3972c7394d01..214e3e5ad509df 100644 --- a/Lib/test/test_dis.py +++ b/Lib/test/test_dis.py @@ -608,12 +608,17 @@ async def _asyncwith(c): L1: RESUME 0 %4d LOAD_FAST 0 (c) + PUSH_NULL + SWAP 2 COPY 1 LOAD_SPECIAL 3 (__aexit__) SWAP 2 SWAP 3 + PUSH_NULL + SWAP 2 LOAD_SPECIAL 2 (__aenter__) CALL 0 + END_AWAITED_CALL 3 (to L3) GET_AWAITABLE 1 L2: SEND 4 (to L5) L3: YIELD_VALUE 1 @@ -629,6 +634,7 @@ async def _asyncwith(c): LOAD_COMMON_CONSTANT 7 (None) LOAD_COMMON_CONSTANT 7 (None) CALL 3 + END_AWAITED_CALL 3 (to L9) GET_AWAITABLE 2 L8: SEND 4 (to L11) L9: YIELD_VALUE 1 @@ -643,7 +649,7 @@ async def _asyncwith(c): RETURN_VALUE %4d L12: CLEANUP_THROW - L13: JUMP_BACKWARD_NO_INTERRUPT 26 (to L5) + L13: JUMP_BACKWARD_NO_INTERRUPT 27 (to L5) L14: CLEANUP_THROW L15: JUMP_BACKWARD_NO_INTERRUPT 10 (to L11) L16: PUSH_EXC_INFO @@ -664,6 +670,7 @@ async def _asyncwith(c): POP_TOP POP_TOP POP_TOP + POP_TOP %4d LOAD_SMALL_INT 2 STORE_FAST 2 (y) @@ -677,16 +684,16 @@ async def _asyncwith(c): RERAISE 1 ExceptionTable: L1 to L3 -> L25 [0] lasti - L3 to L4 -> L12 [5] + L3 to L4 -> L12 [6] L4 to L6 -> L25 [0] lasti - L6 to L7 -> L16 [2] lasti + L6 to L7 -> L16 [3] lasti L7 to L9 -> L25 [0] lasti L9 to L10 -> L14 [3] L10 to L13 -> L25 [0] lasti L14 to L15 -> L25 [0] lasti - L16 to L18 -> L24 [4] lasti - L18 to L19 -> L20 [8] - L19 to L23 -> L24 [4] lasti + L16 to L18 -> L24 [5] lasti + L18 to L19 -> L20 [9] + L19 to L23 -> L24 [5] lasti L23 to L25 -> L25 [0] lasti """ % (_asyncwith.__code__.co_firstlineno, _asyncwith.__code__.co_firstlineno + 1, @@ -1308,6 +1315,23 @@ async def afunc(): self.assertNotIn("to", line) self.assertIn("from", line) + def test_awaited_call(self): + + async def afunc(): + await f(1) + await x + + instrs = list(dis.get_instructions(afunc)) + names = [i.opname for i in instrs] + start = names.index('END_AWAITED_CALL') + self.assertEqual(names[start - 2:start + 5], [ + 'LOAD_SMALL_INT', 'CALL', 'END_AWAITED_CALL', 'GET_AWAITABLE', + 'SEND', 'YIELD_VALUE', 'RESUME']) + self.assertEqual(instrs[start].jump_target, + instrs[start + 3].offset) + # Only `await ` gets END_AWAITED_CALL. + self.assertEqual(names.count('END_AWAITED_CALL'), 1) + @staticmethod def code_quicken(f): diff --git a/Lib/test/test_opcache.py b/Lib/test/test_opcache.py index 5f7c15f93a8332..033c349aca4bf4 100644 --- a/Lib/test/test_opcache.py +++ b/Lib/test/test_opcache.py @@ -548,6 +548,101 @@ def count_args(self, *args): MyClass.__init__.__code__ = count_args.__code__ instantiate() + @requires_jit_disabled + @requires_specialization + def test_awaited_calls(self): + async def exact(x): + return sys._getframe().f_generator is None + + async def general(x, y=None): + return sys._getframe().f_generator is None + + class C: + async def exact(self, x): + return sys._getframe().f_generator is None + + async def general(self, x, y=None): + return sys._getframe().f_generator is None + + c = C() + bound_exact = c.exact + bound_general = c.general + + async def outer(): + return [ + await exact(1), + await general(1), + await bound_exact(1), + await bound_general(1), + await exact(x=1), + await bound_exact(x=1), + ] + + def run(): + coro = outer() + try: + coro.send(None) + except StopIteration as exc: + return exc.value + self.fail("outer() suspended") + + for _ in range(_testinternalcapi.SPECIALIZATION_THRESHOLD): + # All coroutines run without a coroutine object. + self.assertEqual(run(), [True] * 6) + for opname in ("CALL_PY_EXACT_ARGS_AWAITED", + "CALL_PY_GENERAL_AWAITED", + "CALL_BOUND_METHOD_EXACT_ARGS_AWAITED", + "CALL_BOUND_METHOD_GENERAL_AWAITED", + "CALL_KW_PY_AWAITED", + "CALL_KW_BOUND_METHOD_AWAITED"): + self.assert_specialized(outer, opname) + self.assert_no_opcode(outer, "CALL_PY_EXACT_ARGS") + self.assertEqual(run(), [True] * 6) + + @requires_jit_disabled + @requires_specialization + def test_awaited_non_coroutine_calls(self): + # Awaited calls of anything but a coroutine function get the same + # specializations as other calls. + class Ready: + def __init__(self, value): + self.value = value + + def __await__(self): + return self.value + yield + + ready = Ready(1) + + def make_ready(): + return ready + + get_ready = [ready].__getitem__ + + async def outer(): + return [ + await Ready(1), + await make_ready(), + await get_ready(0), + ] + + def run(): + coro = outer() + try: + coro.send(None) + except StopIteration as exc: + return exc.value + self.fail("outer() suspended") + + for _ in range(_testinternalcapi.SPECIALIZATION_THRESHOLD): + self.assertEqual(run(), [1, 1, 1]) + for opname in ("CALL_ALLOC_AND_ENTER_INIT", + "CALL_PY_EXACT_ARGS", + "CALL_BUILTIN_O"): + self.assert_specialized(outer, opname) + self.assert_no_opcode(outer, "CALL_PY_EXACT_ARGS_AWAITED") + self.assertEqual(run(), [1, 1, 1]) + @requires_jit_disabled @requires_specialization def test_push_init_frame_fails(self): @@ -1630,8 +1725,15 @@ def run_async(coro): except StopIteration: break + class Suspend: + def __await__(self): + yield + class CM: async def __aenter__(self): + # Without suspending, it would run lazily and the SEND + # after it would be skipped. + await Suspend() return self async def __aexit__(self, *exc): diff --git a/Lib/test/test_sys_settrace.py b/Lib/test/test_sys_settrace.py index a5e7bbbfad5ffc..917625964c1231 100644 --- a/Lib/test/test_sys_settrace.py +++ b/Lib/test/test_sys_settrace.py @@ -42,6 +42,9 @@ async def __aenter__(self): async def __aexit__(self, *exc_info): self.output.append(-self.value) +async def async_noop(): + pass + async def asynciter(iterable): """Convert an iterable to an asynchronous iterator.""" for x in iterable: @@ -2165,6 +2168,20 @@ def test_jump_out_of_block_backwards(output): output.append(6) output.append(7) + @async_jump_test(3, 4, [1, 4]) + async def test_jump_forwards_after_awaited_call(output): + output.append(1) + await async_noop() + output.append(3) + output.append(4) + + @async_jump_test(4, 2, [1, 3, 3, 4]) + async def test_jump_backwards_over_awaited_call(output): + output.append(1) + await async_noop() + output.append(3) + output.append(4) + @async_jump_test(4, 5, [3, 5]) @clean_asynciter async def test_jump_out_of_async_for_block_forwards(output, asynciter): diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-27-12-00-00.gh-issue-161170.lazyCo.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-27-12-00-00.gh-issue-161170.lazyCo.rst new file mode 100644 index 00000000000000..fb20cc7fa50ba0 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-27-12-00-00.gh-issue-161170.lazyCo.rst @@ -0,0 +1,5 @@ +Make ``await`` of a coroutine that completes without suspending about twice as +fast by running it without creating a coroutine object. This also applies to +``async def`` :meth:`~object.__aenter__` and :meth:`~object.__aexit__` methods +in :keyword:`async with`. Until such a coroutine +first suspends, :attr:`frame.f_generator` is ``None``. diff --git a/Modules/_testinternalcapi/test_cases.c.h b/Modules/_testinternalcapi/test_cases.c.h index 8bb3f857437792..47420e905fe4ad 100644 --- a/Modules/_testinternalcapi/test_cases.c.h +++ b/Modules/_testinternalcapi/test_cases.c.h @@ -1896,6 +1896,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL) { + MAYBE_START_LAZY_CORO(new_frame); + } frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); } @@ -2233,6 +2236,160 @@ DISPATCH(); } + TARGET(CALL_BOUND_METHOD_EXACT_ARGS_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_BOUND_METHOD_EXACT_ARGS_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_BOUND_METHOD_EXACT_ARGS_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef null; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_CALL_BOUND_METHOD_EXACT_ARGS + { + null = stack_pointer[-1 - oparg]; + callable = stack_pointer[-2 - oparg]; + if (!PyStackRef_IsNull(null)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + if (Py_TYPE(PyStackRef_AsPyObjectBorrow(callable)) != &PyMethod_Type) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _INIT_CALL_BOUND_METHOD_EXACT_ARGS + { + self_or_null = null; + assert(PyStackRef_IsNull(self_or_null)); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + STAT_INC(CALL, hit); + self_or_null = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_self); + _PyStackRef temp = callable; + callable = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_func); + stack_pointer[-2 - oparg] = callable; + stack_pointer[-1 - oparg] = self_or_null; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } + // flush + // _CHECK_FUNCTION_VERSION + { + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_EXACT_ARGS + { + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(PyFunction_Check(callable_o)); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (code->co_argcount != oparg + (!PyStackRef_IsNull(self_or_null))) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_STACK_SPACE + { + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (!_PyThreadState_HasStackSpace(tstate, code->co_framesize)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _INIT_CALL_PY_EXACT_ARGS + { + args = &stack_pointer[-oparg]; + int has_self = !PyStackRef_IsNull(self_or_null); + STAT_INC(CALL, hit); + _PyInterpreterFrame *pushed_frame = _PyFrame_PushUnchecked(tstate, callable, oparg + has_self, frame); + _PyStackRef *first_non_self_local = pushed_frame->localsplus + has_self; + pushed_frame->localsplus[0] = self_or_null; + for (int i = 0; i < oparg; i++) { + first_non_self_local[i] = args[i]; + } + new_frame = PyStackRef_Wrap(pushed_frame); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_BOUND_METHOD_GENERAL) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_BOUND_METHOD_GENERAL; @@ -2369,6 +2526,146 @@ DISPATCH(); } + TARGET(CALL_BOUND_METHOD_GENERAL_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_BOUND_METHOD_GENERAL_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_BOUND_METHOD_GENERAL_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef null; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_METHOD_VERSION + { + null = stack_pointer[-1 - oparg]; + callable = stack_pointer[-2 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (Py_TYPE(callable_o) != &PyMethod_Type) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyObject *func = ((PyMethodObject *)callable_o)->im_func; + if (!PyFunction_Check(func)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + if (((PyFunctionObject *)func)->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + if (!PyStackRef_IsNull(null)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _EXPAND_METHOD + { + self_or_null = null; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(PyStackRef_IsNull(self_or_null)); + assert(Py_TYPE(callable_o) == &PyMethod_Type); + self_or_null = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_self); + _PyStackRef temp = callable; + callable = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_func); + assert(PyStackRef_FunctionCheck(callable)); + stack_pointer[-2 - oparg] = callable; + stack_pointer[-1 - oparg] = self_or_null; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } + // flush + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _PY_FRAME_GENERAL + { + args = &stack_pointer[-oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + if (!PyStackRef_IsNull(self_or_null)) { + args--; + total_args++; + } + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + args, total_args, NULL, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_BUILTIN_CLASS) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_BUILTIN_CLASS; @@ -2972,6 +3269,13 @@ } ex_frame = PyStackRef_Wrap(new_frame); } + // _MAYBE_LAZY_CORO + { + new_frame = ex_frame; + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + } // _SAVE_RETURN_OFFSET { #if TIER_ONE @@ -2983,7 +3287,6 @@ } // _PUSH_FRAME { - new_frame = ex_frame; assert(!IS_PEP523_HOOKED(tstate)); _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); _PyFrame_SetStackPointer(frame, stack_pointer); @@ -3150,6 +3453,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 2u == 1 + INLINE_CACHE_ENTRIES_CALL_FUNCTION_EX); frame->return_offset = 2u ; DISPATCH_INLINED(new_frame); @@ -3466,6 +3772,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL_KW) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 4u == 1 + INLINE_CACHE_ENTRIES_CALL_KW); frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); @@ -3491,22 +3800,161 @@ } res = PyStackRef_FromPyObjectSteal(res_o); } - stack_pointer[-3 - oparg] = res; - stack_pointer += -2 - oparg; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + stack_pointer[-3 - oparg] = res; + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + DISPATCH(); + } + + TARGET(CALL_KW_BOUND_METHOD) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_KW_BOUND_METHOD; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_KW_BOUND_METHOD); + static_assert(INLINE_CACHE_ENTRIES_CALL_KW == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef null; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef kwnames; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _CHECK_METHOD_VERSION_KW + { + null = stack_pointer[-2 - oparg]; + callable = stack_pointer[-3 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (Py_TYPE(callable_o) != &PyMethod_Type) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + PyObject *func = ((PyMethodObject *)callable_o)->im_func; + if (!PyFunction_Check(func)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + if (((PyFunctionObject *)func)->func_version != func_version) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + if (!PyStackRef_IsNull(null)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _EXPAND_METHOD_KW + { + self_or_null = null; + assert(PyStackRef_IsNull(self_or_null)); + _PyStackRef callable_s = callable; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(Py_TYPE(callable_o) == &PyMethod_Type); + self_or_null = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_self); + callable = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_func); + assert(PyStackRef_FunctionCheck(callable)); + stack_pointer[-3 - oparg] = callable; + stack_pointer[-2 - oparg] = self_or_null; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(callable_s); + _PyFrame_StackPointerInvalidate(frame); + } + // flush + // _PY_FRAME_KW + { + kwnames = stack_pointer[-1]; + args = &stack_pointer[-1 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + _PyStackRef *arguments = args; + if (!PyStackRef_IsNull(self_or_null)) { + arguments--; + total_args++; + } + PyObject *kwnames_o = PyStackRef_AsPyObjectBorrow(kwnames); + int positional_args = total_args - (int)PyTuple_GET_SIZE(kwnames_o); + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + arguments, positional_args, kwnames_o, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(kwnames); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } DISPATCH(); } - TARGET(CALL_KW_BOUND_METHOD) { + TARGET(CALL_KW_BOUND_METHOD_AWAITED) { #if _Py_TAIL_CALL_INTERP - int opcode = CALL_KW_BOUND_METHOD; + int opcode = CALL_KW_BOUND_METHOD_AWAITED; (void)(opcode); #endif _Py_CODEUNIT* const this_instr = next_instr; (void)this_instr; frame->instr_ptr = next_instr; next_instr += 4; - INSTRUCTION_STATS(CALL_KW_BOUND_METHOD); + INSTRUCTION_STATS(CALL_KW_BOUND_METHOD_AWAITED); static_assert(INLINE_CACHE_ENTRIES_CALL_KW == 3, "incorrect cache size"); _PyStackRef callable; _PyStackRef null; @@ -3605,6 +4053,10 @@ } new_frame = PyStackRef_Wrap(temp); } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } // _SAVE_RETURN_OFFSET { #if TIER_ONE @@ -3833,6 +4285,128 @@ DISPATCH(); } + TARGET(CALL_KW_PY_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_KW_PY_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_KW_PY_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL_KW == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef kwnames; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _CHECK_FUNCTION_VERSION_KW + { + callable = stack_pointer[-3 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _PY_FRAME_KW + { + kwnames = stack_pointer[-1]; + args = &stack_pointer[-1 - oparg]; + self_or_null = stack_pointer[-2 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + _PyStackRef *arguments = args; + if (!PyStackRef_IsNull(self_or_null)) { + arguments--; + total_args++; + } + PyObject *kwnames_o = PyStackRef_AsPyObjectBorrow(kwnames); + int positional_args = total_args - (int)PyTuple_GET_SIZE(kwnames_o); + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + arguments, positional_args, kwnames_o, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(kwnames); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_LEN) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_LEN; @@ -4564,60 +5138,179 @@ JUMP_TO_PREDICTED(CALL); } } - // _CALL_NON_PY_GENERAL + // _CALL_NON_PY_GENERAL + { + args = &stack_pointer[-oparg]; + self_or_null = stack_pointer[-1 - oparg]; + #if TIER_ONE + assert(opcode != INSTRUMENTED_CALL); + #endif + int total_args = oparg; + _PyStackRef *arguments = args; + if (!PyStackRef_IsNull(self_or_null)) { + arguments--; + total_args++; + } + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *res_o = _Py_VectorCall_StackRefSteal( + callable, + arguments, + total_args, + PyStackRef_NULL); + _PyFrame_StackPointerInvalidate(frame); + if (res_o == NULL) { + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + JUMP_TO_LABEL(error); + } + res = PyStackRef_FromPyObjectSteal(res_o); + } + // _CHECK_PERIODIC_AT_END + { + stack_pointer[-2 - oparg] = res; + stack_pointer += -1 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + int err = check_periodics_at_end(tstate, frame); + _PyFrame_StackPointerInvalidate(frame); + if (err != 0) { + JUMP_TO_LABEL(error); + } + } + DISPATCH(); + } + + TARGET(CALL_PY_EXACT_ARGS) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_PY_EXACT_ARGS; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_PY_EXACT_ARGS); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_VERSION + { + callable = stack_pointer[-2 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_EXACT_ARGS + { + self_or_null = stack_pointer[-1 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(PyFunction_Check(callable_o)); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (code->co_argcount != oparg + (!PyStackRef_IsNull(self_or_null))) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_STACK_SPACE + { + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (!_PyThreadState_HasStackSpace(tstate, code->co_framesize)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _INIT_CALL_PY_EXACT_ARGS + { + args = &stack_pointer[-oparg]; + int has_self = !PyStackRef_IsNull(self_or_null); + STAT_INC(CALL, hit); + _PyInterpreterFrame *pushed_frame = _PyFrame_PushUnchecked(tstate, callable, oparg + has_self, frame); + _PyStackRef *first_non_self_local = pushed_frame->localsplus + has_self; + pushed_frame->localsplus[0] = self_or_null; + for (int i = 0; i < oparg; i++) { + first_non_self_local[i] = args[i]; + } + new_frame = PyStackRef_Wrap(pushed_frame); + } + // _SAVE_RETURN_OFFSET { - args = &stack_pointer[-oparg]; - self_or_null = stack_pointer[-1 - oparg]; #if TIER_ONE - assert(opcode != INSTRUMENTED_CALL); + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; #endif - int total_args = oparg; - _PyStackRef *arguments = args; - if (!PyStackRef_IsNull(self_or_null)) { - arguments--; - total_args++; - } - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyObject *res_o = _Py_VectorCall_StackRefSteal( - callable, - arguments, - total_args, - PyStackRef_NULL); - _PyFrame_StackPointerInvalidate(frame); - if (res_o == NULL) { - stack_pointer += -2 - oparg; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); - JUMP_TO_LABEL(error); - } - res = PyStackRef_FromPyObjectSteal(res_o); } - // _CHECK_PERIODIC_AT_END + // _PUSH_FRAME { - stack_pointer[-2 - oparg] = res; - stack_pointer += -1 - oparg; + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + stack_pointer += -2 - oparg; ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); - int err = check_periodics_at_end(tstate, frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - if (err != 0) { - JUMP_TO_LABEL(error); - } + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); } DISPATCH(); } - TARGET(CALL_PY_EXACT_ARGS) { + TARGET(CALL_PY_EXACT_ARGS_AWAITED) { #if _Py_TAIL_CALL_INTERP - int opcode = CALL_PY_EXACT_ARGS; + int opcode = CALL_PY_EXACT_ARGS_AWAITED; (void)(opcode); #endif _Py_CODEUNIT* const this_instr = next_instr; (void)this_instr; frame->instr_ptr = next_instr; next_instr += 4; - INSTRUCTION_STATS(CALL_PY_EXACT_ARGS); + INSTRUCTION_STATS(CALL_PY_EXACT_ARGS_AWAITED); static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); _PyStackRef callable; _PyStackRef self_or_null; @@ -4694,6 +5387,10 @@ } new_frame = PyStackRef_Wrap(pushed_frame); } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } // _SAVE_RETURN_OFFSET { #if TIER_ONE @@ -4834,6 +5531,117 @@ DISPATCH(); } + TARGET(CALL_PY_GENERAL_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_PY_GENERAL_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_PY_GENERAL_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_VERSION + { + callable = stack_pointer[-2 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _PY_FRAME_GENERAL + { + args = &stack_pointer[-oparg]; + self_or_null = stack_pointer[-1 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + if (!PyStackRef_IsNull(self_or_null)) { + args--; + total_args++; + } + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + args, total_args, NULL, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_STR_1) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_STR_1; @@ -6119,6 +6927,81 @@ DISPATCH(); } + TARGET(END_AWAITED_CALL) { + #if _Py_TAIL_CALL_INTERP + int opcode = END_AWAITED_CALL; + (void)(opcode); + #endif + frame->instr_ptr = next_instr; + next_instr += 1; + INSTRUCTION_STATS(END_AWAITED_CALL); + _PyStackRef lazy_outcome; + _PyStackRef res; + _PyStackRef value; + // _END_AWAITED_CALL + { + res = stack_pointer[-1]; + lazy_outcome = stack_pointer[-2]; + if (PyStackRef_IsTaggedInt(lazy_outcome)) { + lazy_outcome = PyStackRef_NULL; + _Py_CODEUNIT *send = next_instr + oparg - 1 - INLINE_CACHE_ENTRIES_SEND; + stack_pointer[-2] = lazy_outcome; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), + (int)(send - _PyFrame_GetBytecode(frame))).op.code == SEND); + _PyFrame_StackPointerInvalidate(frame); + _Py_CODEUNIT *end_send = next_instr + oparg + send->op.arg; + if (end_send->op.code != END_SEND) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = monitor_stop_iteration(tstate, frame, end_send, + PyStackRef_AsPyObjectBorrow(res)); + _PyFrame_StackPointerInvalidate(frame); + if (err) { + JUMP_TO_LABEL(error); + } + } + JUMPBY(oparg + send->op.arg + 1); + } + else if (!PyStackRef_IsNull(lazy_outcome)) { + _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(lazy_outcome); + lazy_outcome = PyStackRef_NULL; + stack_pointer[-2] = lazy_outcome; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); + _PyFrame_StackPointerInvalidate(frame); + _PyStackRef v = res; + if (gen == NULL) { + stack_pointer[-1] = PyStackRef_NULL; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + frame = _PyEval_ThrowIntoLazyCoro(tstate, lazy_frame, v); + _PyFrame_StackPointerInvalidate(frame); + next_instr = frame->instr_ptr; + LOAD_SP(); + JUMP_TO_LABEL(error); + } + stack_pointer[-2] = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + stack_pointer[-1] = PyStackRef_NULL; + stack_pointer[0] = v; + stack_pointer += 1; + JUMPBY(oparg); + DISPATCH(); + } + } + // _POP_LAZY_OUTCOME + { + assert(PyStackRef_IsNull(lazy_outcome)); + value = res; + } + stack_pointer[-2] = value; + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + DISPATCH(); + } + TARGET(END_FOR) { #if _Py_TAIL_CALL_INTERP int opcode = END_FOR; @@ -7200,6 +8083,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL) { + MAYBE_START_LAZY_CORO(new_frame); + } frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); } @@ -7367,6 +8253,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 2u == 1 + INLINE_CACHE_ENTRIES_CALL_FUNCTION_EX); frame->return_offset = 2u ; DISPATCH_INLINED(new_frame); @@ -7519,6 +8408,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL_KW) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 4u == 1 + INLINE_CACHE_ENTRIES_CALL_KW); frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); @@ -8295,6 +9187,9 @@ _PyStackRef val; _PyStackRef value; _PyStackRef retval; + // _CHECK_LAZY_CORO + { + } // _YIELD_VALUE_EVENT { val = stack_pointer[-1]; @@ -8328,7 +9223,6 @@ retval = value; assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); frame->instr_ptr++; - PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); assert(FRAME_SUSPENDED_YIELD_FROM == FRAME_SUSPENDED + 1); assert(oparg == 0 || oparg == 1); _PyStackRef temp = retval; @@ -8337,27 +9231,37 @@ _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); - tstate->exc_info = gen->gi_exc_state.previous_item; - gen->gi_exc_state.previous_item = NULL; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *gen_frame = frame; - _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); - frame = tstate->current_frame = frame->previous; - gen_frame->previous = NULL; - ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; - FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + int offset = 1 + INLINE_CACHE_ENTRIES_SEND; + if (frame->lazy_coro == LAZY_CORO_RUNNING) { + assert(oparg == 1); + frame = _PyEval_SuspendLazyCoro(tstate, frame); + offset = 0; + } + else { + PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); + tstate->exc_info = gen->gi_exc_state.previous_item; + gen->gi_exc_state.previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *gen_frame = frame; + _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); + frame = tstate->current_frame = frame->previous; + gen_frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + } assert(INLINE_CACHE_ENTRIES_SEND == INLINE_CACHE_ENTRIES_FOR_ITER); #if TIER_ONE && defined(Py_DEBUG) if (!PyStackRef_IsNone(frame->f_executable)) { Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(opcode == SEND || opcode == FOR_ITER); + assert(offset == 0 ? opcode == END_AWAITED_CALL + : (opcode == SEND || opcode == FOR_ITER)); } #endif stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - LOAD_IP(1 + INLINE_CACHE_ENTRIES_SEND); + LOAD_IP(offset); value = temp; LLTRACE_RESUME_FRAME(); } @@ -11454,32 +12358,61 @@ _PyStackRef res; assert(PyStackRef_FunctionCheck(frame->f_funcobj)); PyFunctionObject *func = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(frame->f_funcobj); - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); - _PyFrame_StackPointerInvalidate(frame); - if (gen == NULL) { - JUMP_TO_LABEL(error); + _PyErr_StackItem *exc_info = NULL; + #if TIER_ONE + if (frame->lazy_coro == LAZY_CORO_REQUESTED) { + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + exc_info = (_PyErr_StackItem *)_PyThreadState_PushFrame( + tstate, sizeof(_PyErr_StackItem) / sizeof(PyObject *)); + _PyFrame_StackPointerInvalidate(frame); + if (exc_info == NULL) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyErr_Clear(tstate); + _PyFrame_StackPointerInvalidate(frame); + } + } + #endif + if (exc_info != NULL) { + exc_info->exc_value = NULL; + exc_info->previous_item = tstate->exc_info; + tstate->exc_info = exc_info; + frame->lazy_coro = LAZY_CORO_RUNNING; + _PyInterpreterFrame *caller = frame->previous; + caller->instr_ptr += caller->return_offset; + caller->return_offset = 0; + res = PyStackRef_None; + } + else { + frame->lazy_coro = 0; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); + _PyFrame_StackPointerInvalidate(frame); + if (gen == NULL) { + JUMP_TO_LABEL(error); + } + assert(STACK_LEVEL() <= 2); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *gen_frame = &gen->gi_iframe; + frame->instr_ptr++; + _PyFrame_Copy(frame, gen_frame); + assert(frame->frame_obj == NULL); + gen->gi_frame_state = FRAME_CREATED; + gen_frame->owner = FRAME_OWNED_BY_GENERATOR; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *prev = frame->previous; + _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); + _PyThreadState_PopFrame(tstate, frame); + frame = tstate->current_frame = prev; + LOAD_IP(frame->return_offset); + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + LLTRACE_RESUME_FRAME(); } - assert(STACK_LEVEL() <= 2); - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - _PyInterpreterFrame *gen_frame = &gen->gi_iframe; - frame->instr_ptr++; - _PyFrame_Copy(frame, gen_frame); - assert(frame->frame_obj == NULL); - gen->gi_frame_state = FRAME_CREATED; - gen_frame->owner = FRAME_OWNED_BY_GENERATOR; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *prev = frame->previous; - _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); - _PyThreadState_PopFrame(tstate, frame); - frame = tstate->current_frame = prev; - LOAD_IP(frame->return_offset); - stack_pointer = _PyFrame_GetStackPointer(frame); - _PyFrame_StackPointerInvalidate(frame); - res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); - LLTRACE_RESUME_FRAME(); stack_pointer[0] = res; stack_pointer += 1; ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); @@ -13586,6 +14519,9 @@ opcode = YIELD_VALUE; _PyStackRef value; _PyStackRef retval; + // _CHECK_LAZY_CORO + { + } // _MAKE_HEAP_SAFE { value = stack_pointer[-1]; @@ -13596,7 +14532,6 @@ retval = value; assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); frame->instr_ptr++; - PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); assert(FRAME_SUSPENDED_YIELD_FROM == FRAME_SUSPENDED + 1); assert(oparg == 0 || oparg == 1); _PyStackRef temp = retval; @@ -13605,27 +14540,37 @@ _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); - tstate->exc_info = gen->gi_exc_state.previous_item; - gen->gi_exc_state.previous_item = NULL; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *gen_frame = frame; - _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); - frame = tstate->current_frame = frame->previous; - gen_frame->previous = NULL; - ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; - FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + int offset = 1 + INLINE_CACHE_ENTRIES_SEND; + if (frame->lazy_coro == LAZY_CORO_RUNNING) { + assert(oparg == 1); + frame = _PyEval_SuspendLazyCoro(tstate, frame); + offset = 0; + } + else { + PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); + tstate->exc_info = gen->gi_exc_state.previous_item; + gen->gi_exc_state.previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *gen_frame = frame; + _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); + frame = tstate->current_frame = frame->previous; + gen_frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + } assert(INLINE_CACHE_ENTRIES_SEND == INLINE_CACHE_ENTRIES_FOR_ITER); #if TIER_ONE && defined(Py_DEBUG) if (!PyStackRef_IsNone(frame->f_executable)) { Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(opcode == SEND || opcode == FOR_ITER); + assert(offset == 0 ? opcode == END_AWAITED_CALL + : (opcode == SEND || opcode == FOR_ITER)); } #endif stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - LOAD_IP(1 + INLINE_CACHE_ENTRIES_SEND); + LOAD_IP(offset); value = temp; LLTRACE_RESUME_FRAME(); } diff --git a/Modules/_testinternalcapi/test_targets.h b/Modules/_testinternalcapi/test_targets.h index 91b424773224e4..afcb1ab06419d0 100644 --- a/Modules/_testinternalcapi/test_targets.h +++ b/Modules/_testinternalcapi/test_targets.h @@ -64,6 +64,7 @@ static void *opcode_targets_table[256] = { &&TARGET_DICT_MERGE, &&TARGET_DICT_UPDATE, &&TARGET_END_ASYNC_FOR, + &&TARGET_END_AWAITED_CALL, &&TARGET_EXTENDED_ARG, &&TARGET_FOR_ITER, &&TARGET_GET_AWAITABLE, @@ -127,7 +128,6 @@ static void *opcode_targets_table[256] = { &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, - &&_unknown_opcode, &&TARGET_RESUME, &&TARGET_BINARY_OP_ADD_FLOAT, &&TARGET_BINARY_OP_ADD_INT, @@ -146,7 +146,9 @@ static void *opcode_targets_table[256] = { &&TARGET_BINARY_OP_SUBTRACT_INT, &&TARGET_CALL_ALLOC_AND_ENTER_INIT, &&TARGET_CALL_BOUND_METHOD_EXACT_ARGS, + &&TARGET_CALL_BOUND_METHOD_EXACT_ARGS_AWAITED, &&TARGET_CALL_BOUND_METHOD_GENERAL, + &&TARGET_CALL_BOUND_METHOD_GENERAL_AWAITED, &&TARGET_CALL_BUILTIN_CLASS, &&TARGET_CALL_BUILTIN_FAST, &&TARGET_CALL_BUILTIN_FAST_WITH_KEYWORDS, @@ -155,8 +157,10 @@ static void *opcode_targets_table[256] = { &&TARGET_CALL_EX_PY, &&TARGET_CALL_ISINSTANCE, &&TARGET_CALL_KW_BOUND_METHOD, + &&TARGET_CALL_KW_BOUND_METHOD_AWAITED, &&TARGET_CALL_KW_NON_PY, &&TARGET_CALL_KW_PY, + &&TARGET_CALL_KW_PY_AWAITED, &&TARGET_CALL_LEN, &&TARGET_CALL_LIST_APPEND, &&TARGET_CALL_METHOD_DESCRIPTOR_FAST, @@ -165,7 +169,9 @@ static void *opcode_targets_table[256] = { &&TARGET_CALL_METHOD_DESCRIPTOR_O, &&TARGET_CALL_NON_PY_GENERAL, &&TARGET_CALL_PY_EXACT_ARGS, + &&TARGET_CALL_PY_EXACT_ARGS_AWAITED, &&TARGET_CALL_PY_GENERAL, + &&TARGET_CALL_PY_GENERAL_AWAITED, &&TARGET_CALL_STR_1, &&TARGET_CALL_TUPLE_1, &&TARGET_CALL_TYPE_1, @@ -227,12 +233,6 @@ static void *opcode_targets_table[256] = { &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, &&TARGET_INSTRUMENTED_END_FOR, &&TARGET_INSTRUMENTED_POP_ITER, &&TARGET_INSTRUMENTED_END_SEND, @@ -376,7 +376,7 @@ static void *opcode_tracing_targets_table[256] = { &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, - &&_unknown_opcode, + &&TARGET_TRACE_RECORD, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, @@ -478,12 +478,12 @@ static void *opcode_tracing_targets_table[256] = { &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, @@ -561,7 +561,9 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CACHE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_ALLOC_AND_ENTER_INIT(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_GENERAL(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_GENERAL_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BUILTIN_CLASS(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BUILTIN_FAST(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BUILTIN_FAST_WITH_KEYWORDS(TAIL_CALL_PARAMS); @@ -574,8 +576,10 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_INTRINSIC_2(TAIL_CALL_PARAM static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_ISINSTANCE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_BOUND_METHOD(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_BOUND_METHOD_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_NON_PY(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_PY(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_PY_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_LEN(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_LIST_APPEND(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_METHOD_DESCRIPTOR_FAST(TAIL_CALL_PARAMS); @@ -584,7 +588,9 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_METHOD_DESCRIPTOR_NOARGS(TA static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_METHOD_DESCRIPTOR_O(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_NON_PY_GENERAL(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_EXACT_ARGS(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_EXACT_ARGS_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_GENERAL(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_GENERAL_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_STR_1(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_TUPLE_1(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_TYPE_1(TAIL_CALL_PARAMS); @@ -607,6 +613,7 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_DELETE_SUBSCR(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_DICT_MERGE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_DICT_UPDATE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_ASYNC_FOR(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_AWAITED_CALL(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_FOR(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_SEND(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_ENTER_EXECUTOR(TAIL_CALL_PARAMS); @@ -804,7 +811,9 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [CALL] = _TAIL_CALL_CALL, [CALL_ALLOC_AND_ENTER_INIT] = _TAIL_CALL_CALL_ALLOC_AND_ENTER_INIT, [CALL_BOUND_METHOD_EXACT_ARGS] = _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS_AWAITED, [CALL_BOUND_METHOD_GENERAL] = _TAIL_CALL_CALL_BOUND_METHOD_GENERAL, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = _TAIL_CALL_CALL_BOUND_METHOD_GENERAL_AWAITED, [CALL_BUILTIN_CLASS] = _TAIL_CALL_CALL_BUILTIN_CLASS, [CALL_BUILTIN_FAST] = _TAIL_CALL_CALL_BUILTIN_FAST, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = _TAIL_CALL_CALL_BUILTIN_FAST_WITH_KEYWORDS, @@ -817,8 +826,10 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [CALL_ISINSTANCE] = _TAIL_CALL_CALL_ISINSTANCE, [CALL_KW] = _TAIL_CALL_CALL_KW, [CALL_KW_BOUND_METHOD] = _TAIL_CALL_CALL_KW_BOUND_METHOD, + [CALL_KW_BOUND_METHOD_AWAITED] = _TAIL_CALL_CALL_KW_BOUND_METHOD_AWAITED, [CALL_KW_NON_PY] = _TAIL_CALL_CALL_KW_NON_PY, [CALL_KW_PY] = _TAIL_CALL_CALL_KW_PY, + [CALL_KW_PY_AWAITED] = _TAIL_CALL_CALL_KW_PY_AWAITED, [CALL_LEN] = _TAIL_CALL_CALL_LEN, [CALL_LIST_APPEND] = _TAIL_CALL_CALL_LIST_APPEND, [CALL_METHOD_DESCRIPTOR_FAST] = _TAIL_CALL_CALL_METHOD_DESCRIPTOR_FAST, @@ -827,7 +838,9 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [CALL_METHOD_DESCRIPTOR_O] = _TAIL_CALL_CALL_METHOD_DESCRIPTOR_O, [CALL_NON_PY_GENERAL] = _TAIL_CALL_CALL_NON_PY_GENERAL, [CALL_PY_EXACT_ARGS] = _TAIL_CALL_CALL_PY_EXACT_ARGS, + [CALL_PY_EXACT_ARGS_AWAITED] = _TAIL_CALL_CALL_PY_EXACT_ARGS_AWAITED, [CALL_PY_GENERAL] = _TAIL_CALL_CALL_PY_GENERAL, + [CALL_PY_GENERAL_AWAITED] = _TAIL_CALL_CALL_PY_GENERAL_AWAITED, [CALL_STR_1] = _TAIL_CALL_CALL_STR_1, [CALL_TUPLE_1] = _TAIL_CALL_CALL_TUPLE_1, [CALL_TYPE_1] = _TAIL_CALL_CALL_TYPE_1, @@ -850,6 +863,7 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [DICT_MERGE] = _TAIL_CALL_DICT_MERGE, [DICT_UPDATE] = _TAIL_CALL_DICT_UPDATE, [END_ASYNC_FOR] = _TAIL_CALL_END_ASYNC_FOR, + [END_AWAITED_CALL] = _TAIL_CALL_END_AWAITED_CALL, [END_FOR] = _TAIL_CALL_END_FOR, [END_SEND] = _TAIL_CALL_END_SEND, [ENTER_EXECUTOR] = _TAIL_CALL_ENTER_EXECUTOR, @@ -1005,7 +1019,6 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [UNPACK_SEQUENCE_TWO_TUPLE] = _TAIL_CALL_UNPACK_SEQUENCE_TWO_TUPLE, [WITH_EXCEPT_START] = _TAIL_CALL_WITH_EXCEPT_START, [YIELD_VALUE] = _TAIL_CALL_YIELD_VALUE, - [117] = _TAIL_CALL_UNKNOWN_OPCODE, [118] = _TAIL_CALL_UNKNOWN_OPCODE, [119] = _TAIL_CALL_UNKNOWN_OPCODE, [120] = _TAIL_CALL_UNKNOWN_OPCODE, @@ -1016,12 +1029,6 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [125] = _TAIL_CALL_UNKNOWN_OPCODE, [126] = _TAIL_CALL_UNKNOWN_OPCODE, [127] = _TAIL_CALL_UNKNOWN_OPCODE, - [219] = _TAIL_CALL_UNKNOWN_OPCODE, - [220] = _TAIL_CALL_UNKNOWN_OPCODE, - [221] = _TAIL_CALL_UNKNOWN_OPCODE, - [222] = _TAIL_CALL_UNKNOWN_OPCODE, - [223] = _TAIL_CALL_UNKNOWN_OPCODE, - [224] = _TAIL_CALL_UNKNOWN_OPCODE, [225] = _TAIL_CALL_UNKNOWN_OPCODE, [226] = _TAIL_CALL_UNKNOWN_OPCODE, [227] = _TAIL_CALL_UNKNOWN_OPCODE, @@ -1062,7 +1069,9 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [CALL] = _TAIL_CALL_TRACE_RECORD, [CALL_ALLOC_AND_ENTER_INIT] = _TAIL_CALL_TRACE_RECORD, [CALL_BOUND_METHOD_EXACT_ARGS] = _TAIL_CALL_TRACE_RECORD, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_BOUND_METHOD_GENERAL] = _TAIL_CALL_TRACE_RECORD, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_BUILTIN_CLASS] = _TAIL_CALL_TRACE_RECORD, [CALL_BUILTIN_FAST] = _TAIL_CALL_TRACE_RECORD, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = _TAIL_CALL_TRACE_RECORD, @@ -1075,8 +1084,10 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [CALL_ISINSTANCE] = _TAIL_CALL_TRACE_RECORD, [CALL_KW] = _TAIL_CALL_TRACE_RECORD, [CALL_KW_BOUND_METHOD] = _TAIL_CALL_TRACE_RECORD, + [CALL_KW_BOUND_METHOD_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_KW_NON_PY] = _TAIL_CALL_TRACE_RECORD, [CALL_KW_PY] = _TAIL_CALL_TRACE_RECORD, + [CALL_KW_PY_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_LEN] = _TAIL_CALL_TRACE_RECORD, [CALL_LIST_APPEND] = _TAIL_CALL_TRACE_RECORD, [CALL_METHOD_DESCRIPTOR_FAST] = _TAIL_CALL_TRACE_RECORD, @@ -1085,7 +1096,9 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [CALL_METHOD_DESCRIPTOR_O] = _TAIL_CALL_TRACE_RECORD, [CALL_NON_PY_GENERAL] = _TAIL_CALL_TRACE_RECORD, [CALL_PY_EXACT_ARGS] = _TAIL_CALL_TRACE_RECORD, + [CALL_PY_EXACT_ARGS_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_PY_GENERAL] = _TAIL_CALL_TRACE_RECORD, + [CALL_PY_GENERAL_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_STR_1] = _TAIL_CALL_TRACE_RECORD, [CALL_TUPLE_1] = _TAIL_CALL_TRACE_RECORD, [CALL_TYPE_1] = _TAIL_CALL_TRACE_RECORD, @@ -1108,6 +1121,7 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [DICT_MERGE] = _TAIL_CALL_TRACE_RECORD, [DICT_UPDATE] = _TAIL_CALL_TRACE_RECORD, [END_ASYNC_FOR] = _TAIL_CALL_TRACE_RECORD, + [END_AWAITED_CALL] = _TAIL_CALL_TRACE_RECORD, [END_FOR] = _TAIL_CALL_TRACE_RECORD, [END_SEND] = _TAIL_CALL_TRACE_RECORD, [ENTER_EXECUTOR] = _TAIL_CALL_TRACE_RECORD, @@ -1263,7 +1277,6 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [UNPACK_SEQUENCE_TWO_TUPLE] = _TAIL_CALL_TRACE_RECORD, [WITH_EXCEPT_START] = _TAIL_CALL_TRACE_RECORD, [YIELD_VALUE] = _TAIL_CALL_TRACE_RECORD, - [117] = _TAIL_CALL_UNKNOWN_OPCODE, [118] = _TAIL_CALL_UNKNOWN_OPCODE, [119] = _TAIL_CALL_UNKNOWN_OPCODE, [120] = _TAIL_CALL_UNKNOWN_OPCODE, @@ -1274,12 +1287,6 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [125] = _TAIL_CALL_UNKNOWN_OPCODE, [126] = _TAIL_CALL_UNKNOWN_OPCODE, [127] = _TAIL_CALL_UNKNOWN_OPCODE, - [219] = _TAIL_CALL_UNKNOWN_OPCODE, - [220] = _TAIL_CALL_UNKNOWN_OPCODE, - [221] = _TAIL_CALL_UNKNOWN_OPCODE, - [222] = _TAIL_CALL_UNKNOWN_OPCODE, - [223] = _TAIL_CALL_UNKNOWN_OPCODE, - [224] = _TAIL_CALL_UNKNOWN_OPCODE, [225] = _TAIL_CALL_UNKNOWN_OPCODE, [226] = _TAIL_CALL_UNKNOWN_OPCODE, [227] = _TAIL_CALL_UNKNOWN_OPCODE, diff --git a/Objects/frameobject.c b/Objects/frameobject.c index 475be76dc3da21..c90fb14f14ae49 100644 --- a/Objects/frameobject.c +++ b/Objects/frameobject.c @@ -1453,6 +1453,21 @@ mark_stacks(PyCodeObject *code_obj, int len) stacks[j] = next_stack; stacks[next_i] = next_stack; break; + case END_AWAITED_CALL: + { + /* (lazy_outcome, res) -- res, or jump to YIELD_VALUE + * with (coroutine, NULL, res) as left by SEND */ + next_stack = pop_value(pop_value(next_stack)); + int64_t target_stack = push_value(next_stack, Object); + target_stack = push_value(target_stack, Object); + target_stack = push_value(target_stack, Object); + j = next_i + oparg; + assert(j < len); + assert(stacks[j] == UNINITIALIZED || stacks[j] == target_stack); + stacks[j] = target_stack; + stacks[next_i] = push_value(next_stack, Object); + break; + } case JUMP_FORWARD: j = oparg + i + 1; assert(j < len); diff --git a/Objects/genobject.c b/Objects/genobject.c index 82a1bb1ff42068..5cf8efae9d1ad0 100644 --- a/Objects/genobject.c +++ b/Objects/genobject.c @@ -1104,9 +1104,8 @@ PyTypeObject PyGen_Type = { }; static PyObject * -make_gen(PyTypeObject *type, PyFunctionObject *func) +make_gen(PyTypeObject *type, PyFunctionObject *func, PyCodeObject *code) { - PyCodeObject *code = (PyCodeObject *)func->func_code; int slots = _PyFrame_NumSlotsForCodeObject(code); PyGenObject *gen = PyObject_GC_NewVar(PyGenObject, type, slots); if (gen == NULL) { @@ -1127,18 +1126,44 @@ make_gen(PyTypeObject *type, PyFunctionObject *func) return (PyObject *)gen; } +static PyObject * +make_coro(PyFunctionObject *func, PyCodeObject *code, + _PyInterpreterFrame *caller) +{ + PyObject *coro = make_gen(&PyCoro_Type, func, code); + if (!coro) { + return NULL; + } + PyThreadState *tstate = _PyThreadState_GET(); + int origin_depth = tstate->coroutine_origin_tracking_depth; + + if (origin_depth == 0) { + ((PyCoroObject *)coro)->cr_origin_or_finalizer = NULL; + } else { + _PyInterpreterFrame *frame = _PyFrame_GetFirstComplete(caller); + PyObject *cr_origin = _PyCoro_ComputeOrigin(origin_depth, frame); + ((PyCoroObject *)coro)->cr_origin_or_finalizer = cr_origin; + if (!cr_origin) { + Py_DECREF(coro); + return NULL; + } + } + return coro; +} + PyObject * _Py_MakeCoro(PyFunctionObject *func) { - int coro_flags = ((PyCodeObject *)func->func_code)->co_flags & + PyCodeObject *code = (PyCodeObject *)func->func_code; + int coro_flags = code->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR); assert(coro_flags); if (coro_flags == CO_GENERATOR) { - return make_gen(&PyGen_Type, func); + return make_gen(&PyGen_Type, func, code); } if (coro_flags == CO_ASYNC_GENERATOR) { PyAsyncGenObject *ag; - ag = (PyAsyncGenObject *)make_gen(&PyAsyncGen_Type, func); + ag = (PyAsyncGenObject *)make_gen(&PyAsyncGen_Type, func, code); if (ag == NULL) { return NULL; } @@ -1150,26 +1175,30 @@ _Py_MakeCoro(PyFunctionObject *func) } assert (coro_flags == CO_COROUTINE); - PyObject *coro = make_gen(&PyCoro_Type, func); - if (!coro) { - return NULL; - } PyThreadState *tstate = _PyThreadState_GET(); - int origin_depth = tstate->coroutine_origin_tracking_depth; + _PyInterpreterFrame *frame = tstate->current_frame; + assert(frame); + assert(_PyFrame_IsIncomplete(frame)); + return make_coro(func, code, frame->previous); +} - if (origin_depth == 0) { +/* The body may have replaced func.__code__, so size the coroutine for the + * code the frame is running. The caller moves the frame into it. */ +PyObject * +_PyCoro_MaterializeLazy(_PyInterpreterFrame *frame) +{ + assert(frame->owner == FRAME_OWNED_BY_THREAD); + assert(frame->lazy_coro == LAZY_CORO_RUNNING); + assert(PyStackRef_FunctionCheck(frame->f_funcobj)); + PyFunctionObject *func = + (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(frame->f_funcobj); + PyCodeObject *code = _PyFrame_GetCode(frame); + assert((code->co_flags & + (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) == CO_COROUTINE); + PyObject *coro = make_gen(&PyCoro_Type, func, code); + if (coro != NULL) { + // Origin tracking was off at the call (see MAYBE_START_LAZY_CORO). ((PyCoroObject *)coro)->cr_origin_or_finalizer = NULL; - } else { - _PyInterpreterFrame *frame = tstate->current_frame; - assert(frame); - assert(_PyFrame_IsIncomplete(frame)); - frame = _PyFrame_GetFirstComplete(frame->previous); - PyObject *cr_origin = _PyCoro_ComputeOrigin(origin_depth, frame); - ((PyCoroObject *)coro)->cr_origin_or_finalizer = cr_origin; - if (!cr_origin) { - Py_DECREF(coro); - return NULL; - } } return coro; } diff --git a/Programs/test_frozenmain.h b/Programs/test_frozenmain.h index ebcb38b18dec90..20201f7ec2d99e 100644 --- a/Programs/test_frozenmain.h +++ b/Programs/test_frozenmain.h @@ -1,19 +1,19 @@ // Auto-generated by Programs/freeze_test_frozenmain.py unsigned char M_test_frozenmain[] = { 99,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0, - 0,0,0,0,0,115,188,0,0,0,128,0,0,0,90,0, - 77,7,69,0,112,0,90,0,77,7,69,4,112,1,89,2, - 31,0,78,1,50,1,0,0,0,0,0,0,29,0,89,2, - 31,0,78,2,89,0,76,6,0,0,0,0,0,0,0,0, + 0,0,0,0,0,115,188,0,0,0,128,0,0,0,91,0, + 78,7,70,0,113,0,91,0,78,7,70,4,113,1,90,2, + 31,0,79,1,50,1,0,0,0,0,0,0,29,0,90,2, + 31,0,79,2,90,0,77,6,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,50,2,0,0,0,0, - 0,0,29,0,89,1,76,8,0,0,0,0,0,0,0,0, + 0,0,29,0,90,1,77,8,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,31,0,50,0,0,0, - 0,0,0,0,78,3,42,26,0,0,0,0,0,0,0,0, - 0,0,112,5,78,6,67,0,0,0,65,24,0,0,112,6, - 89,2,31,0,78,4,89,6,12,0,78,5,89,5,89,6, + 0,0,0,0,79,3,42,26,0,0,0,0,0,0,0,0, + 0,0,113,5,79,6,68,0,0,0,66,24,0,0,113,6, + 90,2,31,0,79,4,90,6,12,0,79,5,90,5,90,6, 42,26,0,0,0,0,0,0,0,0,0,0,12,0,48,4, - 50,1,0,0,0,0,0,0,29,0,71,26,0,0,9,0, - 28,0,77,7,33,0,41,7,105,0,0,0,0,122,18,70, + 50,1,0,0,0,0,0,0,29,0,72,26,0,0,9,0, + 28,0,78,7,33,0,41,7,105,0,0,0,0,122,18,70, 114,111,122,101,110,32,72,101,108,108,111,32,87,111,114,108, 100,122,8,115,121,115,46,97,114,103,118,218,6,99,111,110, 102,105,103,122,7,99,111,110,102,105,103,32,122,2,58,32, diff --git a/Python/bytecodes.c b/Python/bytecodes.c index c6f1f61f3e08fe..c022c1183a88cc 100644 --- a/Python/bytecodes.c +++ b/Python/bytecodes.c @@ -1660,6 +1660,53 @@ dummy_func( none = PyStackRef_None; } + replaced op(_END_AWAITED_CALL, (lazy_outcome, res -- lazy_outcome, res)) { + if (PyStackRef_IsTaggedInt(lazy_outcome)) { + lazy_outcome = PyStackRef_NULL; + _Py_CODEUNIT *send = next_instr + oparg - 1 - INLINE_CACHE_ENTRIES_SEND; + assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), + (int)(send - _PyFrame_GetBytecode(frame))).op.code == SEND); + _Py_CODEUNIT *end_send = next_instr + oparg + send->op.arg; + if (end_send->op.code != END_SEND) { + // Emulate the monitoring event of INSTRUMENTED_END_SEND. + int err = monitor_stop_iteration(tstate, frame, end_send, + PyStackRef_AsPyObjectBorrow(res)); + ERROR_IF(err); + } + JUMPBY(oparg + send->op.arg + 1); + } + else if (!PyStackRef_IsNull(lazy_outcome)) { + _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(lazy_outcome); + lazy_outcome = PyStackRef_NULL; + PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); + _PyStackRef v = res; + DEAD(res); + DEAD(lazy_outcome); + if (gen == NULL) { + stack_pointer[-1] = PyStackRef_NULL; + frame = _PyEval_ThrowIntoLazyCoro(tstate, lazy_frame, v); + next_instr = frame->instr_ptr; + LOAD_SP(); + goto error; + } + stack_pointer[-2] = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + stack_pointer[-1] = PyStackRef_NULL; + stack_pointer[0] = v; + stack_pointer += 1; + JUMPBY(oparg); + DISPATCH(); + } + } + + op(_POP_LAZY_OUTCOME, (lazy_outcome, res -- value)) { + assert(PyStackRef_IsNull(lazy_outcome)); + DEAD(lazy_outcome); + value = res; + DEAD(res); + } + + macro(END_AWAITED_CALL) = _END_AWAITED_CALL + _POP_LAZY_OUTCOME; + family(SEND, INLINE_CACHE_ENTRIES_SEND) = { SEND_GEN, SEND_VIRTUAL, @@ -1853,28 +1900,45 @@ dummy_func( EXIT_IF(what == PYGEN_RETURN); } + replaced op(_CHECK_LAZY_CORO, (--)) { + } + + tier2 op(_GUARD_NOT_LAZY_CORO, (--)) { + EXIT_IF(frame->lazy_coro == LAZY_CORO_RUNNING); + } + op(_YIELD_VALUE, (retval -- value)) { // NOTE: It's important that YIELD_VALUE never raises an exception! // The compiler treats any exception raised here as a failed close() // or throw() call. assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); frame->instr_ptr++; - PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); assert(FRAME_SUSPENDED_YIELD_FROM == FRAME_SUSPENDED + 1); assert(oparg == 0 || oparg == 1); _PyStackRef temp = retval; DEAD(retval); SAVE_STACK(); DTRACE_FUNCTION_RETURN(); - tstate->exc_info = gen->gi_exc_state.previous_item; - gen->gi_exc_state.previous_item = NULL; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *gen_frame = frame; - _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); - frame = tstate->current_frame = frame->previous; - gen_frame->previous = NULL; - ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; - FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + int offset = 1 + INLINE_CACHE_ENTRIES_SEND; + if (frame->lazy_coro == LAZY_CORO_RUNNING) { + // The caller's END_AWAITED_CALL creates the coroutine. It is + // never instrumented, so nothing runs in between. + assert(oparg == 1); + frame = _PyEval_SuspendLazyCoro(tstate, frame); + offset = 0; + } + else { + PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); + tstate->exc_info = gen->gi_exc_state.previous_item; + gen->gi_exc_state.previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *gen_frame = frame; + _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); + frame = tstate->current_frame = frame->previous; + gen_frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + } /* We don't know which of these is relevant here, so keep them equal */ assert(INLINE_CACHE_ENTRIES_SEND == INLINE_CACHE_ENTRIES_FOR_ITER); #if TIER_ONE && defined(Py_DEBUG) @@ -1882,16 +1946,18 @@ dummy_func( Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(opcode == SEND || opcode == FOR_ITER); + assert(offset == 0 ? opcode == END_AWAITED_CALL + : (opcode == SEND || opcode == FOR_ITER)); } #endif RELOAD_STACK(); - LOAD_IP(1 + INLINE_CACHE_ENTRIES_SEND); + LOAD_IP(offset); value = temp; LLTRACE_RESUME_FRAME(); } macro(YIELD_VALUE) = + _CHECK_LAZY_CORO + _MAKE_HEAP_SAFE + _YIELD_VALUE; @@ -1911,6 +1977,7 @@ dummy_func( } macro(INSTRUMENTED_YIELD_VALUE) = + _CHECK_LAZY_CORO + _YIELD_VALUE_EVENT + _MAKE_HEAP_SAFE + _YIELD_VALUE; @@ -4318,6 +4385,10 @@ dummy_func( CALL_PY_GENERAL, CALL_BOUND_METHOD_GENERAL, CALL_NON_PY_GENERAL, + CALL_PY_EXACT_ARGS_AWAITED, + CALL_BOUND_METHOD_EXACT_ARGS_AWAITED, + CALL_PY_GENERAL_AWAITED, + CALL_BOUND_METHOD_GENERAL_AWAITED, }; specializing op(_SPECIALIZE_CALL, (counter/1, callable, self_or_null, unused[oparg] -- callable, self_or_null, unused[oparg])) { @@ -4376,6 +4447,9 @@ dummy_func( if (new_frame == NULL) { ERROR_NO_POP(); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL) { + MAYBE_START_LAZY_CORO(new_frame); + } frame->return_offset = INSTRUCTION_SIZE; DISPATCH_INLINED(new_frame); } @@ -4467,6 +4541,17 @@ dummy_func( _SAVE_RETURN_OFFSET + _PUSH_FRAME; + macro(CALL_PY_GENERAL_AWAITED) = + _RECORD_CALLABLE + + unused/1 + + _CHECK_PEP_523 + + _CHECK_FUNCTION_VERSION + + _CHECK_RECURSION_REMAINING + + _PY_FRAME_GENERAL + + _START_LAZY_CORO + + _SAVE_RETURN_OFFSET + + _PUSH_FRAME; + op(_CHECK_METHOD_VERSION, (func_version/2, callable, null, unused[oparg] -- callable, null, unused[oparg])) { PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); @@ -4500,6 +4585,19 @@ dummy_func( _SAVE_RETURN_OFFSET + _PUSH_FRAME; + macro(CALL_BOUND_METHOD_GENERAL_AWAITED) = + _RECORD_BOUND_METHOD + + unused/1 + + _CHECK_PEP_523 + + _CHECK_METHOD_VERSION + + _EXPAND_METHOD + + flush + + _CHECK_RECURSION_REMAINING + + _PY_FRAME_GENERAL + + _START_LAZY_CORO + + _SAVE_RETURN_OFFSET + + _PUSH_FRAME; + op(_CHECK_IS_NOT_PY_CALLABLE, (callable, unused, unused[oparg] -- callable, unused, unused[oparg])) { PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); EXIT_IF(PyFunction_Check(callable_o)); @@ -4620,6 +4718,26 @@ dummy_func( _SAVE_RETURN_OFFSET + _PUSH_FRAME; + macro(CALL_BOUND_METHOD_EXACT_ARGS_AWAITED) = + _RECORD_BOUND_METHOD + + unused/1 + + _CHECK_PEP_523 + + _CHECK_CALL_BOUND_METHOD_EXACT_ARGS + + _INIT_CALL_BOUND_METHOD_EXACT_ARGS + + flush + + _CHECK_FUNCTION_VERSION + + _CHECK_FUNCTION_EXACT_ARGS + + _CHECK_STACK_SPACE + + _CHECK_RECURSION_REMAINING + + _INIT_CALL_PY_EXACT_ARGS + + _START_LAZY_CORO + + _SAVE_RETURN_OFFSET + + _PUSH_FRAME; + + replaced op(_START_LAZY_CORO, (new_frame -- new_frame)) { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + macro(CALL_PY_EXACT_ARGS) = _RECORD_CALLABLE + unused/1 + // Skip over the counter @@ -4632,6 +4750,19 @@ dummy_func( _SAVE_RETURN_OFFSET + _PUSH_FRAME; + macro(CALL_PY_EXACT_ARGS_AWAITED) = + _RECORD_CALLABLE + + unused/1 + + _CHECK_PEP_523 + + _CHECK_FUNCTION_VERSION + + _CHECK_FUNCTION_EXACT_ARGS + + _CHECK_STACK_SPACE + + _CHECK_RECURSION_REMAINING + + _INIT_CALL_PY_EXACT_ARGS + + _START_LAZY_CORO + + _SAVE_RETURN_OFFSET + + _PUSH_FRAME; + op(_GUARD_NOS_NULL, (null, unused -- null, unused)) { EXIT_IF(!PyStackRef_IsNull(null)); } @@ -5354,6 +5485,8 @@ dummy_func( CALL_KW_BOUND_METHOD, CALL_KW_PY, CALL_KW_NON_PY, + CALL_KW_PY_AWAITED, + CALL_KW_BOUND_METHOD_AWAITED, }; op(_MONITOR_CALL_KW, (callable, self_or_null, args[oparg], unused -- callable, self_or_null, args[oparg], unused)) { @@ -5421,6 +5554,9 @@ dummy_func( if (new_frame == NULL) { ERROR_NO_POP(); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL_KW) { + MAYBE_START_LAZY_CORO(new_frame); + } assert(INSTRUCTION_SIZE == 1 + INLINE_CACHE_ENTRIES_CALL_KW); frame->return_offset = INSTRUCTION_SIZE; DISPATCH_INLINED(new_frame); @@ -5489,6 +5625,17 @@ dummy_func( _SAVE_RETURN_OFFSET + _PUSH_FRAME; + macro(CALL_KW_PY_AWAITED) = + _RECORD_CALLABLE_KW + + unused/1 + + _CHECK_PEP_523 + + _CHECK_FUNCTION_VERSION_KW + + _CHECK_RECURSION_REMAINING + + _PY_FRAME_KW + + _START_LAZY_CORO + + _SAVE_RETURN_OFFSET + + _PUSH_FRAME; + op(_CHECK_METHOD_VERSION_KW, (func_version/2, callable, null, unused[oparg], unused -- callable, null, unused[oparg], unused)) { PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); @@ -5521,6 +5668,18 @@ dummy_func( _SAVE_RETURN_OFFSET + _PUSH_FRAME; + macro(CALL_KW_BOUND_METHOD_AWAITED) = + _RECORD_CALLABLE_KW + + unused/1 + + _CHECK_PEP_523 + + _CHECK_METHOD_VERSION_KW + + _EXPAND_METHOD_KW + + flush + + _PY_FRAME_KW + + _START_LAZY_CORO + + _SAVE_RETURN_OFFSET + + _PUSH_FRAME; + specializing op(_SPECIALIZE_CALL_KW, (counter/1, callable, self_or_null, unused[oparg], unused -- callable, self_or_null, unused[oparg], unused)) { #if ENABLE_SPECIALIZATION if (ADAPTIVE_COUNTER_TRIGGERS(counter)) { @@ -5666,6 +5825,9 @@ dummy_func( if (new_frame == NULL) { ERROR_NO_POP(); } + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(new_frame); + } assert(INSTRUCTION_SIZE == 1 + INLINE_CACHE_ENTRIES_CALL_FUNCTION_EX); frame->return_offset = INSTRUCTION_SIZE; DISPATCH_INLINED(new_frame); @@ -5738,6 +5900,7 @@ dummy_func( _MAKE_CALLARGS_A_TUPLE + _CHECK_IS_PY_CALLABLE_EX + _PY_FRAME_EX + + _MAYBE_LAZY_CORO + _SAVE_RETURN_OFFSET + _PUSH_FRAME; @@ -5810,25 +5973,52 @@ dummy_func( inst(RETURN_GENERATOR, (-- res)) { assert(PyStackRef_FunctionCheck(frame->f_funcobj)); PyFunctionObject *func = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(frame->f_funcobj); - PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); - ERROR_IF(gen == NULL); - assert(STACK_LEVEL() <= 2); - SAVE_STACK(); - _PyInterpreterFrame *gen_frame = &gen->gi_iframe; - frame->instr_ptr++; - _PyFrame_Copy(frame, gen_frame); - assert(frame->frame_obj == NULL); - gen->gi_frame_state = FRAME_CREATED; - gen_frame->owner = FRAME_OWNED_BY_GENERATOR; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *prev = frame->previous; - _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); - _PyThreadState_PopFrame(tstate, frame); - frame = tstate->current_frame = prev; - LOAD_IP(frame->return_offset); - RELOAD_STACK(); - res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); - LLTRACE_RESUME_FRAME(); + _PyErr_StackItem *exc_info = NULL; + #if TIER_ONE + if (frame->lazy_coro == LAZY_CORO_REQUESTED) { + /* The body's exception state, as SEND_GEN would push. */ + exc_info = (_PyErr_StackItem *)_PyThreadState_PushFrame( + tstate, sizeof(_PyErr_StackItem) / sizeof(PyObject *)); + if (exc_info == NULL) { + _PyErr_Clear(tstate); + } + } + #endif + if (exc_info != NULL) { + exc_info->exc_value = NULL; + exc_info->previous_item = tstate->exc_info; + tstate->exc_info = exc_info; + frame->lazy_coro = LAZY_CORO_RUNNING; + /* While the body runs, the caller is at the await, as at + * SEND on the eager path. */ + _PyInterpreterFrame *caller = frame->previous; + caller->instr_ptr += caller->return_offset; + caller->return_offset = 0; + /* The following POP_TOP discards this. */ + res = PyStackRef_None; + } + else { + frame->lazy_coro = 0; + PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); + ERROR_IF(gen == NULL); + assert(STACK_LEVEL() <= 2); + SAVE_STACK(); + _PyInterpreterFrame *gen_frame = &gen->gi_iframe; + frame->instr_ptr++; + _PyFrame_Copy(frame, gen_frame); + assert(frame->frame_obj == NULL); + gen->gi_frame_state = FRAME_CREATED; + gen_frame->owner = FRAME_OWNED_BY_GENERATOR; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *prev = frame->previous; + _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); + _PyThreadState_PopFrame(tstate, frame); + frame = tstate->current_frame = prev; + LOAD_IP(frame->return_offset); + RELOAD_STACK(); + res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + LLTRACE_RESUME_FRAME(); + } } inst(BUILD_SLICE, (args[oparg] -- slice)) { @@ -6105,6 +6295,12 @@ dummy_func( DEOPT_IF(!_PyThreadState_HasStackSpace(tstate, framesize)); } + replaced op(_MAYBE_LAZY_CORO, (new_frame -- new_frame)) { + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + } + op(_SAVE_RETURN_OFFSET, (--)) { #if TIER_ONE frame->return_offset = (uint16_t)(next_instr - this_instr); diff --git a/Python/ceval.c b/Python/ceval.c index ccc0edca2fc794..99d4399e4ee661 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -2005,10 +2005,9 @@ initialize_locals(PyThreadState *tstate, PyFunctionObject *func, return -1; } -static void -clear_thread_frame(PyThreadState *tstate, _PyInterpreterFrame * frame) +static inline void +clear_and_pop_thread_frame(PyThreadState *tstate, _PyInterpreterFrame *frame) { - assert(frame->owner == FRAME_OWNED_BY_THREAD); // Make sure that this is, indeed, the top frame. We can't check this in // _PyThreadState_PopFrame, since f_code is already cleared at that point: assert((PyObject **)frame + _PyFrame_GetCode(frame)->co_framesize == @@ -2019,6 +2018,35 @@ clear_thread_frame(PyThreadState *tstate, _PyInterpreterFrame * frame) _PyThreadState_PopFrame(tstate, frame); } +static Py_NO_INLINE void +clear_lazy_coro_frame(PyThreadState *tstate, _PyInterpreterFrame *frame) +{ + _PyErr_StackItem *exc_info = tstate->exc_info; + tstate->exc_info = exc_info->previous_item; + PyObject *exc_value = exc_info->exc_value; + _PyThreadState_PopFrame(tstate, (_PyInterpreterFrame *)exc_info); + frame->lazy_coro = 0; + _PyInterpreterFrame *caller = frame->previous; + assert(PyStackRef_IsNull(caller->stackpointer[-1])); + caller->stackpointer[-1] = PyStackRef_TagInt(0); + // Like clear_gen_frame(): a frame object that outlives the + // coroutine must not keep the caller's frame alive via f_back. + frame->previous = NULL; + clear_and_pop_thread_frame(tstate, frame); + Py_XDECREF(exc_value); +} + +static void +clear_thread_frame(PyThreadState *tstate, _PyInterpreterFrame * frame) +{ + assert(frame->owner == FRAME_OWNED_BY_THREAD); + if (frame->lazy_coro == LAZY_CORO_RUNNING) { + clear_lazy_coro_frame(tstate, frame); + return; + } + clear_and_pop_thread_frame(tstate, frame); +} + static void clear_gen_frame(PyThreadState *tstate, _PyInterpreterFrame * frame) { @@ -3686,6 +3714,85 @@ _PyEval_LoadGlobalStackRef(PyObject *globals, PyObject *builtins, PyObject *name } } +/* Suspend the lazy coroutine running in frame, leaving the frame and its + * exception state on the data stack for the caller's END_AWAITED_CALL. */ +_PyInterpreterFrame * +_PyEval_SuspendLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame) +{ + assert(frame->lazy_coro == LAZY_CORO_RUNNING); + _PyErr_StackItem *exc_info = tstate->exc_info; + tstate->exc_info = exc_info->previous_item; + exc_info->previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *caller = frame->previous; + _PyThreadState_UpdateLastProfiledFrame(tstate, frame, caller); + tstate->current_frame = caller; + frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + assert(caller->return_offset == 0); + assert(PyStackRef_IsNull(caller->stackpointer[-1])); + caller->stackpointer[-1] = PyStackRef_Wrap(frame); + return caller; +} + +PyGenObject * +_PyEval_MaterializeLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame) +{ + assert(frame->owner == FRAME_OWNED_BY_THREAD); + assert(frame->lazy_coro == LAZY_CORO_RUNNING); + assert(frame->previous == NULL); + const int item_slots = sizeof(_PyErr_StackItem) / sizeof(PyObject *); + _PyErr_StackItem *exc_info = + (_PyErr_StackItem *)(tstate->datastack_top - item_slots); + assert(exc_info->previous_item == NULL); + assert((PyObject **)frame + _PyFrame_GetCode(frame)->co_framesize == + (PyObject **)exc_info); + PyGenObject *gen = (PyGenObject *)_PyCoro_MaterializeLazy(frame); + if (gen == NULL) { + return NULL; + } + gen->gi_exc_state.exc_value = exc_info->exc_value; + _PyThreadState_PopFrame(tstate, (_PyInterpreterFrame *)exc_info); + _PyInterpreterFrame *gen_frame = &gen->gi_iframe; + _PyFrame_Copy(frame, gen_frame); + gen_frame->owner = FRAME_OWNED_BY_GENERATOR; + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED_YIELD_FROM); + PyFrameObject *f = gen_frame->frame_obj; + if (f != NULL) { + Py_BEGIN_CRITICAL_SECTION(f); + f->f_frame = gen_frame; + Py_END_CRITICAL_SECTION(); + } + _PyThreadState_PopFrame(tstate, frame); + return gen; +} + +/* Resume the frame of a lazy coroutine that could not be materialized, raising + * the current exception at its suspension point, so its handlers run. */ +_PyInterpreterFrame * +_PyEval_ThrowIntoLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame, + _PyStackRef value) +{ + assert(frame->owner == FRAME_OWNED_BY_THREAD); + assert(frame->lazy_coro == LAZY_CORO_RUNNING); + assert(_PyErr_Occurred(tstate)); + const int item_slots = sizeof(_PyErr_StackItem) / sizeof(PyObject *); + _PyErr_StackItem *exc_info = + (_PyErr_StackItem *)(tstate->datastack_top - item_slots); + exc_info->previous_item = tstate->exc_info; + tstate->exc_info = exc_info; + _PyInterpreterFrame *caller = tstate->current_frame; + assert(caller->return_offset == 0); + frame->previous = caller; + tstate->current_frame = frame; + int too_deep = _Py_EnterRecursivePy(tstate); + assert(!too_deep); + (void)too_deep; + // Stands in for the value sent on resumption, like gen_send_ex2(). + _PyFrame_StackPush(frame, value); + return frame; +} + PyObject * _PyEval_GetAwaitable(PyObject *iterable, int oparg) { diff --git a/Python/ceval.h b/Python/ceval.h index 00db67265a4f3a..0ba365a454b7ad 100644 --- a/Python/ceval.h +++ b/Python/ceval.h @@ -304,6 +304,8 @@ maybe_lltrace_resume_frame(_PyInterpreterFrame *frame, PyObject *globals) lltrace = *python_lltrace - '0'; // TODO: Parse an int and all that } } + // 5 is the highest level; it must fit in frame->lltrace + lltrace = Py_MIN(lltrace, 5); if (lltrace >= 5) { lltrace_resume_frame(frame); } diff --git a/Python/ceval_macros.h b/Python/ceval_macros.h index 36921e35533433..b9e2134c21602c 100644 --- a/Python/ceval_macros.h +++ b/Python/ceval_macros.h @@ -156,6 +156,28 @@ # define LEAVE_TRACING() tracing_mode = 0 #endif +/* Tier one only, after next_instr has skipped the call's inline cache. + * END_AWAITED_CALL is never instrumented or specialized. */ +#define IS_AWAITED_CALL() (next_instr->op.code == END_AWAITED_CALL) + +/* The JIT recorder expects the regular path, and coroutine origin tracking + * captures the origin when the object is created. */ +#if _Py_TIER2 +# define LAZY_CORO_ALLOWED() (!IS_JIT_TRACING()) +#else +# define LAZY_CORO_ALLOWED() 1 +#endif +#define MAYBE_START_LAZY_CORO(FRAME) \ + do { \ + _PyInterpreterFrame *lazy_frame_ = (FRAME); \ + if ((_PyFrame_GetCode(lazy_frame_)->co_flags & CO_COROUTINE) && \ + tstate->coroutine_origin_tracking_depth == 0 && \ + LAZY_CORO_ALLOWED()) \ + { \ + lazy_frame_->lazy_coro = LAZY_CORO_REQUESTED; \ + } \ + } while (0) + #if _Py_TIER2 #define STOP_TRACING() \ do { \ diff --git a/Python/codegen.c b/Python/codegen.c index ae60caf195f23c..bdb6bb1ba59d41 100644 --- a/Python/codegen.c +++ b/Python/codegen.c @@ -496,8 +496,10 @@ codegen_call_exit_with_nones(compiler *c, location loc) return SUCCESS; } +/* If `yield` is a valid label, it is placed on the YIELD_VALUE. */ static int -codegen_add_yield_from(compiler *c, location loc, int await) +codegen_add_yield_from_impl(compiler *c, location loc, int await, + jump_target_label yield) { NEW_JUMP_TARGET_LABEL(c, send); NEW_JUMP_TARGET_LABEL(c, fail); @@ -508,6 +510,9 @@ codegen_add_yield_from(compiler *c, location loc, int await) // Set up a virtual try/except to handle when StopIteration is raised during // a close or throw call. The only way YIELD_VALUE raises if they do! ADDOP_JUMP(c, loc, SETUP_FINALLY, fail); + if (IS_JUMP_TARGET_LABEL(yield)) { + USE_LABEL(c, yield); + } ADDOP_I(c, loc, YIELD_VALUE, 1); ADDOP(c, NO_LOCATION, POP_BLOCK); ADDOP_I(c, loc, RESUME, await ? RESUME_AFTER_AWAIT : RESUME_AFTER_YIELD_FROM); @@ -521,6 +526,23 @@ codegen_add_yield_from(compiler *c, location loc, int await) return SUCCESS; } +static int +codegen_add_yield_from(compiler *c, location loc, int await) +{ + return codegen_add_yield_from_impl(c, loc, await, NO_LABEL); +} + +/* Await the result of a call made with a NULL `lazy_outcome` below the + * callable. */ +static int +codegen_await_call_result(compiler *c, location loc, int oparg) +{ + NEW_JUMP_TARGET_LABEL(c, yield); + ADDOP_JUMP(c, loc, END_AWAITED_CALL, yield); + ADDOP_I(c, loc, GET_AWAITABLE, oparg); + return codegen_add_yield_from_impl(c, loc, 1, yield); +} + static int codegen_pop_except_and_reraise(compiler *c, location loc) { @@ -612,13 +634,16 @@ codegen_unwind_fblock(compiler *c, location *ploc, *ploc = info->fb_loc; ADDOP(c, *ploc, POP_BLOCK); if (preserve_tos) { + if (info->fb_type == COMPILE_FBLOCK_ASYNC_WITH) { + /* Also below the lazy_outcome of __aexit__() */ + ADDOP_I(c, *ploc, SWAP, 4); + } ADDOP_I(c, *ploc, SWAP, 3); ADDOP_I(c, *ploc, SWAP, 2); } RETURN_IF_ERROR(codegen_call_exit_with_nones(c, *ploc)); if (info->fb_type == COMPILE_FBLOCK_ASYNC_WITH) { - ADDOP_I(c, *ploc, GET_AWAITABLE, 2); - ADD_YIELD_FROM(c, *ploc, 1); + RETURN_IF_ERROR(codegen_await_call_result(c, *ploc, 2)); } ADDOP(c, *ploc, POP_TOP); /* The exit block should appear to execute after the @@ -4266,6 +4291,24 @@ codegen_call(compiler *c, expr_ty e) return ret; } +/* `await ` pushes a NULL `lazy_outcome` below the callable, and + * END_AWAITED_CALL after the call marks it as awaited. */ +static int +codegen_await(compiler *c, expr_ty e) +{ + location loc = LOC(e); + expr_ty value = e->v.Await.value; + if (value->kind != Call_kind) { + VISIT(c, expr, value); + ADDOP_I(c, loc, GET_AWAITABLE, 0); + ADD_YIELD_FROM(c, loc, 1); + return SUCCESS; + } + ADDOP(c, LOC(value), PUSH_NULL); + RETURN_IF_ERROR(codegen_call(c, value)); + return codegen_await_call_result(c, loc, 0); +} + static int codegen_template_str(compiler *c, expr_ty e) { @@ -5234,7 +5277,8 @@ codegen_visit_keyword(compiler *c, keyword_ty k) static int -codegen_with_except_finish(compiler *c, jump_target_label cleanup) { +codegen_with_except_finish(compiler *c, jump_target_label cleanup, + int is_async) { NEW_JUMP_TARGET_LABEL(c, suppress); ADDOP(c, NO_LOCATION, TO_BOOL); ADDOP_JUMP(c, NO_LOCATION, POP_JUMP_IF_TRUE, suppress); @@ -5247,6 +5291,10 @@ codegen_with_except_finish(compiler *c, jump_target_label cleanup) { ADDOP(c, NO_LOCATION, POP_TOP); ADDOP(c, NO_LOCATION, POP_TOP); ADDOP(c, NO_LOCATION, POP_TOP); + if (is_async) { + /* The lazy_outcome of __aexit__() */ + ADDOP(c, NO_LOCATION, POP_TOP); + } NEW_JUMP_TARGET_LABEL(c, exit); ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, exit); @@ -5297,14 +5345,19 @@ codegen_async_with_inner(compiler *c, stmt_ty s, int pos) /* Evaluate EXPR */ VISIT(c, expr, item->context_expr); loc = LOC(item->context_expr); + /* The lazy_outcome of __aexit__() */ + ADDOP(c, loc, PUSH_NULL); + ADDOP_I(c, loc, SWAP, 2); ADDOP_I(c, loc, COPY, 1); ADDOP_I(c, loc, LOAD_SPECIAL, SPECIAL___AEXIT__); ADDOP_I(c, loc, SWAP, 2); ADDOP_I(c, loc, SWAP, 3); + /* The lazy_outcome of __aenter__() */ + ADDOP(c, loc, PUSH_NULL); + ADDOP_I(c, loc, SWAP, 2); ADDOP_I(c, loc, LOAD_SPECIAL, SPECIAL___AENTER__); ADDOP_I(c, loc, CALL, 0); - ADDOP_I(c, loc, GET_AWAITABLE, 1); - ADD_YIELD_FROM(c, loc, 1); + RETURN_IF_ERROR(codegen_await_call_result(c, loc, 1)); ADDOP_JUMP(c, loc, SETUP_WITH, final); @@ -5338,8 +5391,7 @@ codegen_async_with_inner(compiler *c, stmt_ty s, int pos) * call __exit__(None, None, None) */ RETURN_IF_ERROR(codegen_call_exit_with_nones(c, loc)); - ADDOP_I(c, loc, GET_AWAITABLE, 2); - ADD_YIELD_FROM(c, loc, 1); + RETURN_IF_ERROR(codegen_await_call_result(c, loc, 2)); ADDOP(c, loc, POP_TOP); @@ -5353,7 +5405,7 @@ codegen_async_with_inner(compiler *c, stmt_ty s, int pos) ADDOP(c, loc, WITH_EXCEPT_START); ADDOP_I(c, loc, GET_AWAITABLE, 2); ADD_YIELD_FROM(c, loc, 1); - RETURN_IF_ERROR(codegen_with_except_finish(c, cleanup)); + RETURN_IF_ERROR(codegen_with_except_finish(c, cleanup, 1)); USE_LABEL(c, exit); return SUCCESS; @@ -5450,7 +5502,7 @@ codegen_with_inner(compiler *c, stmt_ty s, int pos) ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup); ADDOP(c, loc, PUSH_EXC_INFO); ADDOP(c, loc, WITH_EXCEPT_START); - RETURN_IF_ERROR(codegen_with_except_finish(c, cleanup)); + RETURN_IF_ERROR(codegen_with_except_finish(c, cleanup, 0)); USE_LABEL(c, exit); return SUCCESS; @@ -5536,10 +5588,7 @@ codegen_visit_expr_impl(compiler *c, expr_ty e, bool result_is_unused) ADD_YIELD_FROM(c, loc, 0); break; case Await_kind: - VISIT(c, expr, e->v.Await.value); - ADDOP_I(c, loc, GET_AWAITABLE, 0); - ADD_YIELD_FROM(c, loc, 1); - break; + return codegen_await(c, e); case Compare_kind: return codegen_compare(c, e); case Call_kind: diff --git a/Python/executor_cases.c.h b/Python/executor_cases.c.h index 5df8120e7424b9..03e395518fb253 100644 --- a/Python/executor_cases.c.h +++ b/Python/executor_cases.c.h @@ -8946,6 +8946,83 @@ break; } + /* _END_AWAITED_CALL is not a viable micro-op for tier 2 because it is replaced */ + + case _POP_LAZY_OUTCOME_r01: { + CHECK_CURRENT_CACHED_VALUES(0); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + _PyStackRef res; + _PyStackRef lazy_outcome; + _PyStackRef value; + res = stack_pointer[-1]; + lazy_outcome = stack_pointer[-2]; + assert(PyStackRef_IsNull(lazy_outcome)); + value = res; + _tos_cache0 = value; + SET_CURRENT_CACHED_VALUES(1); + stack_pointer += -2; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + + case _POP_LAZY_OUTCOME_r11: { + CHECK_CURRENT_CACHED_VALUES(1); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + _PyStackRef res; + _PyStackRef lazy_outcome; + _PyStackRef value; + _PyStackRef _stack_item_0 = _tos_cache0; + res = _stack_item_0; + lazy_outcome = stack_pointer[-1]; + assert(PyStackRef_IsNull(lazy_outcome)); + value = res; + _tos_cache0 = value; + SET_CURRENT_CACHED_VALUES(1); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + + case _POP_LAZY_OUTCOME_r21: { + CHECK_CURRENT_CACHED_VALUES(2); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + _PyStackRef res; + _PyStackRef lazy_outcome; + _PyStackRef value; + _PyStackRef _stack_item_0 = _tos_cache0; + _PyStackRef _stack_item_1 = _tos_cache1; + res = _stack_item_1; + lazy_outcome = _stack_item_0; + assert(PyStackRef_IsNull(lazy_outcome)); + value = res; + _tos_cache0 = value; + SET_CURRENT_CACHED_VALUES(1); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + + case _POP_LAZY_OUTCOME_r32: { + CHECK_CURRENT_CACHED_VALUES(3); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + _PyStackRef res; + _PyStackRef lazy_outcome; + _PyStackRef value; + _PyStackRef _stack_item_0 = _tos_cache0; + _PyStackRef _stack_item_1 = _tos_cache1; + _PyStackRef _stack_item_2 = _tos_cache2; + res = _stack_item_2; + lazy_outcome = _stack_item_1; + assert(PyStackRef_IsNull(lazy_outcome)); + value = res; + _tos_cache1 = value; + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(2); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + case _SEND_GEN_FRAME_r33: { CHECK_CURRENT_CACHED_VALUES(3); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); @@ -9495,6 +9572,78 @@ break; } + /* _CHECK_LAZY_CORO is not a viable micro-op for tier 2 because it is replaced */ + + case _GUARD_NOT_LAZY_CORO_r00: { + CHECK_CURRENT_CACHED_VALUES(0); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + if (frame->lazy_coro == LAZY_CORO_RUNNING) { + UOP_STAT_INC(uopcode, miss); + SET_CURRENT_CACHED_VALUES(0); + JUMP_TO_JUMP_TARGET(); + } + SET_CURRENT_CACHED_VALUES(0); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + + case _GUARD_NOT_LAZY_CORO_r11: { + CHECK_CURRENT_CACHED_VALUES(1); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + _PyStackRef _stack_item_0 = _tos_cache0; + if (frame->lazy_coro == LAZY_CORO_RUNNING) { + UOP_STAT_INC(uopcode, miss); + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(1); + JUMP_TO_JUMP_TARGET(); + } + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(1); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + + case _GUARD_NOT_LAZY_CORO_r22: { + CHECK_CURRENT_CACHED_VALUES(2); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + _PyStackRef _stack_item_0 = _tos_cache0; + _PyStackRef _stack_item_1 = _tos_cache1; + if (frame->lazy_coro == LAZY_CORO_RUNNING) { + UOP_STAT_INC(uopcode, miss); + _tos_cache1 = _stack_item_1; + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(2); + JUMP_TO_JUMP_TARGET(); + } + _tos_cache1 = _stack_item_1; + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(2); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + + case _GUARD_NOT_LAZY_CORO_r33: { + CHECK_CURRENT_CACHED_VALUES(3); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + _PyStackRef _stack_item_0 = _tos_cache0; + _PyStackRef _stack_item_1 = _tos_cache1; + _PyStackRef _stack_item_2 = _tos_cache2; + if (frame->lazy_coro == LAZY_CORO_RUNNING) { + UOP_STAT_INC(uopcode, miss); + _tos_cache2 = _stack_item_2; + _tos_cache1 = _stack_item_1; + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(3); + JUMP_TO_JUMP_TARGET(); + } + _tos_cache2 = _stack_item_2; + _tos_cache1 = _stack_item_1; + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(3); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + case _YIELD_VALUE_r11: { CHECK_CURRENT_CACHED_VALUES(1); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); @@ -9505,34 +9654,43 @@ retval = _stack_item_0; assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); frame->instr_ptr++; - PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); assert(FRAME_SUSPENDED_YIELD_FROM == FRAME_SUSPENDED + 1); assert(oparg == 0 || oparg == 1); _PyStackRef temp = retval; _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); - tstate->exc_info = gen->gi_exc_state.previous_item; - gen->gi_exc_state.previous_item = NULL; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *gen_frame = frame; - _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); - frame = tstate->current_frame = frame->previous; - gen_frame->previous = NULL; - ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; - FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + int offset = 1 + INLINE_CACHE_ENTRIES_SEND; + if (frame->lazy_coro == LAZY_CORO_RUNNING) { + assert(oparg == 1); + frame = _PyEval_SuspendLazyCoro(tstate, frame); + offset = 0; + } + else { + PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); + tstate->exc_info = gen->gi_exc_state.previous_item; + gen->gi_exc_state.previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *gen_frame = frame; + _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); + frame = tstate->current_frame = frame->previous; + gen_frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + } assert(INLINE_CACHE_ENTRIES_SEND == INLINE_CACHE_ENTRIES_FOR_ITER); #if TIER_ONE && defined(Py_DEBUG) if (!PyStackRef_IsNone(frame->f_executable)) { Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(opcode == SEND || opcode == FOR_ITER); + assert(offset == 0 ? opcode == END_AWAITED_CALL + : (opcode == SEND || opcode == FOR_ITER)); } #endif stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - LOAD_IP(1 + INLINE_CACHE_ENTRIES_SEND); + LOAD_IP(offset); value = temp; LLTRACE_RESUME_FRAME(); _tos_cache0 = value; @@ -17612,6 +17770,8 @@ break; } + /* _START_LAZY_CORO is not a viable micro-op for tier 2 because it is replaced */ + case _GUARD_NOS_NULL_r02: { CHECK_CURRENT_CACHED_VALUES(0); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); @@ -20726,33 +20886,62 @@ _PyStackRef res; assert(PyStackRef_FunctionCheck(frame->f_funcobj)); PyFunctionObject *func = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(frame->f_funcobj); - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); - _PyFrame_StackPointerInvalidate(frame); - if (gen == NULL) { - SET_CURRENT_CACHED_VALUES(0); - JUMP_TO_ERROR(); + _PyErr_StackItem *exc_info = NULL; + #if TIER_ONE + if (frame->lazy_coro == LAZY_CORO_REQUESTED) { + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + exc_info = (_PyErr_StackItem *)_PyThreadState_PushFrame( + tstate, sizeof(_PyErr_StackItem) / sizeof(PyObject *)); + _PyFrame_StackPointerInvalidate(frame); + if (exc_info == NULL) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyErr_Clear(tstate); + _PyFrame_StackPointerInvalidate(frame); + } + } + #endif + if (exc_info != NULL) { + exc_info->exc_value = NULL; + exc_info->previous_item = tstate->exc_info; + tstate->exc_info = exc_info; + frame->lazy_coro = LAZY_CORO_RUNNING; + _PyInterpreterFrame *caller = frame->previous; + caller->instr_ptr += caller->return_offset; + caller->return_offset = 0; + res = PyStackRef_None; + } + else { + frame->lazy_coro = 0; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); + _PyFrame_StackPointerInvalidate(frame); + if (gen == NULL) { + SET_CURRENT_CACHED_VALUES(0); + JUMP_TO_ERROR(); + } + assert(STACK_LEVEL() <= 2); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *gen_frame = &gen->gi_iframe; + frame->instr_ptr++; + _PyFrame_Copy(frame, gen_frame); + assert(frame->frame_obj == NULL); + gen->gi_frame_state = FRAME_CREATED; + gen_frame->owner = FRAME_OWNED_BY_GENERATOR; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *prev = frame->previous; + _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); + _PyThreadState_PopFrame(tstate, frame); + frame = tstate->current_frame = prev; + LOAD_IP(frame->return_offset); + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + LLTRACE_RESUME_FRAME(); } - assert(STACK_LEVEL() <= 2); - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - _PyInterpreterFrame *gen_frame = &gen->gi_iframe; - frame->instr_ptr++; - _PyFrame_Copy(frame, gen_frame); - assert(frame->frame_obj == NULL); - gen->gi_frame_state = FRAME_CREATED; - gen_frame->owner = FRAME_OWNED_BY_GENERATOR; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *prev = frame->previous; - _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); - _PyThreadState_PopFrame(tstate, frame); - frame = tstate->current_frame = prev; - LOAD_IP(frame->return_offset); - stack_pointer = _PyFrame_GetStackPointer(frame); - _PyFrame_StackPointerInvalidate(frame); - res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); - LLTRACE_RESUME_FRAME(); _tos_cache0 = res; _tos_cache1 = PyStackRef_ZERO_BITS; _tos_cache2 = PyStackRef_ZERO_BITS; @@ -22857,6 +23046,8 @@ break; } + /* _MAYBE_LAZY_CORO is not a viable micro-op for tier 2 because it is replaced */ + case _SAVE_RETURN_OFFSET_r00: { CHECK_CURRENT_CACHED_VALUES(0); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); diff --git a/Python/flowgraph.c b/Python/flowgraph.c index fc676dc6feb167..b2fca593e8809c 100644 --- a/Python/flowgraph.c +++ b/Python/flowgraph.c @@ -798,6 +798,12 @@ get_stack_effects(int opcode, int oparg, int jump, stack_effects *effects) effects->net = 0; return 0; } + if (opcode == END_AWAITED_CALL && jump) { + // The jump to YIELD_VALUE leaves (coroutine, NULL, value) in place + // of (lazy_outcome, value). + effects->net = 1; + return 0; + } effects->net = pushed - popped; return 0; } @@ -946,7 +952,11 @@ label_exception_targets(basicblock *entryblock) { else if (is_jump(instr)) { instr->i_except = handler; assert(i == b->b_iused -1); - if (!instr->i_target->b_visited) { + // END_AWAITED_CALL's target is inside the SETUP_FINALLY + // that follows SEND. + if (!instr->i_target->b_visited && + instr->i_opcode != END_AWAITED_CALL) + { if (BB_HAS_FALLTHROUGH(b)) { struct _PyCfgExceptStack *copy = copy_except_stack(except_stack); if (copy == NULL) { @@ -3117,6 +3127,14 @@ optimize_load_fast(cfg_builder *g) break; } + case END_AWAITED_CALL: { + load_fast_push_block(&sp, instr->i_target, refs.size + 1); + ref_stack_pop(&refs); + ref_stack_pop(&refs); + PUSH_REF(i, NOT_LOCAL); + break; + } + case SEND: { load_fast_push_block(&sp, instr->i_target, refs.size); ref_stack_pop(&refs); diff --git a/Python/generated_cases.c.h b/Python/generated_cases.c.h index 3af7863e80d2c6..e4faedd7e80bcd 100644 --- a/Python/generated_cases.c.h +++ b/Python/generated_cases.c.h @@ -1896,6 +1896,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL) { + MAYBE_START_LAZY_CORO(new_frame); + } frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); } @@ -2233,6 +2236,160 @@ DISPATCH(); } + TARGET(CALL_BOUND_METHOD_EXACT_ARGS_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_BOUND_METHOD_EXACT_ARGS_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_BOUND_METHOD_EXACT_ARGS_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef null; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_CALL_BOUND_METHOD_EXACT_ARGS + { + null = stack_pointer[-1 - oparg]; + callable = stack_pointer[-2 - oparg]; + if (!PyStackRef_IsNull(null)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + if (Py_TYPE(PyStackRef_AsPyObjectBorrow(callable)) != &PyMethod_Type) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _INIT_CALL_BOUND_METHOD_EXACT_ARGS + { + self_or_null = null; + assert(PyStackRef_IsNull(self_or_null)); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + STAT_INC(CALL, hit); + self_or_null = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_self); + _PyStackRef temp = callable; + callable = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_func); + stack_pointer[-2 - oparg] = callable; + stack_pointer[-1 - oparg] = self_or_null; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } + // flush + // _CHECK_FUNCTION_VERSION + { + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_EXACT_ARGS + { + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(PyFunction_Check(callable_o)); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (code->co_argcount != oparg + (!PyStackRef_IsNull(self_or_null))) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_STACK_SPACE + { + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (!_PyThreadState_HasStackSpace(tstate, code->co_framesize)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _INIT_CALL_PY_EXACT_ARGS + { + args = &stack_pointer[-oparg]; + int has_self = !PyStackRef_IsNull(self_or_null); + STAT_INC(CALL, hit); + _PyInterpreterFrame *pushed_frame = _PyFrame_PushUnchecked(tstate, callable, oparg + has_self, frame); + _PyStackRef *first_non_self_local = pushed_frame->localsplus + has_self; + pushed_frame->localsplus[0] = self_or_null; + for (int i = 0; i < oparg; i++) { + first_non_self_local[i] = args[i]; + } + new_frame = PyStackRef_Wrap(pushed_frame); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_BOUND_METHOD_GENERAL) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_BOUND_METHOD_GENERAL; @@ -2369,6 +2526,146 @@ DISPATCH(); } + TARGET(CALL_BOUND_METHOD_GENERAL_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_BOUND_METHOD_GENERAL_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_BOUND_METHOD_GENERAL_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef null; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_METHOD_VERSION + { + null = stack_pointer[-1 - oparg]; + callable = stack_pointer[-2 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (Py_TYPE(callable_o) != &PyMethod_Type) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyObject *func = ((PyMethodObject *)callable_o)->im_func; + if (!PyFunction_Check(func)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + if (((PyFunctionObject *)func)->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + if (!PyStackRef_IsNull(null)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _EXPAND_METHOD + { + self_or_null = null; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(PyStackRef_IsNull(self_or_null)); + assert(Py_TYPE(callable_o) == &PyMethod_Type); + self_or_null = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_self); + _PyStackRef temp = callable; + callable = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_func); + assert(PyStackRef_FunctionCheck(callable)); + stack_pointer[-2 - oparg] = callable; + stack_pointer[-1 - oparg] = self_or_null; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } + // flush + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _PY_FRAME_GENERAL + { + args = &stack_pointer[-oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + if (!PyStackRef_IsNull(self_or_null)) { + args--; + total_args++; + } + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + args, total_args, NULL, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_BUILTIN_CLASS) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_BUILTIN_CLASS; @@ -2972,6 +3269,13 @@ } ex_frame = PyStackRef_Wrap(new_frame); } + // _MAYBE_LAZY_CORO + { + new_frame = ex_frame; + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + } // _SAVE_RETURN_OFFSET { #if TIER_ONE @@ -2983,7 +3287,6 @@ } // _PUSH_FRAME { - new_frame = ex_frame; assert(!IS_PEP523_HOOKED(tstate)); _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); _PyFrame_SetStackPointer(frame, stack_pointer); @@ -3150,6 +3453,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 2u == 1 + INLINE_CACHE_ENTRIES_CALL_FUNCTION_EX); frame->return_offset = 2u ; DISPATCH_INLINED(new_frame); @@ -3466,6 +3772,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL_KW) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 4u == 1 + INLINE_CACHE_ENTRIES_CALL_KW); frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); @@ -3491,22 +3800,161 @@ } res = PyStackRef_FromPyObjectSteal(res_o); } - stack_pointer[-3 - oparg] = res; - stack_pointer += -2 - oparg; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + stack_pointer[-3 - oparg] = res; + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + DISPATCH(); + } + + TARGET(CALL_KW_BOUND_METHOD) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_KW_BOUND_METHOD; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_KW_BOUND_METHOD); + static_assert(INLINE_CACHE_ENTRIES_CALL_KW == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef null; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef kwnames; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _CHECK_METHOD_VERSION_KW + { + null = stack_pointer[-2 - oparg]; + callable = stack_pointer[-3 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (Py_TYPE(callable_o) != &PyMethod_Type) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + PyObject *func = ((PyMethodObject *)callable_o)->im_func; + if (!PyFunction_Check(func)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + if (((PyFunctionObject *)func)->func_version != func_version) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + if (!PyStackRef_IsNull(null)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _EXPAND_METHOD_KW + { + self_or_null = null; + assert(PyStackRef_IsNull(self_or_null)); + _PyStackRef callable_s = callable; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(Py_TYPE(callable_o) == &PyMethod_Type); + self_or_null = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_self); + callable = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_func); + assert(PyStackRef_FunctionCheck(callable)); + stack_pointer[-3 - oparg] = callable; + stack_pointer[-2 - oparg] = self_or_null; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(callable_s); + _PyFrame_StackPointerInvalidate(frame); + } + // flush + // _PY_FRAME_KW + { + kwnames = stack_pointer[-1]; + args = &stack_pointer[-1 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + _PyStackRef *arguments = args; + if (!PyStackRef_IsNull(self_or_null)) { + arguments--; + total_args++; + } + PyObject *kwnames_o = PyStackRef_AsPyObjectBorrow(kwnames); + int positional_args = total_args - (int)PyTuple_GET_SIZE(kwnames_o); + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + arguments, positional_args, kwnames_o, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(kwnames); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } DISPATCH(); } - TARGET(CALL_KW_BOUND_METHOD) { + TARGET(CALL_KW_BOUND_METHOD_AWAITED) { #if _Py_TAIL_CALL_INTERP - int opcode = CALL_KW_BOUND_METHOD; + int opcode = CALL_KW_BOUND_METHOD_AWAITED; (void)(opcode); #endif _Py_CODEUNIT* const this_instr = next_instr; (void)this_instr; frame->instr_ptr = next_instr; next_instr += 4; - INSTRUCTION_STATS(CALL_KW_BOUND_METHOD); + INSTRUCTION_STATS(CALL_KW_BOUND_METHOD_AWAITED); static_assert(INLINE_CACHE_ENTRIES_CALL_KW == 3, "incorrect cache size"); _PyStackRef callable; _PyStackRef null; @@ -3605,6 +4053,10 @@ } new_frame = PyStackRef_Wrap(temp); } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } // _SAVE_RETURN_OFFSET { #if TIER_ONE @@ -3833,6 +4285,128 @@ DISPATCH(); } + TARGET(CALL_KW_PY_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_KW_PY_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_KW_PY_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL_KW == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef kwnames; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _CHECK_FUNCTION_VERSION_KW + { + callable = stack_pointer[-3 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _PY_FRAME_KW + { + kwnames = stack_pointer[-1]; + args = &stack_pointer[-1 - oparg]; + self_or_null = stack_pointer[-2 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + _PyStackRef *arguments = args; + if (!PyStackRef_IsNull(self_or_null)) { + arguments--; + total_args++; + } + PyObject *kwnames_o = PyStackRef_AsPyObjectBorrow(kwnames); + int positional_args = total_args - (int)PyTuple_GET_SIZE(kwnames_o); + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + arguments, positional_args, kwnames_o, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(kwnames); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_LEN) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_LEN; @@ -4564,60 +5138,179 @@ JUMP_TO_PREDICTED(CALL); } } - // _CALL_NON_PY_GENERAL + // _CALL_NON_PY_GENERAL + { + args = &stack_pointer[-oparg]; + self_or_null = stack_pointer[-1 - oparg]; + #if TIER_ONE + assert(opcode != INSTRUMENTED_CALL); + #endif + int total_args = oparg; + _PyStackRef *arguments = args; + if (!PyStackRef_IsNull(self_or_null)) { + arguments--; + total_args++; + } + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *res_o = _Py_VectorCall_StackRefSteal( + callable, + arguments, + total_args, + PyStackRef_NULL); + _PyFrame_StackPointerInvalidate(frame); + if (res_o == NULL) { + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + JUMP_TO_LABEL(error); + } + res = PyStackRef_FromPyObjectSteal(res_o); + } + // _CHECK_PERIODIC_AT_END + { + stack_pointer[-2 - oparg] = res; + stack_pointer += -1 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + int err = check_periodics_at_end(tstate, frame); + _PyFrame_StackPointerInvalidate(frame); + if (err != 0) { + JUMP_TO_LABEL(error); + } + } + DISPATCH(); + } + + TARGET(CALL_PY_EXACT_ARGS) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_PY_EXACT_ARGS; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_PY_EXACT_ARGS); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_VERSION + { + callable = stack_pointer[-2 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_EXACT_ARGS + { + self_or_null = stack_pointer[-1 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(PyFunction_Check(callable_o)); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (code->co_argcount != oparg + (!PyStackRef_IsNull(self_or_null))) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_STACK_SPACE + { + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (!_PyThreadState_HasStackSpace(tstate, code->co_framesize)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _INIT_CALL_PY_EXACT_ARGS + { + args = &stack_pointer[-oparg]; + int has_self = !PyStackRef_IsNull(self_or_null); + STAT_INC(CALL, hit); + _PyInterpreterFrame *pushed_frame = _PyFrame_PushUnchecked(tstate, callable, oparg + has_self, frame); + _PyStackRef *first_non_self_local = pushed_frame->localsplus + has_self; + pushed_frame->localsplus[0] = self_or_null; + for (int i = 0; i < oparg; i++) { + first_non_self_local[i] = args[i]; + } + new_frame = PyStackRef_Wrap(pushed_frame); + } + // _SAVE_RETURN_OFFSET { - args = &stack_pointer[-oparg]; - self_or_null = stack_pointer[-1 - oparg]; #if TIER_ONE - assert(opcode != INSTRUMENTED_CALL); + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; #endif - int total_args = oparg; - _PyStackRef *arguments = args; - if (!PyStackRef_IsNull(self_or_null)) { - arguments--; - total_args++; - } - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyObject *res_o = _Py_VectorCall_StackRefSteal( - callable, - arguments, - total_args, - PyStackRef_NULL); - _PyFrame_StackPointerInvalidate(frame); - if (res_o == NULL) { - stack_pointer += -2 - oparg; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); - JUMP_TO_LABEL(error); - } - res = PyStackRef_FromPyObjectSteal(res_o); } - // _CHECK_PERIODIC_AT_END + // _PUSH_FRAME { - stack_pointer[-2 - oparg] = res; - stack_pointer += -1 - oparg; + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + stack_pointer += -2 - oparg; ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); - int err = check_periodics_at_end(tstate, frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - if (err != 0) { - JUMP_TO_LABEL(error); - } + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); } DISPATCH(); } - TARGET(CALL_PY_EXACT_ARGS) { + TARGET(CALL_PY_EXACT_ARGS_AWAITED) { #if _Py_TAIL_CALL_INTERP - int opcode = CALL_PY_EXACT_ARGS; + int opcode = CALL_PY_EXACT_ARGS_AWAITED; (void)(opcode); #endif _Py_CODEUNIT* const this_instr = next_instr; (void)this_instr; frame->instr_ptr = next_instr; next_instr += 4; - INSTRUCTION_STATS(CALL_PY_EXACT_ARGS); + INSTRUCTION_STATS(CALL_PY_EXACT_ARGS_AWAITED); static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); _PyStackRef callable; _PyStackRef self_or_null; @@ -4694,6 +5387,10 @@ } new_frame = PyStackRef_Wrap(pushed_frame); } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } // _SAVE_RETURN_OFFSET { #if TIER_ONE @@ -4834,6 +5531,117 @@ DISPATCH(); } + TARGET(CALL_PY_GENERAL_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_PY_GENERAL_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_PY_GENERAL_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_VERSION + { + callable = stack_pointer[-2 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _PY_FRAME_GENERAL + { + args = &stack_pointer[-oparg]; + self_or_null = stack_pointer[-1 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + if (!PyStackRef_IsNull(self_or_null)) { + args--; + total_args++; + } + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + args, total_args, NULL, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_STR_1) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_STR_1; @@ -6119,6 +6927,81 @@ DISPATCH(); } + TARGET(END_AWAITED_CALL) { + #if _Py_TAIL_CALL_INTERP + int opcode = END_AWAITED_CALL; + (void)(opcode); + #endif + frame->instr_ptr = next_instr; + next_instr += 1; + INSTRUCTION_STATS(END_AWAITED_CALL); + _PyStackRef lazy_outcome; + _PyStackRef res; + _PyStackRef value; + // _END_AWAITED_CALL + { + res = stack_pointer[-1]; + lazy_outcome = stack_pointer[-2]; + if (PyStackRef_IsTaggedInt(lazy_outcome)) { + lazy_outcome = PyStackRef_NULL; + _Py_CODEUNIT *send = next_instr + oparg - 1 - INLINE_CACHE_ENTRIES_SEND; + stack_pointer[-2] = lazy_outcome; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), + (int)(send - _PyFrame_GetBytecode(frame))).op.code == SEND); + _PyFrame_StackPointerInvalidate(frame); + _Py_CODEUNIT *end_send = next_instr + oparg + send->op.arg; + if (end_send->op.code != END_SEND) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = monitor_stop_iteration(tstate, frame, end_send, + PyStackRef_AsPyObjectBorrow(res)); + _PyFrame_StackPointerInvalidate(frame); + if (err) { + JUMP_TO_LABEL(error); + } + } + JUMPBY(oparg + send->op.arg + 1); + } + else if (!PyStackRef_IsNull(lazy_outcome)) { + _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(lazy_outcome); + lazy_outcome = PyStackRef_NULL; + stack_pointer[-2] = lazy_outcome; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); + _PyFrame_StackPointerInvalidate(frame); + _PyStackRef v = res; + if (gen == NULL) { + stack_pointer[-1] = PyStackRef_NULL; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + frame = _PyEval_ThrowIntoLazyCoro(tstate, lazy_frame, v); + _PyFrame_StackPointerInvalidate(frame); + next_instr = frame->instr_ptr; + LOAD_SP(); + JUMP_TO_LABEL(error); + } + stack_pointer[-2] = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + stack_pointer[-1] = PyStackRef_NULL; + stack_pointer[0] = v; + stack_pointer += 1; + JUMPBY(oparg); + DISPATCH(); + } + } + // _POP_LAZY_OUTCOME + { + assert(PyStackRef_IsNull(lazy_outcome)); + value = res; + } + stack_pointer[-2] = value; + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + DISPATCH(); + } + TARGET(END_FOR) { #if _Py_TAIL_CALL_INTERP int opcode = END_FOR; @@ -7200,6 +8083,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL) { + MAYBE_START_LAZY_CORO(new_frame); + } frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); } @@ -7367,6 +8253,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 2u == 1 + INLINE_CACHE_ENTRIES_CALL_FUNCTION_EX); frame->return_offset = 2u ; DISPATCH_INLINED(new_frame); @@ -7519,6 +8408,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL_KW) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 4u == 1 + INLINE_CACHE_ENTRIES_CALL_KW); frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); @@ -8294,6 +9186,9 @@ _PyStackRef val; _PyStackRef value; _PyStackRef retval; + // _CHECK_LAZY_CORO + { + } // _YIELD_VALUE_EVENT { val = stack_pointer[-1]; @@ -8327,7 +9222,6 @@ retval = value; assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); frame->instr_ptr++; - PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); assert(FRAME_SUSPENDED_YIELD_FROM == FRAME_SUSPENDED + 1); assert(oparg == 0 || oparg == 1); _PyStackRef temp = retval; @@ -8336,27 +9230,37 @@ _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); - tstate->exc_info = gen->gi_exc_state.previous_item; - gen->gi_exc_state.previous_item = NULL; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *gen_frame = frame; - _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); - frame = tstate->current_frame = frame->previous; - gen_frame->previous = NULL; - ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; - FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + int offset = 1 + INLINE_CACHE_ENTRIES_SEND; + if (frame->lazy_coro == LAZY_CORO_RUNNING) { + assert(oparg == 1); + frame = _PyEval_SuspendLazyCoro(tstate, frame); + offset = 0; + } + else { + PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); + tstate->exc_info = gen->gi_exc_state.previous_item; + gen->gi_exc_state.previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *gen_frame = frame; + _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); + frame = tstate->current_frame = frame->previous; + gen_frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + } assert(INLINE_CACHE_ENTRIES_SEND == INLINE_CACHE_ENTRIES_FOR_ITER); #if TIER_ONE && defined(Py_DEBUG) if (!PyStackRef_IsNone(frame->f_executable)) { Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(opcode == SEND || opcode == FOR_ITER); + assert(offset == 0 ? opcode == END_AWAITED_CALL + : (opcode == SEND || opcode == FOR_ITER)); } #endif stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - LOAD_IP(1 + INLINE_CACHE_ENTRIES_SEND); + LOAD_IP(offset); value = temp; LLTRACE_RESUME_FRAME(); } @@ -11451,32 +12355,61 @@ _PyStackRef res; assert(PyStackRef_FunctionCheck(frame->f_funcobj)); PyFunctionObject *func = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(frame->f_funcobj); - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); - _PyFrame_StackPointerInvalidate(frame); - if (gen == NULL) { - JUMP_TO_LABEL(error); + _PyErr_StackItem *exc_info = NULL; + #if TIER_ONE + if (frame->lazy_coro == LAZY_CORO_REQUESTED) { + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + exc_info = (_PyErr_StackItem *)_PyThreadState_PushFrame( + tstate, sizeof(_PyErr_StackItem) / sizeof(PyObject *)); + _PyFrame_StackPointerInvalidate(frame); + if (exc_info == NULL) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyErr_Clear(tstate); + _PyFrame_StackPointerInvalidate(frame); + } + } + #endif + if (exc_info != NULL) { + exc_info->exc_value = NULL; + exc_info->previous_item = tstate->exc_info; + tstate->exc_info = exc_info; + frame->lazy_coro = LAZY_CORO_RUNNING; + _PyInterpreterFrame *caller = frame->previous; + caller->instr_ptr += caller->return_offset; + caller->return_offset = 0; + res = PyStackRef_None; + } + else { + frame->lazy_coro = 0; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); + _PyFrame_StackPointerInvalidate(frame); + if (gen == NULL) { + JUMP_TO_LABEL(error); + } + assert(STACK_LEVEL() <= 2); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *gen_frame = &gen->gi_iframe; + frame->instr_ptr++; + _PyFrame_Copy(frame, gen_frame); + assert(frame->frame_obj == NULL); + gen->gi_frame_state = FRAME_CREATED; + gen_frame->owner = FRAME_OWNED_BY_GENERATOR; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *prev = frame->previous; + _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); + _PyThreadState_PopFrame(tstate, frame); + frame = tstate->current_frame = prev; + LOAD_IP(frame->return_offset); + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + LLTRACE_RESUME_FRAME(); } - assert(STACK_LEVEL() <= 2); - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - _PyInterpreterFrame *gen_frame = &gen->gi_iframe; - frame->instr_ptr++; - _PyFrame_Copy(frame, gen_frame); - assert(frame->frame_obj == NULL); - gen->gi_frame_state = FRAME_CREATED; - gen_frame->owner = FRAME_OWNED_BY_GENERATOR; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *prev = frame->previous; - _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); - _PyThreadState_PopFrame(tstate, frame); - frame = tstate->current_frame = prev; - LOAD_IP(frame->return_offset); - stack_pointer = _PyFrame_GetStackPointer(frame); - _PyFrame_StackPointerInvalidate(frame); - res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); - LLTRACE_RESUME_FRAME(); stack_pointer[0] = res; stack_pointer += 1; ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); @@ -13583,6 +14516,9 @@ opcode = YIELD_VALUE; _PyStackRef value; _PyStackRef retval; + // _CHECK_LAZY_CORO + { + } // _MAKE_HEAP_SAFE { value = stack_pointer[-1]; @@ -13593,7 +14529,6 @@ retval = value; assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); frame->instr_ptr++; - PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); assert(FRAME_SUSPENDED_YIELD_FROM == FRAME_SUSPENDED + 1); assert(oparg == 0 || oparg == 1); _PyStackRef temp = retval; @@ -13602,27 +14537,37 @@ _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); - tstate->exc_info = gen->gi_exc_state.previous_item; - gen->gi_exc_state.previous_item = NULL; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *gen_frame = frame; - _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); - frame = tstate->current_frame = frame->previous; - gen_frame->previous = NULL; - ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; - FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + int offset = 1 + INLINE_CACHE_ENTRIES_SEND; + if (frame->lazy_coro == LAZY_CORO_RUNNING) { + assert(oparg == 1); + frame = _PyEval_SuspendLazyCoro(tstate, frame); + offset = 0; + } + else { + PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); + tstate->exc_info = gen->gi_exc_state.previous_item; + gen->gi_exc_state.previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *gen_frame = frame; + _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); + frame = tstate->current_frame = frame->previous; + gen_frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + } assert(INLINE_CACHE_ENTRIES_SEND == INLINE_CACHE_ENTRIES_FOR_ITER); #if TIER_ONE && defined(Py_DEBUG) if (!PyStackRef_IsNone(frame->f_executable)) { Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(opcode == SEND || opcode == FOR_ITER); + assert(offset == 0 ? opcode == END_AWAITED_CALL + : (opcode == SEND || opcode == FOR_ITER)); } #endif stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - LOAD_IP(1 + INLINE_CACHE_ENTRIES_SEND); + LOAD_IP(offset); value = temp; LLTRACE_RESUME_FRAME(); } diff --git a/Python/instrumentation.c b/Python/instrumentation.c index 48daa91259d3c9..bdf09945df2bda 100644 --- a/Python/instrumentation.c +++ b/Python/instrumentation.c @@ -574,6 +574,7 @@ sanity_check_instrumentation(PyCodeObject *code) opcode = _PyCode_GetOriginalOpcode(data->lines, i); CHECK(valid_opcode(opcode)); CHECK(opcode != END_FOR); + CHECK(opcode != END_AWAITED_CALL); CHECK(opcode != RESUME); CHECK(opcode != RESUME_CHECK); CHECK(opcode != RESUME_CHECK_JIT); @@ -1579,6 +1580,14 @@ initialize_lines(_PyCoLineInstrumentationData *line_data, PyCodeObject *code, in * RESUME and POP_ITER must not be instrumented with INSTRUMENTED_LINE */ set_original_opcode(line_data, i, 0); break; + case END_AWAITED_CALL: + /* END_AWAITED_CALL must not be instrumented with INSTRUMENTED_LINE, + * as no events may fire before it handles a lazy coroutine. + * It has the location of the await, which starts a line + * after the call, so it keeps the line of the call. */ + set_line_delta(line_data, i, compute_line_delta(code, current_line)); + set_original_opcode(line_data, i, 0); + break; default: /* Set original_opcode to the opcode iff the instruction * starts a line, and thus should be instrumented. @@ -1638,13 +1647,19 @@ initialize_lines(_PyCoLineInstrumentationData *line_data, PyCodeObject *code, in target = i - oparg; break; } + case END_AWAITED_CALL: + { + /* To YIELD_VALUE; the jump past END_SEND lands on SEND's target */ + target = i + oparg; + break; + } default: continue; } assert(target >= 0); if (get_line_delta(line_data, target) != NO_LINE) { int opcode = _Py_GetBaseCodeUnit(code, target).op.code; - if (opcode != POP_ITER) { + if (opcode != POP_ITER && opcode != END_AWAITED_CALL) { set_original_opcode(line_data, target, opcode); } } @@ -1901,7 +1916,7 @@ force_instrument_lock_held(PyCodeObject *code, PyInterpreterState *interp) if (removed_per_instruction_tools) { for (int i = code->_co_firsttraceable; i < code_len;) { int opcode = _Py_GetBaseCodeUnit(code, i).op.code; - if (opcode == RESUME || opcode == END_FOR) { + if (opcode == RESUME || opcode == END_FOR || opcode == END_AWAITED_CALL) { i += _PyInstruction_GetLength(code, i); continue; } @@ -1928,7 +1943,7 @@ force_instrument_lock_held(PyCodeObject *code, PyInterpreterState *interp) if (new_per_instruction_tools) { for (int i = code->_co_firsttraceable; i < code_len;) { int opcode = _Py_GetBaseCodeUnit(code, i).op.code; - if (opcode == RESUME || opcode == END_FOR) { + if (opcode == RESUME || opcode == END_FOR || opcode == END_AWAITED_CALL) { i += _PyInstruction_GetLength(code, i); continue; } diff --git a/Python/intrinsics.c b/Python/intrinsics.c index dfa81baa654e12..df6c992d4c53da 100644 --- a/Python/intrinsics.c +++ b/Python/intrinsics.c @@ -144,7 +144,10 @@ static PyObject * stopiteration_error(PyThreadState* tstate, PyObject *exc) { _PyInterpreterFrame *frame = tstate->current_frame; - assert(frame->owner == FRAME_OWNED_BY_GENERATOR); + /* A lazily started coroutine (see RETURN_GENERATOR). */ + assert(frame->owner == FRAME_OWNED_BY_GENERATOR || + (frame->owner == FRAME_OWNED_BY_THREAD && + (_PyFrame_GetCode(frame)->co_flags & CO_COROUTINE))); assert(PyExceptionInstance_Check(exc)); const char *msg = NULL; if (PyErr_GivenExceptionMatches(exc, PyExc_StopIteration)) { diff --git a/Python/opcode_targets.h b/Python/opcode_targets.h index 91b424773224e4..afcb1ab06419d0 100644 --- a/Python/opcode_targets.h +++ b/Python/opcode_targets.h @@ -64,6 +64,7 @@ static void *opcode_targets_table[256] = { &&TARGET_DICT_MERGE, &&TARGET_DICT_UPDATE, &&TARGET_END_ASYNC_FOR, + &&TARGET_END_AWAITED_CALL, &&TARGET_EXTENDED_ARG, &&TARGET_FOR_ITER, &&TARGET_GET_AWAITABLE, @@ -127,7 +128,6 @@ static void *opcode_targets_table[256] = { &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, - &&_unknown_opcode, &&TARGET_RESUME, &&TARGET_BINARY_OP_ADD_FLOAT, &&TARGET_BINARY_OP_ADD_INT, @@ -146,7 +146,9 @@ static void *opcode_targets_table[256] = { &&TARGET_BINARY_OP_SUBTRACT_INT, &&TARGET_CALL_ALLOC_AND_ENTER_INIT, &&TARGET_CALL_BOUND_METHOD_EXACT_ARGS, + &&TARGET_CALL_BOUND_METHOD_EXACT_ARGS_AWAITED, &&TARGET_CALL_BOUND_METHOD_GENERAL, + &&TARGET_CALL_BOUND_METHOD_GENERAL_AWAITED, &&TARGET_CALL_BUILTIN_CLASS, &&TARGET_CALL_BUILTIN_FAST, &&TARGET_CALL_BUILTIN_FAST_WITH_KEYWORDS, @@ -155,8 +157,10 @@ static void *opcode_targets_table[256] = { &&TARGET_CALL_EX_PY, &&TARGET_CALL_ISINSTANCE, &&TARGET_CALL_KW_BOUND_METHOD, + &&TARGET_CALL_KW_BOUND_METHOD_AWAITED, &&TARGET_CALL_KW_NON_PY, &&TARGET_CALL_KW_PY, + &&TARGET_CALL_KW_PY_AWAITED, &&TARGET_CALL_LEN, &&TARGET_CALL_LIST_APPEND, &&TARGET_CALL_METHOD_DESCRIPTOR_FAST, @@ -165,7 +169,9 @@ static void *opcode_targets_table[256] = { &&TARGET_CALL_METHOD_DESCRIPTOR_O, &&TARGET_CALL_NON_PY_GENERAL, &&TARGET_CALL_PY_EXACT_ARGS, + &&TARGET_CALL_PY_EXACT_ARGS_AWAITED, &&TARGET_CALL_PY_GENERAL, + &&TARGET_CALL_PY_GENERAL_AWAITED, &&TARGET_CALL_STR_1, &&TARGET_CALL_TUPLE_1, &&TARGET_CALL_TYPE_1, @@ -227,12 +233,6 @@ static void *opcode_targets_table[256] = { &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, &&TARGET_INSTRUMENTED_END_FOR, &&TARGET_INSTRUMENTED_POP_ITER, &&TARGET_INSTRUMENTED_END_SEND, @@ -376,7 +376,7 @@ static void *opcode_tracing_targets_table[256] = { &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, - &&_unknown_opcode, + &&TARGET_TRACE_RECORD, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, @@ -478,12 +478,12 @@ static void *opcode_tracing_targets_table[256] = { &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, @@ -561,7 +561,9 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CACHE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_ALLOC_AND_ENTER_INIT(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_GENERAL(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_GENERAL_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BUILTIN_CLASS(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BUILTIN_FAST(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BUILTIN_FAST_WITH_KEYWORDS(TAIL_CALL_PARAMS); @@ -574,8 +576,10 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_INTRINSIC_2(TAIL_CALL_PARAM static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_ISINSTANCE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_BOUND_METHOD(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_BOUND_METHOD_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_NON_PY(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_PY(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_PY_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_LEN(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_LIST_APPEND(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_METHOD_DESCRIPTOR_FAST(TAIL_CALL_PARAMS); @@ -584,7 +588,9 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_METHOD_DESCRIPTOR_NOARGS(TA static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_METHOD_DESCRIPTOR_O(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_NON_PY_GENERAL(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_EXACT_ARGS(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_EXACT_ARGS_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_GENERAL(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_GENERAL_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_STR_1(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_TUPLE_1(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_TYPE_1(TAIL_CALL_PARAMS); @@ -607,6 +613,7 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_DELETE_SUBSCR(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_DICT_MERGE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_DICT_UPDATE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_ASYNC_FOR(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_AWAITED_CALL(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_FOR(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_SEND(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_ENTER_EXECUTOR(TAIL_CALL_PARAMS); @@ -804,7 +811,9 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [CALL] = _TAIL_CALL_CALL, [CALL_ALLOC_AND_ENTER_INIT] = _TAIL_CALL_CALL_ALLOC_AND_ENTER_INIT, [CALL_BOUND_METHOD_EXACT_ARGS] = _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS_AWAITED, [CALL_BOUND_METHOD_GENERAL] = _TAIL_CALL_CALL_BOUND_METHOD_GENERAL, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = _TAIL_CALL_CALL_BOUND_METHOD_GENERAL_AWAITED, [CALL_BUILTIN_CLASS] = _TAIL_CALL_CALL_BUILTIN_CLASS, [CALL_BUILTIN_FAST] = _TAIL_CALL_CALL_BUILTIN_FAST, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = _TAIL_CALL_CALL_BUILTIN_FAST_WITH_KEYWORDS, @@ -817,8 +826,10 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [CALL_ISINSTANCE] = _TAIL_CALL_CALL_ISINSTANCE, [CALL_KW] = _TAIL_CALL_CALL_KW, [CALL_KW_BOUND_METHOD] = _TAIL_CALL_CALL_KW_BOUND_METHOD, + [CALL_KW_BOUND_METHOD_AWAITED] = _TAIL_CALL_CALL_KW_BOUND_METHOD_AWAITED, [CALL_KW_NON_PY] = _TAIL_CALL_CALL_KW_NON_PY, [CALL_KW_PY] = _TAIL_CALL_CALL_KW_PY, + [CALL_KW_PY_AWAITED] = _TAIL_CALL_CALL_KW_PY_AWAITED, [CALL_LEN] = _TAIL_CALL_CALL_LEN, [CALL_LIST_APPEND] = _TAIL_CALL_CALL_LIST_APPEND, [CALL_METHOD_DESCRIPTOR_FAST] = _TAIL_CALL_CALL_METHOD_DESCRIPTOR_FAST, @@ -827,7 +838,9 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [CALL_METHOD_DESCRIPTOR_O] = _TAIL_CALL_CALL_METHOD_DESCRIPTOR_O, [CALL_NON_PY_GENERAL] = _TAIL_CALL_CALL_NON_PY_GENERAL, [CALL_PY_EXACT_ARGS] = _TAIL_CALL_CALL_PY_EXACT_ARGS, + [CALL_PY_EXACT_ARGS_AWAITED] = _TAIL_CALL_CALL_PY_EXACT_ARGS_AWAITED, [CALL_PY_GENERAL] = _TAIL_CALL_CALL_PY_GENERAL, + [CALL_PY_GENERAL_AWAITED] = _TAIL_CALL_CALL_PY_GENERAL_AWAITED, [CALL_STR_1] = _TAIL_CALL_CALL_STR_1, [CALL_TUPLE_1] = _TAIL_CALL_CALL_TUPLE_1, [CALL_TYPE_1] = _TAIL_CALL_CALL_TYPE_1, @@ -850,6 +863,7 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [DICT_MERGE] = _TAIL_CALL_DICT_MERGE, [DICT_UPDATE] = _TAIL_CALL_DICT_UPDATE, [END_ASYNC_FOR] = _TAIL_CALL_END_ASYNC_FOR, + [END_AWAITED_CALL] = _TAIL_CALL_END_AWAITED_CALL, [END_FOR] = _TAIL_CALL_END_FOR, [END_SEND] = _TAIL_CALL_END_SEND, [ENTER_EXECUTOR] = _TAIL_CALL_ENTER_EXECUTOR, @@ -1005,7 +1019,6 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [UNPACK_SEQUENCE_TWO_TUPLE] = _TAIL_CALL_UNPACK_SEQUENCE_TWO_TUPLE, [WITH_EXCEPT_START] = _TAIL_CALL_WITH_EXCEPT_START, [YIELD_VALUE] = _TAIL_CALL_YIELD_VALUE, - [117] = _TAIL_CALL_UNKNOWN_OPCODE, [118] = _TAIL_CALL_UNKNOWN_OPCODE, [119] = _TAIL_CALL_UNKNOWN_OPCODE, [120] = _TAIL_CALL_UNKNOWN_OPCODE, @@ -1016,12 +1029,6 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [125] = _TAIL_CALL_UNKNOWN_OPCODE, [126] = _TAIL_CALL_UNKNOWN_OPCODE, [127] = _TAIL_CALL_UNKNOWN_OPCODE, - [219] = _TAIL_CALL_UNKNOWN_OPCODE, - [220] = _TAIL_CALL_UNKNOWN_OPCODE, - [221] = _TAIL_CALL_UNKNOWN_OPCODE, - [222] = _TAIL_CALL_UNKNOWN_OPCODE, - [223] = _TAIL_CALL_UNKNOWN_OPCODE, - [224] = _TAIL_CALL_UNKNOWN_OPCODE, [225] = _TAIL_CALL_UNKNOWN_OPCODE, [226] = _TAIL_CALL_UNKNOWN_OPCODE, [227] = _TAIL_CALL_UNKNOWN_OPCODE, @@ -1062,7 +1069,9 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [CALL] = _TAIL_CALL_TRACE_RECORD, [CALL_ALLOC_AND_ENTER_INIT] = _TAIL_CALL_TRACE_RECORD, [CALL_BOUND_METHOD_EXACT_ARGS] = _TAIL_CALL_TRACE_RECORD, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_BOUND_METHOD_GENERAL] = _TAIL_CALL_TRACE_RECORD, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_BUILTIN_CLASS] = _TAIL_CALL_TRACE_RECORD, [CALL_BUILTIN_FAST] = _TAIL_CALL_TRACE_RECORD, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = _TAIL_CALL_TRACE_RECORD, @@ -1075,8 +1084,10 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [CALL_ISINSTANCE] = _TAIL_CALL_TRACE_RECORD, [CALL_KW] = _TAIL_CALL_TRACE_RECORD, [CALL_KW_BOUND_METHOD] = _TAIL_CALL_TRACE_RECORD, + [CALL_KW_BOUND_METHOD_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_KW_NON_PY] = _TAIL_CALL_TRACE_RECORD, [CALL_KW_PY] = _TAIL_CALL_TRACE_RECORD, + [CALL_KW_PY_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_LEN] = _TAIL_CALL_TRACE_RECORD, [CALL_LIST_APPEND] = _TAIL_CALL_TRACE_RECORD, [CALL_METHOD_DESCRIPTOR_FAST] = _TAIL_CALL_TRACE_RECORD, @@ -1085,7 +1096,9 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [CALL_METHOD_DESCRIPTOR_O] = _TAIL_CALL_TRACE_RECORD, [CALL_NON_PY_GENERAL] = _TAIL_CALL_TRACE_RECORD, [CALL_PY_EXACT_ARGS] = _TAIL_CALL_TRACE_RECORD, + [CALL_PY_EXACT_ARGS_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_PY_GENERAL] = _TAIL_CALL_TRACE_RECORD, + [CALL_PY_GENERAL_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_STR_1] = _TAIL_CALL_TRACE_RECORD, [CALL_TUPLE_1] = _TAIL_CALL_TRACE_RECORD, [CALL_TYPE_1] = _TAIL_CALL_TRACE_RECORD, @@ -1108,6 +1121,7 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [DICT_MERGE] = _TAIL_CALL_TRACE_RECORD, [DICT_UPDATE] = _TAIL_CALL_TRACE_RECORD, [END_ASYNC_FOR] = _TAIL_CALL_TRACE_RECORD, + [END_AWAITED_CALL] = _TAIL_CALL_TRACE_RECORD, [END_FOR] = _TAIL_CALL_TRACE_RECORD, [END_SEND] = _TAIL_CALL_TRACE_RECORD, [ENTER_EXECUTOR] = _TAIL_CALL_TRACE_RECORD, @@ -1263,7 +1277,6 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [UNPACK_SEQUENCE_TWO_TUPLE] = _TAIL_CALL_TRACE_RECORD, [WITH_EXCEPT_START] = _TAIL_CALL_TRACE_RECORD, [YIELD_VALUE] = _TAIL_CALL_TRACE_RECORD, - [117] = _TAIL_CALL_UNKNOWN_OPCODE, [118] = _TAIL_CALL_UNKNOWN_OPCODE, [119] = _TAIL_CALL_UNKNOWN_OPCODE, [120] = _TAIL_CALL_UNKNOWN_OPCODE, @@ -1274,12 +1287,6 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [125] = _TAIL_CALL_UNKNOWN_OPCODE, [126] = _TAIL_CALL_UNKNOWN_OPCODE, [127] = _TAIL_CALL_UNKNOWN_OPCODE, - [219] = _TAIL_CALL_UNKNOWN_OPCODE, - [220] = _TAIL_CALL_UNKNOWN_OPCODE, - [221] = _TAIL_CALL_UNKNOWN_OPCODE, - [222] = _TAIL_CALL_UNKNOWN_OPCODE, - [223] = _TAIL_CALL_UNKNOWN_OPCODE, - [224] = _TAIL_CALL_UNKNOWN_OPCODE, [225] = _TAIL_CALL_UNKNOWN_OPCODE, [226] = _TAIL_CALL_UNKNOWN_OPCODE, [227] = _TAIL_CALL_UNKNOWN_OPCODE, diff --git a/Python/optimizer.c b/Python/optimizer.c index e05adb344c8d06..0a1a2c8afc75a4 100644 --- a/Python/optimizer.c +++ b/Python/optimizer.c @@ -502,6 +502,10 @@ _PyUOp_Replacements[MAX_UOP_ID + 1] = { [_LOAD_BYTECODE] = _NOP, [_SEND_VIRTUAL] = _SEND_VIRTUAL_TIER_TWO, [_SEND_ASYNC_GEN] = _SEND_ASYNC_GEN_TIER_TWO, + [_END_AWAITED_CALL] = _GUARD_NOS_NULL, + [_MAYBE_LAZY_CORO] = _NOP, + [_START_LAZY_CORO] = _NOP, + [_CHECK_LAZY_CORO] = _GUARD_NOT_LAZY_CORO, }; static const uint8_t @@ -731,7 +735,9 @@ _PyJit_translate_single_bytecode_to_trace( } // Strange control-flow - bool has_dynamic_jump_taken = OPCODE_HAS_UNPREDICTABLE_JUMP(opcode) && + // Tier two only runs END_AWAITED_CALL's fall-through. + bool has_dynamic_jump_taken = + (OPCODE_HAS_UNPREDICTABLE_JUMP(opcode) || opcode == END_AWAITED_CALL) && (next_instr != this_instr + 1 + _PyOpcode_Caches[_PyOpcode_Deopt[opcode]]); /* Special case the first instruction, @@ -966,6 +972,10 @@ _PyJit_translate_single_bytecode_to_trace( target = next_inst; } } + else if (uop == _GUARD_NOS_NULL || + uop == _NOP || uop == _GUARD_NOT_LAZY_CORO) { + // These don't jump. + } else { int extended_arg = orig_oparg > 255; uint32_t jump_target = next_inst + orig_oparg + extended_arg; @@ -1136,6 +1146,11 @@ _PyJit_TryInitializeTracing( if (oparg > 0xFFFF) { return 0; } + // IS_AWAITED_CALL() needs END_AWAITED_CALL in the bytecode, so no + // ENTER_EXECUTOR may replace it. + if (start_instr->op.code == END_AWAITED_CALL) { + return 0; + } PyObject *func = PyStackRef_AsPyObjectBorrow(frame->f_funcobj); if (func == NULL || !PyFunction_Check(func)) { return 0; diff --git a/Python/optimizer_cases.c.h b/Python/optimizer_cases.c.h index c86121fcfc0e79..1c2d2d194740d3 100644 --- a/Python/optimizer_cases.c.h +++ b/Python/optimizer_cases.c.h @@ -1908,6 +1908,18 @@ break; } + /* _END_AWAITED_CALL is not a viable micro-op for tier 2 */ + + case _POP_LAZY_OUTCOME: { + JitOptRef value; + value = sym_new_not_null(ctx); + CHECK_STACK_BOUNDS(-1); + stack_pointer[-2] = value; + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + break; + } + case _SEND_GEN_FRAME: { JitOptRef v; JitOptRef receiver; @@ -1978,6 +1990,12 @@ break; } + /* _CHECK_LAZY_CORO is not a viable micro-op for tier 2 */ + + case _GUARD_NOT_LAZY_CORO: { + break; + } + case _YIELD_VALUE: { JitOptRef retval; JitOptRef value; @@ -4290,6 +4308,8 @@ break; } + /* _START_LAZY_CORO is not a viable micro-op for tier 2 */ + case _GUARD_NOS_NULL: { JitOptRef null; null = stack_pointer[-2]; @@ -5596,6 +5616,8 @@ break; } + /* _MAYBE_LAZY_CORO is not a viable micro-op for tier 2 */ + case _SAVE_RETURN_OFFSET: { break; } diff --git a/Python/record_functions.c.h b/Python/record_functions.c.h index 98abe3d0505e20..cd2ff022f48eb1 100644 --- a/Python/record_functions.c.h +++ b/Python/record_functions.c.h @@ -171,10 +171,14 @@ const _PyOpcodeRecordEntry _PyOpcode_RecordEntries[256] = { [LOAD_ATTR_METHOD_LAZY_DICT] = {1, {_RECORD_TOS_INDEX}}, [CALL] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_PY_GENERAL] = {1, {_RECORD_CALLABLE_INDEX}}, + [CALL_PY_GENERAL_AWAITED] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_BOUND_METHOD_GENERAL] = {1, {_RECORD_CALLABLE_INDEX}}, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_NON_PY_GENERAL] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_BOUND_METHOD_EXACT_ARGS] = {1, {_RECORD_CALLABLE_INDEX}}, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_PY_EXACT_ARGS] = {1, {_RECORD_CALLABLE_INDEX}}, + [CALL_PY_EXACT_ARGS_AWAITED] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_TYPE_1] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_STR_1] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_TUPLE_1] = {1, {_RECORD_CALLABLE_INDEX}}, @@ -191,7 +195,9 @@ const _PyOpcodeRecordEntry _PyOpcode_RecordEntries[256] = { [CALL_METHOD_DESCRIPTOR_NOARGS] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_METHOD_DESCRIPTOR_FAST] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_KW_PY] = {1, {_RECORD_CALLABLE_KW_INDEX}}, + [CALL_KW_PY_AWAITED] = {1, {_RECORD_CALLABLE_KW_INDEX}}, [CALL_KW_BOUND_METHOD] = {1, {_RECORD_CALLABLE_KW_INDEX}}, + [CALL_KW_BOUND_METHOD_AWAITED] = {1, {_RECORD_CALLABLE_KW_INDEX}}, [CALL_KW] = {1, {_RECORD_CALLABLE_KW_INDEX}}, [CALL_KW_NON_PY] = {1, {_RECORD_CALLABLE_KW_INDEX}}, [CALL_FUNCTION_EX] = {1, {_RECORD_4OS_INDEX}}, @@ -229,10 +235,14 @@ const _PyOpcodeRecordSlotMap _PyOpcode_RecordSlotMaps[256] = { [LOAD_ATTR_NONDESCRIPTOR_NO_DICT] = {1, 1, {0}}, [LOAD_ATTR_METHOD_LAZY_DICT] = {1, 1, {0}}, [CALL_PY_GENERAL] = {1, 0, {0}}, + [CALL_PY_GENERAL_AWAITED] = {1, 0, {0}}, [CALL_BOUND_METHOD_GENERAL] = {1, 1, {0}}, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = {1, 1, {0}}, [CALL_NON_PY_GENERAL] = {1, 0, {0}}, [CALL_BOUND_METHOD_EXACT_ARGS] = {1, 1, {0}}, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = {1, 1, {0}}, [CALL_PY_EXACT_ARGS] = {1, 0, {0}}, + [CALL_PY_EXACT_ARGS_AWAITED] = {1, 0, {0}}, [CALL_ALLOC_AND_ENTER_INIT] = {1, 0, {0}}, [CALL_BUILTIN_CLASS] = {1, 0, {0}}, [CALL_BUILTIN_O] = {1, 0, {0}}, @@ -242,7 +252,9 @@ const _PyOpcodeRecordSlotMap _PyOpcode_RecordSlotMaps[256] = { [CALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS] = {1, 0, {0}}, [CALL_METHOD_DESCRIPTOR_NOARGS] = {1, 0, {0}}, [CALL_KW_PY] = {1, 0, {0}}, + [CALL_KW_PY_AWAITED] = {1, 0, {0}}, [CALL_KW_BOUND_METHOD] = {1, 0, {0}}, + [CALL_KW_BOUND_METHOD_AWAITED] = {1, 0, {0}}, [CALL_EX_PY] = {1, 0, {0}}, [BINARY_OP] = {2, 2, {1, 0}}, }; diff --git a/Python/specialize.c b/Python/specialize.c index b5cf4ebc31142a..fb3c483d2d31d4 100644 --- a/Python/specialize.c +++ b/Python/specialize.c @@ -1751,6 +1751,14 @@ specialize_method_descriptor(PyMethodDescrObject *descr, PyObject *self_or_null, return 0; } +static bool +is_awaited_coroutine_call(_Py_CODEUNIT *instr, int cache_entries, + PyCodeObject *code) +{ + return (instr[1 + cache_entries].op.code == END_AWAITED_CALL && + (code->co_flags & CO_COROUTINE)); +} + static int specialize_py_call(PyFunctionObject *func, _Py_CODEUNIT *instr, int nargs, bool bound_method) @@ -1782,7 +1790,17 @@ specialize_py_call(PyFunctionObject *func, _Py_CODEUNIT *instr, int nargs, } write_u32(cache->func_version, version); uint8_t opcode; - if (argcount == nargs + bound_method) { + if (is_awaited_coroutine_call(instr, INLINE_CACHE_ENTRIES_CALL, code)) { + if (argcount == nargs + bound_method) { + opcode = bound_method ? CALL_BOUND_METHOD_EXACT_ARGS_AWAITED + : CALL_PY_EXACT_ARGS_AWAITED; + } + else { + opcode = bound_method ? CALL_BOUND_METHOD_GENERAL_AWAITED + : CALL_PY_GENERAL_AWAITED; + } + } + else if (argcount == nargs + bound_method) { opcode = bound_method ? CALL_BOUND_METHOD_EXACT_ARGS : CALL_PY_EXACT_ARGS; } @@ -1820,7 +1838,13 @@ specialize_py_call_kw(PyFunctionObject *func, _Py_CODEUNIT *instr, int nargs, return -1; } write_u32(cache->func_version, version); - specialize(instr, bound_method ? CALL_KW_BOUND_METHOD : CALL_KW_PY); + if (is_awaited_coroutine_call(instr, INLINE_CACHE_ENTRIES_CALL_KW, code)) { + specialize(instr, bound_method ? CALL_KW_BOUND_METHOD_AWAITED + : CALL_KW_PY_AWAITED); + } + else { + specialize(instr, bound_method ? CALL_KW_BOUND_METHOD : CALL_KW_PY); + } return 0; } From 8f6678a0a49bbaa22e08281ee5e1e6430777595d Mon Sep 17 00:00:00 2001 From: Andrew Svetlov Date: Sun, 22 Nov 2026 14:12:30 +0100 Subject: [PATCH 02/10] Trim comments on lazy coroutine compilation Co-Authored-By: Claude Opus 5.5 --- Python/codegen.c | 9 --------- Python/flowgraph.c | 5 +++-- 2 files changed, 3 insertions(+), 11 deletions(-) diff --git a/Python/codegen.c b/Python/codegen.c index bdb6bb1ba59d41..160730ba090d35 100644 --- a/Python/codegen.c +++ b/Python/codegen.c @@ -496,7 +496,6 @@ codegen_call_exit_with_nones(compiler *c, location loc) return SUCCESS; } -/* If `yield` is a valid label, it is placed on the YIELD_VALUE. */ static int codegen_add_yield_from_impl(compiler *c, location loc, int await, jump_target_label yield) @@ -532,8 +531,6 @@ codegen_add_yield_from(compiler *c, location loc, int await) return codegen_add_yield_from_impl(c, loc, await, NO_LABEL); } -/* Await the result of a call made with a NULL `lazy_outcome` below the - * callable. */ static int codegen_await_call_result(compiler *c, location loc, int oparg) { @@ -635,7 +632,6 @@ codegen_unwind_fblock(compiler *c, location *ploc, ADDOP(c, *ploc, POP_BLOCK); if (preserve_tos) { if (info->fb_type == COMPILE_FBLOCK_ASYNC_WITH) { - /* Also below the lazy_outcome of __aexit__() */ ADDOP_I(c, *ploc, SWAP, 4); } ADDOP_I(c, *ploc, SWAP, 3); @@ -4291,8 +4287,6 @@ codegen_call(compiler *c, expr_ty e) return ret; } -/* `await ` pushes a NULL `lazy_outcome` below the callable, and - * END_AWAITED_CALL after the call marks it as awaited. */ static int codegen_await(compiler *c, expr_ty e) { @@ -5292,7 +5286,6 @@ codegen_with_except_finish(compiler *c, jump_target_label cleanup, ADDOP(c, NO_LOCATION, POP_TOP); ADDOP(c, NO_LOCATION, POP_TOP); if (is_async) { - /* The lazy_outcome of __aexit__() */ ADDOP(c, NO_LOCATION, POP_TOP); } NEW_JUMP_TARGET_LABEL(c, exit); @@ -5345,14 +5338,12 @@ codegen_async_with_inner(compiler *c, stmt_ty s, int pos) /* Evaluate EXPR */ VISIT(c, expr, item->context_expr); loc = LOC(item->context_expr); - /* The lazy_outcome of __aexit__() */ ADDOP(c, loc, PUSH_NULL); ADDOP_I(c, loc, SWAP, 2); ADDOP_I(c, loc, COPY, 1); ADDOP_I(c, loc, LOAD_SPECIAL, SPECIAL___AEXIT__); ADDOP_I(c, loc, SWAP, 2); ADDOP_I(c, loc, SWAP, 3); - /* The lazy_outcome of __aenter__() */ ADDOP(c, loc, PUSH_NULL); ADDOP_I(c, loc, SWAP, 2); ADDOP_I(c, loc, LOAD_SPECIAL, SPECIAL___AENTER__); diff --git a/Python/flowgraph.c b/Python/flowgraph.c index b2fca593e8809c..955069dd391a72 100644 --- a/Python/flowgraph.c +++ b/Python/flowgraph.c @@ -799,8 +799,9 @@ get_stack_effects(int opcode, int oparg, int jump, stack_effects *effects) return 0; } if (opcode == END_AWAITED_CALL && jump) { - // The jump to YIELD_VALUE leaves (coroutine, NULL, value) in place - // of (lazy_outcome, value). + // When the body suspends, the jump to YIELD_VALUE replaces + // (lazy_outcome, value) with (coroutine, NULL, value), where value + // is what the body yielded. effects->net = 1; return 0; } From b58cf965985a83b00a0e50779525416c4f499314 Mon Sep 17 00:00:00 2001 From: Andrew Svetlov Date: Sun, 22 Nov 2026 14:28:54 +0100 Subject: [PATCH 03/10] Fix resuming a lazy coroutine after failed materialization Pop the yielded value from the caller's stack, fire PY_THROW, and allow CLEANUP_THROW in a lazily run body. Make the MemoryError tests target the coroutine allocation and cover a body that catches the error. Co-Authored-By: Claude Opus 5.5 --- Lib/test/test_coroutines.py | 131 +++++++++++++++++++---- Modules/_testinternalcapi/test_cases.c.h | 3 +- Python/bytecodes.c | 3 +- Python/ceval.c | 5 + Python/generated_cases.c.h | 3 +- 5 files changed, 122 insertions(+), 23 deletions(-) diff --git a/Lib/test/test_coroutines.py b/Lib/test/test_coroutines.py index 865b0db28f554e..5f78676e01751f 100644 --- a/Lib/test/test_coroutines.py +++ b/Lib/test/test_coroutines.py @@ -3134,12 +3134,45 @@ async def outer(): self.assertIs(frame.f_code, inner.__code__) self.assertIsNone(frame.f_back) - @unittest.skipIf(_testcapi is None, "requires _testcapi") - def test_memory_error_at_first_suspension(self): + def run_failing_first_suspension(self, make_outer): + """Drive the coroutine returned by make_outer(awaitable, fail, failed). + + fail() makes allocation number *start* fail; failed() stops that + and records the state of the awaitable. Retry with a later *start* + until the allocation that fails creates a coroutine object when its + body first suspends at "await awaitable". + """ @types.coroutine def suspend(): - yield 1 + yield "suspended" + + for start in range(20): + awaitable = suspend() + states = [] + def fail(): + _testcapi.set_nomemory(start, start + 1) + def failed(): + _testcapi.remove_mem_hooks() + states.append(inspect.getgeneratorstate(awaitable)) + coro = make_outer(awaitable, fail, failed) + yields = [] + try: + try: + while True: + yields.append(coro.send(None)) + except BaseException as e: + outcome = e + finally: + _testcapi.remove_mem_hooks() + awaitable.close() + if (states[:1] == [inspect.GEN_SUSPENDED] + and "suspended" not in yields): + return yields, outcome + coro.close() + self.fail("no allocation failed at the first suspension") + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_memory_error_at_first_suspension(self): class CM: async def __aenter__(self): log.append("enter") @@ -3147,29 +3180,87 @@ async def __aexit__(self, typ, *args): log.append(("exit", typ)) log = [] - awaitable = suspend() + def make_outer(awaitable, fail, failed): + async def inner(): + async with CM(): + fail() + try: + await awaitable + finally: + failed() + log.append("finally") + return "resumed" + + async def outer(): + return await inner() - async def inner(): - async with CM(): - _testcapi.set_nomemory(0, 1) + log.clear() + return outer() + + yields, outcome = self.run_failing_first_suspension(make_outer) + self.assertEqual(yields, []) + self.assertIsInstance(outcome, MemoryError) + self.assertEqual(log, ["enter", "finally", ("exit", MemoryError)]) + + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_memory_error_at_first_suspension_caught(self): + @types.coroutine + def suspend_again(): + yield "again" + + def make_outer(awaitable, fail, failed): + async def inner(): + fail() try: await awaitable + except MemoryError: + failed() + await suspend_again() + return "caught" finally: - _testcapi.remove_mem_hooks() - log.append("finally") - return "resumed" + failed() - async def outer(): - return await inner() + async def outer(): + # The list checks the stack of outer() after the await. + return ["x", await inner(), "y"] - coro = outer() - try: - with self.assertRaises(MemoryError): - coro.send(None) - finally: - _testcapi.remove_mem_hooks() - awaitable.close() - self.assertEqual(log, ["enter", "finally", ("exit", MemoryError)]) + return outer() + + yields, outcome = self.run_failing_first_suspension(make_outer) + self.assertEqual(yields, ["again"]) + self.assertIsInstance(outcome, StopIteration) + self.assertEqual(outcome.value, ["x", "caught", "y"]) + + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_memory_error_at_first_suspension_monitoring(self): + events = [] + tool = 2 + E = sys.monitoring.events + sys.monitoring.use_tool_id(tool, "test_coroutines") + self.addCleanup(sys.monitoring.free_tool_id, tool) + sys.monitoring.register_callback( + tool, E.PY_THROW, + lambda code, offset, exc: events.append((code.co_name, type(exc)))) + sys.monitoring.set_events(tool, E.PY_THROW) + self.addCleanup(sys.monitoring.set_events, tool, 0) + + def make_outer(awaitable, fail, failed): + async def inner(): + fail() + try: + await awaitable + finally: + failed() + + async def outer(): + return await inner() + + events.clear() + return outer() + + _, outcome = self.run_failing_first_suspension(make_outer) + self.assertIsInstance(outcome, MemoryError) + self.assertEqual(events[0], ("inner", MemoryError)) def test_recursion_error_before_body_runs(self): async def f(): diff --git a/Modules/_testinternalcapi/test_cases.c.h b/Modules/_testinternalcapi/test_cases.c.h index 47420e905fe4ad..a11f5c96489241 100644 --- a/Modules/_testinternalcapi/test_cases.c.h +++ b/Modules/_testinternalcapi/test_cases.c.h @@ -6006,7 +6006,8 @@ sub_iter = stack_pointer[-4]; PyObject *exc_value = PyStackRef_AsPyObjectBorrow(exc_value_st); #if !_Py_TAIL_CALL_INTERP - assert(throwflag); + + assert(throwflag || frame->lazy_coro == LAZY_CORO_RUNNING); #endif assert(exc_value && PyExceptionInstance_Check(exc_value)); _PyFrame_SetStackPointer(frame, stack_pointer); diff --git a/Python/bytecodes.c b/Python/bytecodes.c index c022c1183a88cc..87e0dac795bf49 100644 --- a/Python/bytecodes.c +++ b/Python/bytecodes.c @@ -2034,7 +2034,8 @@ dummy_func( tier1 inst(CLEANUP_THROW, (sub_iter, null_in, last_sent_val, exc_value_st -- none, null_out, value)) { PyObject *exc_value = PyStackRef_AsPyObjectBorrow(exc_value_st); #if !_Py_TAIL_CALL_INTERP - assert(throwflag); + // _PyEval_ThrowIntoLazyCoro() raises in a lazily run body. + assert(throwflag || frame->lazy_coro == LAZY_CORO_RUNNING); #endif assert(exc_value && PyExceptionInstance_Check(exc_value)); int matches = PyErr_GivenExceptionMatches(exc_value, PyExc_StopIteration); diff --git a/Python/ceval.c b/Python/ceval.c index 99d4399e4ee661..71b26e8451c9c6 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -3783,6 +3783,10 @@ _PyEval_ThrowIntoLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame, tstate->exc_info = exc_info; _PyInterpreterFrame *caller = tstate->current_frame; assert(caller->return_offset == 0); + // The value moves to the body, leaving the caller as while the body runs. + assert(PyStackRef_IsNull(caller->stackpointer[-1])); + caller->stackpointer--; + assert(PyStackRef_IsNull(caller->stackpointer[-1])); frame->previous = caller; tstate->current_frame = frame; int too_deep = _Py_EnterRecursivePy(tstate); @@ -3790,6 +3794,7 @@ _PyEval_ThrowIntoLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame, (void)too_deep; // Stands in for the value sent on resumption, like gen_send_ex2(). _PyFrame_StackPush(frame, value); + monitor_throw(tstate, frame, frame->instr_ptr); return frame; } diff --git a/Python/generated_cases.c.h b/Python/generated_cases.c.h index e4faedd7e80bcd..e489bb08907e00 100644 --- a/Python/generated_cases.c.h +++ b/Python/generated_cases.c.h @@ -6006,7 +6006,8 @@ sub_iter = stack_pointer[-4]; PyObject *exc_value = PyStackRef_AsPyObjectBorrow(exc_value_st); #if !_Py_TAIL_CALL_INTERP - assert(throwflag); + + assert(throwflag || frame->lazy_coro == LAZY_CORO_RUNNING); #endif assert(exc_value && PyExceptionInstance_Check(exc_value)); _PyFrame_SetStackPointer(frame, stack_pointer); From b5c5db852ce9407f5c44f29adf55db6fa0ee6704 Mon Sep 17 00:00:00 2001 From: Andrew Svetlov Date: Sun, 22 Nov 2026 20:16:53 +0100 Subject: [PATCH 04/10] Name the lazy_outcome of a returned lazy coroutine Co-Authored-By: Claude Opus 5.5 --- InternalDocs/generators.md | 6 +++--- Python/ceval.c | 2 +- Python/ceval_macros.h | 4 ++++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/InternalDocs/generators.md b/InternalDocs/generators.md index da2f7c6acc85cb..a8f119e864a358 100644 --- a/InternalDocs/generators.md +++ b/InternalDocs/generators.md @@ -67,9 +67,9 @@ an awaited call and follows the call with `END_AWAITED_CALL`, whose oparg jumps to the `YIELD_VALUE` of the `SEND` loop for the await. A lazily run body reports in `lazy_outcome` how it ended: -- It returned: `clear_thread_frame()` stores a tagged int, and - `END_AWAITED_CALL` skips the `SEND` loop, jumping past the `END_SEND` that - the `SEND` right before `YIELD_VALUE` jumps to. +- It returned: `clear_thread_frame()` stores the tagged int + `LAZY_CORO_RETURNED`, and `END_AWAITED_CALL` skips the `SEND` loop, jumping + past the `END_SEND` that the `SEND` right before `YIELD_VALUE` jumps to. - It suspended: `YIELD_VALUE` leaves the frame and its `_PyErr_StackItem` on the data stack and stores a pointer to the frame. `END_AWAITED_CALL` creates the coroutine object, moves the frame and the exception state into it (see diff --git a/Python/ceval.c b/Python/ceval.c index 71b26e8451c9c6..5af6a3b9be8e7c 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -2028,7 +2028,7 @@ clear_lazy_coro_frame(PyThreadState *tstate, _PyInterpreterFrame *frame) frame->lazy_coro = 0; _PyInterpreterFrame *caller = frame->previous; assert(PyStackRef_IsNull(caller->stackpointer[-1])); - caller->stackpointer[-1] = PyStackRef_TagInt(0); + caller->stackpointer[-1] = LAZY_CORO_RETURNED; // Like clear_gen_frame(): a frame object that outlives the // coroutine must not keep the caller's frame alive via f_back. frame->previous = NULL; diff --git a/Python/ceval_macros.h b/Python/ceval_macros.h index b9e2134c21602c..fceb20d34676c9 100644 --- a/Python/ceval_macros.h +++ b/Python/ceval_macros.h @@ -167,6 +167,10 @@ #else # define LAZY_CORO_ALLOWED() 1 #endif + +/* The lazy_outcome of a lazily run body that returned. */ +#define LAZY_CORO_RETURNED PyStackRef_TagInt(0) + #define MAYBE_START_LAZY_CORO(FRAME) \ do { \ _PyInterpreterFrame *lazy_frame_ = (FRAME); \ From 0dbe15bfb1a5d87f95ff386d297ead0c2f814d57 Mon Sep 17 00:00:00 2001 From: Andrew Svetlov Date: Mon, 23 Nov 2026 08:55:53 +0100 Subject: [PATCH 05/10] gh-161170: Merge END_AWAITED_CALL into GET_AWAITABLE GET_AWAITABLE after an awaited call now has the GET_AWAITABLE_AWAITED_CALL flag (4) in its oparg, next to 'where' in the low two bits, and handles the lazy outcome itself. The SEND loop always starts right after it, so the target of the suspended case needs no offset in the oparg and GET_AWAITABLE is not a jump. Co-Authored-By: Claude Opus 5.5 --- Doc/library/dis.rst | 50 +++--- Doc/whatsnew/3.16.rst | 6 +- Include/internal/pycore_opcode_metadata.h | 14 +- Include/internal/pycore_opcode_utils.h | 4 + Include/internal/pycore_uop_ids.h | 13 +- Include/internal/pycore_uop_metadata.h | 33 ++-- Include/opcode_ids.h | 107 +++++++------ InternalDocs/generators.md | 22 +-- Lib/_opcode_metadata.py | 107 +++++++------ Lib/test/test__opcode.py | 7 +- Lib/test/test_capi/test_opt.py | 4 +- Lib/test/test_coroutines.py | 4 +- Lib/test/test_dis.py | 21 ++- Modules/_testinternalcapi/test_cases.c.h | 184 +++++++++++----------- Modules/_testinternalcapi/test_targets.h | 9 +- Objects/frameobject.c | 33 ++-- Programs/test_frozenmain.h | 20 +-- Python/bytecodes.c | 93 ++++++----- Python/ceval.c | 2 +- Python/ceval_macros.h | 7 +- Python/codegen.c | 20 +-- Python/executor_cases.c.h | 81 +++------- Python/flowgraph.c | 21 +-- Python/generated_cases.c.h | 184 +++++++++++----------- Python/instrumentation.c | 49 ++++-- Python/opcode_targets.h | 9 +- Python/optimizer.c | 12 +- Python/optimizer_cases.c.h | 12 +- Python/specialize.c | 4 +- 29 files changed, 556 insertions(+), 576 deletions(-) diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst index f46d793b60ffe6..c96a71acc3dab5 100644 --- a/Doc/library/dis.rst +++ b/Doc/library/dis.rst @@ -815,7 +815,7 @@ not have to be) the original ``STACK[-2]``. **Coroutine opcodes** -.. opcode:: GET_AWAITABLE (where) +.. opcode:: GET_AWAITABLE (flags) Replaces ``STACK[-1]`` with ``get_awaitable(STACK[-1])``, ``NULL`` and ``None``, ready for :opcode:`SEND`. ``get_awaitable(o)`` @@ -823,11 +823,26 @@ not have to be) the original ``STACK[-2]``. the :data:`~inspect.CO_ITERABLE_COROUTINE` flag, or resolves ``o.__await__``. - If the ``where`` operand is nonzero, it indicates where the instruction - occurs: - - * ``1``: After a call to ``__aenter__`` - * ``2``: After a call to ``__aexit__`` + The low two bits of *flags*, if nonzero, indicate where the instruction + occurs: + + * ``1``: After a call to ``__aenter__`` + * ``2``: After a call to ``__aexit__`` + + If bit ``4`` of *flags* is set, the instruction follows a call whose + result is awaited right away (``await f()``, and the calls of + :meth:`~object.__aenter__` and :meth:`~object.__aexit__` in + :keyword:`async with`). The compiler pushes an extra ``NULL``, the + *lazy outcome*, below the callable of such a call, and the call may run + the body of a coroutine function without creating the coroutine object, + reporting in the lazy outcome, ``STACK[-2]``, how the body ended. + If the lazy outcome is ``NULL``, it is removed and the instruction + proceeds as described above. If the body returned, it is removed and + execution continues after the :opcode:`END_SEND` of the following + :opcode:`SEND` loop. If the body suspended, the coroutine object is + created and execution continues at the :opcode:`YIELD_VALUE` of that + loop, with ``STACK[-3:]`` set to the coroutine, ``NULL`` and the yielded + value. .. versionadded:: 3.5 @@ -836,28 +851,7 @@ not have to be) the original ``STACK[-2]``. .. versionchanged:: next Also pushes ``NULL`` and ``None``, which were previously pushed by - separate instructions. - - -.. opcode:: END_AWAITED_CALL (delta) - - Follows a call whose result is awaited right away (``await f()``, and the - calls of :meth:`~object.__aenter__` and :meth:`~object.__aexit__` in - :keyword:`async with`). - The compiler pushes an extra ``NULL``, the *lazy outcome*, below the - callable of such a call, and the call may run the body of a coroutine - function without creating the coroutine object, reporting in the lazy - outcome how the body ended. - - If the lazy outcome is ``NULL``, it is removed and execution continues with - :opcode:`GET_AWAITABLE`. If the body returned, it is removed and - execution continues after the :opcode:`END_SEND` of the following - :opcode:`SEND` loop. If the body suspended, the coroutine object is - created and the bytecode counter is incremented by *delta*, to the - :opcode:`YIELD_VALUE` of that loop, with ``STACK[-3:]`` set to the - coroutine, ``NULL`` and the yielded value. - - .. versionadded:: 3.16 + separate instructions. Added the awaited call flag. .. opcode:: GET_AITER diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index f7e1d9922cd3da..d64e3b5a6ccbc1 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -1528,9 +1528,9 @@ CPython bytecode changes * ``await `` and the calls of :meth:`~object.__aenter__` and :meth:`~object.__aexit__` in :keyword:`async with` now push an extra ``NULL`` below the callable and - follow the call with the new :opcode:`END_AWAITED_CALL` instruction, - which either goes on to :opcode:`GET_AWAITABLE`, skips the - :opcode:`SEND` loop, or jumps to its :opcode:`YIELD_VALUE`. + follow the call with :opcode:`GET_AWAITABLE` with a new flag in its oparg. + It then also either skips the :opcode:`SEND` loop or jumps to its + :opcode:`YIELD_VALUE`. (Contributed by Andrew Svetlov in :gh:`161170`.) diff --git a/Include/internal/pycore_opcode_metadata.h b/Include/internal/pycore_opcode_metadata.h index d81ad35d1fe754..31dadf002b72de 100644 --- a/Include/internal/pycore_opcode_metadata.h +++ b/Include/internal/pycore_opcode_metadata.h @@ -202,8 +202,6 @@ int _PyOpcode_num_popped(int opcode, int oparg) { return 2 + (oparg - 1); case END_ASYNC_FOR: return 2; - case END_AWAITED_CALL: - return 2; case END_FOR: return 1; case END_SEND: @@ -235,7 +233,7 @@ int _PyOpcode_num_popped(int opcode, int oparg) { case GET_ANEXT: return 1; case GET_AWAITABLE: - return 1; + return 1 + ((oparg >> 2) & 1); case GET_ITER: return 1; case GET_ITER_SELF: @@ -711,8 +709,6 @@ int _PyOpcode_num_pushed(int opcode, int oparg) { return 1 + (oparg - 1); case END_ASYNC_FOR: return 0; - case END_AWAITED_CALL: - return 1; case END_FOR: return 0; case END_SEND: @@ -1210,7 +1206,6 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = { [DICT_MERGE] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, [DICT_UPDATE] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, [END_ASYNC_FOR] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_UNPREDICTABLE_JUMP_FLAG | HAS_NEEDS_GUARD_IP_FLAG }, - [END_AWAITED_CALL] = { true, INSTR_FMT_IB, HAS_ARG_FLAG | HAS_JUMP_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG }, [END_FOR] = { true, INSTR_FMT_IX, HAS_ESCAPES_FLAG | HAS_NO_SAVE_IP_FLAG }, [END_SEND] = { true, INSTR_FMT_IX, HAS_ESCAPES_FLAG | HAS_PURE_FLAG }, [ENTER_EXECUTOR] = { true, INSTR_FMT_IB, HAS_ARG_FLAG }, @@ -1466,7 +1461,6 @@ _PyOpcode_macro_expansion[256] = { [DELETE_SUBSCR] = { .nuops = 1, .uops = { { _DELETE_SUBSCR, OPARG_SIMPLE, 0 } } }, [DICT_MERGE] = { .nuops = 2, .uops = { { _DICT_MERGE, OPARG_SIMPLE, 0 }, { _POP_TOP, OPARG_SIMPLE, 0 } } }, [DICT_UPDATE] = { .nuops = 2, .uops = { { _DICT_UPDATE, OPARG_SIMPLE, 0 }, { _POP_TOP, OPARG_SIMPLE, 0 } } }, - [END_AWAITED_CALL] = { .nuops = 2, .uops = { { _END_AWAITED_CALL, OPARG_REPLACED, 0 }, { _POP_LAZY_OUTCOME, OPARG_SIMPLE, 0 } } }, [END_FOR] = { .nuops = 1, .uops = { { _END_FOR, OPARG_SIMPLE, 0 } } }, [END_SEND] = { .nuops = 1, .uops = { { _END_SEND, OPARG_SIMPLE, 0 } } }, [EXIT_INIT_CHECK] = { .nuops = 1, .uops = { { _EXIT_INIT_CHECK, OPARG_SIMPLE, 0 } } }, @@ -1480,7 +1474,7 @@ _PyOpcode_macro_expansion[256] = { [FOR_ITER_VIRTUAL] = { .nuops = 2, .uops = { { _GUARD_TOS_NOT_NULL, OPARG_SIMPLE, 1 }, { _FOR_ITER_VIRTUAL, OPARG_REPLACED, 1 } } }, [GET_AITER] = { .nuops = 1, .uops = { { _GET_AITER, OPARG_SIMPLE, 0 } } }, [GET_ANEXT] = { .nuops = 1, .uops = { { _GET_ANEXT, OPARG_SIMPLE, 0 } } }, - [GET_AWAITABLE] = { .nuops = 1, .uops = { { _GET_AWAITABLE, OPARG_SIMPLE, 0 } } }, + [GET_AWAITABLE] = { .nuops = 3, .uops = { { _LAZY_CALL_OUTCOME, OPARG_REPLACED, 0 }, { _POP_LAZY_OUTCOME, OPARG_SIMPLE, 0 }, { _GET_AWAITABLE, OPARG_SIMPLE, 0 } } }, [GET_ITER] = { .nuops = 2, .uops = { { _RECORD_TOS_TYPE, OPARG_SIMPLE, 0 }, { _GET_ITER, OPARG_SIMPLE, 0 } } }, [GET_ITER_SELF] = { .nuops = 3, .uops = { { _RECORD_TOS_TYPE, OPARG_SIMPLE, 0 }, { _GUARD_ITERATOR, OPARG_SIMPLE, 1 }, { _PUSH_NULL, OPARG_SIMPLE, 1 } } }, [GET_ITER_VIRTUAL] = { .nuops = 3, .uops = { { _RECORD_TOS_TYPE, OPARG_SIMPLE, 0 }, { _GUARD_ITER_VIRTUAL, OPARG_SIMPLE, 1 }, { _PUSH_TAGGED_ZERO, OPARG_SIMPLE, 1 } } }, @@ -1677,7 +1671,6 @@ const char *_PyOpcode_OpName[267] = { [DICT_MERGE] = "DICT_MERGE", [DICT_UPDATE] = "DICT_UPDATE", [END_ASYNC_FOR] = "END_ASYNC_FOR", - [END_AWAITED_CALL] = "END_AWAITED_CALL", [END_FOR] = "END_FOR", [END_SEND] = "END_SEND", [ENTER_EXECUTOR] = "ENTER_EXECUTOR", @@ -1877,6 +1870,7 @@ const uint8_t _PyOpcode_Caches[256] = { PyAPI_DATA(const uint8_t) _PyOpcode_Deopt[256]; #ifdef NEED_OPCODE_METADATA const uint8_t _PyOpcode_Deopt[256] = { + [117] = 117, [118] = 118, [119] = 119, [120] = 120, @@ -1977,7 +1971,6 @@ const uint8_t _PyOpcode_Deopt[256] = { [DICT_MERGE] = DICT_MERGE, [DICT_UPDATE] = DICT_UPDATE, [END_ASYNC_FOR] = END_ASYNC_FOR, - [END_AWAITED_CALL] = END_AWAITED_CALL, [END_FOR] = END_FOR, [END_SEND] = END_SEND, [ENTER_EXECUTOR] = ENTER_EXECUTOR, @@ -2138,6 +2131,7 @@ const uint8_t _PyOpcode_Deopt[256] = { #endif // NEED_OPCODE_METADATA #define EXTRA_CASES \ + case 117: \ case 118: \ case 119: \ case 120: \ diff --git a/Include/internal/pycore_opcode_utils.h b/Include/internal/pycore_opcode_utils.h index 7067b48ec22cb3..d70c6eeab8eeda 100644 --- a/Include/internal/pycore_opcode_utils.h +++ b/Include/internal/pycore_opcode_utils.h @@ -98,6 +98,10 @@ extern "C" { #define GET_ITER_YIELD_FROM_NO_CHECK 2 #define GET_ITER_YIELD_FROM_CORO_CHECK 3 +/* Values used in the oparg for GET_AWAITABLE */ +#define GET_AWAITABLE_WHERE_MASK 0x3 +#define GET_AWAITABLE_AWAITED_CALL 0x4 + #ifdef __cplusplus } #endif diff --git a/Include/internal/pycore_uop_ids.h b/Include/internal/pycore_uop_ids.h index 93d7c8fcfdcc48..9bc947b1cd0dc8 100644 --- a/Include/internal/pycore_uop_ids.h +++ b/Include/internal/pycore_uop_ids.h @@ -117,7 +117,6 @@ enum { _DO_CALL_FUNCTION_EX, _DO_CALL_KW, _DYNAMIC_EXIT, - _END_AWAITED_CALL, _ERROR_POP_N, _EXPAND_METHOD, _EXPAND_METHOD_KW, @@ -127,6 +126,7 @@ enum { _FOR_ITER_TIER_TWO, _FOR_ITER_VIRTUAL, _FOR_ITER_VIRTUAL_TIER_TWO, + _GET_AWAITABLE, _GET_ITER, _GET_ITER_TRAD, _GUARD_3OS_ASYNC_GEN_ASEND, @@ -175,6 +175,7 @@ enum { _GUARD_IS_TRUE_POP, _GUARD_ITERATOR, _GUARD_ITER_VIRTUAL, + _GUARD_LAZY_OUTCOME_NULL, _GUARD_LOAD_SUPER_ATTR_METHOD, _GUARD_NOS_COMPACT_ASCII, _GUARD_NOS_DICT_STORE_SUBSCRIPT, @@ -237,6 +238,7 @@ enum { _ITER_NEXT_RANGE, _ITER_NEXT_TUPLE, _JUMP_TO_TOP, + _LAZY_CALL_OUTCOME, _LIST_EXTEND, _LOAD_ATTR, _LOAD_ATTR_CLASS, @@ -372,7 +374,7 @@ enum { _UNPACK_SEQUENCE_UNIQUE_TWO_TUPLE, _YIELD_VALUE, }; -#define MAX_UOP_ID 660 +#define MAX_UOP_ID 662 #define _BUILD_INTERPOLATION BUILD_INTERPOLATION #define _BUILD_LIST BUILD_LIST @@ -396,7 +398,6 @@ enum { #define _FORMAT_WITH_SPEC FORMAT_WITH_SPEC #define _GET_AITER GET_AITER #define _GET_ANEXT GET_ANEXT -#define _GET_AWAITABLE GET_AWAITABLE #define _GET_LEN GET_LEN #define _IMPORT_FROM IMPORT_FROM #define _IMPORT_NAME IMPORT_NAME @@ -675,7 +676,6 @@ enum { _DYNAMIC_EXIT_r10, _DYNAMIC_EXIT_r20, _DYNAMIC_EXIT_r30, - _END_AWAITED_CALL_r22, _END_FOR_r10, _END_SEND_r31, _ERROR_POP_N_r00, @@ -859,6 +859,7 @@ enum { _GUARD_ITER_VIRTUAL_r11, _GUARD_ITER_VIRTUAL_r22, _GUARD_ITER_VIRTUAL_r33, + _GUARD_LAZY_OUTCOME_NULL_r11, _GUARD_LOAD_SUPER_ATTR_METHOD_r03, _GUARD_LOAD_SUPER_ATTR_METHOD_r13, _GUARD_LOAD_SUPER_ATTR_METHOD_r23, @@ -1092,6 +1093,7 @@ enum { _JUMP_BACKWARD_NO_INTERRUPT_r22, _JUMP_BACKWARD_NO_INTERRUPT_r33, _JUMP_TO_TOP_r00, + _LAZY_CALL_OUTCOME_r11, _LIST_APPEND_r10, _LIST_EXTEND_r11, _LOAD_ATTR_r10, @@ -1277,10 +1279,7 @@ enum { _POP_JUMP_IF_TRUE_r10, _POP_JUMP_IF_TRUE_r21, _POP_JUMP_IF_TRUE_r32, - _POP_LAZY_OUTCOME_r01, _POP_LAZY_OUTCOME_r11, - _POP_LAZY_OUTCOME_r21, - _POP_LAZY_OUTCOME_r32, _POP_TOP_r10, _POP_TOP_FLOAT_r00, _POP_TOP_FLOAT_r10, diff --git a/Include/internal/pycore_uop_metadata.h b/Include/internal/pycore_uop_metadata.h index a7c440bc0db24d..b41e49fb03d2b8 100644 --- a/Include/internal/pycore_uop_metadata.h +++ b/Include/internal/pycore_uop_metadata.h @@ -168,7 +168,8 @@ const uint32_t _PyUop_Flags[MAX_UOP_ID+1] = { [_GET_AITER] = HAS_ERROR_FLAG | HAS_ESCAPES_FLAG, [_GET_ANEXT] = HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG, [_GET_AWAITABLE] = HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG, - [_POP_LAZY_OUTCOME] = 0, + [_GUARD_LAZY_OUTCOME_NULL] = HAS_ARG_FLAG | HAS_EXIT_FLAG, + [_POP_LAZY_OUTCOME] = HAS_ARG_FLAG, [_SEND_GEN_FRAME] = HAS_ARG_FLAG | HAS_EXIT_FLAG, [_GUARD_TOS_IS_NONE] = HAS_EXIT_FLAG, [_GUARD_NOS_NOT_NULL] = HAS_EXIT_FLAG, @@ -1646,13 +1647,22 @@ const _PyUopCachingInfo _PyUop_Caching[MAX_UOP_ID+1] = { { -1, -1, -1 }, }, }, + [_GUARD_LAZY_OUTCOME_NULL] = { + .best = { 1, 1, 1, 1 }, + .entries = { + { -1, -1, -1 }, + { 1, 1, _GUARD_LAZY_OUTCOME_NULL_r11 }, + { -1, -1, -1 }, + { -1, -1, -1 }, + }, + }, [_POP_LAZY_OUTCOME] = { - .best = { 0, 1, 2, 3 }, + .best = { 1, 1, 1, 1 }, .entries = { - { 1, 0, _POP_LAZY_OUTCOME_r01 }, + { -1, -1, -1 }, { 1, 1, _POP_LAZY_OUTCOME_r11 }, - { 1, 2, _POP_LAZY_OUTCOME_r21 }, - { 2, 3, _POP_LAZY_OUTCOME_r32 }, + { -1, -1, -1 }, + { -1, -1, -1 }, }, }, [_SEND_GEN_FRAME] = { @@ -4305,10 +4315,8 @@ const uint16_t _PyUop_Uncached[MAX_UOP_REGS_ID+1] = { [_GET_AITER_r11] = _GET_AITER, [_GET_ANEXT_r13] = _GET_ANEXT, [_GET_AWAITABLE_r13] = _GET_AWAITABLE, - [_POP_LAZY_OUTCOME_r01] = _POP_LAZY_OUTCOME, + [_GUARD_LAZY_OUTCOME_NULL_r11] = _GUARD_LAZY_OUTCOME_NULL, [_POP_LAZY_OUTCOME_r11] = _POP_LAZY_OUTCOME, - [_POP_LAZY_OUTCOME_r21] = _POP_LAZY_OUTCOME, - [_POP_LAZY_OUTCOME_r32] = _POP_LAZY_OUTCOME, [_SEND_GEN_FRAME_r33] = _SEND_GEN_FRAME, [_GUARD_TOS_IS_NONE_r01] = _GUARD_TOS_IS_NONE, [_GUARD_TOS_IS_NONE_r11] = _GUARD_TOS_IS_NONE, @@ -5473,6 +5481,8 @@ const char *const _PyOpcode_uop_name[MAX_UOP_REGS_ID+1] = { [_GUARD_ITER_VIRTUAL_r11] = "_GUARD_ITER_VIRTUAL_r11", [_GUARD_ITER_VIRTUAL_r22] = "_GUARD_ITER_VIRTUAL_r22", [_GUARD_ITER_VIRTUAL_r33] = "_GUARD_ITER_VIRTUAL_r33", + [_GUARD_LAZY_OUTCOME_NULL] = "_GUARD_LAZY_OUTCOME_NULL", + [_GUARD_LAZY_OUTCOME_NULL_r11] = "_GUARD_LAZY_OUTCOME_NULL_r11", [_GUARD_LOAD_SUPER_ATTR_METHOD] = "_GUARD_LOAD_SUPER_ATTR_METHOD", [_GUARD_LOAD_SUPER_ATTR_METHOD_r03] = "_GUARD_LOAD_SUPER_ATTR_METHOD_r03", [_GUARD_LOAD_SUPER_ATTR_METHOD_r13] = "_GUARD_LOAD_SUPER_ATTR_METHOD_r13", @@ -5962,10 +5972,7 @@ const char *const _PyOpcode_uop_name[MAX_UOP_REGS_ID+1] = { [_POP_ITER] = "_POP_ITER", [_POP_ITER_r20] = "_POP_ITER_r20", [_POP_LAZY_OUTCOME] = "_POP_LAZY_OUTCOME", - [_POP_LAZY_OUTCOME_r01] = "_POP_LAZY_OUTCOME_r01", [_POP_LAZY_OUTCOME_r11] = "_POP_LAZY_OUTCOME_r11", - [_POP_LAZY_OUTCOME_r21] = "_POP_LAZY_OUTCOME_r21", - [_POP_LAZY_OUTCOME_r32] = "_POP_LAZY_OUTCOME_r32", [_POP_TOP] = "_POP_TOP", [_POP_TOP_r10] = "_POP_TOP_r10", [_POP_TOP_FLOAT] = "_POP_TOP_FLOAT", @@ -6502,8 +6509,10 @@ int _PyUop_num_popped(int opcode, int oparg) return 0; case _GET_AWAITABLE: return 1; + case _GUARD_LAZY_OUTCOME_NULL: + return 0; case _POP_LAZY_OUTCOME: - return 2; + return 1 + ((oparg >> 2) & 1); case _SEND_GEN_FRAME: return 1; case _GUARD_TOS_IS_NONE: diff --git a/Include/opcode_ids.h b/Include/opcode_ids.h index 5d1d741a609650..c0d307f78dec28 100644 --- a/Include/opcode_ids.h +++ b/Include/opcode_ids.h @@ -74,60 +74,59 @@ extern "C" { #define DICT_MERGE 61 #define DICT_UPDATE 62 #define END_ASYNC_FOR 63 -#define END_AWAITED_CALL 64 -#define EXTENDED_ARG 65 -#define FOR_ITER 66 -#define GET_AWAITABLE 67 -#define GET_ITER 68 -#define IMPORT_FROM 69 -#define IMPORT_NAME 70 -#define IS_OP 71 -#define JUMP_BACKWARD 72 -#define JUMP_BACKWARD_NO_INTERRUPT 73 -#define JUMP_FORWARD 74 -#define LIST_APPEND 75 -#define LIST_EXTEND 76 -#define LOAD_ATTR 77 -#define LOAD_COMMON_CONSTANT 78 -#define LOAD_CONST 79 -#define LOAD_DEREF 80 -#define LOAD_FAST 81 -#define LOAD_FAST_AND_CLEAR 82 -#define LOAD_FAST_BORROW 83 -#define LOAD_FAST_BORROW_LOAD_FAST_BORROW 84 -#define LOAD_FAST_CHECK 85 -#define LOAD_FAST_LOAD_FAST 86 -#define LOAD_FROM_DICT_OR_DEREF 87 -#define LOAD_FROM_DICT_OR_GLOBALS 88 -#define LOAD_GLOBAL 89 -#define LOAD_NAME 90 -#define LOAD_SMALL_INT 91 -#define LOAD_SPECIAL 92 -#define LOAD_SUPER_ATTR 93 -#define MAKE_CELL 94 -#define MAP_ADD 95 -#define MATCH_CLASS 96 -#define POP_JUMP_IF_FALSE 97 -#define POP_JUMP_IF_NONE 98 -#define POP_JUMP_IF_NOT_NONE 99 -#define POP_JUMP_IF_TRUE 100 -#define RAISE_VARARGS 101 -#define RERAISE 102 -#define SEND 103 -#define SET_ADD 104 -#define SET_FUNCTION_ATTRIBUTE 105 -#define SET_UPDATE 106 -#define STORE_ATTR 107 -#define STORE_DEREF 108 -#define STORE_FAST 109 -#define STORE_FAST_LOAD_FAST 110 -#define STORE_FAST_STORE_FAST 111 -#define STORE_GLOBAL 112 -#define STORE_NAME 113 -#define SWAP 114 -#define UNPACK_EX 115 -#define UNPACK_SEQUENCE 116 -#define YIELD_VALUE 117 +#define EXTENDED_ARG 64 +#define FOR_ITER 65 +#define GET_AWAITABLE 66 +#define GET_ITER 67 +#define IMPORT_FROM 68 +#define IMPORT_NAME 69 +#define IS_OP 70 +#define JUMP_BACKWARD 71 +#define JUMP_BACKWARD_NO_INTERRUPT 72 +#define JUMP_FORWARD 73 +#define LIST_APPEND 74 +#define LIST_EXTEND 75 +#define LOAD_ATTR 76 +#define LOAD_COMMON_CONSTANT 77 +#define LOAD_CONST 78 +#define LOAD_DEREF 79 +#define LOAD_FAST 80 +#define LOAD_FAST_AND_CLEAR 81 +#define LOAD_FAST_BORROW 82 +#define LOAD_FAST_BORROW_LOAD_FAST_BORROW 83 +#define LOAD_FAST_CHECK 84 +#define LOAD_FAST_LOAD_FAST 85 +#define LOAD_FROM_DICT_OR_DEREF 86 +#define LOAD_FROM_DICT_OR_GLOBALS 87 +#define LOAD_GLOBAL 88 +#define LOAD_NAME 89 +#define LOAD_SMALL_INT 90 +#define LOAD_SPECIAL 91 +#define LOAD_SUPER_ATTR 92 +#define MAKE_CELL 93 +#define MAP_ADD 94 +#define MATCH_CLASS 95 +#define POP_JUMP_IF_FALSE 96 +#define POP_JUMP_IF_NONE 97 +#define POP_JUMP_IF_NOT_NONE 98 +#define POP_JUMP_IF_TRUE 99 +#define RAISE_VARARGS 100 +#define RERAISE 101 +#define SEND 102 +#define SET_ADD 103 +#define SET_FUNCTION_ATTRIBUTE 104 +#define SET_UPDATE 105 +#define STORE_ATTR 106 +#define STORE_DEREF 107 +#define STORE_FAST 108 +#define STORE_FAST_LOAD_FAST 109 +#define STORE_FAST_STORE_FAST 110 +#define STORE_GLOBAL 111 +#define STORE_NAME 112 +#define SWAP 113 +#define UNPACK_EX 114 +#define UNPACK_SEQUENCE 115 +#define YIELD_VALUE 116 #define RESUME 128 #define BINARY_OP_ADD_FLOAT 129 #define BINARY_OP_ADD_INT 130 diff --git a/InternalDocs/generators.md b/InternalDocs/generators.md index a8f119e864a358..c1acf4582d2625 100644 --- a/InternalDocs/generators.md +++ b/InternalDocs/generators.md @@ -49,13 +49,14 @@ which time its frame is destroyed). There is one exception: a coroutine function called by an awaited call (`await f()` or the calls of `__aenter__` and `__aexit__` in `async with`: a -`CALL`, `CALL_KW` or `CALL_FUNCTION_EX` followed by `END_AWAITED_CALL`, see +`CALL`, `CALL_KW` or `CALL_FUNCTION_EX` followed by `GET_AWAITABLE` with the +`GET_AWAITABLE_AWAITED_CALL` flag, see `IS_AWAITED_CALL()`) sets `lazy_coro` to `LAZY_CORO_REQUESTED` on its frame (see `MAYBE_START_LAZY_CORO()`). The specializer gives such a call of a coroutine function an `*_AWAITED` form, which does the same. `RETURN_GENERATOR` then pushes the body's own `_PyErr_StackItem` on the data stack right after the frame, sets `lazy_coro` -to `LAZY_CORO_RUNNING`, moves the caller to its `END_AWAITED_CALL` (which has +to `LAZY_CORO_RUNNING`, moves the caller to its `GET_AWAITABLE` (which has the location of the `await`, like `SEND`) and keeps running the body in that frame, so that a body that returns or raises without suspending never creates a coroutine @@ -63,23 +64,24 @@ object. A frame that unwinds before `RETURN_GENERATOR` (for example on `RecursionError`) is cleared like any other. The compiler pushes an extra `NULL`, the `lazy_outcome`, below the callable of -an awaited call and follows the call with `END_AWAITED_CALL`, whose oparg jumps -to the `YIELD_VALUE` of the `SEND` loop for the await. A lazily run body reports -in `lazy_outcome` how it ended: +an awaited call and follows the call with `GET_AWAITABLE` with the +`GET_AWAITABLE_AWAITED_CALL` flag set in its oparg. The `SEND` loop for the +await starts right after it. A lazily run body reports in `lazy_outcome` how it +ended: - It returned: `clear_thread_frame()` stores the tagged int - `LAZY_CORO_RETURNED`, and `END_AWAITED_CALL` skips the `SEND` loop, jumping + `LAZY_CORO_RETURNED`, and `GET_AWAITABLE` skips the `SEND` loop, jumping past the `END_SEND` that the `SEND` right before `YIELD_VALUE` jumps to. - It suspended: `YIELD_VALUE` leaves the frame and its `_PyErr_StackItem` on the - data stack and stores a pointer to the frame. `END_AWAITED_CALL` creates the + data stack and stores a pointer to the frame. `GET_AWAITABLE` creates the coroutine object, moves the frame and the exception state into it (see `_PyEval_MaterializeLazyCoro()`) and jumps to `YIELD_VALUE` with the coroutine, `NULL` and the yielded value on the stack, as `SEND` would have left them. -- It raised: the exception is raised from the caller's `END_AWAITED_CALL`. +- It raised: the exception is raised from the caller's `GET_AWAITABLE`. -Otherwise `lazy_outcome` stays `NULL`, and `END_AWAITED_CALL` pops it and goes -on to `GET_AWAITABLE`. +Otherwise `lazy_outcome` stays `NULL`, and `GET_AWAITABLE` pops it and gets +the awaitable as usual. When the generator is next resumed by [`gen_send_ex2()`](../Objects/genobject.c), `_PyEval_EvalFrame()` is called diff --git a/Lib/_opcode_metadata.py b/Lib/_opcode_metadata.py index 5584815a777cfe..d9c4eefe137e8f 100644 --- a/Lib/_opcode_metadata.py +++ b/Lib/_opcode_metadata.py @@ -306,60 +306,59 @@ DICT_MERGE=61, DICT_UPDATE=62, END_ASYNC_FOR=63, - END_AWAITED_CALL=64, - EXTENDED_ARG=65, - FOR_ITER=66, - GET_AWAITABLE=67, - GET_ITER=68, - IMPORT_FROM=69, - IMPORT_NAME=70, - IS_OP=71, - JUMP_BACKWARD=72, - JUMP_BACKWARD_NO_INTERRUPT=73, - JUMP_FORWARD=74, - LIST_APPEND=75, - LIST_EXTEND=76, - LOAD_ATTR=77, - LOAD_COMMON_CONSTANT=78, - LOAD_CONST=79, - LOAD_DEREF=80, - LOAD_FAST=81, - LOAD_FAST_AND_CLEAR=82, - LOAD_FAST_BORROW=83, - LOAD_FAST_BORROW_LOAD_FAST_BORROW=84, - LOAD_FAST_CHECK=85, - LOAD_FAST_LOAD_FAST=86, - LOAD_FROM_DICT_OR_DEREF=87, - LOAD_FROM_DICT_OR_GLOBALS=88, - LOAD_GLOBAL=89, - LOAD_NAME=90, - LOAD_SMALL_INT=91, - LOAD_SPECIAL=92, - LOAD_SUPER_ATTR=93, - MAKE_CELL=94, - MAP_ADD=95, - MATCH_CLASS=96, - POP_JUMP_IF_FALSE=97, - POP_JUMP_IF_NONE=98, - POP_JUMP_IF_NOT_NONE=99, - POP_JUMP_IF_TRUE=100, - RAISE_VARARGS=101, - RERAISE=102, - SEND=103, - SET_ADD=104, - SET_FUNCTION_ATTRIBUTE=105, - SET_UPDATE=106, - STORE_ATTR=107, - STORE_DEREF=108, - STORE_FAST=109, - STORE_FAST_LOAD_FAST=110, - STORE_FAST_STORE_FAST=111, - STORE_GLOBAL=112, - STORE_NAME=113, - SWAP=114, - UNPACK_EX=115, - UNPACK_SEQUENCE=116, - YIELD_VALUE=117, + EXTENDED_ARG=64, + FOR_ITER=65, + GET_AWAITABLE=66, + GET_ITER=67, + IMPORT_FROM=68, + IMPORT_NAME=69, + IS_OP=70, + JUMP_BACKWARD=71, + JUMP_BACKWARD_NO_INTERRUPT=72, + JUMP_FORWARD=73, + LIST_APPEND=74, + LIST_EXTEND=75, + LOAD_ATTR=76, + LOAD_COMMON_CONSTANT=77, + LOAD_CONST=78, + LOAD_DEREF=79, + LOAD_FAST=80, + LOAD_FAST_AND_CLEAR=81, + LOAD_FAST_BORROW=82, + LOAD_FAST_BORROW_LOAD_FAST_BORROW=83, + LOAD_FAST_CHECK=84, + LOAD_FAST_LOAD_FAST=85, + LOAD_FROM_DICT_OR_DEREF=86, + LOAD_FROM_DICT_OR_GLOBALS=87, + LOAD_GLOBAL=88, + LOAD_NAME=89, + LOAD_SMALL_INT=90, + LOAD_SPECIAL=91, + LOAD_SUPER_ATTR=92, + MAKE_CELL=93, + MAP_ADD=94, + MATCH_CLASS=95, + POP_JUMP_IF_FALSE=96, + POP_JUMP_IF_NONE=97, + POP_JUMP_IF_NOT_NONE=98, + POP_JUMP_IF_TRUE=99, + RAISE_VARARGS=100, + RERAISE=101, + SEND=102, + SET_ADD=103, + SET_FUNCTION_ATTRIBUTE=104, + SET_UPDATE=105, + STORE_ATTR=106, + STORE_DEREF=107, + STORE_FAST=108, + STORE_FAST_LOAD_FAST=109, + STORE_FAST_STORE_FAST=110, + STORE_GLOBAL=111, + STORE_NAME=112, + SWAP=113, + UNPACK_EX=114, + UNPACK_SEQUENCE=115, + YIELD_VALUE=116, INSTRUMENTED_END_FOR=233, INSTRUMENTED_POP_ITER=234, INSTRUMENTED_END_SEND=235, diff --git a/Lib/test/test__opcode.py b/Lib/test/test__opcode.py index 3a689d5e7010b4..150187b36e557d 100644 --- a/Lib/test/test__opcode.py +++ b/Lib/test/test__opcode.py @@ -67,6 +67,9 @@ def test_stack_effect(self): self.assertEqual(stack_effect(dis.opmap['POP_TOP']), -1) self.assertEqual(stack_effect(dis.opmap['BUILD_SLICE'], 2), -1) self.assertEqual(stack_effect(dis.opmap['BUILD_SLICE'], 3), -2) + # After an awaited call, GET_AWAITABLE also pops the lazy outcome. + self.assertEqual(stack_effect(dis.opmap['GET_AWAITABLE'], 1), 2) + self.assertEqual(stack_effect(dis.opmap['GET_AWAITABLE'], 4 | 1), 1) self.assertRaises(ValueError, stack_effect, 30000) # All defined opcodes has_arg = dis.hasarg @@ -91,10 +94,6 @@ def test_stack_effect_jump(self): self.assertEqual(stack_effect(JUMP_FORWARD, 0), 0) self.assertEqual(stack_effect(JUMP_FORWARD, 0, jump=True), 0) self.assertEqual(stack_effect(JUMP_FORWARD, 0, jump=False), 0) - END_AWAITED_CALL = dis.opmap['END_AWAITED_CALL'] - self.assertEqual(stack_effect(END_AWAITED_CALL, 0), 1) - self.assertEqual(stack_effect(END_AWAITED_CALL, 0, jump=True), 1) - self.assertEqual(stack_effect(END_AWAITED_CALL, 0, jump=False), -1) # All defined opcodes has_arg = dis.hasarg has_exc = dis.hasexc diff --git a/Lib/test/test_capi/test_opt.py b/Lib/test/test_capi/test_opt.py index 174d8c7e71aebe..0fef739eb2dbb4 100644 --- a/Lib/test/test_capi/test_opt.py +++ b/Lib/test/test_capi/test_opt.py @@ -189,7 +189,7 @@ def setUp(self): self.guard_is_false, self.guard_is_true = get_bool_guard_ops() def test_awaited_call_jump_not_traced(self): - # Tier two runs only END_AWAITED_CALL's fall-through: no trace may + # Tier two runs only GET_AWAITABLE's fall-through: no trace may # continue past END_SEND after a lazily started coroutine returned. async def body(): t = 0 @@ -210,7 +210,7 @@ def run(): return "suspended" offset = next(i.offset for i in dis.get_instructions(main) - if i.opname == "END_AWAITED_CALL") + if i.opname == "GET_AWAITABLE" and i.arg & 4) enter_executor = dis.opmap["ENTER_EXECUTOR"] for _ in range(30_000): # Long enough to chain side exits. self.assertEqual(run(), 2) diff --git a/Lib/test/test_coroutines.py b/Lib/test/test_coroutines.py index 5f78676e01751f..6b5aa366743340 100644 --- a/Lib/test/test_coroutines.py +++ b/Lib/test/test_coroutines.py @@ -3338,7 +3338,7 @@ async def outer(): run_async(outer()) def test_line_events_at_awaited_call_jump_target(self): - # The list(genexpr) fast path jumps to END_AWAITED_CALL. + # The list(genexpr) fast path jumps to GET_AWAITABLE. async def list(arg): await AsyncYield("suspended") return "done" @@ -3506,7 +3506,7 @@ def format_tb(): self.assertEqual(lazy, eager) def test_instrumentation_enabled_before_first_suspension(self): - # END_AWAITED_CALL must run right after the body suspends, before + # GET_AWAITABLE must run right after the body suspends, before # anything else, even if LINE or INSTRUCTION events get enabled # while the body runs. E = sys.monitoring.events diff --git a/Lib/test/test_dis.py b/Lib/test/test_dis.py index 214e3e5ad509df..c3ff3ced29808c 100644 --- a/Lib/test/test_dis.py +++ b/Lib/test/test_dis.py @@ -618,8 +618,7 @@ async def _asyncwith(c): SWAP 2 LOAD_SPECIAL 2 (__aenter__) CALL 0 - END_AWAITED_CALL 3 (to L3) - GET_AWAITABLE 1 + GET_AWAITABLE 5 L2: SEND 4 (to L5) L3: YIELD_VALUE 1 L4: RESUME 3 @@ -634,8 +633,7 @@ async def _asyncwith(c): LOAD_COMMON_CONSTANT 7 (None) LOAD_COMMON_CONSTANT 7 (None) CALL 3 - END_AWAITED_CALL 3 (to L9) - GET_AWAITABLE 2 + GET_AWAITABLE 6 L8: SEND 4 (to L11) L9: YIELD_VALUE 1 L10: RESUME 3 @@ -649,7 +647,7 @@ async def _asyncwith(c): RETURN_VALUE %4d L12: CLEANUP_THROW - L13: JUMP_BACKWARD_NO_INTERRUPT 27 (to L5) + L13: JUMP_BACKWARD_NO_INTERRUPT 26 (to L5) L14: CLEANUP_THROW L15: JUMP_BACKWARD_NO_INTERRUPT 10 (to L11) L16: PUSH_EXC_INFO @@ -1323,14 +1321,13 @@ async def afunc(): instrs = list(dis.get_instructions(afunc)) names = [i.opname for i in instrs] - start = names.index('END_AWAITED_CALL') - self.assertEqual(names[start - 2:start + 5], [ - 'LOAD_SMALL_INT', 'CALL', 'END_AWAITED_CALL', 'GET_AWAITABLE', + start = names.index('GET_AWAITABLE') + self.assertEqual(names[start - 2:start + 4], [ + 'LOAD_SMALL_INT', 'CALL', 'GET_AWAITABLE', 'SEND', 'YIELD_VALUE', 'RESUME']) - self.assertEqual(instrs[start].jump_target, - instrs[start + 3].offset) - # Only `await ` gets END_AWAITED_CALL. - self.assertEqual(names.count('END_AWAITED_CALL'), 1) + # Only `await ` sets the awaited call flag. + self.assertEqual([i.arg for i in instrs if i.opname == 'GET_AWAITABLE'], + [4, 0]) @staticmethod diff --git a/Modules/_testinternalcapi/test_cases.c.h b/Modules/_testinternalcapi/test_cases.c.h index a11f5c96489241..183e937955c1b0 100644 --- a/Modules/_testinternalcapi/test_cases.c.h +++ b/Modules/_testinternalcapi/test_cases.c.h @@ -6928,81 +6928,6 @@ DISPATCH(); } - TARGET(END_AWAITED_CALL) { - #if _Py_TAIL_CALL_INTERP - int opcode = END_AWAITED_CALL; - (void)(opcode); - #endif - frame->instr_ptr = next_instr; - next_instr += 1; - INSTRUCTION_STATS(END_AWAITED_CALL); - _PyStackRef lazy_outcome; - _PyStackRef res; - _PyStackRef value; - // _END_AWAITED_CALL - { - res = stack_pointer[-1]; - lazy_outcome = stack_pointer[-2]; - if (PyStackRef_IsTaggedInt(lazy_outcome)) { - lazy_outcome = PyStackRef_NULL; - _Py_CODEUNIT *send = next_instr + oparg - 1 - INLINE_CACHE_ENTRIES_SEND; - stack_pointer[-2] = lazy_outcome; - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), - (int)(send - _PyFrame_GetBytecode(frame))).op.code == SEND); - _PyFrame_StackPointerInvalidate(frame); - _Py_CODEUNIT *end_send = next_instr + oparg + send->op.arg; - if (end_send->op.code != END_SEND) { - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - int err = monitor_stop_iteration(tstate, frame, end_send, - PyStackRef_AsPyObjectBorrow(res)); - _PyFrame_StackPointerInvalidate(frame); - if (err) { - JUMP_TO_LABEL(error); - } - } - JUMPBY(oparg + send->op.arg + 1); - } - else if (!PyStackRef_IsNull(lazy_outcome)) { - _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(lazy_outcome); - lazy_outcome = PyStackRef_NULL; - stack_pointer[-2] = lazy_outcome; - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); - _PyFrame_StackPointerInvalidate(frame); - _PyStackRef v = res; - if (gen == NULL) { - stack_pointer[-1] = PyStackRef_NULL; - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - frame = _PyEval_ThrowIntoLazyCoro(tstate, lazy_frame, v); - _PyFrame_StackPointerInvalidate(frame); - next_instr = frame->instr_ptr; - LOAD_SP(); - JUMP_TO_LABEL(error); - } - stack_pointer[-2] = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); - stack_pointer[-1] = PyStackRef_NULL; - stack_pointer[0] = v; - stack_pointer += 1; - JUMPBY(oparg); - DISPATCH(); - } - } - // _POP_LAZY_OUTCOME - { - assert(PyStackRef_IsNull(lazy_outcome)); - value = res; - } - stack_pointer[-2] = value; - stack_pointer += -1; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); - DISPATCH(); - } - TARGET(END_FOR) { #if _Py_TAIL_CALL_INTERP int opcode = END_FOR; @@ -7712,27 +7637,100 @@ frame->instr_ptr = next_instr; next_instr += 1; INSTRUCTION_STATS(GET_AWAITABLE); + _PyStackRef *lazy_outcome; + _PyStackRef res; + _PyStackRef value; _PyStackRef iterable; _PyStackRef iter; _PyStackRef null; _PyStackRef none; - iterable = stack_pointer[-1]; - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), oparg); - _PyFrame_StackPointerInvalidate(frame); - stack_pointer += -1; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyStackRef_CLOSE(iterable); - _PyFrame_StackPointerInvalidate(frame); - if (iter_o == NULL) { - JUMP_TO_LABEL(error); + // _LAZY_CALL_OUTCOME + { + res = stack_pointer[-1]; + lazy_outcome = &stack_pointer[-1 - ((oparg >> 2) & 1)]; + if (oparg & GET_AWAITABLE_AWAITED_CALL) { + _PyStackRef outcome = lazy_outcome[0]; + if (PyStackRef_IsTaggedInt(outcome)) { + lazy_outcome[0] = PyStackRef_NULL; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), + (int)(next_instr - _PyFrame_GetBytecode(frame))).op.code == SEND); + _PyFrame_StackPointerInvalidate(frame); + _Py_CODEUNIT *end_send = next_instr + 1 + INLINE_CACHE_ENTRIES_SEND + next_instr->op.arg; + if (end_send->op.code != END_SEND) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = monitor_stop_iteration(tstate, frame, end_send, + PyStackRef_AsPyObjectBorrow(res)); + _PyFrame_StackPointerInvalidate(frame); + if (err) { + JUMP_TO_LABEL(error); + } + } + _PyStackRef v = res; + stack_pointer[-2] = v; + stack_pointer -= 1; + next_instr = end_send + 1; + DISPATCH(); + } + else if (!PyStackRef_IsNull(outcome)) { + _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(outcome); + lazy_outcome[0] = PyStackRef_NULL; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); + _PyFrame_StackPointerInvalidate(frame); + _PyStackRef v = res; + if (gen == NULL) { + stack_pointer[-1] = PyStackRef_NULL; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + frame = _PyEval_ThrowIntoLazyCoro(tstate, lazy_frame, v); + _PyFrame_StackPointerInvalidate(frame); + next_instr = frame->instr_ptr; + LOAD_SP(); + JUMP_TO_LABEL(error); + } + stack_pointer[-2] = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + stack_pointer[-1] = PyStackRef_NULL; + stack_pointer[0] = v; + stack_pointer += 1; + next_instr += 1 + INLINE_CACHE_ENTRIES_SEND; + DISPATCH(); + } + } + } + // _POP_LAZY_OUTCOME + { + assert(!(oparg & GET_AWAITABLE_AWAITED_CALL) || + PyStackRef_IsNull(lazy_outcome[0])); + value = res; + } + // _GET_AWAITABLE + { + iterable = value; + stack_pointer[-1 - ((oparg >> 2) & 1)] = iterable; + stack_pointer += -((oparg >> 2) & 1); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), + oparg & GET_AWAITABLE_WHERE_MASK); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(iterable); + _PyFrame_StackPointerInvalidate(frame); + if (iter_o == NULL) { + JUMP_TO_LABEL(error); + } + iter = PyStackRef_FromPyObjectSteal(iter_o); + null = PyStackRef_NULL; + none = PyStackRef_None; } - iter = PyStackRef_FromPyObjectSteal(iter_o); - null = PyStackRef_NULL; - none = PyStackRef_None; stack_pointer[0] = iter; stack_pointer[1] = null; stack_pointer[2] = none; @@ -9256,7 +9254,7 @@ Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(offset == 0 ? opcode == END_AWAITED_CALL + assert(offset == 0 ? opcode == GET_AWAITABLE : (opcode == SEND || opcode == FOR_ITER)); } #endif @@ -14565,7 +14563,7 @@ Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(offset == 0 ? opcode == END_AWAITED_CALL + assert(offset == 0 ? opcode == GET_AWAITABLE : (opcode == SEND || opcode == FOR_ITER)); } #endif diff --git a/Modules/_testinternalcapi/test_targets.h b/Modules/_testinternalcapi/test_targets.h index afcb1ab06419d0..8fd141bfb7ba18 100644 --- a/Modules/_testinternalcapi/test_targets.h +++ b/Modules/_testinternalcapi/test_targets.h @@ -64,7 +64,6 @@ static void *opcode_targets_table[256] = { &&TARGET_DICT_MERGE, &&TARGET_DICT_UPDATE, &&TARGET_END_ASYNC_FOR, - &&TARGET_END_AWAITED_CALL, &&TARGET_EXTENDED_ARG, &&TARGET_FOR_ITER, &&TARGET_GET_AWAITABLE, @@ -128,6 +127,7 @@ static void *opcode_targets_table[256] = { &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, + &&_unknown_opcode, &&TARGET_RESUME, &&TARGET_BINARY_OP_ADD_FLOAT, &&TARGET_BINARY_OP_ADD_INT, @@ -376,7 +376,7 @@ static void *opcode_tracing_targets_table[256] = { &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, - &&TARGET_TRACE_RECORD, + &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, @@ -613,7 +613,6 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_DELETE_SUBSCR(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_DICT_MERGE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_DICT_UPDATE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_ASYNC_FOR(TAIL_CALL_PARAMS); -static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_AWAITED_CALL(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_FOR(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_SEND(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_ENTER_EXECUTOR(TAIL_CALL_PARAMS); @@ -863,7 +862,6 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [DICT_MERGE] = _TAIL_CALL_DICT_MERGE, [DICT_UPDATE] = _TAIL_CALL_DICT_UPDATE, [END_ASYNC_FOR] = _TAIL_CALL_END_ASYNC_FOR, - [END_AWAITED_CALL] = _TAIL_CALL_END_AWAITED_CALL, [END_FOR] = _TAIL_CALL_END_FOR, [END_SEND] = _TAIL_CALL_END_SEND, [ENTER_EXECUTOR] = _TAIL_CALL_ENTER_EXECUTOR, @@ -1019,6 +1017,7 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [UNPACK_SEQUENCE_TWO_TUPLE] = _TAIL_CALL_UNPACK_SEQUENCE_TWO_TUPLE, [WITH_EXCEPT_START] = _TAIL_CALL_WITH_EXCEPT_START, [YIELD_VALUE] = _TAIL_CALL_YIELD_VALUE, + [117] = _TAIL_CALL_UNKNOWN_OPCODE, [118] = _TAIL_CALL_UNKNOWN_OPCODE, [119] = _TAIL_CALL_UNKNOWN_OPCODE, [120] = _TAIL_CALL_UNKNOWN_OPCODE, @@ -1121,7 +1120,6 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [DICT_MERGE] = _TAIL_CALL_TRACE_RECORD, [DICT_UPDATE] = _TAIL_CALL_TRACE_RECORD, [END_ASYNC_FOR] = _TAIL_CALL_TRACE_RECORD, - [END_AWAITED_CALL] = _TAIL_CALL_TRACE_RECORD, [END_FOR] = _TAIL_CALL_TRACE_RECORD, [END_SEND] = _TAIL_CALL_TRACE_RECORD, [ENTER_EXECUTOR] = _TAIL_CALL_TRACE_RECORD, @@ -1277,6 +1275,7 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [UNPACK_SEQUENCE_TWO_TUPLE] = _TAIL_CALL_TRACE_RECORD, [WITH_EXCEPT_START] = _TAIL_CALL_TRACE_RECORD, [YIELD_VALUE] = _TAIL_CALL_TRACE_RECORD, + [117] = _TAIL_CALL_UNKNOWN_OPCODE, [118] = _TAIL_CALL_UNKNOWN_OPCODE, [119] = _TAIL_CALL_UNKNOWN_OPCODE, [120] = _TAIL_CALL_UNKNOWN_OPCODE, diff --git a/Objects/frameobject.c b/Objects/frameobject.c index c90fb14f14ae49..adbb152fe11b4b 100644 --- a/Objects/frameobject.c +++ b/Objects/frameobject.c @@ -13,6 +13,7 @@ #include "pycore_modsupport.h" // _PyArg_CheckPositional() #include "pycore_object.h" // _PyObject_GC_UNTRACK() #include "pycore_opcode_metadata.h" // _PyOpcode_Caches +#include "pycore_opcode_utils.h" // GET_AWAITABLE_AWAITED_CALL #include "pycore_optimizer.h" // _Py_Executors_InvalidateDependency() #include "pycore_tuple.h" // _PyTuple_FromPair #include "pycore_unicodeobject.h" // _PyUnicode_Equal() @@ -1453,19 +1454,27 @@ mark_stacks(PyCodeObject *code_obj, int len) stacks[j] = next_stack; stacks[next_i] = next_stack; break; - case END_AWAITED_CALL: + case GET_AWAITABLE: { - /* (lazy_outcome, res) -- res, or jump to YIELD_VALUE - * with (coroutine, NULL, res) as left by SEND */ - next_stack = pop_value(pop_value(next_stack)); - int64_t target_stack = push_value(next_stack, Object); - target_stack = push_value(target_stack, Object); - target_stack = push_value(target_stack, Object); - j = next_i + oparg; - assert(j < len); - assert(stacks[j] == UNINITIALIZED || stacks[j] == target_stack); - stacks[j] = target_stack; - stacks[next_i] = push_value(next_stack, Object); + /* (lazy_outcome, res) after an awaited call, else (res); + * pushes (iter, NULL, None). After an awaited call it may + * also jump to YIELD_VALUE with (coroutine, NULL, res), + * as left by SEND. */ + int awaited_call = oparg & GET_AWAITABLE_AWAITED_CALL; + next_stack = pop_value(next_stack); + if (awaited_call) { + next_stack = pop_value(next_stack); + } + next_stack = push_value(next_stack, Object); + next_stack = push_value(next_stack, Object); + next_stack = push_value(next_stack, Object); + if (awaited_call) { + j = next_i + 1 + INLINE_CACHE_ENTRIES_SEND; + assert(j < len); + assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack); + stacks[j] = next_stack; + } + stacks[next_i] = next_stack; break; } case JUMP_FORWARD: diff --git a/Programs/test_frozenmain.h b/Programs/test_frozenmain.h index 20201f7ec2d99e..ebcb38b18dec90 100644 --- a/Programs/test_frozenmain.h +++ b/Programs/test_frozenmain.h @@ -1,19 +1,19 @@ // Auto-generated by Programs/freeze_test_frozenmain.py unsigned char M_test_frozenmain[] = { 99,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0, - 0,0,0,0,0,115,188,0,0,0,128,0,0,0,91,0, - 78,7,70,0,113,0,91,0,78,7,70,4,113,1,90,2, - 31,0,79,1,50,1,0,0,0,0,0,0,29,0,90,2, - 31,0,79,2,90,0,77,6,0,0,0,0,0,0,0,0, + 0,0,0,0,0,115,188,0,0,0,128,0,0,0,90,0, + 77,7,69,0,112,0,90,0,77,7,69,4,112,1,89,2, + 31,0,78,1,50,1,0,0,0,0,0,0,29,0,89,2, + 31,0,78,2,89,0,76,6,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,50,2,0,0,0,0, - 0,0,29,0,90,1,77,8,0,0,0,0,0,0,0,0, + 0,0,29,0,89,1,76,8,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,31,0,50,0,0,0, - 0,0,0,0,79,3,42,26,0,0,0,0,0,0,0,0, - 0,0,113,5,79,6,68,0,0,0,66,24,0,0,113,6, - 90,2,31,0,79,4,90,6,12,0,79,5,90,5,90,6, + 0,0,0,0,78,3,42,26,0,0,0,0,0,0,0,0, + 0,0,112,5,78,6,67,0,0,0,65,24,0,0,112,6, + 89,2,31,0,78,4,89,6,12,0,78,5,89,5,89,6, 42,26,0,0,0,0,0,0,0,0,0,0,12,0,48,4, - 50,1,0,0,0,0,0,0,29,0,72,26,0,0,9,0, - 28,0,78,7,33,0,41,7,105,0,0,0,0,122,18,70, + 50,1,0,0,0,0,0,0,29,0,71,26,0,0,9,0, + 28,0,77,7,33,0,41,7,105,0,0,0,0,122,18,70, 114,111,122,101,110,32,72,101,108,108,111,32,87,111,114,108, 100,122,8,115,121,115,46,97,114,103,118,218,6,99,111,110, 102,105,103,122,7,99,111,110,102,105,103,32,122,2,58,32, diff --git a/Python/bytecodes.c b/Python/bytecodes.c index 87e0dac795bf49..9465267facb1c8 100644 --- a/Python/bytecodes.c +++ b/Python/bytecodes.c @@ -1651,8 +1651,9 @@ dummy_func( none = PyStackRef_None; } - inst(GET_AWAITABLE, (iterable -- iter, null, none)) { - PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), oparg); + op(_GET_AWAITABLE, (iterable -- iter, null, none)) { + PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), + oparg & GET_AWAITABLE_WHERE_MASK); PyStackRef_CLOSE(iterable); ERROR_IF(iter_o == NULL); iter = PyStackRef_FromPyObjectSteal(iter_o); @@ -1660,52 +1661,66 @@ dummy_func( none = PyStackRef_None; } - replaced op(_END_AWAITED_CALL, (lazy_outcome, res -- lazy_outcome, res)) { - if (PyStackRef_IsTaggedInt(lazy_outcome)) { - lazy_outcome = PyStackRef_NULL; - _Py_CODEUNIT *send = next_instr + oparg - 1 - INLINE_CACHE_ENTRIES_SEND; - assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), - (int)(send - _PyFrame_GetBytecode(frame))).op.code == SEND); - _Py_CODEUNIT *end_send = next_instr + oparg + send->op.arg; - if (end_send->op.code != END_SEND) { - // Emulate the monitoring event of INSTRUMENTED_END_SEND. - int err = monitor_stop_iteration(tstate, frame, end_send, - PyStackRef_AsPyObjectBorrow(res)); - ERROR_IF(err); + // After an awaited call, the SEND loop starts right after + // GET_AWAITABLE: SEND is at next_instr and YIELD_VALUE follows its cache. + replaced op(_LAZY_CALL_OUTCOME, (lazy_outcome[(oparg >> 2) & 1], res -- lazy_outcome[(oparg >> 2) & 1], res)) { + if (oparg & GET_AWAITABLE_AWAITED_CALL) { + _PyStackRef outcome = lazy_outcome[0]; + if (PyStackRef_IsTaggedInt(outcome)) { + lazy_outcome[0] = PyStackRef_NULL; + assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), + (int)(next_instr - _PyFrame_GetBytecode(frame))).op.code == SEND); + _Py_CODEUNIT *end_send = next_instr + 1 + INLINE_CACHE_ENTRIES_SEND + next_instr->op.arg; + if (end_send->op.code != END_SEND) { + // Emulate the monitoring event of INSTRUMENTED_END_SEND. + int err = monitor_stop_iteration(tstate, frame, end_send, + PyStackRef_AsPyObjectBorrow(res)); + ERROR_IF(err); + } + _PyStackRef v = res; + DEAD(res); + stack_pointer[-2] = v; + stack_pointer -= 1; + next_instr = end_send + 1; + DISPATCH(); } - JUMPBY(oparg + send->op.arg + 1); - } - else if (!PyStackRef_IsNull(lazy_outcome)) { - _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(lazy_outcome); - lazy_outcome = PyStackRef_NULL; - PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); - _PyStackRef v = res; - DEAD(res); - DEAD(lazy_outcome); - if (gen == NULL) { + else if (!PyStackRef_IsNull(outcome)) { + _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(outcome); + lazy_outcome[0] = PyStackRef_NULL; + PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); + _PyStackRef v = res; + DEAD(res); + if (gen == NULL) { + stack_pointer[-1] = PyStackRef_NULL; + frame = _PyEval_ThrowIntoLazyCoro(tstate, lazy_frame, v); + next_instr = frame->instr_ptr; + LOAD_SP(); + goto error; + } + stack_pointer[-2] = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); stack_pointer[-1] = PyStackRef_NULL; - frame = _PyEval_ThrowIntoLazyCoro(tstate, lazy_frame, v); - next_instr = frame->instr_ptr; - LOAD_SP(); - goto error; + stack_pointer[0] = v; + stack_pointer += 1; + next_instr += 1 + INLINE_CACHE_ENTRIES_SEND; + DISPATCH(); } - stack_pointer[-2] = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); - stack_pointer[-1] = PyStackRef_NULL; - stack_pointer[0] = v; - stack_pointer += 1; - JUMPBY(oparg); - DISPATCH(); } } - op(_POP_LAZY_OUTCOME, (lazy_outcome, res -- value)) { - assert(PyStackRef_IsNull(lazy_outcome)); + tier2 op(_GUARD_LAZY_OUTCOME_NULL, (lazy_outcome[(oparg >> 2) & 1], unused -- lazy_outcome[(oparg >> 2) & 1], unused)) { + EXIT_IF((oparg & GET_AWAITABLE_AWAITED_CALL) && + !PyStackRef_IsNull(lazy_outcome[0])); + } + + op(_POP_LAZY_OUTCOME, (lazy_outcome[(oparg >> 2) & 1], res -- value)) { + assert(!(oparg & GET_AWAITABLE_AWAITED_CALL) || + PyStackRef_IsNull(lazy_outcome[0])); DEAD(lazy_outcome); value = res; DEAD(res); } - macro(END_AWAITED_CALL) = _END_AWAITED_CALL + _POP_LAZY_OUTCOME; + macro(GET_AWAITABLE) = _LAZY_CALL_OUTCOME + _POP_LAZY_OUTCOME + _GET_AWAITABLE; family(SEND, INLINE_CACHE_ENTRIES_SEND) = { SEND_GEN, @@ -1921,7 +1936,7 @@ dummy_func( DTRACE_FUNCTION_RETURN(); int offset = 1 + INLINE_CACHE_ENTRIES_SEND; if (frame->lazy_coro == LAZY_CORO_RUNNING) { - // The caller's END_AWAITED_CALL creates the coroutine. It is + // The caller's GET_AWAITABLE creates the coroutine. It is // never instrumented, so nothing runs in between. assert(oparg == 1); frame = _PyEval_SuspendLazyCoro(tstate, frame); @@ -1946,7 +1961,7 @@ dummy_func( Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(offset == 0 ? opcode == END_AWAITED_CALL + assert(offset == 0 ? opcode == GET_AWAITABLE : (opcode == SEND || opcode == FOR_ITER)); } #endif diff --git a/Python/ceval.c b/Python/ceval.c index 5af6a3b9be8e7c..4c03667809c768 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -3715,7 +3715,7 @@ _PyEval_LoadGlobalStackRef(PyObject *globals, PyObject *builtins, PyObject *name } /* Suspend the lazy coroutine running in frame, leaving the frame and its - * exception state on the data stack for the caller's END_AWAITED_CALL. */ + * exception state on the data stack for the caller's GET_AWAITABLE. */ _PyInterpreterFrame * _PyEval_SuspendLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame) { diff --git a/Python/ceval_macros.h b/Python/ceval_macros.h index fceb20d34676c9..9cb5815d33f065 100644 --- a/Python/ceval_macros.h +++ b/Python/ceval_macros.h @@ -157,8 +157,11 @@ #endif /* Tier one only, after next_instr has skipped the call's inline cache. - * END_AWAITED_CALL is never instrumented or specialized. */ -#define IS_AWAITED_CALL() (next_instr->op.code == END_AWAITED_CALL) + * GET_AWAITABLE is never specialized, and never instrumented after an + * awaited call. */ +#define IS_AWAITED_CALL() \ + (next_instr->op.code == GET_AWAITABLE && \ + (next_instr->op.arg & GET_AWAITABLE_AWAITED_CALL)) /* The JIT recorder expects the regular path, and coroutine origin tracking * captures the origin when the object is created. */ diff --git a/Python/codegen.c b/Python/codegen.c index 160730ba090d35..f7cbc9f7fd5f62 100644 --- a/Python/codegen.c +++ b/Python/codegen.c @@ -497,8 +497,7 @@ codegen_call_exit_with_nones(compiler *c, location loc) } static int -codegen_add_yield_from_impl(compiler *c, location loc, int await, - jump_target_label yield) +codegen_add_yield_from(compiler *c, location loc, int await) { NEW_JUMP_TARGET_LABEL(c, send); NEW_JUMP_TARGET_LABEL(c, fail); @@ -509,9 +508,6 @@ codegen_add_yield_from_impl(compiler *c, location loc, int await, // Set up a virtual try/except to handle when StopIteration is raised during // a close or throw call. The only way YIELD_VALUE raises if they do! ADDOP_JUMP(c, loc, SETUP_FINALLY, fail); - if (IS_JUMP_TARGET_LABEL(yield)) { - USE_LABEL(c, yield); - } ADDOP_I(c, loc, YIELD_VALUE, 1); ADDOP(c, NO_LOCATION, POP_BLOCK); ADDOP_I(c, loc, RESUME, await ? RESUME_AFTER_AWAIT : RESUME_AFTER_YIELD_FROM); @@ -526,18 +522,10 @@ codegen_add_yield_from_impl(compiler *c, location loc, int await, } static int -codegen_add_yield_from(compiler *c, location loc, int await) -{ - return codegen_add_yield_from_impl(c, loc, await, NO_LABEL); -} - -static int -codegen_await_call_result(compiler *c, location loc, int oparg) +codegen_await_call_result(compiler *c, location loc, int where) { - NEW_JUMP_TARGET_LABEL(c, yield); - ADDOP_JUMP(c, loc, END_AWAITED_CALL, yield); - ADDOP_I(c, loc, GET_AWAITABLE, oparg); - return codegen_add_yield_from_impl(c, loc, 1, yield); + ADDOP_I(c, loc, GET_AWAITABLE, GET_AWAITABLE_AWAITED_CALL | where); + return codegen_add_yield_from(c, loc, 1); } static int diff --git a/Python/executor_cases.c.h b/Python/executor_cases.c.h index 03e395518fb253..914db8636b7408 100644 --- a/Python/executor_cases.c.h +++ b/Python/executor_cases.c.h @@ -8923,7 +8923,8 @@ ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); - PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), oparg); + PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), + oparg & GET_AWAITABLE_WHERE_MASK); _PyFrame_StackPointerInvalidate(frame); stack_pointer += -1; ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); @@ -8946,22 +8947,24 @@ break; } - /* _END_AWAITED_CALL is not a viable micro-op for tier 2 because it is replaced */ + /* _LAZY_CALL_OUTCOME is not a viable micro-op for tier 2 because it is replaced */ - case _POP_LAZY_OUTCOME_r01: { - CHECK_CURRENT_CACHED_VALUES(0); + case _GUARD_LAZY_OUTCOME_NULL_r11: { + CHECK_CURRENT_CACHED_VALUES(1); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); - _PyStackRef res; - _PyStackRef lazy_outcome; - _PyStackRef value; - res = stack_pointer[-1]; - lazy_outcome = stack_pointer[-2]; - assert(PyStackRef_IsNull(lazy_outcome)); - value = res; - _tos_cache0 = value; + _PyStackRef *lazy_outcome; + _PyStackRef _stack_item_0 = _tos_cache0; + oparg = CURRENT_OPARG(); + lazy_outcome = &stack_pointer[-((oparg >> 2) & 1)]; + if ((oparg & GET_AWAITABLE_AWAITED_CALL) && + !PyStackRef_IsNull(lazy_outcome[0])) { + UOP_STAT_INC(uopcode, miss); + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(1); + JUMP_TO_JUMP_TARGET(); + } + _tos_cache0 = _stack_item_0; SET_CURRENT_CACHED_VALUES(1); - stack_pointer += -2; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); break; } @@ -8970,59 +8973,23 @@ CHECK_CURRENT_CACHED_VALUES(1); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); _PyStackRef res; - _PyStackRef lazy_outcome; + _PyStackRef *lazy_outcome; _PyStackRef value; _PyStackRef _stack_item_0 = _tos_cache0; + oparg = CURRENT_OPARG(); res = _stack_item_0; - lazy_outcome = stack_pointer[-1]; - assert(PyStackRef_IsNull(lazy_outcome)); + lazy_outcome = &stack_pointer[-((oparg >> 2) & 1)]; + assert(!(oparg & GET_AWAITABLE_AWAITED_CALL) || + PyStackRef_IsNull(lazy_outcome[0])); value = res; _tos_cache0 = value; SET_CURRENT_CACHED_VALUES(1); - stack_pointer += -1; + stack_pointer += -((oparg >> 2) & 1); ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); break; } - case _POP_LAZY_OUTCOME_r21: { - CHECK_CURRENT_CACHED_VALUES(2); - ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); - _PyStackRef res; - _PyStackRef lazy_outcome; - _PyStackRef value; - _PyStackRef _stack_item_0 = _tos_cache0; - _PyStackRef _stack_item_1 = _tos_cache1; - res = _stack_item_1; - lazy_outcome = _stack_item_0; - assert(PyStackRef_IsNull(lazy_outcome)); - value = res; - _tos_cache0 = value; - SET_CURRENT_CACHED_VALUES(1); - ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); - break; - } - - case _POP_LAZY_OUTCOME_r32: { - CHECK_CURRENT_CACHED_VALUES(3); - ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); - _PyStackRef res; - _PyStackRef lazy_outcome; - _PyStackRef value; - _PyStackRef _stack_item_0 = _tos_cache0; - _PyStackRef _stack_item_1 = _tos_cache1; - _PyStackRef _stack_item_2 = _tos_cache2; - res = _stack_item_2; - lazy_outcome = _stack_item_1; - assert(PyStackRef_IsNull(lazy_outcome)); - value = res; - _tos_cache1 = value; - _tos_cache0 = _stack_item_0; - SET_CURRENT_CACHED_VALUES(2); - ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); - break; - } - case _SEND_GEN_FRAME_r33: { CHECK_CURRENT_CACHED_VALUES(3); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); @@ -9684,7 +9651,7 @@ Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(offset == 0 ? opcode == END_AWAITED_CALL + assert(offset == 0 ? opcode == GET_AWAITABLE : (opcode == SEND || opcode == FOR_ITER)); } #endif diff --git a/Python/flowgraph.c b/Python/flowgraph.c index 955069dd391a72..fc676dc6feb167 100644 --- a/Python/flowgraph.c +++ b/Python/flowgraph.c @@ -798,13 +798,6 @@ get_stack_effects(int opcode, int oparg, int jump, stack_effects *effects) effects->net = 0; return 0; } - if (opcode == END_AWAITED_CALL && jump) { - // When the body suspends, the jump to YIELD_VALUE replaces - // (lazy_outcome, value) with (coroutine, NULL, value), where value - // is what the body yielded. - effects->net = 1; - return 0; - } effects->net = pushed - popped; return 0; } @@ -953,11 +946,7 @@ label_exception_targets(basicblock *entryblock) { else if (is_jump(instr)) { instr->i_except = handler; assert(i == b->b_iused -1); - // END_AWAITED_CALL's target is inside the SETUP_FINALLY - // that follows SEND. - if (!instr->i_target->b_visited && - instr->i_opcode != END_AWAITED_CALL) - { + if (!instr->i_target->b_visited) { if (BB_HAS_FALLTHROUGH(b)) { struct _PyCfgExceptStack *copy = copy_except_stack(except_stack); if (copy == NULL) { @@ -3128,14 +3117,6 @@ optimize_load_fast(cfg_builder *g) break; } - case END_AWAITED_CALL: { - load_fast_push_block(&sp, instr->i_target, refs.size + 1); - ref_stack_pop(&refs); - ref_stack_pop(&refs); - PUSH_REF(i, NOT_LOCAL); - break; - } - case SEND: { load_fast_push_block(&sp, instr->i_target, refs.size); ref_stack_pop(&refs); diff --git a/Python/generated_cases.c.h b/Python/generated_cases.c.h index e489bb08907e00..c53e52f969f0a5 100644 --- a/Python/generated_cases.c.h +++ b/Python/generated_cases.c.h @@ -6928,81 +6928,6 @@ DISPATCH(); } - TARGET(END_AWAITED_CALL) { - #if _Py_TAIL_CALL_INTERP - int opcode = END_AWAITED_CALL; - (void)(opcode); - #endif - frame->instr_ptr = next_instr; - next_instr += 1; - INSTRUCTION_STATS(END_AWAITED_CALL); - _PyStackRef lazy_outcome; - _PyStackRef res; - _PyStackRef value; - // _END_AWAITED_CALL - { - res = stack_pointer[-1]; - lazy_outcome = stack_pointer[-2]; - if (PyStackRef_IsTaggedInt(lazy_outcome)) { - lazy_outcome = PyStackRef_NULL; - _Py_CODEUNIT *send = next_instr + oparg - 1 - INLINE_CACHE_ENTRIES_SEND; - stack_pointer[-2] = lazy_outcome; - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), - (int)(send - _PyFrame_GetBytecode(frame))).op.code == SEND); - _PyFrame_StackPointerInvalidate(frame); - _Py_CODEUNIT *end_send = next_instr + oparg + send->op.arg; - if (end_send->op.code != END_SEND) { - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - int err = monitor_stop_iteration(tstate, frame, end_send, - PyStackRef_AsPyObjectBorrow(res)); - _PyFrame_StackPointerInvalidate(frame); - if (err) { - JUMP_TO_LABEL(error); - } - } - JUMPBY(oparg + send->op.arg + 1); - } - else if (!PyStackRef_IsNull(lazy_outcome)) { - _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(lazy_outcome); - lazy_outcome = PyStackRef_NULL; - stack_pointer[-2] = lazy_outcome; - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); - _PyFrame_StackPointerInvalidate(frame); - _PyStackRef v = res; - if (gen == NULL) { - stack_pointer[-1] = PyStackRef_NULL; - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - frame = _PyEval_ThrowIntoLazyCoro(tstate, lazy_frame, v); - _PyFrame_StackPointerInvalidate(frame); - next_instr = frame->instr_ptr; - LOAD_SP(); - JUMP_TO_LABEL(error); - } - stack_pointer[-2] = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); - stack_pointer[-1] = PyStackRef_NULL; - stack_pointer[0] = v; - stack_pointer += 1; - JUMPBY(oparg); - DISPATCH(); - } - } - // _POP_LAZY_OUTCOME - { - assert(PyStackRef_IsNull(lazy_outcome)); - value = res; - } - stack_pointer[-2] = value; - stack_pointer += -1; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); - DISPATCH(); - } - TARGET(END_FOR) { #if _Py_TAIL_CALL_INTERP int opcode = END_FOR; @@ -7712,27 +7637,100 @@ frame->instr_ptr = next_instr; next_instr += 1; INSTRUCTION_STATS(GET_AWAITABLE); + _PyStackRef *lazy_outcome; + _PyStackRef res; + _PyStackRef value; _PyStackRef iterable; _PyStackRef iter; _PyStackRef null; _PyStackRef none; - iterable = stack_pointer[-1]; - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), oparg); - _PyFrame_StackPointerInvalidate(frame); - stack_pointer += -1; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyStackRef_CLOSE(iterable); - _PyFrame_StackPointerInvalidate(frame); - if (iter_o == NULL) { - JUMP_TO_LABEL(error); + // _LAZY_CALL_OUTCOME + { + res = stack_pointer[-1]; + lazy_outcome = &stack_pointer[-1 - ((oparg >> 2) & 1)]; + if (oparg & GET_AWAITABLE_AWAITED_CALL) { + _PyStackRef outcome = lazy_outcome[0]; + if (PyStackRef_IsTaggedInt(outcome)) { + lazy_outcome[0] = PyStackRef_NULL; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), + (int)(next_instr - _PyFrame_GetBytecode(frame))).op.code == SEND); + _PyFrame_StackPointerInvalidate(frame); + _Py_CODEUNIT *end_send = next_instr + 1 + INLINE_CACHE_ENTRIES_SEND + next_instr->op.arg; + if (end_send->op.code != END_SEND) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = monitor_stop_iteration(tstate, frame, end_send, + PyStackRef_AsPyObjectBorrow(res)); + _PyFrame_StackPointerInvalidate(frame); + if (err) { + JUMP_TO_LABEL(error); + } + } + _PyStackRef v = res; + stack_pointer[-2] = v; + stack_pointer -= 1; + next_instr = end_send + 1; + DISPATCH(); + } + else if (!PyStackRef_IsNull(outcome)) { + _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(outcome); + lazy_outcome[0] = PyStackRef_NULL; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); + _PyFrame_StackPointerInvalidate(frame); + _PyStackRef v = res; + if (gen == NULL) { + stack_pointer[-1] = PyStackRef_NULL; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + frame = _PyEval_ThrowIntoLazyCoro(tstate, lazy_frame, v); + _PyFrame_StackPointerInvalidate(frame); + next_instr = frame->instr_ptr; + LOAD_SP(); + JUMP_TO_LABEL(error); + } + stack_pointer[-2] = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + stack_pointer[-1] = PyStackRef_NULL; + stack_pointer[0] = v; + stack_pointer += 1; + next_instr += 1 + INLINE_CACHE_ENTRIES_SEND; + DISPATCH(); + } + } + } + // _POP_LAZY_OUTCOME + { + assert(!(oparg & GET_AWAITABLE_AWAITED_CALL) || + PyStackRef_IsNull(lazy_outcome[0])); + value = res; + } + // _GET_AWAITABLE + { + iterable = value; + stack_pointer[-1 - ((oparg >> 2) & 1)] = iterable; + stack_pointer += -((oparg >> 2) & 1); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), + oparg & GET_AWAITABLE_WHERE_MASK); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(iterable); + _PyFrame_StackPointerInvalidate(frame); + if (iter_o == NULL) { + JUMP_TO_LABEL(error); + } + iter = PyStackRef_FromPyObjectSteal(iter_o); + null = PyStackRef_NULL; + none = PyStackRef_None; } - iter = PyStackRef_FromPyObjectSteal(iter_o); - null = PyStackRef_NULL; - none = PyStackRef_None; stack_pointer[0] = iter; stack_pointer[1] = null; stack_pointer[2] = none; @@ -9255,7 +9253,7 @@ Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(offset == 0 ? opcode == END_AWAITED_CALL + assert(offset == 0 ? opcode == GET_AWAITABLE : (opcode == SEND || opcode == FOR_ITER)); } #endif @@ -14562,7 +14560,7 @@ Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(offset == 0 ? opcode == END_AWAITED_CALL + assert(offset == 0 ? opcode == GET_AWAITABLE : (opcode == SEND || opcode == FOR_ITER)); } #endif diff --git a/Python/instrumentation.c b/Python/instrumentation.c index bdf09945df2bda..5760f4b865d4b4 100644 --- a/Python/instrumentation.c +++ b/Python/instrumentation.c @@ -191,6 +191,16 @@ _PyCode_Deinstrument(uint8_t opcode) return DE_INSTRUMENT[opcode]; } +/* GET_AWAITABLE after an awaited call is never instrumented, + * see IS_AWAITED_CALL(). */ +static inline bool +is_awaited_call_get_awaitable(PyCodeObject *code, int i) +{ + _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(code, i); + return inst.op.code == GET_AWAITABLE && + (inst.op.arg & GET_AWAITABLE_AWAITED_CALL); +} + static inline bool is_instrumented(int opcode) { @@ -574,7 +584,7 @@ sanity_check_instrumentation(PyCodeObject *code) opcode = _PyCode_GetOriginalOpcode(data->lines, i); CHECK(valid_opcode(opcode)); CHECK(opcode != END_FOR); - CHECK(opcode != END_AWAITED_CALL); + CHECK(!is_awaited_call_get_awaitable(code, i)); CHECK(opcode != RESUME); CHECK(opcode != RESUME_CHECK); CHECK(opcode != RESUME_CHECK_JIT); @@ -1580,14 +1590,18 @@ initialize_lines(_PyCoLineInstrumentationData *line_data, PyCodeObject *code, in * RESUME and POP_ITER must not be instrumented with INSTRUMENTED_LINE */ set_original_opcode(line_data, i, 0); break; - case END_AWAITED_CALL: - /* END_AWAITED_CALL must not be instrumented with INSTRUMENTED_LINE, - * as no events may fire before it handles a lazy coroutine. - * It has the location of the await, which starts a line - * after the call, so it keeps the line of the call. */ - set_line_delta(line_data, i, compute_line_delta(code, current_line)); - set_original_opcode(line_data, i, 0); - break; + case GET_AWAITABLE: + if (is_awaited_call_get_awaitable(code, i)) { + /* GET_AWAITABLE after an awaited call must not be + * instrumented with INSTRUMENTED_LINE, as no events may + * fire before it handles a lazy coroutine. + * It has the location of the await, which starts a line + * after the call, so it keeps the line of the call. */ + set_line_delta(line_data, i, compute_line_delta(code, current_line)); + set_original_opcode(line_data, i, 0); + break; + } + _Py_FALLTHROUGH; default: /* Set original_opcode to the opcode iff the instruction * starts a line, and thus should be instrumented. @@ -1647,10 +1661,13 @@ initialize_lines(_PyCoLineInstrumentationData *line_data, PyCodeObject *code, in target = i - oparg; break; } - case END_AWAITED_CALL: + case GET_AWAITABLE: { + if (!(oparg & GET_AWAITABLE_AWAITED_CALL)) { + continue; + } /* To YIELD_VALUE; the jump past END_SEND lands on SEND's target */ - target = i + oparg; + target = i + 1 + INLINE_CACHE_ENTRIES_SEND; break; } default: @@ -1659,7 +1676,7 @@ initialize_lines(_PyCoLineInstrumentationData *line_data, PyCodeObject *code, in assert(target >= 0); if (get_line_delta(line_data, target) != NO_LINE) { int opcode = _Py_GetBaseCodeUnit(code, target).op.code; - if (opcode != POP_ITER && opcode != END_AWAITED_CALL) { + if (opcode != POP_ITER) { set_original_opcode(line_data, target, opcode); } } @@ -1916,7 +1933,9 @@ force_instrument_lock_held(PyCodeObject *code, PyInterpreterState *interp) if (removed_per_instruction_tools) { for (int i = code->_co_firsttraceable; i < code_len;) { int opcode = _Py_GetBaseCodeUnit(code, i).op.code; - if (opcode == RESUME || opcode == END_FOR || opcode == END_AWAITED_CALL) { + if (opcode == RESUME || opcode == END_FOR || + is_awaited_call_get_awaitable(code, i)) + { i += _PyInstruction_GetLength(code, i); continue; } @@ -1943,7 +1962,9 @@ force_instrument_lock_held(PyCodeObject *code, PyInterpreterState *interp) if (new_per_instruction_tools) { for (int i = code->_co_firsttraceable; i < code_len;) { int opcode = _Py_GetBaseCodeUnit(code, i).op.code; - if (opcode == RESUME || opcode == END_FOR || opcode == END_AWAITED_CALL) { + if (opcode == RESUME || opcode == END_FOR || + is_awaited_call_get_awaitable(code, i)) + { i += _PyInstruction_GetLength(code, i); continue; } diff --git a/Python/opcode_targets.h b/Python/opcode_targets.h index afcb1ab06419d0..8fd141bfb7ba18 100644 --- a/Python/opcode_targets.h +++ b/Python/opcode_targets.h @@ -64,7 +64,6 @@ static void *opcode_targets_table[256] = { &&TARGET_DICT_MERGE, &&TARGET_DICT_UPDATE, &&TARGET_END_ASYNC_FOR, - &&TARGET_END_AWAITED_CALL, &&TARGET_EXTENDED_ARG, &&TARGET_FOR_ITER, &&TARGET_GET_AWAITABLE, @@ -128,6 +127,7 @@ static void *opcode_targets_table[256] = { &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, + &&_unknown_opcode, &&TARGET_RESUME, &&TARGET_BINARY_OP_ADD_FLOAT, &&TARGET_BINARY_OP_ADD_INT, @@ -376,7 +376,7 @@ static void *opcode_tracing_targets_table[256] = { &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, - &&TARGET_TRACE_RECORD, + &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, @@ -613,7 +613,6 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_DELETE_SUBSCR(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_DICT_MERGE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_DICT_UPDATE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_ASYNC_FOR(TAIL_CALL_PARAMS); -static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_AWAITED_CALL(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_FOR(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_END_SEND(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_ENTER_EXECUTOR(TAIL_CALL_PARAMS); @@ -863,7 +862,6 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [DICT_MERGE] = _TAIL_CALL_DICT_MERGE, [DICT_UPDATE] = _TAIL_CALL_DICT_UPDATE, [END_ASYNC_FOR] = _TAIL_CALL_END_ASYNC_FOR, - [END_AWAITED_CALL] = _TAIL_CALL_END_AWAITED_CALL, [END_FOR] = _TAIL_CALL_END_FOR, [END_SEND] = _TAIL_CALL_END_SEND, [ENTER_EXECUTOR] = _TAIL_CALL_ENTER_EXECUTOR, @@ -1019,6 +1017,7 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [UNPACK_SEQUENCE_TWO_TUPLE] = _TAIL_CALL_UNPACK_SEQUENCE_TWO_TUPLE, [WITH_EXCEPT_START] = _TAIL_CALL_WITH_EXCEPT_START, [YIELD_VALUE] = _TAIL_CALL_YIELD_VALUE, + [117] = _TAIL_CALL_UNKNOWN_OPCODE, [118] = _TAIL_CALL_UNKNOWN_OPCODE, [119] = _TAIL_CALL_UNKNOWN_OPCODE, [120] = _TAIL_CALL_UNKNOWN_OPCODE, @@ -1121,7 +1120,6 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [DICT_MERGE] = _TAIL_CALL_TRACE_RECORD, [DICT_UPDATE] = _TAIL_CALL_TRACE_RECORD, [END_ASYNC_FOR] = _TAIL_CALL_TRACE_RECORD, - [END_AWAITED_CALL] = _TAIL_CALL_TRACE_RECORD, [END_FOR] = _TAIL_CALL_TRACE_RECORD, [END_SEND] = _TAIL_CALL_TRACE_RECORD, [ENTER_EXECUTOR] = _TAIL_CALL_TRACE_RECORD, @@ -1277,6 +1275,7 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [UNPACK_SEQUENCE_TWO_TUPLE] = _TAIL_CALL_TRACE_RECORD, [WITH_EXCEPT_START] = _TAIL_CALL_TRACE_RECORD, [YIELD_VALUE] = _TAIL_CALL_TRACE_RECORD, + [117] = _TAIL_CALL_UNKNOWN_OPCODE, [118] = _TAIL_CALL_UNKNOWN_OPCODE, [119] = _TAIL_CALL_UNKNOWN_OPCODE, [120] = _TAIL_CALL_UNKNOWN_OPCODE, diff --git a/Python/optimizer.c b/Python/optimizer.c index 0a1a2c8afc75a4..219c3893163b13 100644 --- a/Python/optimizer.c +++ b/Python/optimizer.c @@ -502,7 +502,7 @@ _PyUOp_Replacements[MAX_UOP_ID + 1] = { [_LOAD_BYTECODE] = _NOP, [_SEND_VIRTUAL] = _SEND_VIRTUAL_TIER_TWO, [_SEND_ASYNC_GEN] = _SEND_ASYNC_GEN_TIER_TWO, - [_END_AWAITED_CALL] = _GUARD_NOS_NULL, + [_LAZY_CALL_OUTCOME] = _GUARD_LAZY_OUTCOME_NULL, [_MAYBE_LAZY_CORO] = _NOP, [_START_LAZY_CORO] = _NOP, [_CHECK_LAZY_CORO] = _GUARD_NOT_LAZY_CORO, @@ -735,9 +735,9 @@ _PyJit_translate_single_bytecode_to_trace( } // Strange control-flow - // Tier two only runs END_AWAITED_CALL's fall-through. + // Tier two only runs GET_AWAITABLE's fall-through. bool has_dynamic_jump_taken = - (OPCODE_HAS_UNPREDICTABLE_JUMP(opcode) || opcode == END_AWAITED_CALL) && + (OPCODE_HAS_UNPREDICTABLE_JUMP(opcode) || opcode == GET_AWAITABLE) && (next_instr != this_instr + 1 + _PyOpcode_Caches[_PyOpcode_Deopt[opcode]]); /* Special case the first instruction, @@ -972,7 +972,7 @@ _PyJit_translate_single_bytecode_to_trace( target = next_inst; } } - else if (uop == _GUARD_NOS_NULL || + else if (uop == _GUARD_LAZY_OUTCOME_NULL || uop == _NOP || uop == _GUARD_NOT_LAZY_CORO) { // These don't jump. } @@ -1146,9 +1146,9 @@ _PyJit_TryInitializeTracing( if (oparg > 0xFFFF) { return 0; } - // IS_AWAITED_CALL() needs END_AWAITED_CALL in the bytecode, so no + // IS_AWAITED_CALL() needs GET_AWAITABLE in the bytecode, so no // ENTER_EXECUTOR may replace it. - if (start_instr->op.code == END_AWAITED_CALL) { + if (start_instr->op.code == GET_AWAITABLE) { return 0; } PyObject *func = PyStackRef_AsPyObjectBorrow(frame->f_funcobj); diff --git a/Python/optimizer_cases.c.h b/Python/optimizer_cases.c.h index 1c2d2d194740d3..005779c0d2de1c 100644 --- a/Python/optimizer_cases.c.h +++ b/Python/optimizer_cases.c.h @@ -1908,14 +1908,18 @@ break; } - /* _END_AWAITED_CALL is not a viable micro-op for tier 2 */ + /* _LAZY_CALL_OUTCOME is not a viable micro-op for tier 2 */ + + case _GUARD_LAZY_OUTCOME_NULL: { + break; + } case _POP_LAZY_OUTCOME: { JitOptRef value; value = sym_new_not_null(ctx); - CHECK_STACK_BOUNDS(-1); - stack_pointer[-2] = value; - stack_pointer += -1; + CHECK_STACK_BOUNDS(-((oparg >> 2) & 1)); + stack_pointer[-1 - ((oparg >> 2) & 1)] = value; + stack_pointer += -((oparg >> 2) & 1); ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); break; } diff --git a/Python/specialize.c b/Python/specialize.c index fb3c483d2d31d4..5e0e29ade1ddf2 100644 --- a/Python/specialize.c +++ b/Python/specialize.c @@ -1755,7 +1755,9 @@ static bool is_awaited_coroutine_call(_Py_CODEUNIT *instr, int cache_entries, PyCodeObject *code) { - return (instr[1 + cache_entries].op.code == END_AWAITED_CALL && + _Py_CODEUNIT next = instr[1 + cache_entries]; + return (next.op.code == GET_AWAITABLE && + (next.op.arg & GET_AWAITABLE_AWAITED_CALL) && (code->co_flags & CO_COROUTINE)); } From 3bc30dd176ce89fef324baaa6987138226b1991c Mon Sep 17 00:00:00 2001 From: Andrew Svetlov Date: Mon, 23 Nov 2026 10:03:57 +0100 Subject: [PATCH 06/10] Read the lazy outcome at a fixed stack offset Indexing the slot through lazy_outcome[(oparg >> 2) & 1] made its load wait for oparg, which slowed down awaits that suspend. Co-Authored-By: Claude Opus 5.5 --- Modules/_testinternalcapi/test_cases.c.h | 8 +++++--- Python/bytecodes.c | 10 +++++++--- Python/generated_cases.c.h | 8 +++++--- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/Modules/_testinternalcapi/test_cases.c.h b/Modules/_testinternalcapi/test_cases.c.h index 183e937955c1b0..6de6788c23f516 100644 --- a/Modules/_testinternalcapi/test_cases.c.h +++ b/Modules/_testinternalcapi/test_cases.c.h @@ -7649,9 +7649,11 @@ res = stack_pointer[-1]; lazy_outcome = &stack_pointer[-1 - ((oparg >> 2) & 1)]; if (oparg & GET_AWAITABLE_AWAITED_CALL) { - _PyStackRef outcome = lazy_outcome[0]; + _PyStackRef *slot = &stack_pointer[-2]; + assert(slot == lazy_outcome); + _PyStackRef outcome = *slot; if (PyStackRef_IsTaggedInt(outcome)) { - lazy_outcome[0] = PyStackRef_NULL; + *slot = PyStackRef_NULL; _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), @@ -7676,7 +7678,7 @@ } else if (!PyStackRef_IsNull(outcome)) { _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(outcome); - lazy_outcome[0] = PyStackRef_NULL; + *slot = PyStackRef_NULL; _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); diff --git a/Python/bytecodes.c b/Python/bytecodes.c index 9465267facb1c8..621c2c9ba8dda4 100644 --- a/Python/bytecodes.c +++ b/Python/bytecodes.c @@ -1665,9 +1665,13 @@ dummy_func( // GET_AWAITABLE: SEND is at next_instr and YIELD_VALUE follows its cache. replaced op(_LAZY_CALL_OUTCOME, (lazy_outcome[(oparg >> 2) & 1], res -- lazy_outcome[(oparg >> 2) & 1], res)) { if (oparg & GET_AWAITABLE_AWAITED_CALL) { - _PyStackRef outcome = lazy_outcome[0]; + // The slot is at a fixed offset here: reading it through + // lazy_outcome would make the load wait for oparg. + _PyStackRef *slot = &stack_pointer[-2]; + assert(slot == lazy_outcome); + _PyStackRef outcome = *slot; if (PyStackRef_IsTaggedInt(outcome)) { - lazy_outcome[0] = PyStackRef_NULL; + *slot = PyStackRef_NULL; assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)(next_instr - _PyFrame_GetBytecode(frame))).op.code == SEND); _Py_CODEUNIT *end_send = next_instr + 1 + INLINE_CACHE_ENTRIES_SEND + next_instr->op.arg; @@ -1686,7 +1690,7 @@ dummy_func( } else if (!PyStackRef_IsNull(outcome)) { _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(outcome); - lazy_outcome[0] = PyStackRef_NULL; + *slot = PyStackRef_NULL; PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); _PyStackRef v = res; DEAD(res); diff --git a/Python/generated_cases.c.h b/Python/generated_cases.c.h index c53e52f969f0a5..205b115a7b718f 100644 --- a/Python/generated_cases.c.h +++ b/Python/generated_cases.c.h @@ -7649,9 +7649,11 @@ res = stack_pointer[-1]; lazy_outcome = &stack_pointer[-1 - ((oparg >> 2) & 1)]; if (oparg & GET_AWAITABLE_AWAITED_CALL) { - _PyStackRef outcome = lazy_outcome[0]; + _PyStackRef *slot = &stack_pointer[-2]; + assert(slot == lazy_outcome); + _PyStackRef outcome = *slot; if (PyStackRef_IsTaggedInt(outcome)) { - lazy_outcome[0] = PyStackRef_NULL; + *slot = PyStackRef_NULL; _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), @@ -7676,7 +7678,7 @@ } else if (!PyStackRef_IsNull(outcome)) { _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(outcome); - lazy_outcome[0] = PyStackRef_NULL; + *slot = PyStackRef_NULL; _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); From 51a686bae6fc1723218f84c0ea37f13e81343523 Mon Sep 17 00:00:00 2001 From: Andrew Svetlov Date: Tue, 24 Nov 2026 16:49:46 +0100 Subject: [PATCH 07/10] Fix crashes found in review of lazy coroutines * Don't let f_lineno jumps land on the awaited-call GET_AWAITABLE. * Don't make YIELD_VALUE a line start; emit the await line's LINE event from GET_AWAITABLE after materializing, so a raising callback is not handled as a throw into the awaited coroutine. * Never line-instrument the awaited-call GET_AWAITABLE as a jump target. * Allow the lazy coroutine's exception state to start a new data stack chunk. * Skip LLTRACE_RESUME_FRAME on a lazy suspension. * Publish the materialized coroutine's frame state after re-pointing its frame object. Co-Authored-By: Claude Opus 5.5 --- Lib/test/test_coroutines.py | 104 +++++++++++++++++++++++ Modules/_testinternalcapi/test_cases.c.h | 28 +++++- Objects/frameobject.c | 11 ++- Python/bytecodes.c | 23 ++++- Python/ceval.c | 8 +- Python/executor_cases.c.h | 4 +- Python/generated_cases.c.h | 28 +++++- Python/instrumentation.c | 13 +-- 8 files changed, 200 insertions(+), 19 deletions(-) diff --git a/Lib/test/test_coroutines.py b/Lib/test/test_coroutines.py index 6b5aa366743340..c07418d9bfe5eb 100644 --- a/Lib/test/test_coroutines.py +++ b/Lib/test/test_coroutines.py @@ -3535,6 +3535,110 @@ async def outer(events): sys.monitoring.set_events(tool, 0) sys.monitoring.free_tool_id(tool) + def test_lazy_with_line_events_at_awaited_call_jump_target(self): + # The list(genexpr) fast path jumps to GET_AWAITABLE, which must + # not get INSTRUMENTED_LINE. + async def list(arg): + return sys._getframe().f_generator is None + + async def outer(): + return await list(i for i in range(3)) + + mon = sys.monitoring + tool = mon.DEBUGGER_ID + self.assertEqual(run_async(outer()), ([], True)) + mon.use_tool_id(tool, "test") + try: + mon.register_callback(tool, mon.events.LINE, lambda *args: None) + mon.set_events(tool, mon.events.LINE) + self.assertEqual(run_async(outer()), ([], True)) + finally: + mon.set_events(tool, 0) + mon.register_callback(tool, mon.events.LINE, None) + mon.free_tool_id(tool) + self.assertEqual(run_async(outer()), ([], True)) + + def test_line_event_raises_after_suspension(self): + async def inner(): + await AsyncYield("suspended") + return "done" + + async def outer(): + x = (await + inner()) + return x + + def line(code, lineno): + if code is outer.__code__ and lineno == code.co_firstlineno + 1: + raise ValueError("line") + + mon = sys.monitoring + tool = mon.DEBUGGER_ID + mon.use_tool_id(tool, "test") + try: + mon.register_callback(tool, mon.events.LINE, line) + mon.set_events(tool, mon.events.LINE) + with self.assertRaisesRegex(ValueError, "line"): + run_async(outer()) + finally: + mon.set_events(tool, 0) + mon.register_callback(tool, mon.events.LINE, None) + mon.free_tool_id(tool) + + def test_set_lineno_to_multiline_await(self): + # The await line must not start at GET_AWAITABLE, whose lazy + # outcome slot cannot hold an arbitrary object. + async def inner(): + return "done" + + async def outer(): + a = b = [1] + t = (a, b, + a) + x = (await + inner()) + return x + + first = outer.__code__.co_firstlineno + errors = [] + def tracer(frame, event, arg): + if (event == "line" and frame.f_code is outer.__code__ + and frame.f_lineno == first + 3): + try: + frame.f_lineno = first + 4 + except ValueError as e: + errors.append(str(e)) + return tracer + + old_trace = sys.gettrace() + sys.settrace(tracer) + try: + self.assertEqual(run_async(outer()), ([], "done")) + finally: + sys.settrace(old_trace) + self.assertEqual(len(errors), 1) + self.assertIn("incompatible stacks", errors[0]) + + def test_exc_state_at_data_stack_chunk_end(self): + # The body's exception state may start a new data stack chunk. + async def rec(n): + if n == 0: + await AsyncYield(None) + return 0 + return await rec(n - 1) + 1 + + def padded(k): + ns = {} + names = "=".join(f"a{i}" for i in range(k)) + body = f" {names} = None\n" if k else "" + exec(f"def f(fn):\n{body} return fn()\n", ns) + return ns["f"] + + # Shift the frames by one slot at a time. + for k in range(32): + self.assertEqual(padded(k)(lambda: run_async(rec(200))), + ([None], 200)) + @support.cpython_only @unittest.skipIf(_testcapi is None, "requires _testcapi") diff --git a/Modules/_testinternalcapi/test_cases.c.h b/Modules/_testinternalcapi/test_cases.c.h index 6de6788c23f516..ccc2a2fbcb6544 100644 --- a/Modules/_testinternalcapi/test_cases.c.h +++ b/Modules/_testinternalcapi/test_cases.c.h @@ -7634,6 +7634,8 @@ int opcode = GET_AWAITABLE; (void)(opcode); #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; frame->instr_ptr = next_instr; next_instr += 1; INSTRUCTION_STATS(GET_AWAITABLE); @@ -7698,7 +7700,25 @@ stack_pointer[-1] = PyStackRef_NULL; stack_pointer[0] = v; stack_pointer += 1; + _Py_CODEUNIT *send = next_instr; next_instr += 1 + INLINE_CACHE_ENTRIES_SEND; + if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { + frame->instr_ptr = send; + SAVE_SP(); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int original_opcode = _Py_call_instrumentation_line( + tstate, frame, send, this_instr); + _PyFrame_StackPointerInvalidate(frame); + LOAD_SP(); + if (original_opcode < 0) { + next_instr = send + 1; + JUMP_TO_LABEL(error); + } + if (frame->instr_ptr != send) { + next_instr = frame->instr_ptr; + } + } DISPATCH(); } } @@ -9264,7 +9284,9 @@ _PyFrame_StackPointerInvalidate(frame); LOAD_IP(offset); value = temp; - LLTRACE_RESUME_FRAME(); + if (offset != 0) { + LLTRACE_RESUME_FRAME(); + } } stack_pointer[0] = value; stack_pointer += 1; @@ -14573,7 +14595,9 @@ _PyFrame_StackPointerInvalidate(frame); LOAD_IP(offset); value = temp; - LLTRACE_RESUME_FRAME(); + if (offset != 0) { + LLTRACE_RESUME_FRAME(); + } } stack_pointer[0] = value; stack_pointer += 1; diff --git a/Objects/frameobject.c b/Objects/frameobject.c index adbb152fe11b4b..eb1c28af96d131 100644 --- a/Objects/frameobject.c +++ b/Objects/frameobject.c @@ -1697,7 +1697,16 @@ marklines(PyCodeObject *code, int len) while (_PyLineTable_NextAddressRange(&bounds)) { assert(bounds.ar_start / (int)sizeof(_Py_CODEUNIT) < len); if (bounds.ar_line != last_line && bounds.ar_line != -1) { - linestarts[bounds.ar_start / sizeof(_Py_CODEUNIT)] = bounds.ar_line; + int i = bounds.ar_start / (int)sizeof(_Py_CODEUNIT); + _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(code, i); + if (inst.op.code == GET_AWAITABLE && + (inst.op.arg & GET_AWAITABLE_AWAITED_CALL)) + { + /* Its lazy outcome slot must hold NULL or an outcome, + * so jump to the SEND that follows it instead. */ + i++; + } + linestarts[i] = bounds.ar_line; last_line = bounds.ar_line; } } diff --git a/Python/bytecodes.c b/Python/bytecodes.c index 621c2c9ba8dda4..e7b08163835eb1 100644 --- a/Python/bytecodes.c +++ b/Python/bytecodes.c @@ -1705,7 +1705,24 @@ dummy_func( stack_pointer[-1] = PyStackRef_NULL; stack_pointer[0] = v; stack_pointer += 1; + _Py_CODEUNIT *send = next_instr; next_instr += 1 + INLINE_CACHE_ENTRIES_SEND; + if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { + // Emit the LINE event of the skipped SEND here, as + // the handler around YIELD_VALUE expects only throws. + frame->instr_ptr = send; + SAVE_SP(); + int original_opcode = _Py_call_instrumentation_line( + tstate, frame, send, this_instr); + LOAD_SP(); + if (original_opcode < 0) { + next_instr = send + 1; + goto error; + } + if (frame->instr_ptr != send) { + next_instr = frame->instr_ptr; + } + } DISPATCH(); } } @@ -1972,7 +1989,11 @@ dummy_func( RELOAD_STACK(); LOAD_IP(offset); value = temp; - LLTRACE_RESUME_FRAME(); + // After a lazy suspension, the caller's lazy outcome slot holds a + // frame pointer, which nothing may see before GET_AWAITABLE runs. + if (offset != 0) { + LLTRACE_RESUME_FRAME(); + } } macro(YIELD_VALUE) = diff --git a/Python/ceval.c b/Python/ceval.c index 4c03667809c768..09bae7f7ecfa40 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -3745,8 +3745,10 @@ _PyEval_MaterializeLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame) _PyErr_StackItem *exc_info = (_PyErr_StackItem *)(tstate->datastack_top - item_slots); assert(exc_info->previous_item == NULL); + // Right after the frame, unless it starts a new data stack chunk. assert((PyObject **)frame + _PyFrame_GetCode(frame)->co_framesize == - (PyObject **)exc_info); + (PyObject **)exc_info || + (PyObject **)exc_info == &tstate->datastack_chunk->data[0]); PyGenObject *gen = (PyGenObject *)_PyCoro_MaterializeLazy(frame); if (gen == NULL) { return NULL; @@ -3756,13 +3758,15 @@ _PyEval_MaterializeLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame) _PyInterpreterFrame *gen_frame = &gen->gi_iframe; _PyFrame_Copy(frame, gen_frame); gen_frame->owner = FRAME_OWNED_BY_GENERATOR; - FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED_YIELD_FROM); PyFrameObject *f = gen_frame->frame_obj; if (f != NULL) { Py_BEGIN_CRITICAL_SECTION(f); f->f_frame = gen_frame; Py_END_CRITICAL_SECTION(); } + // Publish the frame only once the frame object points to it, as the + // critical section may let the GC run. + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED_YIELD_FROM); _PyThreadState_PopFrame(tstate, frame); return gen; } diff --git a/Python/executor_cases.c.h b/Python/executor_cases.c.h index 914db8636b7408..f68af6cea16504 100644 --- a/Python/executor_cases.c.h +++ b/Python/executor_cases.c.h @@ -9659,7 +9659,9 @@ _PyFrame_StackPointerInvalidate(frame); LOAD_IP(offset); value = temp; - LLTRACE_RESUME_FRAME(); + if (offset != 0) { + LLTRACE_RESUME_FRAME(); + } _tos_cache0 = value; _tos_cache1 = PyStackRef_ZERO_BITS; _tos_cache2 = PyStackRef_ZERO_BITS; diff --git a/Python/generated_cases.c.h b/Python/generated_cases.c.h index 205b115a7b718f..561387e37d0ff4 100644 --- a/Python/generated_cases.c.h +++ b/Python/generated_cases.c.h @@ -7634,6 +7634,8 @@ int opcode = GET_AWAITABLE; (void)(opcode); #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; frame->instr_ptr = next_instr; next_instr += 1; INSTRUCTION_STATS(GET_AWAITABLE); @@ -7698,7 +7700,25 @@ stack_pointer[-1] = PyStackRef_NULL; stack_pointer[0] = v; stack_pointer += 1; + _Py_CODEUNIT *send = next_instr; next_instr += 1 + INLINE_CACHE_ENTRIES_SEND; + if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { + frame->instr_ptr = send; + SAVE_SP(); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int original_opcode = _Py_call_instrumentation_line( + tstate, frame, send, this_instr); + _PyFrame_StackPointerInvalidate(frame); + LOAD_SP(); + if (original_opcode < 0) { + next_instr = send + 1; + JUMP_TO_LABEL(error); + } + if (frame->instr_ptr != send) { + next_instr = frame->instr_ptr; + } + } DISPATCH(); } } @@ -9263,7 +9283,9 @@ _PyFrame_StackPointerInvalidate(frame); LOAD_IP(offset); value = temp; - LLTRACE_RESUME_FRAME(); + if (offset != 0) { + LLTRACE_RESUME_FRAME(); + } } stack_pointer[0] = value; stack_pointer += 1; @@ -14570,7 +14592,9 @@ _PyFrame_StackPointerInvalidate(frame); LOAD_IP(offset); value = temp; - LLTRACE_RESUME_FRAME(); + if (offset != 0) { + LLTRACE_RESUME_FRAME(); + } } stack_pointer[0] = value; stack_pointer += 1; diff --git a/Python/instrumentation.c b/Python/instrumentation.c index 5760f4b865d4b4..39301cdecbddf5 100644 --- a/Python/instrumentation.c +++ b/Python/instrumentation.c @@ -1661,22 +1661,15 @@ initialize_lines(_PyCoLineInstrumentationData *line_data, PyCodeObject *code, in target = i - oparg; break; } - case GET_AWAITABLE: - { - if (!(oparg & GET_AWAITABLE_AWAITED_CALL)) { - continue; - } - /* To YIELD_VALUE; the jump past END_SEND lands on SEND's target */ - target = i + 1 + INLINE_CACHE_ENTRIES_SEND; - break; - } default: continue; } assert(target >= 0); if (get_line_delta(line_data, target) != NO_LINE) { int opcode = _Py_GetBaseCodeUnit(code, target).op.code; - if (opcode != POP_ITER) { + if (opcode != POP_ITER && + !is_awaited_call_get_awaitable(code, target)) + { set_original_opcode(line_data, target, opcode); } } From 86a62f5d3d2ec8e84bd6aa768ee7255dcd33c971 Mon Sep 17 00:00:00 2001 From: Andrew Svetlov Date: Tue, 24 Nov 2026 17:01:53 +0100 Subject: [PATCH 08/10] Make tracing of lazy coroutine awaits match the eager path * Keep the await's line for GET_AWAITABLE after an awaited call, so tracebacks don't depend on whether LINE monitoring was ever set up; the SEND after it starts the line. * Allow INSTRUCTION events at that GET_AWAITABLE, making the call eager, and skip the event if instrumentation was enabled while a lazy body ran. * Emit the await's LINE event before the lazy body runs, as the eager path does at SEND, and forbid jumps from it. Co-Authored-By: Claude Opus 5.5 --- Lib/test/test_coroutines.py | 141 ++++++++++++++++++++++- Modules/_testinternalcapi/test_cases.c.h | 31 ++--- Objects/frameobject.c | 14 +++ Python/bytecodes.c | 25 ++-- Python/ceval_macros.h | 5 +- Python/executor_cases.c.h | 12 ++ Python/generated_cases.c.h | 31 ++--- Python/instrumentation.c | 27 +++-- 8 files changed, 216 insertions(+), 70 deletions(-) diff --git a/Lib/test/test_coroutines.py b/Lib/test/test_coroutines.py index c07418d9bfe5eb..2254474bd61808 100644 --- a/Lib/test/test_coroutines.py +++ b/Lib/test/test_coroutines.py @@ -1,6 +1,7 @@ import ast import contextlib import copy +import dis import builtins import gc import inspect @@ -3558,7 +3559,7 @@ async def outer(): mon.free_tool_id(tool) self.assertEqual(run_async(outer()), ([], True)) - def test_line_event_raises_after_suspension(self): + def test_line_event_raises_at_await(self): async def inner(): await AsyncYield("suspended") return "done" @@ -3585,6 +3586,144 @@ def line(code, lineno): mon.register_callback(tool, mon.events.LINE, None) mon.free_tool_id(tool) + @staticmethod + @contextlib.contextmanager + def eager(): + # Origin tracking makes awaited calls create the coroutine eagerly. + old_depth = sys.get_coroutine_origin_tracking_depth() + sys.set_coroutine_origin_tracking_depth(1) + try: + yield + finally: + sys.set_coroutine_origin_tracking_depth(old_depth) + + def test_settrace_events_like_eager_coroutine(self): + async def returns(): + return 1 + + async def suspends(): + await AsyncYield(None) + return 1 + + async def raises(): + raise ValueError + + async def outer(f): + try: + x = (await + f()) + except ValueError: + x = 0 + return x + + def trace(f): + events = [] + def tracer(frame, event, arg): + code = frame.f_code + if code in (outer.__code__, f.__code__): + events.append((code.co_name, event, + frame.f_lineno - code.co_firstlineno)) + return tracer + old_trace = sys.gettrace() + sys.settrace(tracer) + try: + run_async(outer(f)) + finally: + sys.settrace(old_trace) + return events + + for f in returns, suspends, raises: + with self.subTest(f=f.__name__): + lazy = trace(f) + with self.eager(): + eager = trace(f) + self.assertEqual(lazy, eager) + + def test_traceback_lineno_with_line_events(self): + async def outer(): + await ( + int()) + + def tb_lineno(): + try: + run_async(outer()) + except TypeError as e: + tb = e.__traceback__ + while tb.tb_frame.f_code is not outer.__code__: + tb = tb.tb_next + return tb.tb_lineno - outer.__code__.co_firstlineno + + mon = sys.monitoring + tool = mon.DEBUGGER_ID + self.assertEqual(tb_lineno(), 1) + mon.use_tool_id(tool, "test") + try: + mon.register_callback(tool, mon.events.LINE, lambda *args: None) + mon.set_local_events(tool, outer.__code__, mon.events.LINE) + self.assertEqual(tb_lineno(), 1) + mon.set_local_events(tool, outer.__code__, 0) + self.assertEqual(tb_lineno(), 1) + finally: + mon.register_callback(tool, mon.events.LINE, None) + mon.free_tool_id(tool) + + def test_instruction_events_at_awaited_call(self): + async def inner(): + return 1 + + async def outer(): + return await inner() + + get_awaitable = [i.offset for i in dis.get_instructions(outer) + if i.opname == "GET_AWAITABLE"] + offsets = [] + def instruction(code, offset): + if code is outer.__code__: + offsets.append(offset) + + mon = sys.monitoring + tool = mon.DEBUGGER_ID + mon.use_tool_id(tool, "test") + try: + mon.register_callback(tool, mon.events.INSTRUCTION, instruction) + mon.set_local_events(tool, outer.__code__, mon.events.INSTRUCTION) + self.assertEqual(run_async(outer()), ([], 1)) + finally: + mon.set_local_events(tool, outer.__code__, 0) + mon.register_callback(tool, mon.events.INSTRUCTION, None) + mon.free_tool_id(tool) + self.assertEqual(len(get_awaitable), 1) + self.assertIn(get_awaitable[0], offsets) + + def test_set_lineno_on_await_line_before_body(self): + async def inner(): + return "done" + + async def outer(): + x = (await + inner()) + return x + + first = outer.__code__.co_firstlineno + errors = [] + def tracer(frame, event, arg): + if (event == "line" and frame.f_code is outer.__code__ + and frame.f_lineno == first + 1): + try: + frame.f_lineno = first + 3 + except ValueError as e: + errors.append(str(e)) + return tracer + + old_trace = sys.gettrace() + sys.settrace(tracer) + try: + self.assertEqual(run_async(outer()), ([], "done")) + finally: + sys.settrace(old_trace) + self.assertEqual(errors, + ["can't jump from the await of a lazily run coroutine"]) + def test_set_lineno_to_multiline_await(self): # The await line must not start at GET_AWAITABLE, whose lazy # outcome slot cannot hold an arbitrary object. diff --git a/Modules/_testinternalcapi/test_cases.c.h b/Modules/_testinternalcapi/test_cases.c.h index ccc2a2fbcb6544..ce60bed97c405f 100644 --- a/Modules/_testinternalcapi/test_cases.c.h +++ b/Modules/_testinternalcapi/test_cases.c.h @@ -7634,8 +7634,6 @@ int opcode = GET_AWAITABLE; (void)(opcode); #endif - _Py_CODEUNIT* const this_instr = next_instr; - (void)this_instr; frame->instr_ptr = next_instr; next_instr += 1; INSTRUCTION_STATS(GET_AWAITABLE); @@ -7700,25 +7698,7 @@ stack_pointer[-1] = PyStackRef_NULL; stack_pointer[0] = v; stack_pointer += 1; - _Py_CODEUNIT *send = next_instr; next_instr += 1 + INLINE_CACHE_ENTRIES_SEND; - if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { - frame->instr_ptr = send; - SAVE_SP(); - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - int original_opcode = _Py_call_instrumentation_line( - tstate, frame, send, this_instr); - _PyFrame_StackPointerInvalidate(frame); - LOAD_SP(); - if (original_opcode < 0) { - next_instr = send + 1; - JUMP_TO_LABEL(error); - } - if (frame->instr_ptr != send) { - next_instr = frame->instr_ptr; - } - } DISPATCH(); } } @@ -12405,6 +12385,17 @@ _PyInterpreterFrame *caller = frame->previous; caller->instr_ptr += caller->return_offset; caller->return_offset = 0; + _Py_CODEUNIT *send = caller->instr_ptr + 1; + if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + int err = _Py_call_instrumentation_line( + tstate, caller, send, caller->instr_ptr) < 0; + _PyFrame_StackPointerInvalidate(frame); + if (err) { + JUMP_TO_LABEL(error); + } + } res = PyStackRef_None; } else { diff --git a/Objects/frameobject.c b/Objects/frameobject.c index eb1c28af96d131..50a37536afca27 100644 --- a/Objects/frameobject.c +++ b/Objects/frameobject.c @@ -1820,6 +1820,20 @@ frame_lineno_set_impl(PyFrameObject *self, PyObject *value) return -1; } + if (!is_suspended) { + _Py_CODEUNIT inst = _Py_GetBaseCodeUnit( + code, _PyInterpreterFrame_LASTI(self->f_frame)); + if (inst.op.code == GET_AWAITABLE && + (inst.op.arg & GET_AWAITABLE_AWAITED_CALL)) + { + /* The LINE event of an await, emitted before a lazily run + * body starts, when the stack is not as at a line start. */ + PyErr_SetString(PyExc_ValueError, + "can't jump from the await of a lazily run coroutine"); + return -1; + } + } + int new_lineno; /* Fail if the line falls outside the code block and diff --git a/Python/bytecodes.c b/Python/bytecodes.c index e7b08163835eb1..48bf28cfcaed7f 100644 --- a/Python/bytecodes.c +++ b/Python/bytecodes.c @@ -1705,24 +1705,7 @@ dummy_func( stack_pointer[-1] = PyStackRef_NULL; stack_pointer[0] = v; stack_pointer += 1; - _Py_CODEUNIT *send = next_instr; next_instr += 1 + INLINE_CACHE_ENTRIES_SEND; - if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { - // Emit the LINE event of the skipped SEND here, as - // the handler around YIELD_VALUE expects only throws. - frame->instr_ptr = send; - SAVE_SP(); - int original_opcode = _Py_call_instrumentation_line( - tstate, frame, send, this_instr); - LOAD_SP(); - if (original_opcode < 0) { - next_instr = send + 1; - goto error; - } - if (frame->instr_ptr != send) { - next_instr = frame->instr_ptr; - } - } DISPATCH(); } } @@ -6035,6 +6018,14 @@ dummy_func( _PyInterpreterFrame *caller = frame->previous; caller->instr_ptr += caller->return_offset; caller->return_offset = 0; + _Py_CODEUNIT *send = caller->instr_ptr + 1; + if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { + /* The LINE event of the await, which the eager path + * emits at SEND before the body runs. */ + int err = _Py_call_instrumentation_line( + tstate, caller, send, caller->instr_ptr) < 0; + ERROR_IF(err); + } /* The following POP_TOP discards this. */ res = PyStackRef_None; } diff --git a/Python/ceval_macros.h b/Python/ceval_macros.h index 9cb5815d33f065..957d8fe89aaa4d 100644 --- a/Python/ceval_macros.h +++ b/Python/ceval_macros.h @@ -157,8 +157,9 @@ #endif /* Tier one only, after next_instr has skipped the call's inline cache. - * GET_AWAITABLE is never specialized, and never instrumented after an - * awaited call. */ + * GET_AWAITABLE is never specialized. After an awaited call, it is never + * instrumented with INSTRUMENTED_LINE; with INSTRUCTION events on, the call + * is not lazy. */ #define IS_AWAITED_CALL() \ (next_instr->op.code == GET_AWAITABLE && \ (next_instr->op.arg & GET_AWAITABLE_AWAITED_CALL)) diff --git a/Python/executor_cases.c.h b/Python/executor_cases.c.h index f68af6cea16504..c254f13a7fc21a 100644 --- a/Python/executor_cases.c.h +++ b/Python/executor_cases.c.h @@ -20879,6 +20879,18 @@ _PyInterpreterFrame *caller = frame->previous; caller->instr_ptr += caller->return_offset; caller->return_offset = 0; + _Py_CODEUNIT *send = caller->instr_ptr + 1; + if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + int err = _Py_call_instrumentation_line( + tstate, caller, send, caller->instr_ptr) < 0; + _PyFrame_StackPointerInvalidate(frame); + if (err) { + SET_CURRENT_CACHED_VALUES(0); + JUMP_TO_ERROR(); + } + } res = PyStackRef_None; } else { diff --git a/Python/generated_cases.c.h b/Python/generated_cases.c.h index 561387e37d0ff4..12cc2808a4966f 100644 --- a/Python/generated_cases.c.h +++ b/Python/generated_cases.c.h @@ -7634,8 +7634,6 @@ int opcode = GET_AWAITABLE; (void)(opcode); #endif - _Py_CODEUNIT* const this_instr = next_instr; - (void)this_instr; frame->instr_ptr = next_instr; next_instr += 1; INSTRUCTION_STATS(GET_AWAITABLE); @@ -7700,25 +7698,7 @@ stack_pointer[-1] = PyStackRef_NULL; stack_pointer[0] = v; stack_pointer += 1; - _Py_CODEUNIT *send = next_instr; next_instr += 1 + INLINE_CACHE_ENTRIES_SEND; - if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { - frame->instr_ptr = send; - SAVE_SP(); - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - int original_opcode = _Py_call_instrumentation_line( - tstate, frame, send, this_instr); - _PyFrame_StackPointerInvalidate(frame); - LOAD_SP(); - if (original_opcode < 0) { - next_instr = send + 1; - JUMP_TO_LABEL(error); - } - if (frame->instr_ptr != send) { - next_instr = frame->instr_ptr; - } - } DISPATCH(); } } @@ -12402,6 +12382,17 @@ _PyInterpreterFrame *caller = frame->previous; caller->instr_ptr += caller->return_offset; caller->return_offset = 0; + _Py_CODEUNIT *send = caller->instr_ptr + 1; + if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + int err = _Py_call_instrumentation_line( + tstate, caller, send, caller->instr_ptr) < 0; + _PyFrame_StackPointerInvalidate(frame); + if (err) { + JUMP_TO_LABEL(error); + } + } res = PyStackRef_None; } else { diff --git a/Python/instrumentation.c b/Python/instrumentation.c index 39301cdecbddf5..a39a75962e3405 100644 --- a/Python/instrumentation.c +++ b/Python/instrumentation.c @@ -1364,8 +1364,13 @@ _Py_call_instrumentation_line(PyThreadState *tstate, _PyInterpreterFrame* frame, int prev_opcode = bytecode[prev_index].op.code; /* RESUME and INSTRUMENTED_RESUME are needed for the operation of * instrumentation, so must never be hidden by an INSTRUMENTED_LINE. + * GET_AWAITABLE after an awaited call cannot start a line, so + * the SEND after it does. */ - if (prev_opcode != RESUME && prev_opcode != INSTRUMENTED_RESUME) { + if (prev_opcode != RESUME && prev_opcode != INSTRUMENTED_RESUME && + !(i == prev_index + 1 && + is_awaited_call_get_awaitable(code, prev_index))) + { goto done; } } @@ -1462,6 +1467,14 @@ _Py_call_instrumentation_instruction(PyThreadState *tstate, _PyInterpreterFrame* if (tstate->tracing) { return next_opcode; } + if (next_opcode == GET_AWAITABLE && + (instr->op.arg & GET_AWAITABLE_AWAITED_CALL) && + !PyStackRef_IsNull(frame->stackpointer[-2])) + { + /* Instrumented while a lazy coroutine ran: its outcome must reach + * GET_AWAITABLE before anything else runs. */ + return next_opcode; + } assert(debug_check_sanity(tstate->interp, code)); PyInterpreterState *interp = tstate->interp; uint8_t tools = instrumentation_data->per_instruction_tools != NULL ? @@ -1595,9 +1608,7 @@ initialize_lines(_PyCoLineInstrumentationData *line_data, PyCodeObject *code, in /* GET_AWAITABLE after an awaited call must not be * instrumented with INSTRUMENTED_LINE, as no events may * fire before it handles a lazy coroutine. - * It has the location of the await, which starts a line - * after the call, so it keeps the line of the call. */ - set_line_delta(line_data, i, compute_line_delta(code, current_line)); + * The SEND after it starts the line of the await. */ set_original_opcode(line_data, i, 0); break; } @@ -1926,9 +1937,7 @@ force_instrument_lock_held(PyCodeObject *code, PyInterpreterState *interp) if (removed_per_instruction_tools) { for (int i = code->_co_firsttraceable; i < code_len;) { int opcode = _Py_GetBaseCodeUnit(code, i).op.code; - if (opcode == RESUME || opcode == END_FOR || - is_awaited_call_get_awaitable(code, i)) - { + if (opcode == RESUME || opcode == END_FOR) { i += _PyInstruction_GetLength(code, i); continue; } @@ -1955,9 +1964,7 @@ force_instrument_lock_held(PyCodeObject *code, PyInterpreterState *interp) if (new_per_instruction_tools) { for (int i = code->_co_firsttraceable; i < code_len;) { int opcode = _Py_GetBaseCodeUnit(code, i).op.code; - if (opcode == RESUME || opcode == END_FOR || - is_awaited_call_get_awaitable(code, i)) - { + if (opcode == RESUME || opcode == END_FOR) { i += _PyInstruction_GetLength(code, i); continue; } From 4c39dacd45b34ef0a1189446119d5a64fbe8fe03 Mon Sep 17 00:00:00 2001 From: Andrew Svetlov Date: Tue, 24 Nov 2026 17:11:01 +0100 Subject: [PATCH 09/10] Fix docs, a release-build warning and a test skip * PyFrame_GetGenerator() returns None, not NULL, without a generator. * The awaited-call flag of GET_AWAITABLE is the value 4, not bit 4. * Don't warn that lazy_outcome is unused when asserts are disabled. * Skip test_memory_error_before_body_runs without _testcapi. Co-Authored-By: Claude Opus 5.5 --- Doc/c-api/frame.rst | 8 ++++---- Doc/library/dis.rst | 2 +- Doc/whatsnew/3.16.rst | 2 +- Lib/test/test_coroutines.py | 1 + Modules/_testinternalcapi/test_cases.c.h | 2 ++ Python/bytecodes.c | 2 ++ Python/executor_cases.c.h | 1 + Python/generated_cases.c.h | 2 ++ 8 files changed, 14 insertions(+), 6 deletions(-) diff --git a/Doc/c-api/frame.rst b/Doc/c-api/frame.rst index bfd39507461d03..2fe2192ac030cd 100644 --- a/Doc/c-api/frame.rst +++ b/Doc/c-api/frame.rst @@ -78,15 +78,15 @@ See also :ref:`Reflection `. .. c:function:: PyObject* PyFrame_GetGenerator(PyFrameObject *frame) Get the generator, coroutine, or async generator that owns this frame, - or ``NULL`` if this frame is not owned by a generator. - Does not raise an exception, even if the return value is ``NULL``. + or ``None`` if this frame is not owned by a generator. + Does not raise an exception. - Return a :term:`strong reference`, or ``NULL``. + Return a :term:`strong reference`. .. versionadded:: 3.11 .. versionchanged:: 3.16 - May return ``NULL`` for a coroutine frame before its first suspension; + May return ``None`` for a coroutine frame before its first suspension; see :attr:`frame.f_generator`. diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst index c96a71acc3dab5..f86e59d50289e0 100644 --- a/Doc/library/dis.rst +++ b/Doc/library/dis.rst @@ -829,7 +829,7 @@ not have to be) the original ``STACK[-2]``. * ``1``: After a call to ``__aenter__`` * ``2``: After a call to ``__aexit__`` - If bit ``4`` of *flags* is set, the instruction follows a call whose + If *flags* has the ``4`` bit set, the instruction follows a call whose result is awaited right away (``await f()``, and the calls of :meth:`~object.__aenter__` and :meth:`~object.__aexit__` in :keyword:`async with`). The compiler pushes an extra ``NULL``, the diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index d64e3b5a6ccbc1..b941c3b95dd1ac 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -1434,7 +1434,7 @@ This section lists previously described changes and other bugfixes that may require changes to your code. * :attr:`frame.f_generator` and :c:func:`PyFrame_GetGenerator` may now - return ``None``/``NULL`` for a coroutine frame before its first + return ``None`` for a coroutine frame before its first suspension, because a coroutine that is awaited as soon as it is called (``await coro_func()``) runs without a coroutine object until then. Code that used ``frame.f_generator is None`` to detect frames of normal diff --git a/Lib/test/test_coroutines.py b/Lib/test/test_coroutines.py index 2254474bd61808..0a53ae162348e6 100644 --- a/Lib/test/test_coroutines.py +++ b/Lib/test/test_coroutines.py @@ -3272,6 +3272,7 @@ async def f(): with self.assertRaises(RecursionError): coro.send(None) + @unittest.skipIf(_testcapi is None, "requires _testcapi") def test_memory_error_before_body_runs(self): # MAKE_CELL runs before RETURN_GENERATOR. async def inner(x): diff --git a/Modules/_testinternalcapi/test_cases.c.h b/Modules/_testinternalcapi/test_cases.c.h index ce60bed97c405f..022b9ef8800352 100644 --- a/Modules/_testinternalcapi/test_cases.c.h +++ b/Modules/_testinternalcapi/test_cases.c.h @@ -7651,6 +7651,7 @@ if (oparg & GET_AWAITABLE_AWAITED_CALL) { _PyStackRef *slot = &stack_pointer[-2]; assert(slot == lazy_outcome); + (void)lazy_outcome; _PyStackRef outcome = *slot; if (PyStackRef_IsTaggedInt(outcome)) { *slot = PyStackRef_NULL; @@ -7707,6 +7708,7 @@ { assert(!(oparg & GET_AWAITABLE_AWAITED_CALL) || PyStackRef_IsNull(lazy_outcome[0])); + (void)lazy_outcome; value = res; } // _GET_AWAITABLE diff --git a/Python/bytecodes.c b/Python/bytecodes.c index 48bf28cfcaed7f..2a8d6ca43f8e38 100644 --- a/Python/bytecodes.c +++ b/Python/bytecodes.c @@ -1669,6 +1669,7 @@ dummy_func( // lazy_outcome would make the load wait for oparg. _PyStackRef *slot = &stack_pointer[-2]; assert(slot == lazy_outcome); + (void)lazy_outcome; _PyStackRef outcome = *slot; if (PyStackRef_IsTaggedInt(outcome)) { *slot = PyStackRef_NULL; @@ -1719,6 +1720,7 @@ dummy_func( op(_POP_LAZY_OUTCOME, (lazy_outcome[(oparg >> 2) & 1], res -- value)) { assert(!(oparg & GET_AWAITABLE_AWAITED_CALL) || PyStackRef_IsNull(lazy_outcome[0])); + (void)lazy_outcome; DEAD(lazy_outcome); value = res; DEAD(res); diff --git a/Python/executor_cases.c.h b/Python/executor_cases.c.h index c254f13a7fc21a..f5426de99f5cb2 100644 --- a/Python/executor_cases.c.h +++ b/Python/executor_cases.c.h @@ -8981,6 +8981,7 @@ lazy_outcome = &stack_pointer[-((oparg >> 2) & 1)]; assert(!(oparg & GET_AWAITABLE_AWAITED_CALL) || PyStackRef_IsNull(lazy_outcome[0])); + (void)lazy_outcome; value = res; _tos_cache0 = value; SET_CURRENT_CACHED_VALUES(1); diff --git a/Python/generated_cases.c.h b/Python/generated_cases.c.h index 12cc2808a4966f..69529db99fa6fd 100644 --- a/Python/generated_cases.c.h +++ b/Python/generated_cases.c.h @@ -7651,6 +7651,7 @@ if (oparg & GET_AWAITABLE_AWAITED_CALL) { _PyStackRef *slot = &stack_pointer[-2]; assert(slot == lazy_outcome); + (void)lazy_outcome; _PyStackRef outcome = *slot; if (PyStackRef_IsTaggedInt(outcome)) { *slot = PyStackRef_NULL; @@ -7707,6 +7708,7 @@ { assert(!(oparg & GET_AWAITABLE_AWAITED_CALL) || PyStackRef_IsNull(lazy_outcome[0])); + (void)lazy_outcome; value = res; } // _GET_AWAITABLE From 6ef84935cecaf59abb8645f4c910b8bcbf293d6e Mon Sep 17 00:00:00 2001 From: Andrew Svetlov Date: Tue, 24 Nov 2026 19:03:57 +0100 Subject: [PATCH 10/10] Mark running lazy coroutines with their own frame owner A running lazy coroutine body now has owner FRAME_OWNED_BY_LAZY_CORO instead of a lazy_coro state bit, so returning from an ordinary function no longer checks for it: _PyEval_FrameClearAndPop dispatches on the owner it already tests. The new value is 4, keeping the existing values that outside tools rely on, so range checks against FRAME_OWNED_BY_INTERPRETER become equality checks. Co-Authored-By: Claude Opus 5.5 --- Include/internal/pycore_interpframe.h | 2 +- Include/internal/pycore_interpframe_structs.h | 8 +++++--- InternalDocs/generators.md | 4 ++-- Modules/_remote_debugging/frames.c | 4 +++- Modules/_testinternalcapi/test_cases.c.h | 8 ++++---- Objects/frameobject.c | 4 +++- Objects/genobject.c | 3 +-- Python/bytecodes.c | 10 +++++----- Python/ceval.c | 17 +++++++---------- Python/ceval.h | 4 ++-- Python/executor_cases.c.h | 14 +++++++------- Python/frame.c | 4 ++-- Python/gc_free_threading.c | 4 ++-- Python/generated_cases.c.h | 8 ++++---- Python/instrumentation.c | 2 +- Python/intrinsics.c | 4 +--- 16 files changed, 50 insertions(+), 50 deletions(-) diff --git a/Include/internal/pycore_interpframe.h b/Include/internal/pycore_interpframe.h index 8b90f3d9b0e9fe..7eeb6b1a6a9766 100644 --- a/Include/internal/pycore_interpframe.h +++ b/Include/internal/pycore_interpframe.h @@ -294,7 +294,7 @@ _PyFrame_StackAssertInvalid(_PyInterpreterFrame *frame) static inline bool _Py_NO_SANITIZE_THREAD _PyFrame_IsIncomplete(_PyInterpreterFrame *frame) { - if (frame->owner >= FRAME_OWNED_BY_INTERPRETER) { + if (frame->owner == FRAME_OWNED_BY_INTERPRETER) { return true; } return frame->owner != FRAME_OWNED_BY_GENERATOR && diff --git a/Include/internal/pycore_interpframe_structs.h b/Include/internal/pycore_interpframe_structs.h index 03726ff0a45750..572f7301b52709 100644 --- a/Include/internal/pycore_interpframe_structs.h +++ b/Include/internal/pycore_interpframe_structs.h @@ -24,6 +24,9 @@ enum _frameowner { FRAME_OWNED_BY_GENERATOR = 1, FRAME_OWNED_BY_FRAME_OBJECT = 2, FRAME_OWNED_BY_INTERPRETER = 3, + /* A coroutine body running in the frame of the thread, without a + * coroutine object; see RETURN_GENERATOR. */ + FRAME_OWNED_BY_LAZY_CORO = 4, }; struct _PyInterpreterFrame { @@ -44,17 +47,16 @@ struct _PyInterpreterFrame { char owner; uint8_t visited:1; uint8_t external:1; /* Set when the frame was pushed by something other than the VM */ - uint8_t lazy_coro:2; /* LAZY_CORO_REQUESTED or LAZY_CORO_RUNNING */ + uint8_t lazy_coro:1; /* LAZY_CORO_REQUESTED */ #ifdef Py_DEBUG uint8_t stackpointer_valid:1; - uint8_t lltrace:3; + uint8_t lltrace:4; #endif /* Locals and stack */ _PyStackRef localsplus[1]; }; #define LAZY_CORO_REQUESTED 1 -#define LAZY_CORO_RUNNING 2 /* _PyGenObject_HEAD defines the initial segment of generator diff --git a/InternalDocs/generators.md b/InternalDocs/generators.md index c1acf4582d2625..919043ea97de77 100644 --- a/InternalDocs/generators.md +++ b/InternalDocs/generators.md @@ -55,8 +55,8 @@ There is one exception: a coroutine function called by an awaited call `LAZY_CORO_REQUESTED` on its frame (see `MAYBE_START_LAZY_CORO()`). The specializer gives such a call of a coroutine function an `*_AWAITED` form, which does the same. `RETURN_GENERATOR` then pushes the body's own -`_PyErr_StackItem` on the data stack right after the frame, sets `lazy_coro` -to `LAZY_CORO_RUNNING`, moves the caller to its `GET_AWAITABLE` (which has +`_PyErr_StackItem` on the data stack right after the frame, sets the frame's +`owner` to `FRAME_OWNED_BY_LAZY_CORO`, moves the caller to its `GET_AWAITABLE` (which has the location of the `await`, like `SEND`) and keeps running the body in that frame, so that a body that returns or raises without suspending never creates a coroutine diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index 3f8d628a6314e6..e1e3050a7e2214 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -182,7 +182,9 @@ is_frame_valid( return FRAME_PARSE_INTERPRETER; // C frame or sentinel base frame } - if (owner != FRAME_OWNED_BY_GENERATOR && owner != FRAME_OWNED_BY_THREAD) { + if (owner != FRAME_OWNED_BY_GENERATOR && owner != FRAME_OWNED_BY_THREAD && + owner != FRAME_OWNED_BY_LAZY_CORO) + { PyErr_Format(PyExc_RuntimeError, "Unhandled frame owner %d.\n", owner); set_exception_cause(unwinder, PyExc_RuntimeError, "Unhandled frame owner type in async frame"); return -1; diff --git a/Modules/_testinternalcapi/test_cases.c.h b/Modules/_testinternalcapi/test_cases.c.h index 022b9ef8800352..e49b28757ccac9 100644 --- a/Modules/_testinternalcapi/test_cases.c.h +++ b/Modules/_testinternalcapi/test_cases.c.h @@ -6007,7 +6007,7 @@ PyObject *exc_value = PyStackRef_AsPyObjectBorrow(exc_value_st); #if !_Py_TAIL_CALL_INTERP - assert(throwflag || frame->lazy_coro == LAZY_CORO_RUNNING); + assert(throwflag || frame->owner == FRAME_OWNED_BY_LAZY_CORO); #endif assert(exc_value && PyExceptionInstance_Check(exc_value)); _PyFrame_SetStackPointer(frame, stack_pointer); @@ -9235,7 +9235,7 @@ _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); int offset = 1 + INLINE_CACHE_ENTRIES_SEND; - if (frame->lazy_coro == LAZY_CORO_RUNNING) { + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { assert(oparg == 1); frame = _PyEval_SuspendLazyCoro(tstate, frame); offset = 0; @@ -12383,7 +12383,7 @@ exc_info->exc_value = NULL; exc_info->previous_item = tstate->exc_info; tstate->exc_info = exc_info; - frame->lazy_coro = LAZY_CORO_RUNNING; + frame->owner = FRAME_OWNED_BY_LAZY_CORO; _PyInterpreterFrame *caller = frame->previous; caller->instr_ptr += caller->return_offset; caller->return_offset = 0; @@ -14557,7 +14557,7 @@ _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); int offset = 1 + INLINE_CACHE_ENTRIES_SEND; - if (frame->lazy_coro == LAZY_CORO_RUNNING) { + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { assert(oparg == 1); frame = _PyEval_SuspendLazyCoro(tstate, frame); offset = 0; diff --git a/Objects/frameobject.c b/Objects/frameobject.c index 50a37536afca27..8b5d9d218e0c40 100644 --- a/Objects/frameobject.c +++ b/Objects/frameobject.c @@ -2138,7 +2138,9 @@ frame_clear_impl(PyFrameObject *self) return NULL; } } - else if (self->f_frame->owner == FRAME_OWNED_BY_THREAD) { + else if (self->f_frame->owner == FRAME_OWNED_BY_THREAD || + self->f_frame->owner == FRAME_OWNED_BY_LAZY_CORO) + { PyErr_SetString(PyExc_RuntimeError, "cannot clear an executing frame"); return NULL; diff --git a/Objects/genobject.c b/Objects/genobject.c index 5cf8efae9d1ad0..4e9ef3cd640158 100644 --- a/Objects/genobject.c +++ b/Objects/genobject.c @@ -1187,8 +1187,7 @@ _Py_MakeCoro(PyFunctionObject *func) PyObject * _PyCoro_MaterializeLazy(_PyInterpreterFrame *frame) { - assert(frame->owner == FRAME_OWNED_BY_THREAD); - assert(frame->lazy_coro == LAZY_CORO_RUNNING); + assert(frame->owner == FRAME_OWNED_BY_LAZY_CORO); assert(PyStackRef_FunctionCheck(frame->f_funcobj)); PyFunctionObject *func = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(frame->f_funcobj); diff --git a/Python/bytecodes.c b/Python/bytecodes.c index 2a8d6ca43f8e38..0994d9ee5328ab 100644 --- a/Python/bytecodes.c +++ b/Python/bytecodes.c @@ -1925,7 +1925,7 @@ dummy_func( } tier2 op(_GUARD_NOT_LAZY_CORO, (--)) { - EXIT_IF(frame->lazy_coro == LAZY_CORO_RUNNING); + EXIT_IF(frame->owner == FRAME_OWNED_BY_LAZY_CORO); } op(_YIELD_VALUE, (retval -- value)) { @@ -1941,7 +1941,7 @@ dummy_func( SAVE_STACK(); DTRACE_FUNCTION_RETURN(); int offset = 1 + INLINE_CACHE_ENTRIES_SEND; - if (frame->lazy_coro == LAZY_CORO_RUNNING) { + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { // The caller's GET_AWAITABLE creates the coroutine. It is // never instrumented, so nothing runs in between. assert(oparg == 1); @@ -2060,7 +2060,7 @@ dummy_func( PyObject *exc_value = PyStackRef_AsPyObjectBorrow(exc_value_st); #if !_Py_TAIL_CALL_INTERP // _PyEval_ThrowIntoLazyCoro() raises in a lazily run body. - assert(throwflag || frame->lazy_coro == LAZY_CORO_RUNNING); + assert(throwflag || frame->owner == FRAME_OWNED_BY_LAZY_CORO); #endif assert(exc_value && PyExceptionInstance_Check(exc_value)); int matches = PyErr_GivenExceptionMatches(exc_value, PyExc_StopIteration); @@ -6014,7 +6014,7 @@ dummy_func( exc_info->exc_value = NULL; exc_info->previous_item = tstate->exc_info; tstate->exc_info = exc_info; - frame->lazy_coro = LAZY_CORO_RUNNING; + frame->owner = FRAME_OWNED_BY_LAZY_CORO; /* While the body runs, the caller is at the await, as at * SEND on the eager path. */ _PyInterpreterFrame *caller = frame->previous; @@ -6465,7 +6465,7 @@ dummy_func( tier2 op(_COLD_EXIT, ( -- )) { _PyExitData *exit = tstate->jit_exit; assert(exit != NULL); - assert(frame->owner < FRAME_OWNED_BY_INTERPRETER); + assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); _Py_CODEUNIT *target = _PyFrame_GetBytecode(frame) + exit->target; _Py_BackoffCounter temperature = exit->temperature; _PyExecutorObject *executor; diff --git a/Python/ceval.c b/Python/ceval.c index 09bae7f7ecfa40..ff4f6a01e53b0f 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -2025,7 +2025,7 @@ clear_lazy_coro_frame(PyThreadState *tstate, _PyInterpreterFrame *frame) tstate->exc_info = exc_info->previous_item; PyObject *exc_value = exc_info->exc_value; _PyThreadState_PopFrame(tstate, (_PyInterpreterFrame *)exc_info); - frame->lazy_coro = 0; + frame->owner = FRAME_OWNED_BY_THREAD; _PyInterpreterFrame *caller = frame->previous; assert(PyStackRef_IsNull(caller->stackpointer[-1])); caller->stackpointer[-1] = LAZY_CORO_RETURNED; @@ -2040,10 +2040,6 @@ static void clear_thread_frame(PyThreadState *tstate, _PyInterpreterFrame * frame) { assert(frame->owner == FRAME_OWNED_BY_THREAD); - if (frame->lazy_coro == LAZY_CORO_RUNNING) { - clear_lazy_coro_frame(tstate, frame); - return; - } clear_and_pop_thread_frame(tstate, frame); } @@ -2076,6 +2072,9 @@ _PyEval_FrameClearAndPop(PyThreadState *tstate, _PyInterpreterFrame * frame) if (frame->owner == FRAME_OWNED_BY_THREAD) { clear_thread_frame(tstate, frame); } + else if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { + clear_lazy_coro_frame(tstate, frame); + } else { clear_gen_frame(tstate, frame); } @@ -3719,7 +3718,7 @@ _PyEval_LoadGlobalStackRef(PyObject *globals, PyObject *builtins, PyObject *name _PyInterpreterFrame * _PyEval_SuspendLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame) { - assert(frame->lazy_coro == LAZY_CORO_RUNNING); + assert(frame->owner == FRAME_OWNED_BY_LAZY_CORO); _PyErr_StackItem *exc_info = tstate->exc_info; tstate->exc_info = exc_info->previous_item; exc_info->previous_item = NULL; @@ -3738,8 +3737,7 @@ _PyEval_SuspendLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame) PyGenObject * _PyEval_MaterializeLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame) { - assert(frame->owner == FRAME_OWNED_BY_THREAD); - assert(frame->lazy_coro == LAZY_CORO_RUNNING); + assert(frame->owner == FRAME_OWNED_BY_LAZY_CORO); assert(frame->previous == NULL); const int item_slots = sizeof(_PyErr_StackItem) / sizeof(PyObject *); _PyErr_StackItem *exc_info = @@ -3777,8 +3775,7 @@ _PyInterpreterFrame * _PyEval_ThrowIntoLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame, _PyStackRef value) { - assert(frame->owner == FRAME_OWNED_BY_THREAD); - assert(frame->lazy_coro == LAZY_CORO_RUNNING); + assert(frame->owner == FRAME_OWNED_BY_LAZY_CORO); assert(_PyErr_Occurred(tstate)); const int item_slots = sizeof(_PyErr_StackItem) / sizeof(PyObject *); _PyErr_StackItem *exc_info = diff --git a/Python/ceval.h b/Python/ceval.h index 0ba365a454b7ad..19b3e9b6f3bfe5 100644 --- a/Python/ceval.h +++ b/Python/ceval.h @@ -229,7 +229,7 @@ lltrace_instruction(_PyInterpreterFrame *frame, int oparg) { int offset = 0; - if (frame->owner < FRAME_OWNED_BY_INTERPRETER) { + if (frame->owner != FRAME_OWNED_BY_INTERPRETER) { dump_stack(frame, stack_pointer); offset = (int)(next_instr - _PyFrame_GetBytecode(frame)); } @@ -288,7 +288,7 @@ maybe_lltrace_resume_frame(_PyInterpreterFrame *frame, PyObject *globals) if (globals == NULL) { return 0; } - if (frame->owner >= FRAME_OWNED_BY_INTERPRETER) { + if (frame->owner == FRAME_OWNED_BY_INTERPRETER) { return 0; } int r = PyDict_Contains(globals, &_Py_ID(__lltrace__)); diff --git a/Python/executor_cases.c.h b/Python/executor_cases.c.h index f5426de99f5cb2..760b870317a1a1 100644 --- a/Python/executor_cases.c.h +++ b/Python/executor_cases.c.h @@ -9545,7 +9545,7 @@ case _GUARD_NOT_LAZY_CORO_r00: { CHECK_CURRENT_CACHED_VALUES(0); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); - if (frame->lazy_coro == LAZY_CORO_RUNNING) { + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { UOP_STAT_INC(uopcode, miss); SET_CURRENT_CACHED_VALUES(0); JUMP_TO_JUMP_TARGET(); @@ -9559,7 +9559,7 @@ CHECK_CURRENT_CACHED_VALUES(1); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); _PyStackRef _stack_item_0 = _tos_cache0; - if (frame->lazy_coro == LAZY_CORO_RUNNING) { + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { UOP_STAT_INC(uopcode, miss); _tos_cache0 = _stack_item_0; SET_CURRENT_CACHED_VALUES(1); @@ -9576,7 +9576,7 @@ ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); _PyStackRef _stack_item_0 = _tos_cache0; _PyStackRef _stack_item_1 = _tos_cache1; - if (frame->lazy_coro == LAZY_CORO_RUNNING) { + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { UOP_STAT_INC(uopcode, miss); _tos_cache1 = _stack_item_1; _tos_cache0 = _stack_item_0; @@ -9596,7 +9596,7 @@ _PyStackRef _stack_item_0 = _tos_cache0; _PyStackRef _stack_item_1 = _tos_cache1; _PyStackRef _stack_item_2 = _tos_cache2; - if (frame->lazy_coro == LAZY_CORO_RUNNING) { + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { UOP_STAT_INC(uopcode, miss); _tos_cache2 = _stack_item_2; _tos_cache1 = _stack_item_1; @@ -9629,7 +9629,7 @@ _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); int offset = 1 + INLINE_CACHE_ENTRIES_SEND; - if (frame->lazy_coro == LAZY_CORO_RUNNING) { + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { assert(oparg == 1); frame = _PyEval_SuspendLazyCoro(tstate, frame); offset = 0; @@ -20876,7 +20876,7 @@ exc_info->exc_value = NULL; exc_info->previous_item = tstate->exc_info; tstate->exc_info = exc_info; - frame->lazy_coro = LAZY_CORO_RUNNING; + frame->owner = FRAME_OWNED_BY_LAZY_CORO; _PyInterpreterFrame *caller = frame->previous; caller->instr_ptr += caller->return_offset; caller->return_offset = 0; @@ -24207,7 +24207,7 @@ ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); _PyExitData *exit = tstate->jit_exit; assert(exit != NULL); - assert(frame->owner < FRAME_OWNED_BY_INTERPRETER); + assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); _Py_CODEUNIT *target = _PyFrame_GetBytecode(frame) + exit->target; _Py_BackoffCounter temperature = exit->temperature; _PyExecutorObject *executor; diff --git a/Python/frame.c b/Python/frame.c index 79522b00b47f11..f860a6b603dcff 100644 --- a/Python/frame.c +++ b/Python/frame.c @@ -55,7 +55,7 @@ static void take_ownership(PyFrameObject *f, _PyInterpreterFrame *frame) { Py_BEGIN_CRITICAL_SECTION(f); - assert(frame->owner < FRAME_OWNED_BY_INTERPRETER); + assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); assert(frame->owner != FRAME_OWNED_BY_FRAME_OBJECT); _PyInterpreterFrame *new_frame = (_PyInterpreterFrame *)f->_f_frame_data; _PyFrame_Copy(frame, new_frame); @@ -75,7 +75,7 @@ take_ownership(PyFrameObject *f, _PyInterpreterFrame *frame) assert(f->f_back == NULL); _PyInterpreterFrame *prev = _PyFrame_GetFirstComplete(frame->previous); if (prev) { - assert(prev->owner < FRAME_OWNED_BY_INTERPRETER); + assert(prev->owner != FRAME_OWNED_BY_INTERPRETER); PyObject *exc = PyErr_GetRaisedException(); /* Link PyFrameObjects.f_back and remove link through _PyInterpreterFrame.previous */ PyFrameObject *back = _PyFrame_GetFrameObject(prev); diff --git a/Python/gc_free_threading.c b/Python/gc_free_threading.c index f4f1a7777f3522..f839f968dd6e9f 100644 --- a/Python/gc_free_threading.c +++ b/Python/gc_free_threading.c @@ -457,7 +457,7 @@ gc_visit_thread_stacks(PyInterpreterState *interp, struct collection_state *stat } for (_PyInterpreterFrame *f = p->current_frame; f != NULL; f = f->previous) { - if (f->owner >= FRAME_OWNED_BY_INTERPRETER) { + if (f->owner == FRAME_OWNED_BY_INTERPRETER) { continue; } @@ -855,7 +855,7 @@ gc_visit_thread_stacks_mark_alive(PyInterpreterState *interp, gc_mark_args_t *ar int err = 0; _Py_FOR_EACH_TSTATE_BEGIN(interp, p) { for (_PyInterpreterFrame *f = p->current_frame; f != NULL; f = f->previous) { - if (f->owner >= FRAME_OWNED_BY_INTERPRETER) { + if (f->owner == FRAME_OWNED_BY_INTERPRETER) { continue; } diff --git a/Python/generated_cases.c.h b/Python/generated_cases.c.h index 69529db99fa6fd..589dbc65af57aa 100644 --- a/Python/generated_cases.c.h +++ b/Python/generated_cases.c.h @@ -6007,7 +6007,7 @@ PyObject *exc_value = PyStackRef_AsPyObjectBorrow(exc_value_st); #if !_Py_TAIL_CALL_INTERP - assert(throwflag || frame->lazy_coro == LAZY_CORO_RUNNING); + assert(throwflag || frame->owner == FRAME_OWNED_BY_LAZY_CORO); #endif assert(exc_value && PyExceptionInstance_Check(exc_value)); _PyFrame_SetStackPointer(frame, stack_pointer); @@ -9234,7 +9234,7 @@ _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); int offset = 1 + INLINE_CACHE_ENTRIES_SEND; - if (frame->lazy_coro == LAZY_CORO_RUNNING) { + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { assert(oparg == 1); frame = _PyEval_SuspendLazyCoro(tstate, frame); offset = 0; @@ -12380,7 +12380,7 @@ exc_info->exc_value = NULL; exc_info->previous_item = tstate->exc_info; tstate->exc_info = exc_info; - frame->lazy_coro = LAZY_CORO_RUNNING; + frame->owner = FRAME_OWNED_BY_LAZY_CORO; _PyInterpreterFrame *caller = frame->previous; caller->instr_ptr += caller->return_offset; caller->return_offset = 0; @@ -14554,7 +14554,7 @@ _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); int offset = 1 + INLINE_CACHE_ENTRIES_SEND; - if (frame->lazy_coro == LAZY_CORO_RUNNING) { + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { assert(oparg == 1); frame = _PyEval_SuspendLazyCoro(tstate, frame); offset = 0; diff --git a/Python/instrumentation.c b/Python/instrumentation.c index a39a75962e3405..9767397e65cf79 100644 --- a/Python/instrumentation.c +++ b/Python/instrumentation.c @@ -2026,7 +2026,7 @@ instrument_all_executing_code_objects(PyInterpreterState *interp) _Py_FOR_EACH_TSTATE_BEGIN(interp, ts) { _PyInterpreterFrame *frame = ts->current_frame; while (frame) { - if (frame->owner < FRAME_OWNED_BY_INTERPRETER) { + if (frame->owner != FRAME_OWNED_BY_INTERPRETER) { err = instrument_lock_held(_PyFrame_GetCode(frame), interp); if (err) { goto done; diff --git a/Python/intrinsics.c b/Python/intrinsics.c index df6c992d4c53da..50c53ba603e246 100644 --- a/Python/intrinsics.c +++ b/Python/intrinsics.c @@ -144,10 +144,8 @@ static PyObject * stopiteration_error(PyThreadState* tstate, PyObject *exc) { _PyInterpreterFrame *frame = tstate->current_frame; - /* A lazily started coroutine (see RETURN_GENERATOR). */ assert(frame->owner == FRAME_OWNED_BY_GENERATOR || - (frame->owner == FRAME_OWNED_BY_THREAD && - (_PyFrame_GetCode(frame)->co_flags & CO_COROUTINE))); + frame->owner == FRAME_OWNED_BY_LAZY_CORO); assert(PyExceptionInstance_Check(exc)); const char *msg = NULL; if (PyErr_GivenExceptionMatches(exc, PyExc_StopIteration)) {