tags:

views:

754

answers:

2
+3  Q: 

strict aliasing

in C, what exactly are the performance benefits that come with observing strict aliasing?

+1  A: 

Basically the compile can optimize more aggressively with strict aliasing... see this article for more detail: http://www.cellperformance.com/mike_acton/2006/06/understanding_strict_aliasing.html

fret
+7  A: 

There is a page that describes aliasing very thoroughly here.

There are also some SO topics here and here.

To summarize, the compiler cannot assume the value of data when two pointers of different types are accessing the same location (i.e. it must read the value every time and therefore cannot make optimizations).

This only occurs when strict aliasing is not being enforced. Strict aliasing options:

  • gcc: -fstrict-aliasing [default] and -fno-strict-aliasing
  • msvc: Strict aliasing is off by default. (If somebody knows how to turn it on, please say so.)


Example

Copy-paste this code into main.c:

void f(unsigned u)
{
    unsigned short* const bad = (unsigned short*)&u;
} 

int main(void)
{
    f(5);

    return 0;
}

Then compile the code with these options:

gcc main.c -Wall -O2

And you will get:

main.c:3: warning: dereferencing type-punned pointer will break strict-aliasing rules

Disable aliasing with:

gcc main.c -fno-strict-aliasing -Wall -O2

And the warning goes away. (Or just take out -Wall but...don't compile without it)

Try as I might I could not get MSVC to give me a warning.

GMan
+1, but please make it clear that the compiler cannot make that assumption when strict aliasing is *not* observed.
j_random_hacker
Perfect! :) Unfortunate that MSVC++ doesn't seem to have an option for strict aliasing. It does have __restrict and __declspec(restrict) though, which can be used in individual cases.
j_random_hacker
Looks like a typo “-fno-strict-aliasing [default] and -fno-strict-aliasing” I'm guessing the default is actually -fstrict-aliasing (at least in modern GCC) rather than -fno-strict-aliasing, but in any case one of the two GCC options listed should be -fstrict-aliasing, and right now they both say -fno-strict-aliasing.
tialaramex
Ha, nice catch, I'm surprised nobody saw that until now.
GMan