Functions
Functions in assembly is reasonably simple if all you need to do is modularise your code
There is no need to worry about parameter passing and return values since the code accesses the memory and
registers from anywhere.
I'm sure that there are more complex implementations of functions but I won't be considering them.
The code to demonstrate the use of functions is below
// funcitons_4.s
.global main
.extern printf
.data
output_msg:
.asciz "Result is %d.\n"
num:
.quad 0
four:
.quad 4
five:
.quad 5
two:
.quad 2
.text
main:
// prolog
stp x29, x30, [sp, -16]!
mov x29, sp
// main code
bl load_reg
bl add_five
bl mult_four
bl div_two
bl print_result
end:
// cleanup
mov x0, #0
ldp x29, x30, [sp], 16
RET
// functions
load_reg:
ldr x19, =num
ldr x19, [x19]
RET
add_five:
ldr x0, =five
ldr x0, [x0]
add x19, x19, x0
RET
mult_four:
ldr x0, =four
ldr x0, [x0]
mul x19, x19, x0
RET
div_two:
ldr x0, =two
ldr x0, [x0]
sdiv x19, x19, x0
RET
print_result:
ldr x0, =output_msg
mov x1, x19
stp x29, x30, [sp, -16]!
bl printf
ldp x29, x30, [sp], 16
RET
It is worth pointing out the code in the print_result function.
Before the code runs it stores the frame pointer and link
andrew@master:~/assm2 $ ./functions_4
Result is 10.
^C
andrew@master:~/assm2 $ nano functions_4.s
andrew@master:~/assm2 $ gcc -g functions_4.s -o functions_4
andrew@master:~/assm2 $ ./functions_4
Result is 10.
andrew@master:~/assm2 $