gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

ASM > question about function calling

#25551 - Darmstadium - Tue Aug 24, 2004 11:39 pm

I'm trying to write a function is ASM and then call it using C code. I can call the function with no problems, but once i have i seem to have some problems. I know that in my ASM function I should back-up the values in registers 4-7 before using them. i try to push them on the stack like this:
Code:

mov r12,sp

stmfd sp!,{r4}
stmfd sp!,{r5}
stmfd sp!,{r6}
stmfd sp!,{r7}

the top line stores the address of the first of my arguments that were pushed on the stack when the function was called. now i try to access them like so:
Code:

ldmfd r12!,{r4}
ldmfd r12!,{r5}
ldmfd r12!,{r6}
ldmfd r12!,{r7}

Does the above code put the first argument in r4 and the second one in r5 and so on?
now i do all the fun stuff that my function does and am ready to return to the C code. First I have to restore the values of r4-r7 to what they were when my asm function was called. i try to do that like this:
Code:

ldmfd sp!,{r7}
ldmfd sp!,{r6}
ldmfd sp!,{r5}
ldmfd sp!,{r4}

Have i done this correctly? i seem to have a problem when running my c code after my asm function is done executing.
Thanks for your help!

#25552 - poslundc - Tue Aug 24, 2004 11:48 pm

Nothing jumps out as being incorrect about what you're doing. But make sure you realize that the first four parameters passed to your function are not on the stack, but are passed into registers r0-r3.

You're also wasting cycles by not performing your stores/loads in a single instruction. Instead of going one at a time, do the following:

Code:
stmfd sp!, {r4-r7}
@ etc.
ldmfd r12!, {r4-r7}
@ etc.
ldmfd sp!, {r4-r7}


Also realize that in addition to r4-r7 you are expected to preserve r8, r9, r10, r11 and r14 across your function call.

Dan.

#25554 - Darmstadium - Wed Aug 25, 2004 12:06 am

thanks for your speedy response! its good to know that you can load and store a lotta registers at once. i'm sure i'm doing it right, but could you check out my new code for me?:
Code:

mov r12,sp

stmfd sp!,{r4-r11}
stmfd sp!,{r14}

ldmfd r12!,{r4-r7}

ldmfd sp!,{r14}
ldmfd sp!,{r11-r4}

#25555 - poslundc - Wed Aug 25, 2004 12:12 am

Your code is correct, but again, there is a more concise and more efficient notation. ;)

Code:
stmfd sp!, {r4-r11, r14}
ldmfd sp!, {r4-r11, r14}


Dan.