Opposite keyword of “restrict” in C?

冷暖自知 提交于 2019-12-22 05:43:10

问题


Since strict aliasing may help compiler optimize better, C99 introduced the restrict keyword which can be used as a qualifier of a variable if programmers guarantee that it won't be accessed through a pointer to a different type. However, typecasting between different types is inevitable for several reasons and this will make compiler assume that one pointer is not an alias of the other. Therefore, the workaround method is to disable the global strict aliasing optimization by passing -fno-strict-aliasing (a GCC flag). This makes totally no sense because there may only have two pointers that should not be fully optimized. Hence, why not introduce an opposite keyword of restrict which tells compiler that do not assume that those two pointers point to different addresses. This is somewhat similar to what volatile does, and that tells compiler this variable is changed vastly, so treat them in a special way. Is it possible to create such keyword?

EDIT: There is a way to solve this problem. Please see yano's comment below.


回答1:


Given the code:

int foo(int * restrict p)
{
  *p = 3;
  someOutsideFunction();
  return *p;
}

a compiler is entitled to assume that as long as p is in scope, no object which is written using *p will be accessed via any means other than via pointer which is copied or otherwise "derived" from p. Other pointers to the object may exist elsewhere in the universe, but until foo returns none of them will be usable to access *p. Consequently, a compiler could replace the above with

int foo(int * restrict p)
{
  someOutsideFunction();
  *p = 3;
  return 3;
}

since it can see that no pointer copied or derived from p is ever exposed in a way that someOutsideFunction could see it, and thus no legitimate way for someOutsideFunction to access the object *p.

If someOutsideFunction could--unbeknownst to the compiler processing foo--include a keyword that behaved as the opposite of restrict, and could allow it to access the object identified by p [receiving a pointer to that object from a global variable or other such means], that would make it impossible for the compiler processing foo to know whether someOutsideFunction might access *p, and thus impossible for it to know whether it could safely apply the indicated optimization.



来源:https://stackoverflow.com/questions/39373964/opposite-keyword-of-restrict-in-c

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