-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Get emulator to correctly execute gcc -Os Fibonacci #313
Labels
Comments
Not sure what the issue is with the GCC compilation, but I wrote the Fibonacci program myself in assembly and it worked fine, for what it's worth. Reference code: static int fib(int n)
{
if (n <= 1)
return n;
return fib(n - 1) + fib(n - 2);
}
int main()
{
int n = 6;
int ans = fib(n);
return ans;
} Assembly: main:
addiu $sp, $sp, -4
sw $ra, 0($sp)
ori $a0, $zero, 6 # n = 6
jal fib
# Answer will be in $v0.
lw $ra, 0($sp)
addiu $sp, $sp, 4
syscall # End program.
fib:
addiu $sp, $sp, -20
sw $s0, 0($sp) # $s0 stores the result of fib(n - 1).
sw $s1, 4($sp) # $s1 stores the result of fib(n - 2).
sw $s2, 8($sp) # $s2 stores a copy of n.
sw $a0, 12($sp) # $a0 stores n.
sw $ra, 16($sp)
# Copy n to $s2.
or $s2, $zero, $a0
# If n <= 1 (or n < 2), return.
ori $at, $zero, 2
slt $t0, $s2, $at
bne $t0, $zero, return_base_case
# fib(n - 1)
or $a0, $zero, $s2
addiu $a0, $a0, -1
jal fib
# Save result in $s0.
or $s0, $zero, $v0
# fib(n - 2)
or $a0, $zero, $s2
addiu $a0, $a0, -2
jal fib
# Save result in $s1.
or $s1, $zero, $v0
# Add the two results together.
addu $v0, $s0, $s1
b return_fib
return_base_case:
# Copy n to the return value register.
or $v0, $zero, $s2
return_fib:
lw $ra, 16($sp)
lw $a0, 12($sp)
lw $s2, 8($sp)
lw $s1, 4($sp)
lw $s0, 0($sp)
addiu $sp, $sp, 20
jr $ra At the end of this program, |
Some relevant Stack Overflow posts you may have already seen: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The following code was partially generated with GCC using the -Os option. The return from main was replaced with a syscall to halt. Branch and load instructions were moved around as needed to undo GCC reorganization of instructions. GCC did instruction reorganization to fill the delay slots. Our emulator does not implement delay slots.
This code should result in 108 in register $2. Currently this code executes forever. There is some fishy bug that needs to be fixed.
Here's the initial GCC generated code:
Bugs to look out for:
The text was updated successfully, but these errors were encountered: