C to MIPS
arithmetic expression
int f, g, h, i, j; $s0 (g + h) - (i + j)
f = (g + h) - (i + j); $s1 i + j - correct answer MIPS
add $s0, $s1, $s2 # $s0 = g + h
add $s1, $s3, $s4 # $s1 = i + j
sub $s0, $s0, $s1 # f = (g + h) - (i + j)
simple if statement:
if ( i == j ) $s1 i
i++ ; $s2 j
j-- ; - correct answer assuming $s1 stores i and $s2 stores j:
bne $s1, $s2, L1 # branch if !( i == j )
addi $s1, $s1, 1 # i++
L1: addi $s2, $s2, -1 # j--
Conditional: if-else:
if ( i == j ) $s1 i
i++ ; $s2 j
else
j-- ;
j += i ; - correct answer Once we've done the if-body, we need to jump over
the else-body
bne $s1, $s2, ELSE # branch if !( i == j )
, addi $s1, $s1, 1 # i++
j NEXT # jump over else
ELSE: addi $s2, $s2, -1 # else j--
NEXT: add $s2, $s2, $s1 # j += i
Conditional: compound condition with AND:
if ( i == j && i == k ) // if ( <cond1> && <cond2> )
i++ ; // if body
else $s1 i
j-- ; // else body $s2 j
j = i + k ; $s3 k - correct answer bne $s1, $s2, ELSE # cond1: branch if !( i == j )
bne $s1, $s3, ELSE # cond2: branch if !( i == k )
addi $s1, $s1, 1 # if-body: i++
j NEXT # jump over else
ELSE: addi $s2, $s2, -1 # else-body: j--
NEXT: add $s2, $s1, $s3 # j = i + k
Conditional: compound condition with OR:
if ( <cond1> || <cond2> )
i++ ; // if-body $s1 i
else $s2 j
j-- ; // else-body $s3 k
j = i + k ; - correct answer beq $s1, $s2, IF # cond1: branch if ( i == j )
# Notice branch on TRUE
bne $s1, $s3, ELSE # cond2: branch if ! ( i == k )
IF: addi $s1, $s1, 1 # if-body: i++
j NEXT # jump over else