Skip to content
Closed
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
12 changes: 10 additions & 2 deletions mypyc/lib-rt/CPy.h
Original file line number Diff line number Diff line change
Expand Up @@ -341,8 +341,16 @@ static inline bool CPyTagged_IsSubtractOverflow(CPyTagged diff, CPyTagged left,
}

static inline bool CPyTagged_IsMultiplyOverflow(CPyTagged left, CPyTagged right) {
// This is conservative -- return false only in a small number of all non-overflow cases
return left >= (1U << (CPY_INT_BITS/2 - 1)) || right >= (1U << (CPY_INT_BITS/2 - 1));
// This is conservative -- return false only in a small number of all non-overflow cases.
// Both operands (as tagged values) have to fit in a signed integer of half the width of
// CPyTagged, so the tagged product is at most 2**(N-3) in magnitude (N is CPY_INT_BITS).
#if SIZEOF_SIZE_T == 4
return (Py_ssize_t)(int16_t)left != (Py_ssize_t)left
|| (Py_ssize_t)(int16_t)right != (Py_ssize_t)right;
#else
return (Py_ssize_t)(int32_t)left != (Py_ssize_t)left
|| (Py_ssize_t)(int32_t)right != (Py_ssize_t)right;
#endif
}

static inline bool CPyTagged_MaybeFloorDivideFault(CPyTagged left, CPyTagged right) {
Expand Down
32 changes: 32 additions & 0 deletions mypyc/test-data/run-integers.test
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,38 @@ except ZeroDivisionError:
else:
assert False, "Expected ZeroDivisionError"

[case testIntMultiplySigns]
def multiply(x: int, y: int) -> int:
return x * y

def multiply_by_constants(x: int) -> tuple[int, int, int, int, int, int, int, int]:
return (
x * 3, x * -3, -3 * x, x * (2**14 - 1), x * -(2**14), x * (2**30 - 1), x * -(2**30),
x * 2**30,
)

[file driver.py]
from native import multiply, multiply_by_constants

# Two ints are multiplied inline if both are in [-2**14, 2**14) (32-bit) or [-2**30, 2**30)
# (64-bit). Short ints are in [-2**30, 2**30) or [-2**62, 2**62).
magnitudes = (
0, 1, 3, 2**14 - 1, 2**14, 2**15, 2**29, 2**30 - 1, 2**30, 2**31 - 1, 2**31, 2**32,
2**61, 2**62 - 1, 2**62, 10**20,
)
for x in magnitudes:
for y in magnitudes:
for sx in (1, -1):
for sy in (1, -1):
assert multiply(sx * x, sy * y) == sx * x * sy * y, (sx * x, sy * y)
for x in magnitudes:
for v in (x, -x):
expected = (
v * 3, v * -3, -3 * v, v * (2**14 - 1), v * -(2**14), v * (2**30 - 1), v * -(2**30),
v * 2**30,
)
assert multiply_by_constants(v) == expected, v

[case testBigIntLiteral]
def big_int() -> None:
a_62_bit = 4611686018427387902
Expand Down
Loading