Memory aliasing
Memory aliasing, closely related (arguably synonymous) to pointer aliasing, means that more than one variable name points to the same underlying stored value.
Since a compiler decides when to (re-)fetch memory contents, this has various effects on performance, and correctness.
...including:
- if multiple threads of execution access aliased memory, this amounts to shared memory
- Without some protocol or locking, or being purely read-only, this will probably go wrong via someone or something's bad assumptions
- just how wrong further varies with compiler assumptions - see also the next point
- if everything only reads, it might be fine
- When a compiler cannot assume two things are not aliased, it must fetch values more often.
- in part because of variable reuse, and the possible case of different arguments to a function pointing to the same variable
- When a compiler can / just does assume things are not aliased, it can assume the value it has is right.
- Helps performance because of less memory access (mostly inner-loop stuff), and also because intrinsics apply more easily
- e.g.
- Fortran compilers assume lack of aliasing, though code can certainly violate it so programmers should know not to
- C does not assume a lack of aliasing (its standard says so) until you tell it to
- Note that higher-level languages often make it harder to alias memory
- C has restrict, a property on a pointer that is the programmer promising that data written via it does not need to be read by another pointer.(verify), which allows assumptions useful for vectorisation
- GPU code can also benefit. CUDA docs note that the combination of const and restrict can help.
C's aliasing rules (you'll probably have seen it referenced in compiler warnings) are mostly about situations that become ill defined, such as when casting pointers to an incompatible type (because the behaviour of dereferencing such incompatible pointers is undefined). . If you need this, consider using a union. Or perhaps look at the details of the exception case that is char *.
See also:
- https://en.wikipedia.org/wiki/Aliasing_(computing)
- https://en.wikipedia.org/wiki/Restrict
- http://dbp-consulting.com/tutorials/StrictAliasing.html
Unsorted: