Why does GCC not optimise away the function prologue and epilogue (push ebp; mov ebp, esp; ...; pop ebp) [duplicate]

StackOverflow https://stackoverflow.com/questions/21620215

Domanda

When compiling a simple function that does not even alter the ebp register GCC still saves the value at the start of the function and then restores the same value at the end:

#add.c
int add( int a, int b )
{
  return ( a + b );
}

gcc -c -S -m32 -O3 add.c -o add.S

#add.S
    .file   "add.c"
    .text
    .p2align 4,,15
.globl add
    .type   add, @function
add:
    pushl   %ebp
    movl    %esp, %ebp
    movl    12(%ebp), %eax
    addl    8(%ebp), %eax
    popl    %ebp
    ret
    .size   add, .-add
    .ident  "GCC: (GNU) 4.4.6"
    .section        .note.GNU-stack,"",@progbits

It would seem like a simple optimisation to leave ebp untouched, calculate offsets relative to esp and save 3 instructions.

Why does GCC not do this?

Thanks,

Andrew

È stato utile?

Soluzione

Tools such as debuggers and stack walkers used to expect code to have a prologue that constructed a frame pointer, and couldn't understand code that didn't have it. Over time, the restriction has been removed.

The compiler itself has no difficulty generating code without a frame pointer, and you can ask for it to be removed with -fomit-frame-pointer. I believe that recent versions of gcc (~4.8) and gcc on x86-64 omit the frame pointer by default.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top