CpS 450 Language Translation Systems

Code Generation - Control Structures

if/then/else/end if

Consider the following Dream if statement:

if x < 5 then
  x = x + 1
else
  y = y + 5
end if

For each if statement, we need to generate code like this:

... code to compute value of boolean expression ...
    popl %eax
    cmpl 0, %eax
    jne _doif23
    jmp _else23
_doif23:
    ... code for statements in then part ...
    jmp _endif23
_else23:
     ... code for statements in else part ...
_endif23:
... continue with next statement ...
  • Note that the conditional instruction jne jumps to a nearby label, within architecture limitations (+/- 127 bytes).
  • We need to generate unique else/endif labels.
  • Suggest keeping
    int ifLabelCounter;
    

    instance variable in CodeGen class that keeps track of how many if statements have been created

  • Add a local variable to visitIfStmt that stores the current value of iflabel for use throughout that if statement

loop while

Consider the following Dream loop:

loop while x < 5 and y = 0
  x = x + 1
end loop

Generate code like this:

_while56:
    ... code to evaluation loop expression ...
    popl %eax
    cmpl $0, %eax
    jne _startwhilebody56
    jmp _endwhile56
_startwhilebody56:
    ... code for statements in while loop ...
    jmp _while56
    _endwhile56:
... statements after while loop ...

Like if statements, need a unique while loop counter for labels.