Int division

Simon Marlow simonmarhaskell at gmail.com
Fri Dec 14 09:23:24 EST 2007


Roman Leshchinskiy wrote:
> Simon Marlow wrote:
>> Roman Leshchinskiy wrote:
>>
>>> Hmm, I should have investigated further before posting. That's a very 
>>> Intel-specific reason, though. On the Sparc, for instance, it 
>>> wouldn't make much sense to implement divInt# in terms of quotInt#, I 
>>> think (but then again, we don't have a Sparc NCG).
>>>
>>> Anyway, I don't think it's an inliner bug because divInt# and friends 
>>> aren't marked INLINE. If nobody objects, I'll go ahead and add the 
>>> INLINE pragmas at least. We lose the opportunity to have rewrite 
>>> rules for divInt# this way, though, which is a pity.
>>
>> After inlining you'll get constant folding for quotInt#, so it should 
>> be ok, no?
> 
> Yes, but I'd also like to have the rule divInt# x# 1# = x#. With the 
> current definition of divInt#, just inlining it and having the rule
> quotInt# x# 1# = x# (which I'd like to add, too) wouldn't be quite 
> enough, I think.

It ought to be enough :)  With an extra simplification (described below), 
we could do it.

divInt# :: Int# -> Int# -> Int#
x# `divInt#` y#
     | (x# ># 0#) && (y# <# 0#) = ((x# -# 1#) `quotInt#` y#) -# 1#
     | (x# <# 0#) && (y# ># 0#) = ((x# +# 1#) `quotInt#` y#) -# 1#
     | otherwise                = x# `quotInt#` y#

so whey y# is 1#, we get

x# `divInt#` 1#
     | (x# <# 0#) = ((x# +# 1#) `quotInt#` 1#) -# 1#
     | otherwise  = x# `quotInt#` 1#

and with quotInt# x# 1# == 1#, we get

x# `divInt#` 1#
     | (x# <# 0#) = (x# +# 1#) -# 1#
     | otherwise  = x#

GHC doesn't simplify (x# +# 1#) -# 1#, but it should.  If that happened, 
we'd have

x# `divInt#` 1#
     | (x# <# 0#) = x#
     | otherwise  = x#

which simplifies to just x#, and GHC does manage this, I just tried it. 
(However if you change the conditional to (x# ==# 0#) then it doesn't 
completely eliminate the case, this looks like a bug).

Cheers,
	Simon



More information about the Cvs-ghc mailing list