Simple variadic function implementation in NASM Assembly. When implemented like I have below:
;; bits 64 default rel extern printf section .text global main global sum main: sub rsp, 40 mov r9d, 3 mov r8d, 2 mov edx, 1 mov ecx, 3 call sum lea rcx, [fmt] mov edx, eax call printf xor eax, eax add rsp, 40 ret sum: sub rsp, 24 test ecx, ecx mov qword [rsp+28H], rdx lea rdx, [rsp+28H] mov qword [rsp+30H], r8 mov qword [rsp+38H], r9 mov qword [rsp+8H], rdx jle .end lea eax, [rcx-1H] lea rcx, [rsp+rax*8+30H] xor eax, eax .recurse: add eax, dword [rdx] add rdx, 8 cmp rdx, rcx jnz .recurse add rsp, 24 ret .end: xor eax, eax add rsp, 24 ret %macro str 2 %2: db %1, 0 %endmacro section .rdata str "%d", fmt
We can change how many variables are being given to the function without having to change the amount of memory being allocated to the function itself.
main: sub rsp, 72 mov dword [rsp+30H], 6 mov dword [rsp+28H], 5 mov dword [rsp+20H], 4 mov r9d, 3 mov r8d, 2 mov edx, 1 mov ecx, 6 call sum lea rcx, [fmt] mov edx, eax call printf xor eax, eax add rsp, 72 ret
There are no comments in the code since what I'm doing should be pretty self-explanatory. Any advice and all topical comments on optimizing the code and its performance, as well as standard conventions, is appreciated!
Compiled as follows using
VS2017 x64 Native Tools Command Prompt:
> nasm -g -f win64 sum.asm > cl /Zi sum.obj msvcrt.lib legacy_stdio_definitions.lib