How c compiler processes return value of struct from function in ASM

Speaking of the return value of the C function, the return value is stored in the register EAX. Let us assume that we are talking about 32-bit register, welcome integers, but what happens when we return these types: long long, long double, a struct/ union, which is greater than 32 bits.

+4
source share
2 answers

In conventional x86 calling conventions, objects that fit in two registers are returned in RDX:RAX. This is the same pair of registers that is implicit input / output for div and mul commands, and for cdq/ cqo(the character stretches e / rax to e / rdx).

The i386 Linux calling convention (SysV) returns only 64-bit integers. Structures (even a structure consisting of one int32_t) use the method of hidden parameters instead of packing eaxor edx:eax. 64-bit Linux and the current Microsoft standard __vectorcall, both packages are structured in e/raxor e/rdx:e/rax.

, : . ABI ABI, . ( wiki).

, (, , ), , .

+5

:

struct object_t
{
  int m1;
  int m2;
  int m3;
};

struct object_t
test1(void)
{
  struct object_t o = {1, 2, 3};
  return o;
}

long long
test2(void)
{
  return 0LL;
}

long double
test3(void)
{
  return 0.0L;
}

Windows ( , x87):

$ gcc -Wall -c -O2 -mno-80387 test.c -o test.o

:

00000000 <_test1>:
   0:   8b 44 24 04             mov    eax,DWORD PTR [esp+0x4]
   4:   c7 00 01 00 00 00       mov    DWORD PTR [eax],0x1
   a:   c7 40 04 02 00 00 00    mov    DWORD PTR [eax+0x4],0x2
  11:   c7 40 08 03 00 00 00    mov    DWORD PTR [eax+0x8],0x3
  18:   c3                      ret

, , test1 .

(sizeof(long long) == 8):

00000020 <_test2>:
  20:   31 c0                   xor    eax,eax
  22:   31 d2                   xor    edx,edx
  24:   c3                      ret

eax edx, eax.

(sizeof(long double) == 12):

00000030 <_test3>:
  30:   31 c0                   xor    eax,eax
  32:   31 d2                   xor    edx,edx
  34:   31 c9                   xor    ecx,ecx
  36:   c3                      ret

, eax, edx, ecx.

+3

Source: https://habr.com/ru/post/1548370/


All Articles