Conditional Structures

If Statements

Implementation

  1. Evaluate subexpression e1
  2. Write result to variable, t1
  3. Evaluate subexpression e2
  4. Read variable t1 into scratch register
    Result register has value of e2, scratch register has value of e1
  5. Apply operator to result and scratch registers, then use branching instructions (beq or bne) to branch to the else label if the comparison is false

Pseudocode for the implementation of an if statement:

/**
 * Generate assembly language code to implement the if statement
 * if(e1 op e2) T else E
 */
def generateCode(e1: Code, operator: Code, e2: Code, T: Code, E: Code): Code = {
    t1 = new Variable()
    elseLabel = new Label()
    endLabel = new Label()

    Scope(t1, block(
        generateCode(e1),
        write(t1, Reg(3)),
        generateCode(e2),
        read(Reg(4), t1),
        Reg(3) := Reg(4) op Reg(3)
        beq(Reg(3), Reg(0), elseLabel),
    
        T,
        beq(Reg(0), Reg(0), endLabel),
        Define(elseLabel),
        E,
        Define(endLabel),
    ))
}

While Loop

A while loop is similar to an if statement.

Implementation

Code for the implementation of a while loop:

def implWhileLoop(  
    e1: Code,  
    comp: Label => Code,  
    e2: Code,  
    body: Code,  
): Code = {  
  val bodyStart = new Label("bodyStart")  
  val bodyEnd = new Label("bodyEnd")  
  
  block(  
    beq(Reg(0), Reg(0), bodyEnd),  
    Define(bodyStart),  
    body,  
    Define(bodyEnd),  
    ifStmt(e1, comp, e2, beq(Reg(0), Reg(0), bodyStart)),  
  )
}