[PATCH] Check if Signed Addition Overflows
suyog sarda
sardask01 at gmail.com
Mon May 19 22:54:04 PDT 2014
On Mon, May 19, 2014 at 11:52 PM, Marshall Clow <mclow.lists at gmail.com>wrote:
>
> On May 15, 2014, at 9:42 AM, suyog sarda <sardask01 at gmail.com> wrote:
>
> > Hi,
> >
> > Attaching patch for checking if Signed Addition overflows.
> > This patch implements two things :
> >
> > 1. If we know one number is positive and another is negative, we return
> true as signed addition of two opposite signed numbers will never overflow.
> >
> > 2. Implemented TODO : If one of the operands only has one non-zero bit,
> and if the other operand has a known-zero bit in a more significant place
> than it (not including the sign bit) the ripple may go up to and fill the
> zero, but won't change the sign.
> > e.x - (x & ~4) + 1
> > We make sure that we are ignoring 0 at MSB.
>
> I suspect that you are thinking too hard about this.
> a + b will overflow (both positive) if
> MAX_VALUE - a < b
>
> where MAX_VALUE is the maximum possible positive value for that type.
>
> Both negative can be handled similarly.
>
> Bonus is that this doesn't require the assumption of twos-complement
> representation.
>
This will work only if we know that both the operands are known constant.
The attached patch works for example like (X & ~4) + 1 given in TODO where
one of the operand can be variable.
>
> [ If course, if we don't have MAX_VALUE for the type, or the compiler
> can't do math on that type, then my suggestion won't work. ]
>
I am not sure if we have MAX_VALUE. In my view, if we are handling cases
where one of the operand can be variable, MAX_VALUE won't work in that case.
>
> -- Marshall
>
>
> > 3 Test case included :
> >
> > 1. To check if 0 in one number is at more significant place than 1 in
> second number. We emit 'add nsw' as we are sure there will be no overflow
> as the ripple will die at that zero.
> > 2. If 0 is at less significant place than one, then emit normal 'add' as
> we are not sure if the ripple will die before reaching Sign bit.
> > 3. IF the two numbers are of opposite sign, we emit 'add nsw' as we are
> sure that it will never overflow.
> >
> > Please help in reviewing the patch.
> >
> > --
> > With regards,
> > Suyog Sarda
> > <AddOverFlow.patch>_______________________________________________
> > llvm-commits mailing list
> > llvm-commits at cs.uiuc.edu
> > http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits
>
>
--
With regards,
Suyog Sarda
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20140520/28b8a81e/attachment.html>
More information about the llvm-commits
mailing list