; mallocFree.inc-
;
; Source code for memory allocation
; and free functions, based on the
; C stdlib malloc and free functions.
;
;
; Register preservation locations
; in local variables area to use
; when calling Microsoft ABI
; functions and you want to preserve
; all volatile registers

            include    aoalib.inc
	
	.code
            
saveRCX     textequ <[rbp-8]>
saveRDX     textequ <[rbp-16]>
saveR8      textequ <[rbp-24]>
saveR9      textequ <[rbp-32]>
saveR10     textequ <[rbp-40]>
saveR11     textequ <[rbp-48]>
saveXMM0    textequ <[rbp-64]>
saveXMM1    textequ <[rbp-80]>
saveXMM2    textequ <[rbp-96]>
saveXMM3    textequ <[rbp-112]>
saveXMM4    textequ <[rbp-128]>
saveXMM5    textequ <[rbp-144]>

abiEntry    macro   localsSize
            push    rbp
            mov     rbp, rsp
            sub     rsp, localsSize+144
            and     rsp, -16
            mov     saveRCX, rcx
            mov     saveRDX, rdx
            mov     saveR8, r8
            mov     saveR9, r9
            mov     saveR10, r10
            mov     saveR11, r11
            movdqu  saveXMM0, xmm0
            movdqu  saveXMM1, xmm1
            movdqu  saveXMM2, xmm2
            movdqu  saveXMM3, xmm3
            movdqu  saveXMM4, xmm4
            movdqu  saveXMM5, xmm5
            endm

abiExit     macro   
            mov     rcx,  saveRCX  
            mov     rdx,  saveRDX  
            mov     r8,   saveR8   
            mov     r9,   saveR9   
            mov     r10,  saveR10  
            mov     r11,  saveR11  
            movdqu  xmm0, saveXMM0 
            movdqu  xmm1, saveXMM1 
            movdqu  xmm2, saveXMM2 
            movdqu  xmm3, saveXMM3 
            movdqu  xmm4, saveXMM4 
            movdqu  xmm5, saveXMM5 
            leave
            endm
            
            

; mem$alloc-
;
; Passed a size in EAX. Allocates the
; specified amount of memory and returns
; a pointer to the block in RAX. Returns
; NULL (0) if there was an error.
;
; A "Wrapper" around the C malloc function
; to preserve registers (SSE only, tweak
; if you need to preserve AVX registers,
; too).

            externdef malloc:proc
mem$alloc	proc
            abiEntry 64
            
            mov        ecx, eax ;Zero extends!
            call       malloc

            abiExit
            ret
mem$alloc   endp


; malloc$free-
;
; Wrapper around C++ free function.
; On entry:
;
;  RAX contains a pointer to the block of memory
; to free.

	externdef free:proc
mem$free    proc
            push      rax        ;Preserve RAX, too!
            abiEntry  64
            
            mov       rcx, rax  ;Zero extends!
            call      free
            
            abiExit
            pop       rax
            ret
mem$free    endp

	end