Compile C to MIPS assembly in 7 instructions?

I just passed the final exam, and a question arose that seemed impossible given the limitations. I would be glad to be mistaken, but as far as I checked, at least all my classmates agreed with my conclusion. Here is the question and answer (s) I gave:

A program fragment of program C is provided as follows:

c = a + b + 6;
while (c > 5) {
  c = c - a;
  b = b + 1;
}

Write the equivalent in the MIPS assembly using no more than 7 instructions, using only the following set of commands:

add, addi, sub, subi, slt, slti, bne

a, b and c are available through the registers $ t0, $ t1 and $ s0, respectively. You can use other registers as needed, but you cannot accept the initial value.

Here is the answer I gave as a few lines that I could:

      add $s0, $t0, $t1
      addi $s0, $s0, 6
loop: slti $t2, $s0, 6
      bne $t2, $0, skip
      sub $s0, $s0, $t0
      addi $t1, $t1, 1
skip: subi $t2, $t2, 1
      bne $t2, $0, loop

30 3- , , . , , do-while. , beq . , :

, :

      add $s0, $t0, $t1
      addi $s0, $s0, 6
loop: sub $s0, $s0, $t0
      addi $t1, $t1, 1
      slti $t2, $s0, 6
      subi $t2, $t2, 1
      bne $t2, $0, loop

beq :

      add $s0, $t0, $t1
      addi $s0, $s0, 6
loop: slti $t2, $s0, 6
      bne $t2, $0, skip
      sub $s0, $s0, $t0
      addi $t1, $t1, 1
skip: beq $t2, $0, loop

- , , .

Update

, , , , . , , , , , , , 4.0 .

, , Verilog, , , , MIPS. , , , @Smac89:

      addi $t2, $t0, 6   # d = a + 6
      add $s0, $t2, $t1  # c = d + b
      bne $t2, $t0, comp # (d != a) ? comp
loop: sub $s0, $s0, $t0  # c = c - a;
      addi $t1, $t1, 1   # b = b + 1;
comp: slti $t2, $s0, 6   # d = (c < 6)
      subi $t2, $t2, 1   # invert the flag
      bne $t2, $0, loop  # !(c < 6) ? loop

, . , , , . slt slti bne. , , , , 7 .

.

+4
2

?

      addi $s1, $t0, 6     # d = a + 6
      add $s0, $s1, $t1    # c = d + b
loop: slti $t2, $s0, 6     # while (is c less than 6? i.e. c is not greater than 5) 
      bne $t2, $zero, exit # (c <= 5)? exit
      sub $s0, $s0, $t0    # c = c - a;
      addi $t1, $t1, 1     # b = b + 1;
      bne $s1, $t0, loop   # (True condition to loop: d != a)
exit:
+3

Smac89, , C 0, , C .

      add  $s0, $t0, $t1    # c = a + b
loop: slti $t2, $s0, 0      # while (is c less than 0? 
      bne  $t2, $zero, exit # (c > 5)
      sub  $s0, $s0, $t0    # c = c - a;
      addi $t1, $t1, 1      # b = b + 1;
      bne  $t2, $s0, loop   # Loop again unless s0 is 0 -- then we're done
exit: addi $s0, $s0, 6      # add the missing 6 
+3

All Articles