blob: 8aa62d22ac082a0a8ba7b38611d77688051572ae (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
# y86 implementation of
#
# def fibonacci(n):
# if n <= 1:
# return n
# return fibonacci(n-1) + fibonacci(n-2)
#
# run it:
# * https://www.students.cs.ubc.ca/~cs-313/simulator/?arch=y86&impl=seq
# * https://www.eecs.yorku.ca/~jonatan/simulator/?arch=y86&impl=seq
.pos 0
main:
irmovq stack, %rsp # initialize stack pointer
irmovq $13, %rdi # %rdi = n
call fib # fib(n)
halt
fib:
irmovq $2, %rsi
irmovq $1, %rdx
rrmovq %rdi, %rcx
rrmovq %rdi, %r8
subq %rsi, %rcx # %rcx = n-2
subq %rdx, %r8 # %r8 = n-1
jle base # goto base if n <= 1
recursed:
# save to stack
pushq %r8 # %r8 = n-1
# recurse
rrmovq %rcx, %rdi # %rdi = n-2
call fib # fib(n-2)
# restore from stack
popq %r8 # %r8 = n-1
# save to stack
pushq %rax # %rax = fib(n-2)
# recurse
rrmovq %r8, %rdi # %rdi = n-1
call fib # fib(n-1)
# restore from stack
popq %r10 # r10 = fib(n-2)
addq %r10, %rax # %rax = fib(n-2) + fib(n-1)
jmp end
base:
rrmovq %rdi, %rax # return n
end:
ret
.pos 0x1000
stack:
|