in Compiler Design
5,026 views
16 votes
16 votes

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; 
}

What is the minimum number of registers needed in the instruction set architecture of the processor to compile this code segment without any spill to memory? Do not apply any optimization other than optimizing register allocation.

  1. 3
  2. 4
  3. 5
  4. 6
in Compiler Design
5.0k views

2 Comments

this is still in syllabus asked in 2017
0
0

If there are not enough registers to hold all the variables, some variables may be moved to and from RAM. This process is called "spilling" the registers. Over the lifetime of a program, a variable can be both spilled and stored in registers: this variable is then considered as "split".

0
0

3 Answers

23 votes
23 votes
Best answer

Here, we are told not to do code motion. So, we start with 3 registers

c = a + b; //a, c in register
d = c * a; //a, c, d in register
e = c + a; //a, c, e in register, d spilled. 

So, now we try with 4 registers

c = a + b; //a, c in register
d = c * a; //a, c, d in register
e = c + a; //a, c, d, e in register
x = c * c; //a, x, d, e in register
if (x > a) { 
 y = a * a; 
} 
else { 
 d = d * d; 
 e = e * e; 
} 

No spilling. So, 4 is the minimum number of registers needed for avoiding spilling. (If code motion was allowed, we need only 3 registers for avoiding spilling).

selected by
by

3 Comments

$\text{sir , why you have not considered registers(?) below the code }$

if (x > a) { 
 y = a * a; 
} 
else { 
 d = d * d; 
 e = e * e; 
} 
0
0
Thanks sir  for this wonderful explanation.
0
0

 cause it’s trivial to implement the rest with 4 registers

0
0
13 votes
13 votes

Here 4 registers are needed


 

3 votes
3 votes

BOLD lines describe Live variable just before entering the next statement 


{ a,b }
c = a + b;
{ a,c }
d = c * a;
{ a,c,d }
e = c + a;
{ a,c,d,e }
x = c * c;
{ a,d,x,e }
if (x > a)
Either IF condition passes
{ a }
{ y = a * a; }
or when IF condition fails
{ d,e }
else 
{d = d * d;
e = e * e; }

So as we can see that at max only 4 variables are live, therefore we need 4 registers to avoid register spilling.

@ sir, is this method correct?

Because everyone draws a graph and then finds its chromatic number, i don’t understand why do we need a graph?

For example, https://gateoverflow.in/78311/how-to-draw-register-allocation-interference-graph

edited by

4 Comments

Have you got the answer?
0
0
yes, i have mentioned it as 4 in the answer.
0
0

Accurate answer, just watched NPTEL lecture on it .link
but what happened to variable b after the 2nd line?

0
0
Since it has not been used ahead, therefore dead.
0
0
Answer:

Related questions