strict aliasing question

Howard Chu hyc@highlandsun.com
Sun Nov 12 03:57:00 GMT 2006


Ian Lance Taylor wrote:
> Howard Chu <hyc@highlandsun.com> writes:
>
>   
>> Daniel Berlin wrote:
>>     
>>> We ask the TBAA analyzer "can a store to a short * touch i.
>>> In this case, it says "no", because it's not legal.
>>>
>>>       
>> If you know the code is not legal, why don't you abort the compilation
>> with an error code?
>>     
>
> It's not actually that easy to detect the undefined cases.  Sometimes
> it's easy, sure.  But most times it is not.  The compiler does not
> normally do the sort of analysis which is required.
>   

OK, that makes sense too. Dan's statement implied that there was a 
cut-and-dry test. If the analysis has not occurred, then you obviously 
cannot know that certain statements can be ignored. You can't even know 
that they're safe to re-order.
> That said, one of my co-workers has developed a patch which detects
> most aliasing violations, based on the compiler's existing alias
> analysis.  It is able to give warnings for a wide range of cases which
> the compiler does not currently detect, for a relatively small
> increase in compilation time.  If everything works out right, we'll
> propose it for gcc 4.3.
>   

Here's a different example, which produces the weaker warning
 warning: type-punning to incomplete type might break strict-aliasing rules

struct foo;

int blah(int fd) {
        int buf[BIG_ENOUGH];
        void *v = buf;
        struct foo *f;

        f = v;
        f = (struct foo *)buf;

        init(f, fd);
        munge(f);
        flush(f);
}

"foo" is an opaque structure. We have no idea what's inside, we just 
know that it's relatively small. There are allocators available that 
will malloc them for us, but we don't want to use malloc here because 
it's too slow, so we want to reserve space for it on the stack, do a few 
things with it, then forget it.

If we go through the temporary variable v, there's no warning. If we 
don't use the temporary variable, we get the "might break" message. In 
this case, nothing in our code will ever dereference the pointer.  Why 
is there any problem here, considering that using the temporary variable 
accomplishes exactly the same thing, but requires two extra statements?

-- 
  -- Howard Chu
  Chief Architect, Symas Corp.  http://www.symas.com
  Director, Highland Sun        http://highlandsun.com/hyc
  OpenLDAP Core Team            http://www.openldap.org/project/



More information about the Gcc mailing list