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

流过昼夜 提交于 2019-12-11 22:05:20

问题


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);
}

来源:https://stackoverflow.com/questions/18667056/c-bypassing-strict-aliasing-through-union-then-use-restrict-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!