Compiler optimizations questions for ghc 6.10...

Krasimir Angelov kr.angelov at gmail.com
Fri Feb 20 03:00:30 EST 2009


I think that what happens is that this function:

a `quot` b
    | b == 0                     = divZeroError
    | a == minBound && b == (-1) = overflowError
    | otherwise                  =  a `quotInt` b

is expanded to:

a `quot` b =
   if b == 0
     then divZeroError
     else if a == minBound
              then if b == (-1)
                       then overflowError
                       else a `quotInt` b
              else a `quotInt` b

Then the compiler sees that b is a constant and computes that b == 0
is False and b == (-1) is also False so it could eliminate two If
statements. The result is:

a `quot` b =
   if a == minBound
     then a `quotInt` b
     else a `quotInt` b

and this is exactly what we get. I bet that if the original function was:

a `quot` b
    | b == 0                     = divZeroError
    | b == (-1) && a == minBound = overflowError   -- Note the changed
order here
    | otherwise                  =  a `quotInt` b

then we would get what we want. I think that it is much more often to
have division where the divisor is known so we will get the best code
in this case.

Regards,
   Krasimir


On Fri, Feb 20, 2009 at 4:00 AM, Tyson Whitehead <twhitehead at gmail.com> wrote:
> On February 19, 2009 18:20:33 Krasimir Angelov wrote:
>> Oh. I looked at the primops.txt.pp for something suspicious but I
>> didn't checked the actual implementation of quot. I thought that quot
>> calls quotInt# directly. When I use quotInt in the code I can get the
>> real idiv assembly instruction. Still the code generated by GHC is
>> strange it doesn't throw any exception actually. It just evaluates the
>> same expression but with the constant maxBound.
>>
>> On Thu, Feb 19, 2009 at 11:19 PM, Max Bolingbroke
>> >    a `quot` b
>> >
>> >     | b == 0                     = divZeroError
>> >     | a == minBound && b == (-1) = overflowError
>> >     | otherwise                  =  a `quotInt` b
>
> I checked the quot one like you said.  Kind of strange all right.
>
> It looks like it is performing the a == minBound check (where a = maxBound-x)
> despite the b == (-1) check (where b = 10) being optimized away.
>
> Cheers!  -Tyson
>


More information about the Glasgow-haskell-users mailing list