petdance/scratch — Issue #305: Look into GCC -flto and -fwhole-program link options
Author: petdance
Created: 2011-11-01 05:41:58+00:00
State: open
Labels: experimental, Pri-normal, Sev-medium

-flto is link-time optimization.
-fwhole-program is optimization for the entire program.

From http://lwn.net/Articles/387122/

When source files are compiled and linked using -flto, GCC applies optimizations as if all the source code were in a single file. This allows GCC to perform more aggressive optimizations across files, such as inlining the body of a function from one file that is called from a different file, and propagating constants across files. In general, the LTO framework enables all the usual optimizations that work at a higher level than a single function to also work across files that are independently compiled.

The LTO option works almost like any other optimization flag. First, one needs to use optimization (using one of the -O{1,2,3,s} options). In cases where compilation and linking are done in a single step, adding the option -flto is sufficient

gcc -o myprog -flto -O2 foo.c bar.c

This effectively deprecates the old -combine option, which was too slow in practice and only supported for C.

With independent compilation steps, the option -flto must be specified at all steps of the process:

gcc -c -O2 -flto foo.c

gcc -c -O2 -flto bar.c

gcc -o myprog -flto -O2 foo.o bar.o

An interesting possibility is to combine the options -flto and -fwhole-program. The latter assumes that the current compilation unit represents the whole program being compiled. This means that most functions and variables are optimized more aggressively. Adding -fwhole-program in the final link step in the example above, makes LTO even more powerful.

When using multiple steps, it is strongly recommended to use exactly the same optimization and machine-dependent options in all commands, because conflicting options during compilation and link-time may lead to strange errors. In the best case, the options used during compilation will be silently overridden by those used at link-time. In the worst case, the different options may introduce subtle inconsistencies leading to unpredictable results at runtime. This, of course, is far from ideal, and, hence, in the next minor release, GCC will identify such conflicting options and provide appropriate diagnostics. Meanwhile, some extra care should be taken when using LTO.

Originally http://trac.parrot.org/parrot/ticket/1691