optimization/7799: [3.2/3.3 regression] Loop bug with optimization flag -Os in gcc

Segher Boessenkool segher@koffie.nl
Thu Dec 19 22:52:00 GMT 2002


Christian Ehrhardt wrote:
> 
> void fill (int* p, int* q[10])
> {
>         int i;
>         for (i = 0; i < 10; i++)
>                 *q++ = &p[i];
> }
> 
> The asm-Code is this:
> 
>         pushl   %ebp
>         movl    %esp, %ebp
>         movl    8(%ebp), %eax
>         movl    12(%ebp), %edx
>         leal    36(%eax), %ecx
> .L6:
>         movl    %eax, (%edx)
>         addl    $4, %eax
>         addl    $4, %edx
>         cmpl    %ecx, %eax
>         jle     .L6
>         popl    %ebp
>         ret

[SNIP]

> This transformation is IMHO illegal because there is no way to make the
> comparison in general equivialent to that in the original for loop.
> If p is initially 0x7ffffffc the comparison must be treated as unsigned,
> however, if p is initially 0xfffffffc the comparison must be treated as
> signed.


>From C99 final draft (I wish I had the final version of the standard):

6.5.2.1.2

	A postfix expression followed by an expression in square brackets []
	is a subscripted designation of an element of an array object. ...

So  p[i]  refers to an array element.


6.2.5.19:
	... An array type describes a contiguously allocated nonempty set of
	objects with a particular member object type, called the element
	type. ...

So an array can not wrap around address 0.


6.5.6.8

	When an expression that has integer type is added to or subtracted from
	a pointer, the result has the type of the pointer operand. ...

	... If both the pointer operand and the result point to elements of the
	same array object, or one past the last element of the array object, the
	evaluation shall not produce an overflow; otherwise, the behavior is
	undefined. ...

So, if  p == 0xfffffffc  , the behaviour is undefined, as, for example,  &p[9]
doesn't point to the same array as  p  .

The comparison should always be unsigned; I don't remember the x86 ISA well
enough to know if  jle  is unsigned, but I believe so.

What am I missing / does C90 behave otherwise?


Regards,

Segher




More information about the Gcc mailing list