I've read the essay Surviving the Release Version.
Under the "Aliasing bugs" clause it says:
You can get tighter code if you tell the compiler that it can assume no aliasing....
I've also read Aliasing (computing).
What exactly is a variable alias? I understand it means using a pointer to a variable is an alias, but, how/why does it affect badly, or in other words - why telling the compiler that it can assume no aliasing would get me a "tighter code"
Aliasing is when you have two different references to the same underlying memory. Consider this made up example:
int doit(int *n1, int *n2)
{
int x = 0;
if (*n1 == 1)
{
*n2 = 0;
x += *n1 // line of interest
}
return x;
}
int main()
{
int x = 1;
doit(&x, &x); // aliasing happening
}
If the compiler has to allow for aliasing, it needs to consider the possibility that n1 == n2
. Therefore, when it needs to use the value of *n1
at "line of interest", it needs to allow for the possibility it was changed by the line *n2 = 0
.
If the compiler can assume no aliasing, it can assume at "line of interest" that *n1 == 1
(because otherwise we would not be inside the if
). The optimizer can then use this information to optimize the code (in this case, change "line of interest" from following the pointer and doing a general purpose addition to using a simple increment).
Disallowing aliasing means if you have a pointer char* b
, you can assume that b is the only pointer in the program that points to that particular memory location, which means the only time that memory location is going to change is when the programmer uses b
to change it. The generated assembly thus doesn't need to reload the memory pointed to by b
into a register as long as the compiler knows nothing has used b
to modify it. If aliasing is allowed it's possible there's another pointer char* c = b;
that was used elsewhere to mess with that memory
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With