0

In converting the below code to MIPS, while saving the value to memory, I don't know what should I do. In the Foo function, Zoo is called(when returning the output). Here is the full code:

int Foo(int[] n, int m)
{
    n[m] -= m;
    m++;
    return Zoo(m, n);
}
int Zoo(int m, int[] n)
{
   m++;
   return n[m];
}

This is the MIPS code, which I have written for this question.

Foo:
    addi $sp, $sp, -12
    sw $a0, 0($sp)
    sw $a1, 4($sp)
    sw $ra, 8($sp)
    
    sll $t0, $a1, 2       # 4 * m
    add $t1, $t0, $a0
    lw $t2, 0($t1)        # n[m]
    sub $t3, $t2, $a1
    sw $t3, $t1($a0)        # here is the problem
    
    addi $a1, $a1, 1
    jal Zoo
    lw $a0m 0($sp)
    lw $a1, 4($sp)
    lw $ra, 8($sp)
    addi $spm $sp, 12
    jr $ra                  # ??

Zoo:
    addi $a0, $a0, 1
    sll $t0, $a0, 2
    add $t1, $t0, $a1
    lw $t2, 0($t1)
    add $v0, $t2, $zero # ??
    jr $ra               # ??

I think there are more problems with my code. But the main question is about setting offset in sw instruction. I will be grateful for your help in how to make it correct.

Aylin Naebzadeh
  • 125
  • 2
  • 9
  • This is not a "nested function" example. `Zoo` is just an ordinary function. – MSalters Apr 08 '22 at 07:57
  • Yes, but `Foo` is nested. I edited the text a bit. Now I think it is correct.@MSalters – Aylin Naebzadeh Apr 08 '22 at 08:14
  • `Foo` isn't nested either? Both are functions at global scope. The source code looks like C, though, and Standard C doesn't even have nested functions. – MSalters Apr 08 '22 at 08:18
  • 1
    For arithmetic assignment, such as `a[i] += 10`, you have to load `a[i]` and store the result *back to the same exact place it came from*. So, store it back the same as you load it. (FYI, `$t1` is already a pointer to `a[i]`, so it makes no sense to add `a` to that, that would be `a+i+a`, wihich is nonsense.) – Erik Eidt Apr 08 '22 at 14:58
  • 1
    To answer your title question: No, the offset cannot be a register. MIPS has only one addressing mode, namely base + offset, where base is a register and offset a constant. – Erik Eidt Apr 08 '22 at 15:01
  • You'd have to `addu $a0,$a0,$t1` first. Make sure you use `addu` since pointers are unsigned. – puppydrum64 Dec 08 '22 at 18:33

0 Answers0