On Sat, May 21, 2011 at 9:07 AM, Matt Turner <matts...@gmail.com> wrote: > Hi, > > While trying to optimize pixman, I noticed that gcc is unable to > recognize that 'while (n >= 1)' can often be simplified to 'if (n >= > 1)'. Consider the following example, where there are loops that > operate on larger amounts of data and smaller loops that deal with > small or unaligned data. > > int sum(const int *l, int n) > { > int s = 0; > > while (n >= 2) { > s += l[0] + l[1]; > > l += 2; > n -= 2; > } > > while (n >= 1) { > s += l[0]; > > l += 1; > n -= 1; > } > > return s; > } > > Clearly the while (n >= 1) loop can never execute more than once, as n > must be < 2, and in the body of the loop, n is decremented. > > The resulting machine code includes the backward branch to the top of > the while (n >= 1) loop, which can never be taken. > > I suppose this is a missed optimization. Is this known, or should I > make a new bug report?
I have an old bugreport for a somewhat related problem: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=37734 It's not difficult for modify C code and replace 'while' with 'if' where appropriate. But in the end, the compilers still can perform pessimization even if given enough hints about how to generate efficient code (the result of expression used for comparison with zero, which makes it obvious that the flags already set by arithmetic instruction can be reused without emitting an extra comparison instruction). Though it's somewhat more complicated when targeting MIPS processors. -- Best regards, Siarhei Siamashka