Strict aliasing in D
Peter Alexander
peter.alexander.au at gmail.com
Sun Jan 29 08:25:32 PST 2012
On Sunday, 29 January 2012 at 14:05:25 UTC, Daniel Murphy wrote:
> "Denis Shelomovskij" <verylonglogin.reg at gmail.com> wrote in
> message news:jg3f21$1jqa$1 at digitalmars.com...
>> It was originally posted to D.learn but there was no reply. So:
>>
>> Is there a strict aliasing rule in D?
>>
>> I just saw
>> https://bitbucket.org/goshawk/gdc/changeset/b44331053062
>
> Struct aliasing is required when doing array operations.
>
> eg.
> int[] a, b, c;
> a[] = b[] + c[];
>
> The arrays used must not overlap.
> I'm pretty sure that's what that commit was about.
That's not strict aliasing, that's just a language rule about
aliasing for vector ops.
Strict aliasing is the assumption that no two pointers of
different types point to the same location (char is an
exception). For example, with -fstrict-aliasing in gcc, the
following could generate unexpected code:
int* i = new int;
float* f = (float*)i;
*i = 0;
*f = 1.0f;
printf("%d\n", *i); // could still write 0
Because of strict aliasing, the compiler may assume that the
assignment *f = 1.0f can't affect the int, so it could just print
out 0 instead of whatever 1.0f is as an int. To get around it,
you would have to either use a union (which is still
implementation defined, but works around aliasing), or make i
volatile.
As for D, I can't see anything in the standard that prevents two
pointers of different types from pointing to the same location,
but I suspect it is an assumption that is being made.
More information about the Digitalmars-d
mailing list