Common data questions
Common Data for Questions 48 and 49:
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;
}
Shared with question 49.
Question
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?
Official answer and solution
- Official answer
- B
- From
- Official GATE 2013 answer key
Solution
Apply code motion to move computations of variables that are only used conditionally into their respective branches and determine the minimum memory spills with two registers.
Consider the 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;
}
Notice that the variables d and e are only used inside the else branch. Since code motion is permitted, we can defer the computations of d and e until inside the else block:
c = a + b;
x = c * c;
if (x > a) {
y = a * a;
}
else {
d = c * a;
d = d * d;
e = c + a;
e = e * e;
}
Let us evaluate register requirements with 2 registers :
- To compute
c = a + b, registers hold and , computingc. - To compute
x = c * c, registers hold , producingx. - In the condition
if (x > a), we comparexanda. Both and must be in registers. - But notice: for the
elsebranch, variable must be preserved across the comparison to computed = c * aande = c + a! At the point ofx > a, the variables needed subsequently in theelsebranch are and , plus is needed for the test. This requires 3 active values (), while only 2 registers are available. - Therefore, at least one value (specifically ) must be spilled to memory before the branch and reloaded in the
elsebranch.
Thus, the minimum number of spills to memory is 1, which corresponds to option (B).
B
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2013 Computer Science and Information Technology (CS)
- Question
- 48 of 65, printed as CS Q.48
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.