Thursday, 24 September (delayed) Exam date re-set for Thursday, 8 October Conditional instructions in MIPS Loops
In C, Lots of Relational Operators: “>”, “<”, “>=”, “<=”, “==”, “!=” We don’t need them all. For instance, “<” and “>” , “<=” and “>=” are symmetric: a < b is the same as b > a . Also, a <= b is the opposite of (the negation of) a > b , and a >= b is the negation of a < b . Similarly, “==” and “!=” are opposites.
Relational Operators in MIPS In MIPS, we have just “less than”, “equals”, and “not equals”. All the rest can be constructed from these. The “beq” instruction takes two registers and an instruction address: beq $t0,$t1,label Meaning: “If $t0 == $t1, go to label”
Relational Operators in MIPS The “bne” instruction takes two registers and an instruction address: bne $t0,$t1,label Meaning: “If $t0 != $t1, go to label”
Example C: MIPS: # Assume i = $t0, j = $t1 if (i == j) { bne $t0,$t1,skip j = j-1; subi $t1,$t1,1 } skip: ... Note how we used the “not equal” branch ( bne ) to skip around the “ j=j-1 ” code in MIPS.
Unconditional Branching MIPS has a way to go to any labeled statement unconditionally: the “ j ” instruction (for “J”ump): j label where “ label ” is a label of some other instruction.
Unconditional Branching--Example C: MIPS: # Assume a = $s0, b = $s1 if (a != b) { beq $s0, $s1, else a++; addi $s0,$s0,1 } j done else { else: addi $s1,$s1,1 done: ... b++; } We used the “j” command to skip around the “else” part.
What About “<”? “Less than” operations are slightly more complicated to implement than equality (for “==” all we need to do is compare bit patterns; for “<” we need to worry about signed numbers). As a result, the implementers of MIPS did not create “branch” instructions for “<”, “<=”, etc. (although these might exist as “pseudoinstructions” in some implementations). Instead, they split this into a two-step process: first, set a register with the results of the comparison ; second, check the contents of the register and do a “bne” or “beq” branch.
The “slt” Instruction The slt instruction stands for “set if less-than”. It takes three register arguments: slt $x, $y, $z and it does the following: TERMINOLOGY NOTE: in if $y < $z then electronics and circuit design, “set” means “set to 1”, $x = 1 “reset” means “set to 0”. So else “set if less-than” means “set $x = 0 to 1 if less-than”
The “slt” Instruction We usually use slt in combination with a beq or bne. For instance, let’s translate the following if-statement into MIPS (I’ve used register names as variables to help you understand): slt $t0,$t2,$t1 if (t1 <= t2) bne $t0,$zero,else t3++; addi $t3,$t3,1 j done else else: addi $t4,$t4,1 t4++; done: ...
For More Examples... The class shared repository has more examples. In folder “sep24” you will find: conditional.asm loop.asm fib.asm
Recommend
More recommend