Content deleted Content added
Replaced {{unreferenced}} with {{more citations needed}} and other General fixes, removed stub tag |
|||
Line 1:
{{
In [[computer programming]], '''[[loop-invariant code]]''' consists of statements or expressions (in an [[imperative programming|imperative]] [[programming language]]) which can be moved outside the body of a loop without affecting the semantics of the program. '''Loop-invariant code motion''' (also called '''hoisting''' or '''scalar promotion''') is a [[compiler optimization]] which performs this movement automatically.
==Example==
In the following code sample, two optimizations can be applied.
<syntaxhighlight lang="C">
Line 15:
</syntaxhighlight>
Although the calculation <code>x = y + z</code> and <code>x * x</code> is loop-invariant, precautions must be taken before moving the code outside the loop. It is possible that the loop condition is <code>false</code> (for example, if <code>n</code> holds a negative value), and in such case, the loop body should not be executed at all. One way of guaranteeing correct behaviour is using a conditional branch outside of the loop. Evaluating the loop condition can have [[
<syntaxhighlight lang="C">
Line 39:
==Benefits==
Loop-invariant code which has been hoisted out of a loop is executed less often, providing a speedup. Another effect of this transformation is allowing constants to be stored in registers and not having to calculate the address and access the memory (or cache line) at each iteration.
However, if too many variables are created, there will be high [[register pressure]], especially on processors with few registers, like the 32-bit [[x86]]. If the compiler runs out of registers, some variables will be [[register spilling|spilled]]. To counteract this, the inverse optimization can be performed, [[rematerialization]].
Line 48:
==Further reading==
* Aho, Alfred V.; Sethi, Ravi; & Ullman, Jeffrey D. (1986). Compilers: Principles, Techniques, and Tools. Addison Wesley. {{ISBN|0-201-10088-6}}.
==References==
{{Reflist}}
==External links==
Line 55 ⟶ 58:
[[Category:Compiler optimizations]]
|