Optimizations such as constant propagation are possible across functions within the same compilation unit (ie. same file).
For example :
int f(int x)
{
return 3 + x;
}
int main(void)
{
printf("%d\n", 1 + f(4));
return 0;
}
In that example, I think that a sufficiently smart compiler can propagate the ‘4’ constant to the function ‘f’, solving the integer arithmetic with
the other constant ‘3’, and propagates back the result value thus folding everything to the final value ‘8’.
(Well, correct me if I’m wrong..)
However, what is happening if the function ‘f’ is in another compilation unit. Since they both units are compiled separately, the compiler can’t
optimize that way.
Does it mean that optimizations are only possible within the same compilation unit, or is there some form late optimizations performed of link-time?
Both MSVC (since 8.0: VS2005) and GCC (since 4.5) support the concept.
MSVC uses a compiler switch
/GLand linker switch/LTCG. DocumentationGCC must have it enabled and uses the
-flto,-fwhole-program,-fwhopr, and/or-combineto the same effect. Documentation (search for the options in your browser)The “problem” is that every compilation unit (source file) (and in the case of MSVC every library) needs to be compiled with this, so you can’t use old binary object files compiled without it. It also makes debugging harder, because the optimizer is a lot more aggressive and unpredictable.