[cfe-dev] [PATCH] Fix for bug 21725: wrong results with union and strict-aliasing

Jeroen Dobbelaere jeroen.dobbelaere at gmail.com
Tue Mar 17 15:32:07 PDT 2015


On Tue, Mar 17, 2015 at 11:15 PM, Daniel Berlin <dberlin at dberlin.org> wrote:

>
> [..]
> I don't understand what this means. How should they do that?
>
> So, his point was the arrays have no connections to the union. This is not
> the only case this occurs in.
>
> Let's take the canonical example:
>
>
> For example
>
> union foo {
> int a;
> float b;
> };
>
> int ihateunions(int *a, float *b)
> {
> <do a thing with a and b>
> }
>
> int passtounion()
> {
> union foo bar;
> ihateunions(&bar.a, &bar.b);
>
> }
>
> Inside ihateunions, you will have no idea that a and b are connected to
> unions.
>
> Let's say this example is easy, i mean, they are both at offset 0, so they
> can alias, right?
>
>
My understanding is that if you access members of a union in this way,  the
compiler is allowed
to assume that a and b do not alias.

If you access a member (or nested member) of a union, starting from the
union itself, then it depends if the other type is also accessible through
the union.


So:

int foo(union foo* a, float* b, int* c) {
  a->a=1;
  *b=2;
  // compiler must assume a->a and *b can alias
  // compiler must not assume *b and *c alias (access not through union)
}

(Also see section 3.10 of the c++03 standard; and
http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule )


Greetings,

Jeroen Dobbelaere
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20150317/d5f69759/attachment.html>


More information about the cfe-dev mailing list