SPRUIG8J January 2018 – March 2024
Through the use of the MUST_ITERATE pragma, you can guarantee that a loop executes a certain number of times. The example below tells the compiler that the loop is guaranteed to run exactly 10 times:
#pragma MUST_ITERATE(10,10)
for(i = 0; i < iteration_count; i++) { ...
In this example, the compiler attempts to generate a software pipelined loop even without the pragma. However, if MUST_ITERATE is not specified for a loop such as this, the compiler generates code to bypass the loop, to account for the possibility of 0 iterations. With the pragma specification, the compiler knows that the loop iterates at least once and can eliminate the loop-bypassing code.
MUST_ITERATE can specify a range for the iteration count as well as a factor of the iteration count. The following example tells the compiler that the loop executes between 8 and 48 times and the iteration_count variable is a multiple of 8 (8, 16, 24, 32, 40, 48). The multiple argument allows the compiler to unroll the loop.
#pragma MUST_ITERATE(8, 48, 8)
for(i = 0; i < iteration_count; i++) { ...
You should consider using MUST_ITERATE for loops with complicated bounds. In the following example, the compiler would have to generate a divide function call to determine, at run time, the number of iterations performed.
for(i2 = ipos[2]; i2 < 40; i2 += 5) { ...
The compiler will not do the above. In this case, using MUST_ITERATE to specify that the loop always executes eight times allows the compiler to attempt to generate a software pipelined loop:
#pragma MUST_ITERATE(8, 8)
for(i2 = ipos[2]; i2 < 40; i2 += 5) { ...
Typically, if the MUST_ITERATE pragma is used to optimize loop execution, a DINT instruction is prepended to the optimized code, the loop code is executed, and then an RINT instruction is executed when the loop is terminated.