如何将以下代码翻译成MIPS汇编语言?
# include < stdio .h >
int fibRecursive ( int n )
{
int answer ;
if ( n < 2 ) {
answer = n ;
}
else {
answer = fibRecursive ( n - 1 ) + fibRecursive ( n - 2 ) ;
}
return answer ;
}
int main ( int argc , char * argv [] )
{
int input = 10;
int result = fibRecursive ( input ) ;
printf ( " The %d - th Fibonacci number is % d .\ n " , input , result ) ;
return 0;
}
感谢您的帮助。 我遇到了问题:
answer = fibRecursive ( n - 1 ) + fibRecursive ( n - 2 ) ;
这是我到目前为止的MIPS:
fibRecursive:
addi $sp, $sp, -4
sw $ra, 0($sp)
addi $s0, $zero, 0
slti $t0, $a0, 2
beq $t0, $zero, ELSE
add $s0, $a0, $zero
j EXIT
ELSE:
addi $sp, $sp, -4
sw $a0, 0($sp)
addi $a0, $a0, -1
jal fibRecursive
EXIT:
add $v0, $zero, $s0
答案 0 :(得分:2)
我会运行一个编译器(如GCC),其标志设置为发出汇编代码。 (例如,对于GCC,您可以使用-S选项)
答案 1 :(得分:1)
// Swapped to MIPs syntax :)
main:
jal function
...
function:
// if code here
// return value here
jal function
// gather answer into reg.
jal function
// add away
// return value here
...
在那里,您现在看到如何在main中调用两次递归函数。清理最终案例留给用户练习。
答案 2 :(得分:0)
编译为MIPS我得到了这个 .file 1“c2mips.c”
# -G value = 8, Cpu = 3000, ISA = 1
# GNU C version cygnus-2.7.2-970404 (mips-mips-ecoff) compiled by GNU C version cygnus-2.7.2-970404.
# options passed: -msoft-float
# options enabled: -fpeephole -ffunction-cse -fkeep-static-consts
# -fpcc-struct-return -fcommon -fverbose-asm -fgnu-linker -msoft-float
# -meb -mcpu=3000
gcc2_compiled.:
__gnu_compiled_c:
.text
.align 2
.globl fibRecursive
.ent fibRecursive
fibRecursive:
.frame $fp,40,$31 # vars= 8, regs= 3/0, args= 16, extra= 0
.mask 0xc0010000,-8
.fmask 0x00000000,0
subu $sp,$sp,40
sw $31,32($sp)
sw $fp,28($sp)
sw $16,24($sp)
move $fp,$sp
sw $4,40($fp)
lw $2,40($fp)
slt $3,$2,2
beq $3,$0,$L2
lw $2,40($fp)
sw $2,16($fp)
j $L3
$L2:
lw $3,40($fp)
addu $2,$3,-1
move $4,$2
jal fibRecursive
move $16,$2
lw $3,40($fp)
addu $2,$3,-2
move $4,$2
jal fibRecursive
addu $3,$16,$2
sw $3,16($fp)
$L3:
lw $3,16($fp)
move $2,$3
j $L1
$L1:
move $sp,$fp # sp not trusted here
lw $31,32($sp)
lw $fp,28($sp)
lw $16,24($sp)
addu $sp,$sp,40
j $31
.end fibRecursive
.rdata
.align 2
$LC0:
.ascii " The %d - th Fibonacci number is % d . n \000"
.text
.align 2
.globl main
.ent main
main:
.frame $fp,32,$31 # vars= 8, regs= 2/0, args= 16, extra= 0
.mask 0xc0000000,-4
.fmask 0x00000000,0
subu $sp,$sp,32
sw $31,28($sp)
sw $fp,24($sp)
move $fp,$sp
sw $4,32($fp)
sw $5,36($fp)
jal __main
li $2,10 # 0x0000000a
sw $2,16($fp)
lw $4,16($fp)
jal fibRecursive
sw $2,20($fp)
la $4,$LC0
lw $5,16($fp)
lw $6,20($fp)
jal printf
move $2,$0
j $L4
$L4:
move $sp,$fp # sp not trusted here
lw $31,28($sp)
lw $fp,24($sp)
addu $sp,$sp,32
j $31
.end main