# ----------------------------------------------------------------------------- # A 64-bit Linux application that writes the first 25 Fibonacci numbers. # Demonstrates use of macros and saving registers. # Another way to handle registers more susceptible to being clobbered. # Prepared by Dr. Spiegel # # Assemble and Link: asm fib # ----------------------------------------------------------------------------- define(countdown,rcx) define(previous,rdx) define(current,rax) define(next,rbx) .global main .text main: push %next # we have to save this since we use it mov $25, %countdown # countdown will countdown to 0 xor %current, %current # current will hold the current number xor %next, %next # next will hold the next number inc %next # next is originally 1 print: # We need to call printf, but we are using rax, rbx, and rcx. # printf may destroy eax and countdown so we will save these before the call and # restore them afterwards. # Save clobber-susceptible registers. push %current # caller-save register push %countdown # caller-save register mov $format, %rdi # set 1st parameter (format) mov %current, %rsi # set 2nd parameter (current_number) xor %current, %current # because printf is varargs # Stack is already aligned because we pushed three 8 byte registers call printf # printf(format, current_number) # printf is done. Now, we can restore clobber-susceptible registers. pop %countdown # restore caller-save register pop %current # restore caller-save register mov %current, %previous # save the current number mov %next, %current # next number is now current add %previous, %next # get the new next number dec %countdown # count down jnz print # if not done counting, do some more pop %next # restore rbx before returning ret format: .asciz "%20ld\n"