0

I need to tranlate piece of C code

int main(){
int a, b, result;
if(a == b)
result = a*b;
else
result = assess(a, b);
return result;
}
int assess(int a, int b){
if(b<a)
return upgrade(a, b);
else
return demote(a, b);
}
int upgrade(int a, int b)
{return 4*(a+b);}
int demote(int a, int b)
{return 4*(b-a);}

a and b will be tested for a=8 b=8 a=3 b=5 a=5 b=3 here is what i tried


.text
main:
    add $s0,$s0,5
    add $s1,$s1,3
    add $s3,$s3,0
    beq $s0,$s1,Resultmul
    bne $s0,$s1,assess
    li $v0, 10
    syscall
assess:
    addi $sp,$sp,-8
    sw $s3,0($sp)
    sw $ra,4($sp)
    jal upgrade
    lw $ra,4($sp)
    add $sp,$sp,4
    jr $ra
Resultmul :
    mul $s3,$s1,$s0
    li $v0, 10
    syscall

upgrade:
    add $s3,$s0,$s1
    mul $s3,$s3,4
    jr $ra

demote:
    sub $v0,$s1,$s0
    mul $v0,$v0,4
    jr $ra

But it gets stuck in jr $ra in the assess procedure can someone fix this issue that would be great.

Teurin
  • 11
  • 2
  • 2
    Please [edit] your question. Indent your code to make it easier to read. Explain in your question what you mean with "I need to translate piece of C code". Do you use a compiler? Do you want to manually create equivalent assembler code? What exactly means "it gets stuck in `jr $ra`? Are you running the code in a debugger? What happens and what do you want to happen? The variables `a` and `b` are uninitialized, so the behavior of the code is undefined. – Bodo Apr 15 '20 at 20:00
  • Strange. I already answered such a question just today, with the exact same labels and explanation … https://stackoverflow.com/questions/61234603/mips-translating-c-code-to-mips-problem-in-function-calls-and-returns/61247347#61247347 –  Apr 16 '20 at 11:48

1 Answers1

0

You are branching to assess instead of calling it like a function via jal.  Thus, there is no proper value in $ra upon the entry to assess for it use upon completion to return to main.

You are (almost) properly saving $ra and restoring it later, but it never had a good value in the first place, so the save & restore (which will be needed) doesn't help yet.

You should pop as many bytes off the stack as you push — you're pushing 8 but popping only 4.

You are also not restoring $s3 though you do save it.

You might consider $ra as a parameter passed to a function, and inspect its value upon function entry and during function execution to see where becomes incorrect.  The value passed to the callee should be the address of the return point in the caller — a code address.

Erik Eidt
  • 23,049
  • 2
  • 29
  • 53