The following code segment is executed on a processor which allows only register operands in its instructions. Each instruction can have atmost two source operands and one destination operand. Assume that all variables are dead after this code segment.
c = a + b;
d = c * a;
e = c + a;
x = c * c;
if (x > a) {
y = a * a;
}
else {
d = d * d;
e = e * e;
} Q.48 Suppose the instruction set architecture of the processor has only two registers. The only allowed compiler optimization is code motion, which moves statements from one place to another while preserving correctness. What is the minimum number of spills to memory in the compiled code?
View worked solution
Answer: B
Using the only allowed optimization, code motion, we can move the computations of d and e into the else block because they are only used there and their operands a and c are not modified before the branch. This minimizes their live ranges.
The optimized code becomes:
c = a + b;
x = c * c;
if (x > a) {
y = a * a;
}
else {
d = c * a;
e = c + a;
d = d * d;
e = e * e;
}
Let us allocate the two available registers, and :
- Load into and into .
- Compute and store it in (since is now dead). Currently: , .
- To evaluate the condition
x > a, both and must reside in registers. Thus, we must compute and store in . - Since is still needed in the
elseblock, we must spill to memory before overwriting . This counts as 1 spill. - Now, and . We perform the comparison
x > a. - If the
elsebranch is taken, we reload from memory into (as is now dead) and complete the remaining calculations without any further spills.
Thus, the minimum number of spills to memory is 1.
Free practice · Your answers on this page are not saved.
