Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-91049: Introduce set vectorcall field API for PyFunctionObject #92257

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
9cf96ec
Enable setting vectorcall field on PyFunctionObjects
May 3, 2022
282e3dc
check if vectorcall is nondefault before inlining call
May 3, 2022
edcdcf1
📜🤖 Added by blurb_it.
blurb-it[bot] May 3, 2022
debf5a9
Apply suggestions from code review
adphrost May 3, 2022
473d18d
addressed comments
May 3, 2022
76e8c9d
added to docs
May 3, 2022
3337459
Merge branch 'main' into pyfunctionobject-set-vectorcall-field
Jun 16, 2022
1543f44
updated doc with fix by itamaro
Jun 16, 2022
08082bd
formatting
Jun 16, 2022
ed93327
removed doc from 3.11
Jun 16, 2022
24ffd30
remove lines from 3.11
Jun 16, 2022
89cb4b2
Apply review feedback from vstinner and markshannon
itamaro Jun 21, 2022
3387d4a
Merge branch 'main' into gh-91049-set-vectorcall
itamaro Sep 2, 2022
b0cc28a
Merge branch 'main' into gh-91049-set-vectorcall
itamaro Sep 5, 2022
99e4085
Add deopt on func version in LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN
itamaro Sep 6, 2022
24353c8
write func version to cache keys version when specializing LOAD_ATTR_…
itamaro Sep 6, 2022
60f7769
remove redundant argcount check in LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN …
itamaro Sep 6, 2022
376ee75
Add missing periods in docs
itamaro Sep 6, 2022
56ffc70
move warning comment to the function C API docs
itamaro Sep 6, 2022
5340e87
Merge branch 'main' into pyfunctionobject-set-vectorcall-field
itamaro Sep 6, 2022
a5e9d13
fix race with GH-96519 (removed func_version in LOAD_ATTR_GETATTRIBUT…
itamaro Sep 6, 2022
12faf52
PEP-7 formatting
itamaro Sep 7, 2022
6623470
Address review feedback
itamaro Sep 7, 2022
9149f14
Add test for LOAD_ATTR specialization when overriding vectorcall of _…
itamaro Sep 8, 2022
e732d7e
Improve setvectorcall + specialization testing
itamaro Sep 8, 2022
84874fb
Merge branch 'main' into pyfunctionobject-set-vectorcall-field
itamaro Sep 15, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions Doc/c-api/function.rst
Expand Up @@ -83,6 +83,15 @@ There are a few functions specific to Python functions.
Raises :exc:`SystemError` and returns ``-1`` on failure.


.. c:function:: void PyFunction_SetVectorcall(PyFunctionObject *func, vectorcallfunc vectorcall)

Set the vectorcall field of a given function object *func*.

Warning: extensions using this API must preserve the behavior
of the unaltered (default) vectorcall function!

.. versionadded:: 3.12

.. c:function:: PyObject* PyFunction_GetClosure(PyObject *op)

Return the closure associated with the function object *op*. This can be ``NULL``
Expand Down
4 changes: 4 additions & 0 deletions Doc/whatsnew/3.12.rst
Expand Up @@ -493,6 +493,10 @@ New Features
functions in all running threads in addition to the calling one. (Contributed
by Pablo Galindo in :gh:`93503`.)

* Added new function :c:func:`PyFunction_SetVectorcall` to the C API
which sets the vectorcall field of a given :c:type:`PyFunctionObject`.
(Contributed by Andrew Frost in :gh:`92257`.)

Porting to Python 3.12
----------------------

Expand Down
4 changes: 3 additions & 1 deletion Include/cpython/funcobject.h
Expand Up @@ -48,7 +48,8 @@ typedef struct {
* defaults
* kwdefaults (only if the object changes, not the contents of the dict)
* code
* annotations */
* annotations
* vectorcall function pointer */
uint32_t func_version;

/* Invariant:
Expand All @@ -69,6 +70,7 @@ PyAPI_FUNC(PyObject *) PyFunction_GetGlobals(PyObject *);
PyAPI_FUNC(PyObject *) PyFunction_GetModule(PyObject *);
PyAPI_FUNC(PyObject *) PyFunction_GetDefaults(PyObject *);
PyAPI_FUNC(int) PyFunction_SetDefaults(PyObject *, PyObject *);
PyAPI_FUNC(void) PyFunction_SetVectorcall(PyFunctionObject *, vectorcallfunc);
PyAPI_FUNC(PyObject *) PyFunction_GetKwDefaults(PyObject *);
PyAPI_FUNC(int) PyFunction_SetKwDefaults(PyObject *, PyObject *);
PyAPI_FUNC(PyObject *) PyFunction_GetClosure(PyObject *);
Expand Down
51 changes: 51 additions & 0 deletions Lib/test/test_call.py
Expand Up @@ -580,6 +580,9 @@ def testfunction_kw(self, *, kw):
return self


QUICKENING_WARMUP_DELAY = 8


class TestPEP590(unittest.TestCase):

def test_method_descriptor_flag(self):
Expand Down Expand Up @@ -760,6 +763,54 @@ def __call__(self, *args):
self.assertEqual(expected, meth(*args1, **kwargs))
self.assertEqual(expected, wrapped(*args, **kwargs))

def test_setvectorcall(self):
from _testcapi import function_setvectorcall
def f(num): return num + 1
assert_equal = self.assertEqual
num = 10
assert_equal(11, f(num))
function_setvectorcall(f)
# make sure specializer is triggered by running > 50 times
for _ in range(10 * QUICKENING_WARMUP_DELAY):
assert_equal("overridden", f(num))

def test_setvectorcall_load_attr_specialization_skip(self):
from _testcapi import function_setvectorcall

class X:
def __getattribute__(self, attr):
return attr

assert_equal = self.assertEqual
x = X()
assert_equal("a", x.a)
function_setvectorcall(X.__getattribute__)
# make sure specialization doesn't trigger
# when vectorcall is overridden
for _ in range(QUICKENING_WARMUP_DELAY):
assert_equal("overridden", x.a)

def test_setvectorcall_load_attr_specialization_deopt(self):
from _testcapi import function_setvectorcall

class X:
def __getattribute__(self, attr):
return attr

def get_a(x):
return x.a

assert_equal = self.assertEqual
x = X()
# trigger LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN specialization
for _ in range(QUICKENING_WARMUP_DELAY):
assert_equal("a", get_a(x))
function_setvectorcall(X.__getattribute__)
# make sure specialized LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN
# gets deopted due to overridden vectorcall
for _ in range(QUICKENING_WARMUP_DELAY):
assert_equal("overridden", get_a(x))

@requires_limited_api
def test_vectorcall_limited(self):
from _testcapi import pyobject_vectorcall
Expand Down
@@ -0,0 +1,5 @@
Add new function :c:func:`PyFunction_SetVectorcall` to the C API
which sets the vectorcall field of a given :c:type:`PyFunctionObject`.

Warning: extensions using this API must preserve the behavior
of the unaltered function!
19 changes: 19 additions & 0 deletions Modules/_testcapi/vectorcall.c
Expand Up @@ -102,6 +102,24 @@ test_pyobject_vectorcall(PyObject *self, PyObject *args)
return PyObject_Vectorcall(func, stack, nargs, kwnames);
}

static PyObject *
override_vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf,
PyObject *kwnames)
{
return PyUnicode_FromString("overridden");
}

static PyObject *
function_setvectorcall(PyObject *self, PyObject *func)
{
if (!PyFunction_Check(func)) {
PyErr_SetString(PyExc_TypeError, "'func' must be a function");
return NULL;
}
PyFunction_SetVectorcall((PyFunctionObject *)func, (vectorcallfunc)override_vectorcall);
Py_RETURN_NONE;
}

static PyObject *
test_pyvectorcall_call(PyObject *self, PyObject *args)
{
Expand Down Expand Up @@ -244,6 +262,7 @@ static PyMethodDef TestMethods[] = {
{"pyobject_fastcall", test_pyobject_fastcall, METH_VARARGS},
{"pyobject_fastcalldict", test_pyobject_fastcalldict, METH_VARARGS},
{"pyobject_vectorcall", test_pyobject_vectorcall, METH_VARARGS},
{"function_setvectorcall", function_setvectorcall, METH_O},
{"pyvectorcall_call", test_pyvectorcall_call, METH_VARARGS},
_TESTCAPI_MAKE_VECTORCALL_CLASS_METHODDEF
_TESTCAPI_HAS_VECTORCALL_FLAG_METHODDEF
Expand Down
11 changes: 11 additions & 0 deletions Objects/funcobject.c
Expand Up @@ -134,6 +134,9 @@ uint32_t _PyFunction_GetVersionForCurrentState(PyFunctionObject *func)
if (func->func_version != 0) {
return func->func_version;
}
if (func->vectorcall != _PyFunction_Vectorcall) {
return 0;
markshannon marked this conversation as resolved.
Show resolved Hide resolved
}
if (next_func_version == 0) {
return 0;
}
Expand Down Expand Up @@ -209,6 +212,14 @@ PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
return 0;
}

void
PyFunction_SetVectorcall(PyFunctionObject *func, vectorcallfunc vectorcall)
{
assert(func != NULL);
func->func_version = 0;
erlend-aasland marked this conversation as resolved.
Show resolved Hide resolved
func->vectorcall = vectorcall;
}

PyObject *
PyFunction_GetKwDefaults(PyObject *op)
{
Expand Down
10 changes: 8 additions & 2 deletions Python/ceval.c
Expand Up @@ -3126,8 +3126,11 @@ _PyEval_EvalFrameDefault(PyThreadState *tstate, _PyInterpreterFrame *frame, int
PyObject *getattribute = read_obj(cache->descr);
assert(Py_IS_TYPE(getattribute, &PyFunction_Type));
PyFunctionObject *f = (PyFunctionObject *)getattribute;
uint32_t func_version = read_u32(cache->keys_version);
assert(func_version != 0);
DEOPT_IF(f->func_version != func_version, LOAD_ATTR);
erlend-aasland marked this conversation as resolved.
Show resolved Hide resolved
PyCodeObject *code = (PyCodeObject *)f->func_code;
DEOPT_IF(((PyCodeObject *)f->func_code)->co_argcount != 2, LOAD_ATTR);
assert(code->co_argcount == 2);
DEOPT_IF(!_PyThreadState_HasStackSpace(tstate, code->co_framesize), CALL);
STAT_INC(LOAD_ATTR, hit);

Expand Down Expand Up @@ -4133,7 +4136,10 @@ _PyEval_EvalFrameDefault(PyThreadState *tstate, _PyInterpreterFrame *frame, int
function = PEEK(total_args + 1);
int positional_args = total_args - KWNAMES_LEN();
// Check if the call can be inlined or not
if (Py_TYPE(function) == &PyFunction_Type && tstate->interp->eval_frame == NULL) {
if (Py_TYPE(function) == &PyFunction_Type &&
tstate->interp->eval_frame == NULL &&
((PyFunctionObject *)function)->vectorcall == _PyFunction_Vectorcall)
{
int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(function))->co_flags;
PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(function));
STACK_SHRINK(total_args);
Expand Down
5 changes: 5 additions & 0 deletions Python/specialize.c
Expand Up @@ -837,6 +837,11 @@ _Py_Specialize_LoadAttr(PyObject *owner, _Py_CODEUNIT *instr, PyObject *name)
if (!function_check_args(descr, 2, LOAD_ATTR)) {
goto fail;
}
uint32_t version = function_get_version(descr, LOAD_ATTR);
if (version == 0) {
goto fail;
}
write_u32(lm_cache->keys_version, version);
/* borrowed */
write_obj(lm_cache->descr, descr);
write_u32(lm_cache->type_version, type->tp_version_tag);
Expand Down