This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Why this loop is not optimised out?
- From: Ian Lance Taylor <iant at google dot com>
- To: jgojgo <chairmanguo at gmail dot com>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Thu, 06 Oct 2011 16:59:49 -0700
- Subject: Re: Why this loop is not optimised out?
- References: <32602004.post@talk.nabble.com>
jgojgo <chairmanguo@gmail.com> writes:
> I've got a very simple c program which copies all elements from array A to
> back to array A. For example,
>
> int *A;
> A = (int*)malloc(sizeof(int)*SIZE);
> for( i = 0; i < SIZE; i++) {
> A[i] = A[i];
> }
> I was expecting this to be optimised out by the compiler and eventually
> turned into a noop. However, by measuring the runtime of this loop and
> looking at the assembly code, it seems that the element is indeed loaded
> from memory into register and then stored back to the same memory location.
> I have -O3 enabled. Can anyone explain to me why the c compiler does not
> optimise it? Or am I missing something here?
You neglected to mention which version of the compiler you tested.
I turned your fragment into a real program:
extern void *malloc (long unsigned int);
#define SIZE 100
void f()
{
int *A;
int i;
A = (int*)malloc(sizeof(int)*SIZE);
for( i = 0; i < SIZE; i++) {
A[i] = A[i];
}
}
I compiled it with -O2 using current mainline sources. The entire loop
was eliminated and the function turned into a no-op.
Ian