Loop-Invariant Code Motion

Loop-invariant code motion moves expressions out of a loop if the expressions are not affected by the loop or the loop does not affect the expression. This optimization improves execution speed.

The following table explains how to control the optimization for loop-invariant code motion.
Table 1. Controlling loop-invariant code motion
Turn control this option from here... use this setting
CodeWarrior IDE Choose Level 3 or Level 4 in the Optimization Level settings panel.
source code #pragma opt_loop_invariants on | off | reset
command line -opt [no]loop[invariants]

For example, in the following listing, the assignment to the variable circ does not refer to the counter variable of the for loop, i. But the assignment to circ will be executed at each loop iteration.

Listing: Before loop-invariant code motion

void func_from(float* vec, int max, float val)

{

    float circ;

    int i;

    for (i = 0; i < max; ++i)

    {

        circ = val * 2 * PI;

        vec[i] = circ;

    }

}

The following listing shows source code that is equivalent to how the compiler would rearrange instructions after applying this optimization. The compiler has moved the assignment to circ outside the for loop so that it is only executed once instead of each time the for loop iterates.

Listing: After loop-invariant code motion

void func_to(float* vec, int max, float val)

{

    float circ;

    int i;

    circ = val * 2 * PI;

    for (i = 0; i < max; ++i)

    {

        vec[i] = circ;

    }

}