i wrote a code for computing factorial on C, however im trying to translate it to assembly language to work on PCspim but have no idea how?? can someone help please?
C code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void factorial(long argument, long *result) {
if(argument < 2) {
printf("%ld", *result);
} else {
long before = argument - 1;
*result = *result * before;
argument = before;
factorial(argument, result);
}
}
int main() {
long argument, answer, *result;
printf("Factorial ");
scanf("%ld", &argument);
result = &answer;
*result = argument;
printf("%ld! = ",argument);
factorial(argument, result);
}
SPIM is a MIPS interpreter, so you'll have to write those procedures in MIPS assembly... You might take a look at the output of
gcc -s <filename>
, which produces assembly representations, however I suspect it is limited to the architecture upon which you are running GCC (likely X86. X86 != MIPS).
When I had to write MIPS assembly for my Fundamentals course a few weeks ago I made heavy use of the Wikipedia article and the following website: http://en.wikibooks.org/wiki/MIPS_Assembly/Arithmetic_Instructions
I wrote a compiler that does it for fun, with a subset of C to SPIM asm syntax (of course recursion is supported)..
According to it
int f(int x)
{
if (x == 1)
return 1;
else
return (x*f(x-1));
}
int main (void) {
f(8);
}
compiles to
.data
.align 4
.align 1
.text
.globl main
main:
subu $sp, $sp, 32
sw $ra, 20($sp)
sw $fp, 16($sp)
addiu $fp, $sp, 28
li $t6, 8
move $a0, $t6
jal f
lw $ra, 20($sp)
lw $fp, 16($sp)
addu $sp, $sp, 32
jr $ra
f:
subu $sp, $sp, 36
sw $ra, 24($sp)
sw $fp, 20($sp)
addiu $fp, $sp, 32
li $t0, 1
bne $a0, $t0, equal0
li $t1, 1
b equal1
equal0:
li $t1, 0
equal1:
li $t2, 0
beq $t1, $t2, if2
li $v0, 1
lw $ra, 24($sp)
lw $fp, 20($sp)
addu $sp, $sp, 36
jr $ra
b if3
if2:
li $t3, 1
subu $t4, $a0, $t3
sw $a0, 0($sp)
move $a0, $t4
jal f
move $t5, $v0
lw $a0, 0($sp)
mulou $v0, $a0, $t5
lw $ra, 24($sp)
lw $fp, 20($sp)
addu $sp, $sp, 36
jr $ra
if3:
lw $ra, 24($sp)
lw $fp, 20($sp)
addu $sp, $sp, 36
jr $ra
Try if it works, it's not optimized at all but you can get a clue and modify it according to your needs..
Are you writing the factorial from scratch, or 'compiling' the C code? two very different approaches.
When I did some RISC coding, I found it best to pseudocode it out and implement it directly without reference to C.
If you are compiling, then each C statement needs to be expanded out to the equivalent RISC assembly.
edit: Here is some information: A page from U of Idaho 's course that uses MIPS/spim.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.