|
|
If the subroutine is not a leaf function, then its values in all or any register can be lost when it invokes another subroutine !!
But if the subroutine does not call any subroutine, it can safely use all register to store the parameters and local variable.
|
|
Example: a method that returns an int typed value
public int sum(int x, int y) { ... return (return_value); } |
|
Therefore:
|
|
/* ---------------------------------------------- sumSquares(a,b): returns (a*a + b*b) ---------------------------------------------- */ int sumSquares( int a, int b ) { return (a*a + b*b); } void main( ) { int x, y, z; z = sumSquares(x, y); } |
sumSquares assumes that all register are "free" (unused) sumSquares reserves r0 to store parameter x and r1 to store parameter y main passes the parameter x in the register r0 main passes the parameter y in the register r1 sumSquares passes the return value back in the register r0 |
/* ------------------------------------------------- Pass parameter x by copying its value in reg r0 ------------------------------------------------- */ movw r0, #:lower16:x movt r0, #:upper16:x ldr r0, [r0] /* ------------------------------------------------- Pass parameter y by copying its value in reg r1 ------------------------------------------------- */ movw r1, #:lower16:y movt r1, #:upper16:y ldr r1, [r1] /* ---------------------------------------------------------------- call z = sumSquares(x,y): agreed inputs: r0 = x, r1 = y ---------------------------------------------------------------- */ bl sumSquares // Call sumSquares /* ----------------------------------------------------------------- Agreed return location: r0 = return value Save return value (in r0) to variable z (z = sumSquares(..)) ----------------------------------------------------------------- */ movw r1, #:lower16:z // Do NOT use r0 !!! movt r1, #:upper16:z // (Because r0 contains the return value) str r0, [r1] // This will store return value in z |
/* ---------------------------------------------------------------- Function sumSquares(a,b): agreed inputs: r0 = a, r1 = b agreed return: r0 = return value ---------------------------------------------------------------- */ sumSquares: // When sumSquares begin, we will have: r0 = a, r1 = b mul r2, r0, r0 // r2 = a*a (use r0 as var a) mul r3, r1, r1 // r3 = b*b (use r1 as var b) add r0, r2, r3 // r0 = a*a + b*b // The return value is now in r0 mov pc, lr // Return to the caller |
How to run the program:
|