This is the mail archive of the
mailing list for the GCC project.
Re: Infering that the condition of a for loop is initially true?
- From: Marc Glisse <marc dot glisse at inria dot fr>
- To: Niels Möller <nisse at lysator dot liu dot se>
- Cc: gcc at gcc dot gnu dot org
- Date: Thu, 14 Sep 2017 21:50:30 +0200 (CEST)
- Subject: Re: Infering that the condition of a for loop is initially true?
- Authentication-results: sourceware.org; auth=none
- References: <email@example.com>
- Reply-to: gcc at gcc dot gnu dot org
On Thu, 14 Sep 2017, Niels Möller wrote:
This is more of a question than a bug report, so I'm trying to send it
to the list rather than filing a bugzilla issue.
I think it's quite common to write for- and while-loops where the
condition is always initially true. A simple example might be
double average (const double *a, size_t n)
assert (n > 0);
for (i = 0, sum = 0; i < n; i++)
sum += a[i];
return sum / n;
The programmer could do the microptimization to rewrite it as a
do-while-loop instead. It would be nice if gcc could infer that the
condition is initially true, and convert to a do-while loop
Converting to a do-while-loop should produce slightly better code,
omitting the typical jump to enter the loop at the end where the
condition is checked. It would also make analysis of where variables are
written more accurate, which is my main concern at the moment.
assert is not what you want, since it completely disappears with -DNDEBUG.
clang has __builtin_assume, with gcc you want a test and
__builtin_unreachable. Replacing your assert with
gcc does skip the first test of the loop, as can be seen in the dump
produced with -fdump-tree-optimized.