Suppose
for (int i = 0; i < N; ++i) {
sum += nums[i];
}
is unrolled by the compiler to something that looks like
for (int i = 0; i < N; i += 4) {
sum1 += data[i];
sum2 += data[i+1];
sum3 += data[i+2];
sum4 += data[i+3];
}
sum = sum1 + sum2 + sum3 + sum4;
What happens if loops are unrolled beyond the bounds of when they should have been? For example, if N
is 101, then i
will at some point be 100 but indices 101, 102, 103 are past the bounds of the array.
Maybe we want to be conservative when unrolling and compute the end of the loop like normal -- but even so, where does a conservative guess for how much the loop can be unrolled come from if the number of iterations is determined at runtime?