GATE / CS ARCHIVE

GATE CSE 1994 / QUESTION 23

A complete one-register translation scheme

Compiler Design · Code Generation & Register Allocation · Full GATE CSE 1994 paper

GATE 1994, Q23 5 marks · Descriptive
Not in GATE 2027 syllabusReport issue

Code Generation & Register Allocation

Question 23, GATE 1994: Generate code for A→id:=E; E→E+T | T; T→(E) | id. The target has one accumulator R and only LOAD x (R:=mem[x]), STORE x (mem[x]:=R), ADD x (R:=R+mem[x]). Provide a syntax-directed translation.
Tap to enlarge
Answer & solution

Answer: Use synthesized code/place attributes and a fresh memory temporary for each addition; assign by LOAD expression.place; STORE target. (no official key was published)

Give every E and T synthesized attributes code (an instruction list) and place (a memory address containing its value). An identifier token has its declared address id.addr. Let newtemp() allocate a fresh, non-aliasing memory cell and || concatenate instruction lists. The following bottom-up semantic rules form a complete syntax-directed definition.

T→id: T.code=[]; T.place=id.addr.
T→(E): T.code=E.code; T.place=E.place.
E→T: E.code=T.code; E.place=T.place.
E→E1+T: choose t=newtemp(); E.code=E1.code || T.code || [LOAD E1.place, ADD T.place, STORE t]; E.place=t.
A→id:=E: A.code=E.code || [LOAD E.place, STORE id.addr].

The invariant is that executing a subtree's code leaves its value in its designated memory cell. Identifier leaves already satisfy this. Parentheses and E→T preserve it. In an addition, both operands are available in memory after their code has run; LOAD fetches the left one and ADD combines the right one without needing a second register. STORE preserves the result for enclosing expressions. Fresh temporaries prevent a right subtree from overwriting the saved left value. The final assignment changes the target only after the whole expression has been evaluated, so x:=x+y also works.

For x:=a+(b+c), first emit LOAD b; ADD c; STORE t1. Then LOAD a; ADD t1; STORE t2. Finally LOAD t2; STORE x. This deliberately simple scheme may contain redundant loads/stores, but optimization is not required. It uses exactly the three allowed instruction types and handles arbitrary nesting, unlike a scheme that leaves an unprotected partial result only in R.

Original paper, page 7