21

Given two registers $s0, $s1, how can I convert the following pseudocode into MIPS assembly language using only the slt (set on less than) and beq and bne (branch if equal, branch if not equal) instructions.

   if ($s0 > $s1) { goto label1 }
   if ($s0 >= $s1) { goto label2 }
   if ($s0 <= $s1) { go to label3 }
jaynp
  • 3,275
  • 4
  • 30
  • 43

3 Answers3

38

I'm assuming that the pseudocode executes sequentially, so an earlier condition being true means you go there and never reach the later if statements. This makes the last branch guaranteed taken if it's reached at all, so it doesn't even need to be conditional. (Also assuming that this is a MIPS without a branch-delay slot.)

slt  $t1,$s1,$s0      # checks if $s0 > $s1
bne  $t1,$zero,label1 # if $s0 >  $s1, goes to label1
beq  $s1,$s2,label2   # if $s0 == $s2, goes to label2 
# beq  $t1,$zero,label3 # if $s0 <  $s1, goes to label3
b    label3            # only possibility left

If that's not the case, you'll want to implement $s0 >= $s1 as
!($s0 < $s1) with slt $t1, $s0, $s1 / beqz $t1, target, for example,
as shown in Ahmed's answer.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
glew
  • 410
  • 4
  • 10
  • Totally not applicable to MIPS. For one thing, MIPS does not have a flags register. Read up on it. – Seva Alekseyev Mar 04 '13 at 04:14
  • 23
    Of course it's applicable. Sure MIPS has no flag register, but that's irrelevant here. `slt` will place a value of 1 in $t1 if $s0 > $s1 – audiFanatic Sep 18 '13 at 15:10
  • 2
    `beq $t1,1, label1` should've been `bnez $t1, label1` or `bne $t1, $zero, label1`. There's no beq/bne instruction with a constant operand (other than the zero register). The assembler is probably doing some work for you here behind the scenes. – Alexey Frunze Mar 17 '19 at 09:21
4

To implement each compare separately, without optimizing across multiple compares with earlier true conditions making later ones unreachable:

slt $at, $s1, $s0           # $s0 > $s1  as ($s1 < $s0) != 0
bne $at, $zero, label1

slt $t0, $s0, $s1           # $s0 >= $s1 as (s0<s1) == 0
beq $t0, $zero, label2

slt $t1, $s1, $s0           # $s0 <= $s1 the same but reversing the inputs
beq $t1, $zero, label3

label1:
label2:
label3:

Related:

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Ahmed Ehab
  • 41
  • 1
0

just remember that x < y means y > x. so you can create set_bigger_than

  • Correct, but this point is already made in [my edit of another answer](https://stackoverflow.com/questions/15183346/greater-than-less-than-equal-greater-than-equal-in-mips/48241173#48241173), in the first comment of the code block about transforming the condition into a `<` less-than which MIPS has an instruction for. – Peter Cordes Apr 19 '23 at 05:50