https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112685

--- Comment #2 from gooncreeper <goon.pri.low at gmail dot com> ---
(In reply to Andrew Pinski from comment #1)
> I thought I had saw this a while back.
> 
> Note the Linux kernel does this kind of loop explicity to avoid the division
> though as the cases where it does is known to be only a few iterations (1 or
> 2) to get the division but the compiler does not have that information. 
> 
> 
> Also I am not 100% sure this is always a win due to how slow the divide
> instruction is on many cores.

This optimization should at least be applied for constant division / modulo.

If the user knows it will only be done for a certain amount of iterations they
could do something like this:

unsigned div(unsigned a) {
    if (a > 9) return 3;
    if (a > 6) return 2;
    if (a > 3) return 1;
    return 0;
}

unsigned mod(unsigned a) {
    if (a > 9) return a - 9;
    if (a > 6) return a - 6;
    if (a > 3) return a - 3;
    return a;
}

In most cases they probably won't intend on it only being a few iterations.

Reply via email to