1
if ($t4 >= $5)
    $t8 = $t8+1

Given that pseudo-code, I put this attempt together based on various sources. Seems simple but i am still learning the foundations. Not too sure if this is correct.

slt $t1, $t5, $t4
beq $t0, $zero, endLoop
addi $8, $8, 1

Main reference: Greater than, less than equal, greater than equal in MIPS

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Mason
  • 173
  • 5
  • 23

1 Answers1

3

You have some typos:

  1. Your branch instruction is testing $t0, but the target of the slt is $t1 so that is a mismatch.
  2. You have a conditional branch instruction with a label, but don't define the label.
  3. Your label name is endLoop, but this is just an if, not a while or other loop condition, and the the statement controlled by the if isn't a break.

Otherwise looks like you have the right idea.  But this is tricky stuff to get right.

To be clear, you are aware that we have to reverse (negate re: boolean logic) the sense of the condition for assembly language's if-goto style, as compared with structured programming's if-then construct.

if (t4 >= t5)
    t8++;

becomes

  if (t4 < t5) goto skip;  //  !(a >= b)  --->  a < b
  t8++;
skip: ;

Now, I would have written the above more directly in assembly:

  slt $t1, $t4 $t5       # let's see if t4 < t5
  bne $t1, $zero, skip   # yes? goto skip
  addi $t8,$t8,1
skip:

Instead you have reversed the operands $t4 and $t5, and then also reversed the branch condition: beq vs. my bne.  This is very close to a triple negation of the (structured style) C (and this would have worked), but there is a subtle difference.

So, what you have written is:

  if (!(t5 < t4)) goto skip;
  t8++;
skip: ;

which — translated to structure programming — is:

if (t5 < t4)      // logically: remove the negation and incorporate then
    t8++;

and we can see that if we reverse the operands but also switch the relation, we have:

if (t4 > t5)      // same exact logical condition as immediately above
    t8++;

So, your code does not produce the same condition test as the C code, since the operation under equality is different from the original.

You assembly code is doing t4 > t5, and the C code is doing t4 >= t5.  See the difference?


This stuff is tricky because:

  1. We have to reverse (negate) the condition when going between structured statement and if-goto style, and,
  2. MIPS provides only one of the ordered relational operations (it has < but not <=, >, >=), and so, that means when we need what would have been sge we have to simulate it (via slt by reversing operands and/or reversing the branch on true vs. branch false).

Related:

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Erik Eidt
  • 23,049
  • 2
  • 29
  • 53