Skip to content
Official PYQ · 2004

GATE CS 2004 Q10 — Local Optimization

Explain with AI

Consider the grammar rule E→E1–E2E \rightarrow E1 – E2 for arith­metic expressions. The code generated is targeted to a CPU having a single user register. The sub­traction operation requires the first operand to be in the register. If E1E1 and E2E2 do not have any com­mon sub expression, in order to get the shortest possible code

Choose one option
View worked solution

Answer: B

To find the evaluation order that produces the shortest code, let's analyze the instructions generated under a single-register (RR) constraint. The subtraction operation E1−E2E1 - E2 requires the first operand (E1E1) to be in the register RR at the time of subtraction (i.e., R←R−operandR \leftarrow R - \text{operand}).

Case 1: E1E1 is evaluated first

  1. Evaluate E1E1 into RR.
  2. Since we need RR to evaluate E2E2, we must spill E1E1 to a temporary memory location:
    Store R → T1
  3. Evaluate E2E2 into RR.
  4. Since the subtraction requires E1E1 (the first operand) to be in RR, we cannot subtract directly. We must:
    • Spill E2E2: Store R → T2
    • Load E1E1 back: Load T1 → R
    • Perform subtraction: Sub T2 from R (R←R−T2R \leftarrow R - T2)

This sequence requires 2 Store and 1 Load extra instructions.

Case 2: E2E2 is evaluated first

  1. Evaluate E2E2 into RR.
  2. Spill E2E2 to a temporary memory location to free RR:
    Store R → T1
  3. Evaluate E1E1 into RR. Now, the first operand E1E1 is already in RR.
  4. Perform subtraction directly using the spilled value of E2E2:
    Sub T1 from R (R←R−T1R \leftarrow R - T1)

This sequence requires only 1 Store extra instruction.

Thus, evaluating E2E2 first yields the shortest possible code.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Local Optimization questions