0

c code

while (save[i]==k)
i+=1;

put i in $s3, k in $s5 and address of k in $s6

mips code

loop: sll $t1, $s3, 2
      add $t1, $t1, $s6
      lw $t0, 0($t1)
      bne $t0, $s5, Exit
      addi $s3, $s3, 1
      j loop
Exit:

1 Answers1

2

Your save array/pointer must be of some 4-byte type (ints?). Therefore to load save[i] from memory, the index i needs to be translated to a byte offset within the array, and then added to the base address of that array. This is done by multiplying i by four:

sll $t1, $s3, 2

and then adding save:

add $t1, $t1, $s6

This doesn't look like an optimized build though. Usually the compiler can re-write this code to advance a temporary pointer in increments of four directly, thus avoiding two of the instructions in that loop.

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
  • Indeed, the loop in the question is really inefficient, and could have used `lw` / `add`(pointer increment) / `bne loop_top` on a fake MIPS without branch-delay slots to at least hide some load latency, and avoid the unconditional branch. – Peter Cordes Nov 20 '21 at 00:51
  • @PeterCordes I actually don't know MIPS instruction set, but that looked unoptimized even to my eye :) – Yakov Galka Nov 20 '21 at 02:25