Evaluate the fixed expression tree (a-b)+(e-(c+d)) on a load-store machine. Leaves a,b,c,d,e start in memory. Binary operations require both operands in registers and leave their result in a register; no intermediate result may be stored in memory. What is the minimum number of registers needed? The tree must be evaluated as given.
(A) 2
(B) 9
(C) 5
(D) 3
Answer & solution
Official answer: D
A leaf needs 1 register; a binary node with equally demanding children needs one more than either, otherwise it needs the larger requirement when evaluated in the favorable order. Thus a−b needs 2; c+d needs 2; e−(c+d) also needs 2; the root combining two 2-register subtrees needs 3. Three suffice by retaining one subtree result while evaluating the other in two registers. Two cannot hold one completed child while evaluating the other fixed subtree. Hence D. This evaluates the supplied tree without algebraic reassociation; rewriting the arithmetic expression into a different tree changes the problem.
A concrete three-register schedule is: load c and d into R1,R2; replace R1 by c+d; load e into R2 and replace R2 by e-R1; then load a into R1 and b into R3, replace R1 by a-b, and add R1 to R2. The two main subtrees each need two registers to combine two operands. Whichever subtree finishes first leaves one live result while the second is evaluated, forcing a third register without spilling or reassociation.
Original paper, page 10 · Answer key