Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 28 additions & 5 deletions mypyc/irbuild/for_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@
from mypyc.primitives.list_ops import (
list_append_op,
list_get_item_int64_op,
list_get_item_or_null_op,
list_get_item_unsafe_op,
new_list_set_item_op,
new_list_set_size_op,
Expand Down Expand Up @@ -236,7 +237,9 @@ def for_loop_helper_with_index(

builder.push_loop_stack(step_block, exit_block)

if isinstance(length, Integer) and length.value > 0:
# If the sequence is known to be non-empty, skip the first condition check, unless the
# item is read as part of the condition
if isinstance(length, Integer) and length.value > 0 and not for_gen.reads_item_in_condition():
builder.goto(body_block)
builder.activate_block(condition_block)
else:
Expand Down Expand Up @@ -1247,6 +1250,12 @@ def init(
index_reg = builder.builder.int_sub(len_val, 1)
self.index_target = builder.ensure_register(index_reg)
self.target_type = target_type
# On free-threaded builds another thread could shrink a list after the length
# check, so the item read can find that the index is out of range. Stop the loop
# in that case, like the list iterator.
self.item_may_be_missing = (
is_list_rprimitive(expr_reg.type) and builder.options.target_python.free_threaded
)

def gen_condition(self) -> None:
builder = self.builder
Expand All @@ -1270,22 +1279,36 @@ def gen_condition(self) -> None:
# (unless input is immutable type).
len_reg = builder.read(self.length_reg, line)
comparison = builder.binary_op(builder.read(self.index_target, line), len_reg, "<", line)
if self.nested:
if self.reads_item_in_condition():
# In zip() or enumerate(), read the item right after the length check, as
# the sequence's iterator would. Other iterators may be advanced and other
# loop targets assigned before our begin_body(), and either could shrink
# the sequence.
# the sequence. If the item may be missing, also stop the loop here.
read_block = BasicBlock()
builder.add_bool_branch(comparison, read_block, self.loop_exit)
builder.activate_block(read_block)
self.next_reg = self.read_item()
builder.goto(self.body_block)
if self.item_may_be_missing:
builder.add(
Branch(self.next_reg, self.loop_exit, self.body_block, Branch.IS_ERROR)
)
else:
builder.goto(self.body_block)
else:
builder.add_bool_branch(comparison, self.body_block, self.loop_exit)

def reads_item_in_condition(self) -> bool:
return self.nested or self.item_may_be_missing

def read_item(self) -> Value:
builder = self.builder
line = self.line
if self.item_may_be_missing:
return builder.call_c(
list_get_item_or_null_op,
[builder.read(self.expr_target, line), builder.read(self.index_target, line)],
line,
)
return unsafe_index(
builder,
builder.read(self.expr_target, line),
Expand All @@ -1297,7 +1320,7 @@ def begin_body(self) -> None:
builder = self.builder
line = self.line
# Read the next list item, unless gen_condition() already did.
value_box = self.next_reg if self.nested else self.read_item()
value_box = self.next_reg if self.reads_item_in_condition() else self.read_item()
# We coerce to the type of list elements here so that
# iterating with tuple unpacking generates a tuple based
# unpack instead of an iterator based one.
Expand Down
11 changes: 11 additions & 0 deletions mypyc/lib-rt/CPy.h
Original file line number Diff line number Diff line change
Expand Up @@ -1050,6 +1050,17 @@ PyObject *CPyList_GetItemInt64Borrow(PyObject *list, int64_t index);
PyObject *CPyList_GetItemUInt64Borrow(PyObject *list, uint64_t index);
void CPyList_SetItemUnsafe(PyObject *list, Py_ssize_t index, PyObject *value);

// Return a new reference to list[index] for a non-negative index, or NULL without an
// exception if the index is out of range. This is used for iterating over a list on
// free-threaded builds, where another thread could shrink the list after a bounds check.
static inline PyObject *CPyList_GetItemOrNull(PyObject *list, Py_ssize_t index) {
PyObject *item = PyList_GetItemRef(list, index);
if (item == NULL) {
PyErr_Clear();
}
return item;
}

// Reduce the size of a list that is being built using CPyList_SetItemUnsafe.
// Items at or after the new size must not have been set.
static inline void CPyList_SetSizeUnsafe(PyObject *list, Py_ssize_t size) {
Expand Down
9 changes: 9 additions & 0 deletions mypyc/primitives/list_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,15 @@
error_kind=ERR_NEVER,
)

# Get list item, or NULL (without an exception) if index is out of range. Used for
# iterating over a list on free-threaded builds, where the list may shrink concurrently.
list_get_item_or_null_op = custom_op(
arg_types=[list_rprimitive, c_pyssize_t_rprimitive],
return_type=object_rprimitive,
c_function_name="CPyList_GetItemOrNull",
error_kind=ERR_NEVER,
)

# list[index] = obj
list_set_item_op = method_op(
name="__setitem__",
Expand Down
47 changes: 47 additions & 0 deletions mypyc/test-data/irbuild-lists.test
Original file line number Diff line number Diff line change
Expand Up @@ -1072,3 +1072,50 @@ L3:
L4:
a = r19
return 1

[case testListComprehensionOverListDisplay_nogil]
def f() -> list[int]:
return [x + 1 for x in [1, 2, 3]]
[out]
def f():
r0 :: list
r1, r2, r3 :: object
r4 :: ptr
r5 :: list
r6, r7 :: native_int
r8 :: bit
r9 :: object
r10, x, r11 :: int
r12 :: object
r13 :: native_int
L0:
r0 = PyList_New(3)
r1 = object 1
r2 = object 2
r3 = object 3
r4 = list_items r0
buf_init_item r4, 0, r1
buf_init_item r4, 1, r2
buf_init_item r4, 2, r3
keep_alive r0
r5 = PyList_New(3)
r6 = 0
L1:
r7 = var_object_size r0
r8 = r6 < r7 :: signed
if r8 goto L2 else goto L5 :: bool
L2:
r9 = CPyList_GetItemOrNull(r0, r6)
if is_error(r9) goto L5 else goto L3
L3:
r10 = unbox(int, r9)
x = r10
r11 = CPyTagged_Add(x, 2)
r12 = box(int, r11)
CPyList_SetItemUnsafe(r5, r6, r12)
L4:
r13 = r6 + 1
r6 = r13
goto L1
L5:
return r5
10 changes: 6 additions & 4 deletions mypyc/test-data/irbuild-statements.test
Original file line number Diff line number Diff line change
Expand Up @@ -387,18 +387,20 @@ L0:
L1:
r1 = var_object_size ls
r2 = r0 < r1 :: signed
if r2 goto L2 else goto L4 :: bool
if r2 goto L2 else goto L5 :: bool
L2:
r3 = CPyList_GetItemInt64(ls, r0)
r3 = CPyList_GetItemOrNull(ls, r0)
if is_error(r3) goto L5 else goto L3
L3:
r4 = unbox(int, r3)
x = r4
r5 = CPyTagged_Add(y, x)
y = r5
L3:
L4:
r6 = r0 + 1
r0 = r6
goto L1
L4:
L5:
return y

[case testForDictBasic]
Expand Down
18 changes: 10 additions & 8 deletions mypyc/test-data/irbuild-vec-i64.test
Original file line number Diff line number Diff line change
Expand Up @@ -365,30 +365,32 @@ L0:
L1:
r4 = var_object_size l
r5 = r3 < r4 :: signed
if r5 goto L2 else goto L7 :: bool
if r5 goto L2 else goto L8 :: bool
L2:
r6 = CPyList_GetItemInt64(l, r3)
r6 = CPyList_GetItemOrNull(l, r3)
if is_error(r6) goto L8 else goto L3
L3:
r7 = unbox(i64, r6)
x = r7
r8 = x + 1
r9 = r3 < r0 :: signed
if r9 goto L3 else goto L4 :: bool
L3:
if r9 goto L4 else goto L5 :: bool
L4:
r10 = r2.items
r11 = r3 * 8
r12 = r10 + r11
set_mem r12, r8 :: i64*
keep_alive r2
goto L5
L4:
goto L6
L5:
r13 = VecI64Api.append(r2, r8)
r2 = r13
L5:
L6:
L7:
r14 = r3 + 1
r3 = r14
goto L1
L7:
L8:
r15 = set_element r2, len, r3
r2 = r15
return r2
Expand Down
41 changes: 41 additions & 0 deletions mypyc/test-data/run-threading.test
Original file line number Diff line number Diff line change
Expand Up @@ -654,3 +654,44 @@ def test_concurrent_weakref_getter() -> None:
thread.join()
r = weakref.ref(o)
assert r() is o

[case testConcurrentListShrinkDuringIteration]
import threading

def iterate(lst: list[int], count: int, errors: list[Exception]) -> None:
try:
for _ in range(count):
n = 0
for x in lst:
n += x
for x in reversed(lst):
n += x
for i, x in enumerate(lst):
n += x
a = [x + 1 for x in lst]
except Exception as e:
errors.append(e)

def resize(lst: list[int], count: int) -> None:
for _ in range(count):
lst.extend(range(20))
for _ in range(20):
# Remove items one at a time, so that loops often see the list shrink
try:
lst.pop()
except IndexError:
pass

def test_concurrent_list_shrink_during_iteration() -> None:
# On a free-threaded build, the list can shrink after the length check in a
# loop. This should stop the loop like the list iterator, not raise IndexError.
lst: list[int] = []
errors: list[Exception] = []
count = 20_000
threads = [threading.Thread(target=iterate, args=(lst, count, errors)) for _ in range(2)]
threads += [threading.Thread(target=resize, args=(lst, count)) for _ in range(2)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
assert errors == []
Loading