Fake Branches
Real branches do only = and !=; fake branches do the others: <, <=, >, and >=
Here's some code using fake branches; you can paste it into MARS and assemble it:
.text
blt $10 $11 target # branch on less than; branches if $10 < $11
bgt $12 $13 target # branch on greater than; branches if $12 > $13
bge $14 $15 target # branch on greater than or equal to; branches if $14 >= $15
ble $16 $17 target # branch on less than or equal to; branches if $16 <= $17
target:
- Let's look at the first one and see how it is faked:
- blt $10 $11 target becomes 2 instructions: slt $1 $10 $11 and bne $1 $zero target
- If $10 is less than $11, the slt will put a 1 (true) into $1; otherwise, it will put 0 (false) there
- If $1 has a 1 in it, then the bne will branch since 1 != 0; if $1 has a 0, it won't branch
- In both cases, it does what we want blt to do
- bgt $12 $13 target becomes this: slt $1 $13 $12 and bne $1 $zero target
- This works because $12 > $13 is the same as $13 < $12
- bge $14 $15 target becomes this: slt $1 $14 $15 and beq $1 $zero target
- This works because $14 >= $15 is the same as $14 is not less than $15
- ble $16 $17 target becomes this: slt $1 $17 $16 and beq $1 $zero target
- This works because $16 <= $17 is the same as $16 is not greater than $17
THIS IS REALLY IMPORTANT: NEVER EVER USE $1 FOR ANYTHING!!!
Let's suppose that you were silly enough to do this anyway
- You put an important value into $1, expecting to find it there later
- The CPU executes a fake that expands to 2 or 3 real instructions
- The expansion of that fake will write something into $1
- When you try to use the value that you left in $1,
you will instead find what the fake expansion left there
- Now you have a very obscure bug
- $1 is named $at for "assembler temporary"; notice how it is used for communication between the two
real instructions that are the expansion of the fake
One more thing: USE THE FAKES; do NOT expand them by hand
This page is not here because you'll ever have to do this yourself;
it's here as a first example of how fakes are expanded;
after all, this course is all about looking under the hood.