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
39 changes: 38 additions & 1 deletion mypyc/irbuild/ll_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@
dict_update_in_display_op,
)
from mypyc.primitives.exc_ops import err_occurred_op, keep_propagating_op
from mypyc.primitives.float_ops import copysign_op, int_to_float_op
from mypyc.primitives.float_ops import copysign_op, float_int_compare_op, int_to_float_op
from mypyc.primitives.generic_ops import (
call_fastcall_wrapper_op,
call_legacy_wrapper_op,
Expand Down Expand Up @@ -257,6 +257,19 @@
# Binary operations on bools that are specialized and don't just promote operands to int
BOOL_BINARY_OPS: Final = {"&", "&=", "|", "|=", "^", "^=", "==", "!=", "<", "<=", ">", ">="}

# Py_LT etc. values of comparison operators
py_comparison_op_ids: Final = {"<": 0, "<=": 1, "==": 2, "!=": 3, ">": 4, ">=": 5}

# Comparison operators with swapped operands (x < y is the same as y > x)
swapped_comparison_ops: Final = {
"<": ">",
"<=": ">=",
"==": "==",
"!=": "!=",
">": "<",
">=": "<=",
}


class PendingKeepAlive:
__slots__ = ("value", "scope", "seq")
Expand Down Expand Up @@ -1845,6 +1858,13 @@ def binary_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value:
return self.comparison_op(lreg, rreg, op_id, line)

if is_float_rprimitive(ltype) or is_float_rprimitive(rtype):
if op in float_comparison_op_to_id:
# Like in CPython, comparisons are exact, so an int can only be converted
# to float if this doesn't lose precision (which may require a runtime check)
if self.needs_exact_float_compare(lreg):
return self.compare_float_and_int(rreg, lreg, swapped_comparison_ops[op], line)
if self.needs_exact_float_compare(rreg):
return self.compare_float_and_int(lreg, rreg, op, line)
if isinstance(lreg, Integer):
lreg = Float(float(lreg.numeric_value()))
elif isinstance(rreg, Integer):
Expand Down Expand Up @@ -2728,6 +2748,23 @@ def float_mod(self, lhs: Value, rhs: Value, line: int) -> Value:
def compare_floats(self, lhs: Value, rhs: Value, op: int, line: int) -> Value:
return self.add(FloatComparisonOp(lhs, rhs, op, line))

def needs_exact_float_compare(self, value: Value) -> bool:
"""Is value an int that may not be exactly representable as a float?"""
if isinstance(value, Integer):
n = value.numeric_value()
return float(n) != n
return is_int_rprimitive(value.type)

def compare_float_and_int(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
"""Compare float and int exactly, like CPython."""
if isinstance(rhs, Integer):
rhs = self.load_int(rhs.numeric_value())
return self.primitive_op(
float_int_compare_op,
[lhs, rhs, Integer(py_comparison_op_ids[op], c_int_rprimitive)],
line,
)

def int_add(self, lhs: Value, rhs: Value | int) -> Value:
"""Helper to add two native integers.

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 @@ -298,6 +298,16 @@ static inline CPyTagged CPyTagged_BorrowFromObject(PyObject *object) {
}
}

// Can x be converted to a double exactly? This is true for short ints with an
// absolute value of at most 2**53 (always true on 32-bit platforms).
static inline bool CPyTagged_FitsInDouble(CPyTagged x) {
if (CPyTagged_CheckLong(x)) {
return false;
}
int64_t value = CPyTagged_ShortAsSsize_t(x);
return value >= -((int64_t)1 << 53) && value <= ((int64_t)1 << 53);
}

static inline bool CPyTagged_TooBig(Py_ssize_t value) {
// Micro-optimized for the common case where it fits.
return (size_t)value > CPY_TAGGED_MAX
Expand Down Expand Up @@ -736,6 +746,7 @@ double CPyFloat_Log(double x);
CPyTagged CPyFloat_Floor(double x);
CPyTagged CPyFloat_Ceil(double x);
double CPyFloat_FromTagged(CPyTagged x);
char CPyFloat_CompareTagged(double x, CPyTagged y, int op);
bool CPyFloat_IsInf(double x);
bool CPyFloat_IsNaN(double x);
double CPyComplex_GetPartSlow(PyObject *o, PyObject *name);
Expand Down
29 changes: 29 additions & 0 deletions mypyc/lib-rt/float_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,35 @@ double CPyFloat_FromTagged(CPyTagged x) {
return result;
}

// Compare a float and an int (op is Py_LT etc.). Like in CPython, the comparison is
// exact, so the int can only be converted to a double if this doesn't lose precision.
// Return 2 on error.
char CPyFloat_CompareTagged(double x, CPyTagged y, int op) {
if (likely(CPyTagged_FitsInDouble(y))) {
double yf = (double)CPyTagged_ShortAsSsize_t(y);
switch (op) {
case Py_LT: return x < yf;
case Py_LE: return x <= yf;
case Py_EQ: return x == yf;
case Py_NE: return x != yf;
case Py_GT: return x > yf;
default: return x >= yf;
}
}
PyObject *xo = PyFloat_FromDouble(x);
if (xo == NULL) {
return 2;
}
PyObject *yo = CPyTagged_AsObject(y);
int result = PyObject_RichCompareBool(xo, yo, op);
Py_DECREF(xo);
Py_DECREF(yo);
if (result < 0) {
return 2;
}
return result;
}

double CPyFloat_Sin(double x) {
double v = sin(x);
if (unlikely(isnan(v)) && !isnan(x)) {
Expand Down
82 changes: 52 additions & 30 deletions mypyc/lib-rt/int_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,25 @@ PyObject *CPyTagged_StealAsObject(CPyTagged x) {
return value;
}

// Like CPyTagged_AsObject, but always return an exact int object. A long tagged int
// can refer to an instance of an int subclass, since unboxing doesn't copy the object.
// The slow paths below use this so that the generic PyNumber_* and rich comparison
// APIs don't call any dunder methods overridden in the subclass, which could return
// arbitrary objects or raise exceptions that can't be propagated.
static PyObject *CPyTagged_AsExactObject(CPyTagged x) {
PyObject *value = CPyTagged_AsObject(x);
if (unlikely(!PyLong_CheckExact(value))) {
// int.__int__ returns an exact copy without calling any overrides
PyObject *copy = PyLong_Type.tp_as_number->nb_int(value);
Py_DECREF(value);
if (copy == NULL) {
CPyError_OutOfMemory();
}
value = copy;
}
return value;
}

Py_ssize_t CPyTagged_AsSsize_t(CPyTagged x) {
if (likely(CPyTagged_CheckShort(x))) {
return CPyTagged_ShortAsSsize_t(x);
Expand Down Expand Up @@ -129,7 +148,7 @@ void CPyTagged_XDecRef(CPyTagged x) {

// Tagged int negation slow path, where the result may be a long integer
CPyTagged CPyTagged_Negate_(CPyTagged num) {
PyObject *num_obj = CPyTagged_AsObject(num);
PyObject *num_obj = CPyTagged_AsExactObject(num);
PyObject *result = PyNumber_Negative(num_obj);
if (result == NULL) {
CPyError_OutOfMemory();
Expand All @@ -140,7 +159,7 @@ CPyTagged CPyTagged_Negate_(CPyTagged num) {

// Tagged int absolute value slow path, where the result may be a long integer
CPyTagged CPyTagged_Absolute_(CPyTagged num) {
PyObject *num_obj = CPyTagged_AsObject(num);
PyObject *num_obj = CPyTagged_AsExactObject(num);
PyObject *result = PyNumber_Absolute(num_obj);
if (result == NULL) {
CPyError_OutOfMemory();
Expand All @@ -151,8 +170,8 @@ CPyTagged CPyTagged_Absolute_(CPyTagged num) {

// Tagged int addition slow path, where the result may be a long integer
CPyTagged CPyTagged_Add_(CPyTagged left, CPyTagged right) {
PyObject *left_obj = CPyTagged_AsObject(left);
PyObject *right_obj = CPyTagged_AsObject(right);
PyObject *left_obj = CPyTagged_AsExactObject(left);
PyObject *right_obj = CPyTagged_AsExactObject(right);
PyObject *result = PyNumber_Add(left_obj, right_obj);
if (result == NULL) {
CPyError_OutOfMemory();
Expand All @@ -164,8 +183,8 @@ CPyTagged CPyTagged_Add_(CPyTagged left, CPyTagged right) {

// Tagged int subtraction slow path, where the result may be a long integer
CPyTagged CPyTagged_Subtract_(CPyTagged left, CPyTagged right) {
PyObject *left_obj = CPyTagged_AsObject(left);
PyObject *right_obj = CPyTagged_AsObject(right);
PyObject *left_obj = CPyTagged_AsExactObject(left);
PyObject *right_obj = CPyTagged_AsExactObject(right);
PyObject *result = PyNumber_Subtract(left_obj, right_obj);
if (result == NULL) {
CPyError_OutOfMemory();
Expand All @@ -177,8 +196,8 @@ CPyTagged CPyTagged_Subtract_(CPyTagged left, CPyTagged right) {

// Tagged int multiplication slow path, where the result may be a long integer
CPyTagged CPyTagged_Multiply_(CPyTagged left, CPyTagged right) {
PyObject *left_obj = CPyTagged_AsObject(left);
PyObject *right_obj = CPyTagged_AsObject(right);
PyObject *left_obj = CPyTagged_AsExactObject(left);
PyObject *right_obj = CPyTagged_AsExactObject(right);
PyObject *result = PyNumber_Multiply(left_obj, right_obj);
if (result == NULL) {
CPyError_OutOfMemory();
Expand All @@ -190,8 +209,8 @@ CPyTagged CPyTagged_Multiply_(CPyTagged left, CPyTagged right) {

// Tagged int // slow path, where the result may be a long integer (or raise)
CPyTagged CPyTagged_FloorDivide_(CPyTagged left, CPyTagged right) {
PyObject *left_obj = CPyTagged_AsObject(left);
PyObject *right_obj = CPyTagged_AsObject(right);
PyObject *left_obj = CPyTagged_AsExactObject(left);
PyObject *right_obj = CPyTagged_AsExactObject(right);
PyObject *result = PyNumber_FloorDivide(left_obj, right_obj);
Py_DECREF(left_obj);
Py_DECREF(right_obj);
Expand All @@ -205,8 +224,8 @@ CPyTagged CPyTagged_FloorDivide_(CPyTagged left, CPyTagged right) {

// Tagged int % slow path, where the result may be a long integer (or raise)
CPyTagged CPyTagged_Remainder_(CPyTagged left, CPyTagged right) {
PyObject *left_obj = CPyTagged_AsObject(left);
PyObject *right_obj = CPyTagged_AsObject(right);
PyObject *left_obj = CPyTagged_AsExactObject(left);
PyObject *right_obj = CPyTagged_AsExactObject(right);
PyObject *result = PyNumber_Remainder(left_obj, right_obj);
Py_DECREF(left_obj);
Py_DECREF(right_obj);
Expand All @@ -222,8 +241,8 @@ bool CPyTagged_IsEq_(CPyTagged left, CPyTagged right) {
if (CPyTagged_CheckShort(right)) {
return false;
} else {
PyObject *left_obj = CPyTagged_AsObject(left);
PyObject *right_obj = CPyTagged_AsObject(right);
PyObject *left_obj = CPyTagged_AsExactObject(left);
PyObject *right_obj = CPyTagged_AsExactObject(right);
int result = PyObject_RichCompareBool(left_obj, right_obj, Py_EQ);
Py_DECREF(left_obj);
Py_DECREF(right_obj);
Expand All @@ -235,8 +254,8 @@ bool CPyTagged_IsEq_(CPyTagged left, CPyTagged right) {
}

bool CPyTagged_IsLt_(CPyTagged left, CPyTagged right) {
PyObject *left_obj = CPyTagged_AsObject(left);
PyObject *right_obj = CPyTagged_AsObject(right);
PyObject *left_obj = CPyTagged_AsExactObject(left);
PyObject *right_obj = CPyTagged_AsExactObject(right);
int result = PyObject_RichCompareBool(left_obj, right_obj, Py_LT);
Py_DECREF(left_obj);
Py_DECREF(right_obj);
Expand Down Expand Up @@ -275,8 +294,8 @@ PyObject *CPyBool_Str(bool b) {

// Bitwise op '&', '|' or '^' using the generic (slow) API
static CPyTagged GenericBitwiseOp(CPyTagged a, CPyTagged b, char op) {
PyObject *aobj = CPyTagged_AsObject(a);
PyObject *bobj = CPyTagged_AsObject(b);
PyObject *aobj = CPyTagged_AsExactObject(a);
PyObject *bobj = CPyTagged_AsExactObject(b);
PyObject *r;
if (op == '&') {
r = PyNumber_And(aobj, bobj);
Expand Down Expand Up @@ -379,7 +398,7 @@ CPyTagged CPyTagged_BitwiseLongOp_(CPyTagged a, CPyTagged b, char op) {

// Bitwise '~' slow path
CPyTagged CPyTagged_Invert_(CPyTagged num) {
PyObject *obj = CPyTagged_AsObject(num);
PyObject *obj = CPyTagged_AsExactObject(num);
PyObject *result = PyNumber_Invert(obj);
if (unlikely(result == NULL)) {
CPyError_OutOfMemory();
Expand All @@ -391,8 +410,8 @@ CPyTagged CPyTagged_Invert_(CPyTagged num) {
// Bitwise '>>' slow path
CPyTagged CPyTagged_Rshift_(CPyTagged left, CPyTagged right) {
// Long integer or negative shift -- use generic op
PyObject *lobj = CPyTagged_AsObject(left);
PyObject *robj = CPyTagged_AsObject(right);
PyObject *lobj = CPyTagged_AsExactObject(left);
PyObject *robj = CPyTagged_AsExactObject(right);
PyObject *result = PyNumber_Rshift(lobj, robj);
Py_DECREF(lobj);
Py_DECREF(robj);
Expand All @@ -406,8 +425,8 @@ CPyTagged CPyTagged_Rshift_(CPyTagged left, CPyTagged right) {
// Bitwise '<<' slow path
CPyTagged CPyTagged_Lshift_(CPyTagged left, CPyTagged right) {
// Long integer or out of range shift -- use generic op
PyObject *lobj = CPyTagged_AsObject(left);
PyObject *robj = CPyTagged_AsObject(right);
PyObject *lobj = CPyTagged_AsExactObject(left);
PyObject *robj = CPyTagged_AsExactObject(right);
PyObject *result = PyNumber_Lshift(lobj, robj);
Py_DECREF(lobj);
Py_DECREF(robj);
Expand Down Expand Up @@ -653,21 +672,24 @@ double CPyTagged_TrueDivide(CPyTagged x, CPyTagged y) {
PyErr_SetString(PyExc_ZeroDivisionError, "division by zero");
return CPY_FLOAT_ERROR;
}
if (likely(!CPyTagged_CheckLong(x) && !CPyTagged_CheckLong(y))) {
// Dividing as doubles is only correctly rounded if both operands can be
// represented exactly as doubles (CPython uses the same fast path)
if (likely(CPyTagged_FitsInDouble(x) && CPyTagged_FitsInDouble(y))) {
return (double)((Py_ssize_t)x >> 1) / (double)((Py_ssize_t)y >> 1);
} else {
PyObject *xo = CPyTagged_AsObject(x);
PyObject *yo = CPyTagged_AsObject(y);
PyObject *xo = CPyTagged_AsExactObject(x);
PyObject *yo = CPyTagged_AsExactObject(y);
PyObject *result = PyNumber_TrueDivide(xo, yo);
Py_DECREF(xo);
Py_DECREF(yo);
if (result == NULL) {
Py_DECREF(xo);
Py_DECREF(yo);
return CPY_FLOAT_ERROR;
}
double value = PyFloat_AsDouble(result);
Py_DECREF(xo);
Py_DECREF(yo);
Py_DECREF(result);
if (unlikely(value == -1.0) && PyErr_Occurred()) {
return CPY_FLOAT_ERROR;
}
return value;
}
return 1.0;
Expand Down
10 changes: 10 additions & 0 deletions mypyc/primitives/float_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from mypyc.ir.rtypes import (
bit_rprimitive,
bool_rprimitive,
c_int_rprimitive,
float_rprimitive,
int_rprimitive,
object_rprimitive,
Expand Down Expand Up @@ -33,6 +34,15 @@
error_kind=ERR_MAGIC_OVERLAPPING,
)

# Exact comparison of float and int (the last argument is Py_LT etc.)
float_int_compare_op = custom_primitive_op(
name="float_int_compare",
arg_types=[float_rprimitive, int_rprimitive, c_int_rprimitive],
return_type=bool_rprimitive,
c_function_name="CPyFloat_CompareTagged",
error_kind=ERR_MAGIC,
)

# float(str)
function_op(
name="builtins.float",
Expand Down
Loading
Loading