Clearer and more efficient MulMayOflo
Currently the (IMHO confusingly-named) MulMayOflo machop is used by Integer multiplication to determine whether the result of a small Integer multiplication will overflow the word size. However, in order to compute whether this overflow will occur it is often necessary to perform the multiplication.
Conceptually, it seems clearer to instead have an operation like:
mulMaybe :: Int -> Int -> Maybe Int
where
-
mulMaybe x y = Just (x*y)ifx*ycertainly fits inInt, or -
mulMaybe x y = Nothingotherwise
As a machop this would be:
mulMaybe# :: r -> r -> (# Bool#, r #)
where, e.g., mulMaybe# @Int16# x y would be:
-
(# 1#, x*y #)if thex*yproduct is guaranteed not to overflowInt16# -
(# 0#, _ #)otherwise
In general, a backend may always conservatively return (# 0#, _ #).
This would allow sharing of the (often rather expensive) multiplication result and make the intended semantics of the operation a bit clearer, IMHO.
Edited by Ben Gamari