C++: Bypassing strict-aliasing through union, then use __restrict extension

308 Views Asked by At

I wonder if it is possible to tailor strict aliasing requirements to specifically designed cases, while still preserving strict aliasing in general or -O2/-O3 optimization respectively.

To be more precise, in cases where it is needed, strict aliasing can be bypassed using an anonymous union (as pointed out here and here):

#define PTR_CAST(type, x) &(((union {typeof(*x) src; type dst;}*) &(x))->dst)

Now I wonder if using __restrict on a pointer obtained by such a cast would re-enable no-alias optimizations in the compiler (or if such a pointer and all copies of it would be considered potentially aliasing for all times). Like this:

void bar(float* __restrict a, float* __restrict b) {
   // Do something with a and b assuming they don't overlap.
}

void baz(float* c) { /* Do something with c... */ }

void foo() {
   int32_t* buffer = new int32_t[1000];
   // Do something with buffer...

   float* bufCast1 = PTR_CAST(float, buffer);
   float* bufCast2 = PTR_CAST(float, buffer + 500);

   // Can the arguments be successfully __restrict-ed in this case?
   bar(bufCast1, bufCast2);

   // Also, would bufCast1 be treated as potentially aliasing inside of baz()?
   baz(bufCast1);
}
0

There are 0 best solutions below