Skip to content

Instantly share code, notes, and snippets.

@davidad
Created April 14, 2014 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidad/10678882 to your computer and use it in GitHub Desktop.
Save davidad/10678882 to your computer and use it in GitHub Desktop.
global fib
global _fib
fib:
_fib:
cmp rdi, 1 ; set flags according to value of rdi minus one, i.e., relationship of rdi to 1
jle return_one; if the relationship is "less than or equal", goto return_one
dec rdi ; rdi = rdi - 1
push rdi ; ^ this guy is going to decrement it again, save "n-1" on the stack
call fib ; do call
pop rdi ; restore "n-1" to rdi
push rax ; save result of fib(rdi-1) onto stack
dec rdi ; rdi = rdi - 1 ( = n-2 )
call fib ; do call - we don't care about n-2 anymore after this anyway
; now rax contains fib(n-2) and fib(n-1) is on the stack
pop rdx ; now rdx contains fib(n-1)
add rax, rdx ; now rax contains fib(n-2)+fib(n-1)
ret ; that's the value we want to return, already in rax!
return_one:
mov rax, 1
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment