If the function return type is a primitive type with its size at most 4 bytes, the result is returned in a register, as detailed below:
If the function return type is an aggregate type or a primitive type with its size greater than 4, the function is called with an additional (leftmost one), hidden argument which contains the address to which the result should be copied.
The example listed below shows how value returning works when the function return type is 'int' (primitive type, 2-byte size).
int func(int p) { return ++p; } ... void main(void) { ... x = func(0x1234); ... }
Assuming inlining has been turned off, the compiler generates the following code for the callee:
19: int func(int p) LEA S,(#-2,S) ST D2,(0,S) 21: return ++p; INC.W (0,S) LD D2,(0,S) 22: }
and the follwing code for the caller:
31: x = func(0x1234); LD D2,#4660 JSR func ST D2,x
The example listed below shows how value returning works when the function return type is a struct type.
typedef struct { int a; int b; } SomeStruct; SomeStruct s; ... SomeStruct func(int p1, int p2) { SomeStruct r; r.a = p1; r.b = p2; return r; } ... void main(void) { ... s = func(1, 2); ... }
Assuming inlining has been turned off, the compiler generates the following code for the callee:
32: SomeStruct func(int p1, int p2) LEA S,(#-11,S) ST X,(0,S) ST D2,(3,S) ST D3,(5,S) 35: r.a = p1; MOV.W (3,S),(7,S) 36: r.b = p2; LEA X,(7,S) LEA X,(2,X) LD D2,(5,S) ST D2,(0,X) 37: return r;
and the follwing code for the caller:
48: s = func3(1, 2); LD D3,#2 LD D2,#1 LD X,@s JSR func
Notice how the first (leftmost) argument to function 'func', passed in register X, is the address of global variable 's' of type 'SomeStruct'.