Loop-invariant code motion: Difference between revisions

Content deleted Content added
Really bad example this loop is entirely unnecessary.
better example; add See also section
Line 13:
 
<source lang="C">
whilefor (ji <= maximum0; -i 1< n; i++) {
x = y + z;
{
ja[i] = j6*i + (4+array[k])x*pi+5x;
}
</source>
 
The calculation ofcalculations <code>maximumx -= 1y + z</code> and <code>(4+array[k])x*pi+5x</code> can be moved outside the loop, and precalculated, resulting in something similar to:
 
<source lang="C">
int maxvalx = maximumy -+ 1z;
t1 = x*x;
int calcval = (4+array[k])*pi+5;
whilefor (ji = 0; i < maxvaln; i++) {
a[i] = 6*i + t1;
{
j += calcval;
}
</source>
 
This code can be optimized further. For example, [[strength reduction]] could remove the two multiplications inside the loop (<code>6*i</code> and <code>a[i]</code>), and [[induction variable]] elimination could then elide <code>i</code> completely.
It might then occur to us that the since the loop exit value of <code>j</code> must fall between <code> maxval - calcval</code> and <code>maxval + calcval</code>, or if not it was already beyond that range, then there is no need for the loop at all.
 
==See also==
 
* [[Loop optimization]]
* [[Compiler optimization]]
 
[[Category:Compiler optimizations]]