[FFmpeg-devel] [PATCH 3/7] Add alias-safe union typedefs

Alexander Strange astrange
Sun Jan 31 21:56:23 CET 2010


On Jan 31, 2010, at 8:08 AM, Michael Niedermayer wrote:

> On Fri, Jan 29, 2010 at 11:06:15AM +0000, M?ns Rullg?rd wrote:
>> Michael Niedermayer <michaelni at gmx.at> writes:
>> 
>>> On Fri, Jan 29, 2010 at 02:12:10AM +0000, Mans Rullgard wrote:
>>>> ---
>>>> libavutil/intreadwrite.h |   18 ++++++++++++++++++
>>>> 1 files changed, 18 insertions(+), 0 deletions(-)
>>> 
>>> I belive these types would be usefull to projects using libavutil
>> 
>> Here we go again...
>> 
>> Those rely on the may_alias attribute being supported, which is tested
>> by configure.  I guess it could be changed to check for gcc version
>> instead, although that is less reliable with non-gcc compilers.
> 
> After looking in the c spec ..
> why do we need may_alias at all? a union should be enough or am i missing
> something?
> 
> That said, these unions only need a char array as a char access can alias
> anything. Otherwise if iam wrong they need float & double too
> 
> And with gcc a much better solution is along the lines of
> 
> #define UD(v,access)\
>    ((union {\
>        access a;\
>        typeof(v) b[sizeof(access)/sizeof(typeof(v))];\
>    }*)(v))->a
> 
> this specifies only the effective type + the accesed type and thus reduces
> the restrictions placed on the optimizer.
> It also shows how ridiculous this is as the compiler clearly knows the types
> already.

It's not legal to cast a pointer like that, so any type cast without extra attributes can't work with strict aliasing:

C99 6.3.2.3 p7:
A pointer to an object or incomplete type may be converted to a pointer to a different object or incomplete type. If the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer. When a pointer to an object is
converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.

There's no text about dereferencing a converted pointer, so it's undefined.

It's also forbidden in the gcc manual:
http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#Type_002dpunning

There's a long recent gcc thread about this here:
http://thread.gmane.org/gmane.comp.gcc.devel/111111

Casts with may_alias were found to work for x264, but the portable solution is probably either no strict aliasing or using memcpy().



More information about the ffmpeg-devel mailing list