This is the mail archive of the mailing list for the GCC project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Why does gcc generate const local array on stack?

I came across the following issue.

int foo (int N)
  const int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

  return a[N];

Compile with x86 O2

movslq %edi, %rdi
movl $0, -56(%rsp)
movl $1, -52(%rsp)
movl $2, -48(%rsp)
movl $3, -44(%rsp)
movl $4, -40(%rsp)
movl $5, -36(%rsp)
movl $6, -32(%rsp)
movl $7, -28(%rsp)
movl $8, -24(%rsp)
movl $9, -20(%rsp)
movl -56(%rsp,%rdi,4), %eax

The array is placed on stack and GCC has to generate a sequence of
instructions to
initialize the array every time the function is called.

On the contrary, LLVM moves the array to global data and doesn't need
within the function.

If I add static to the array, GCC behaves the same as LLVM, just as expected.

Is there some subtle C standard issue or some switch I didn't turned
on? I understand
if this function is recursive and pointer of the array is involved,
GCC would have to maintain
the array on stack and hence the initialization. But here the code is
very simple. I don't understand the logic of generated code, or maybe
missing optimization opportunity?

Bingfeng Mei

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]