Skip to content

Commit 896702b

Browse files
Fidget-Spinnercocolato
authored andcommitted
pythongh-134584: JIT: Borrow references for immortal promoted globals (pythonGH-142921)
JIT: Borrow references for immortal promoted globals
1 parent 7b2f00f commit 896702b

3 files changed

Lines changed: 62 additions & 4 deletions

File tree

Lib/test/test_capi/test_opt.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3077,6 +3077,44 @@ class Obj:
30773077
for _ in range(TIER2_THRESHOLD+1):
30783078
obj.attr = EvilAttr(obj.__dict__)
30793079

3080+
def test_promoted_global_refcount_eliminated(self):
3081+
result = script_helper.run_python_until_end('-c', textwrap.dedent("""
3082+
import _testinternalcapi
3083+
import opcode
3084+
import _opcode
3085+
3086+
def get_first_executor(func):
3087+
code = func.__code__
3088+
co_code = code.co_code
3089+
for i in range(0, len(co_code), 2):
3090+
try:
3091+
return _opcode.get_executor(code, i)
3092+
except ValueError:
3093+
pass
3094+
return None
3095+
3096+
def get_opnames(ex):
3097+
return {item[0] for item in ex}
3098+
3099+
3100+
def testfunc(n):
3101+
y = []
3102+
for i in range(n):
3103+
x = tuple(y)
3104+
return x
3105+
3106+
testfunc(_testinternalcapi.TIER2_THRESHOLD)
3107+
3108+
ex = get_first_executor(testfunc)
3109+
assert ex is not None
3110+
uops = get_opnames(ex)
3111+
assert "_LOAD_GLOBAL_BUILTIN" not in uops
3112+
assert "_LOAD_CONST_INLINE_BORROW" in uops
3113+
assert "_POP_TOP_NOP" in uops
3114+
assert "_POP_TOP" not in uops
3115+
"""), PYTHON_JIT="1")
3116+
self.assertEqual(result[0].rc, 0, result)
3117+
30803118
def test_constant_fold_tuple(self):
30813119
def testfunc(n):
30823120
for _ in range(n):

Python/optimizer_bytecodes.c

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1386,7 +1386,12 @@ dummy_func(void) {
13861386
res = sym_new_not_null(ctx);
13871387
}
13881388
else {
1389-
res = sym_new_const(ctx, cnst);
1389+
if (_Py_IsImmortal(cnst)) {
1390+
res = PyJitRef_Borrow(sym_new_const(ctx, cnst));
1391+
}
1392+
else {
1393+
res = sym_new_const(ctx, cnst);
1394+
}
13901395
}
13911396
}
13921397

@@ -1421,7 +1426,12 @@ dummy_func(void) {
14211426
res = sym_new_not_null(ctx);
14221427
}
14231428
else {
1424-
res = sym_new_const(ctx, cnst);
1429+
if (_Py_IsImmortal(cnst)) {
1430+
res = PyJitRef_Borrow(sym_new_const(ctx, cnst));
1431+
}
1432+
else {
1433+
res = sym_new_const(ctx, cnst);
1434+
}
14251435
}
14261436
}
14271437

Python/optimizer_cases.c.h

Lines changed: 12 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)