Compilation Optimization Guide Joshua Saddler This guide provides an introduction to optimizing compiled code using safe, sane CFLAGS and CXXFLAGS. It also as describes the theory behind optimizing in general. 1.0 2007-06-03 Introduction
What are CFLAGS and CXXFLAGS?

CFLAGS and CXXFLAGS are environment variables that are used to tell the GNU Compiler Collection, gcc, what kinds of switches to use when compiling source code. CFLAGS are for code written in C, while CXXFLAGS are for code written in C++.

They can be used to decrease the amount of debug messages for a program, increase error warning levels, and, of course, to optimize the code produced. The GNU gcc handbook maintains a complete list of available options and their purposes.

How are they used?

CFLAGS and CXXFLAGS can be used in two ways. First, they can be used per-program, by directly invoking gcc and then some bit of code you wish to compile.

$ CFLAGS="-march=i686" gcc file.c

However, this should not be done when installing packages found in the Portage tree. Instead, set your CFLAGS and CXXFLAGS in /etc/make.conf. This way all packages will be compiled using the options you specify.

CFLAGS="-march=athlon64 -O2 -pipe"
CXXFLAGS="${CFLAGS}"

As you can see, CXXFLAGS is set to use all the options present in CFLAGS. This is what you'll want almost without fail. You shouldn't ever need to specify additional options in CXXFLAGS.

Portage cannot use CFLAGS on a per-package basis, nor is there any supported method of forcing it to do so. The flags you set in /etc/make.conf will be used for all packages you install.
Misconceptions

While CFLAGS and CXXFLAGS can be very effective means of getting source code to produce smaller and/or faster binaries, they can also impair the function of your code, bloat its size, slow down its execution time, or even cause compilation failures!

CFLAGS are not a magic bullet; they will not automatically make your system run any faster or your binaries to take up less space on disk. Adding more and more flags in an attempt to optimize (or "rice") your system is a sure recipe for failure. There is a point at which you will reach diminishing returns.

Despite the bragging you'll find on the internet, aggressive CFLAGS and CXXFLAGS are far more likely to harm your programs than do them any good. Keep in mind that the reason the flags exist in the first place is because they are designed to be used at specific places for specific purposes. Just because one particular CFLAG is good for one bit of code doesn't mean that it is suited to compiling everything you will ever install on your machine!

Ready?

Now that you're aware of some of the risks involved, let's take a look at some sane, safe optimizations for your computer. These will hold you in good stead and will endear you to developers the next time you report a problem on Bugzilla. (Developers will usually request that you recompile a package with minimal CFLAGS to see if the problem persists. Remember, aggressive flags can ruin code.)

Optimizing
The basics

The goal behind using CFLAGS and CXXFLAGS is to create code tailor-made to your system; it should function perfectly while being lean and fast, if possible. Sometimes these conditions are mutually exclusive, so we'll stick with combinations known to work well. Ideally, they are the best available for any CPU architecture. We'll mention the aggressive flags later so you know what to look out for. We won't discuss every option listed on the gcc manual (there are hundreds), but we'll cover the basic, most common flags.

Whenever you're not sure what a flag actually does, refer to the relevant chapter of the gcc manual. If you're still stumped, try Google, or check out the gcc mailing lists.
-march

The first and most important option is -march. This tells the compiler what code it should produce for your processor architecture (or arch); it says that it should produce code for a certain kind of CPU. Different CPUs have different capabilities, support different instruction sets, and have different ways of executing code. The -march flag will instruct the compiler to produce code specifically for your CPU, with all its capabilities, features, instruction sets, quirks, and so on.

Even though the CHOST variable in /etc/make.conf specifies the general architecture used, -march should still be used so that programs can be optimized for your specific processor.

What kind of CPU do you have? To find out, run the following command:

$ cat /proc/cpuinfo

Now let's see -march in action. This example is for an older Pentium III chip:

CFLAGS="-march=pentium3"
CXXFLAGS="${CFLAGS}"

Here's another one for a 64-bit Sparc CPU:

CFLAGS="-march=ultrasparc"
CXXFLAGS="${CFLAGS}"

Also available are the -mcpu and -mtune flags. Either of these should only be used when there is no available -march option. What's the difference between them? -march is much more specific about which processor features will be used when compiling code; it is a better choice. -mcpu will produce much more generic code less optimized for your machine. -mtune is even more generic than -mcpu. Whenever possible, use -march. For some less common architectures such as PowerPC and Alpha, -mcpu must be used.

For more suggested -march settings, please read chapter 5 of the appropriate Gentoo Installation Handbook for your arch. Also, read the gcc manual's list of architecture-specific options, as well as more detailed explanations about the differences between -march, -mcpu, and -mtune. This is quite helpful for determining which -march setting you should use, especially since on some architectures, such as x86, -mcpu is deprecated and -mtune should be used instead.
-O

Next up is the -O variable. This controls the overall level of optimization. This makes the code compilation take somewhat more time, and can take up much more memory, especially as you increase the level of optimization.

There are five -O settings: -O0, -O1, -O2, -O3, and -Os. You should use only one of them in /etc/make.conf.

The with the exception of -O0, the -O settings each activate several additional flags, so be sure to read the gcc manual's chapter on optimization options to learn which flags are activated at each -O level, as well as some explanations as to what they do.

Let's examine each optimization level:

  • -O0: This level (that's the letter "O" followed by a zero) turns off optimization entirely and is the default if no -O level is specified in CFLAGS or CXXFLAGS. Your code will not be optimized; it's not normally desired.
  • -O1: This is the most basic optimization level. The compiler will try to produce faster, smaller code without taking much compilation time. It's pretty basic, but it should get the job done all the time.
  • -O2: A step up from -O1. This is the recommended level of optimization unless you have special needs (such as -Os, as will be explained shortly). -O2 will activate a few more flags in addition to the ones activated by -O1. With -O2, the compiler will attempt to increase code performance without compromising on size, and without taking too much compilation time.
  • -O3: This is the highest level of optimization possible, and also the riskiest. It will take a longer time to compile your code with this option, and in fact it should not be used system-wide with gcc 4.x. The behavior of gcc has changed significantly since version 3.x. In 3.x, -O3 has been shown to lead to marginally faster execution times over -O2, but this is no longer the case with gcc 4.x. Compiling all your packages with -O3 will result in larger binaries that require more memory, and will significantly increase the odds of compilation failure or unexpected program behavior (including errors). The downsides outweigh the benefits; remember the principle of diminishing returns. Using -O3 is not recommended for gcc 4.x.
  • -Os: This level will optimize your code for size. It activates all -O2 options that don't increase the size of the generated code. It's useful for machines that have extremely limited disk storage space and/or have CPUs with small cache sizes.

As previously mentioned, -O2 is the recommended optimization level. If package compilations error out, check to make sure that you aren't using -O3. As a fallback option, try setting your CFLAGS and CXXFLAGS to a lower optimization level, such as -O1 or -Os and recompile the package.

-pipe

A fun, safe flag to use is -pipe. This flag actually has no effect on the generated code, but it makes the compilation process faster. It tells the compiler to use pipes instead of temporary files during the different stages of compilation.

-fomit-frame-pointer

This is a very common flag designed to reduce generated code size. It is turned on at all levels of -O (except -O0) on architectures where doing so does not interfere with debugging, but you may need to activate it yourself by adding it to your flags. Though the GNU gcc manual fails to specify all architectures it is turned on by using -O, you will need to explicity activate it on x86 and x86-64. However, using this flag will make debugging hard to impossible.

In particular, it makes troubleshooting applications written in Java much harder, though Java is not the only code affected by using this flag. So while the flag can help, it can also make debugging harder. If you don't plan to do much debugging and haven't added any other debugging-related CFLAGS such as -ggdb (and you aren't installing packages with the debug USE flag), then try using -fomit-frame-pointer.

Do not combine -fomit-frame-pointer with the similar flag -momit-leaf-frame-pointer. Using the latter flag is discouraged, as -fomit-frame-pointer already does the job properly. Furthermore, -momit-frame-pointer has been shown to negatively impact code performance.
-msse, -msse2, -msse3, -mmmx, -m3dnow

These flags enable the SSE, SSE2, SSE3, MMX, and 3DNow! instruction sets for x86 and x86-64 architectures. These are useful primarily in multimedia, gaming, and other floating point-intensive computing tasks, though they also contain several other mathematical enhancements. These instruction sets are found in more modern CPUs.

Be sure to check if your CPU supports these by running cat /proc/cpuinfo. The output will include any supported additional instruction sets. Note that pni is just a different name for SSE3.

You normally don't need to add any of these flags to /etc/make.conf as long as you are using the correct -march (for example, -march=nocona implies -msse3). Some notable exceptions are newer VIA and AMD64 CPUs that support instructions not implied by -march (such as SSE3). For CPUs like these you'll need to enable additional flags where appropriate after checking the output of cat /proc/cpuinfo.

You should check the list of x86 and x86-64-specific flags to see which of these instruction sets are activated by the proper CPU type flag. If an instruction is listed, then you don't need to specify it; it will be turned on by using the proper -march setting.
Optimization FAQs
But I get better performance with -funroll-loops -fomg-optimize!

No, you only think you do because someone has convinced you that more flags are better. Aggressive flags will only hurt your applications when used system-wide. Even the gcc manual says that using -funroll-loops and -funroll-all-loops makes code larger and run more slowly. Yet for some reason, these two flags, along with -ffast-math, -fforce-mem, -fforce-addr, and similar flags, continue to be very popular among ricers who want the biggest bragging rights.

The truth of the matter is that they are dangerously aggressive flags. Take a good look around the Gentoo Forums and Bugzilla to see what those flags do: nothing good!

You don't need to use those flags globally in CFLAGS or CXXFLAGS. They will only hurt performance. They may make you sound like you have a high-performance system running on the bleeding edge, but they don't do anything but bloat your code and get your bugs marked INVALID or WONTFIX.

You don't need dangerous flags like these. Don't use them. Stick to the basics: -march, -O, and -pipe.

What about -O levels higher than 3?

Some users boast about even better performance obtained by using -O4, -O9, and so on, but the reality is that -O levels higher than 3 have no effect. The compiler may accept CFLAGS like -O4, but it actually doesn't do anything with them. It only performs the optimizations for -O3, nothing more.

Need more proof? Examine the gcc source code:

if (optimize >= 3)
    {
      flag_inline_functions = 1;
      flag_unswitch_loops = 1;
      flag_gcse_after_reload = 1;
      /* Allow even more virtual operators.  */
      set_param_value ("max-aliased-vops", 1000);
      set_param_value ("avg-aliased-vops", 3);
    }

As you can see, any value higher than 3 is treated as just -O3.

What about redundant flags?

Oftentimes CFLAGS and CXXFLAGS that are turned on at various -O levels are specified redundantly in /etc/make.conf. Sometimes this is done out of ignorance, but it is also done to avoid flag filtering or flag replacing.

Flag filtering/replacing is done in many of the ebuilds in the Portage tree. It is usually done because packages fail to compile at certain -O levels, or when the source code is too sensitive for any additional flags to be used. The ebuild will either filter out some or all CFLAGS and CXXFLAGS, or it may replace -O with a different level.

The Gentoo Developer Manual outlines where and how flag filtering/replacing works.

It's possible to circumvent -O filtering by redundantly listing the flags for a certain level, such as -O3, by doing things like:

CFLAGS="-O3 -finline-functions -funswitch-loops"

However, this is not a smart thing to do. CFLAGS are filtered for a reason! When flags are filtered, it means that it is unsafe to build a package with those flags. Clearly, it is not safe to compile your whole system with -O3 if some of the flags turned on by that level will cause problems with certain packages. Therefore, you shouldn't try to "outsmart" the developers who maintain those packages. Trust the developers. Flag filtering and replacing is done for your benefit! If an ebuild specifies alternative flags, then don't try to get around it.

You will most likely continue to run into problems when you build a package with unacceptable flags. When you report your troubles on Bugzilla, the flags you use in /etc/make.conf will be readily visible and you will be told to recompile without those flags. Save yourself the trouble of recompiling by not using redundant flags in the first place! Don't just automatically assume that you know better than the developers.

What about LDFLAGS?

Don't use them. You may have heard that they can speed up application load times or reduce binary size, but in reality, LDFLAGS are more likely to make your applications stop working. They are not supported, and you can expect to have your bugs closed and marked INVALID if you report errors with packages while using LDFLAGS. At the very least you will have to recompile all affected packages without setting LDFLAGS.

Resources

The following resources are of some help in further understanding optimization:

  • The GNU gcc manual
  • Chapter 5 of the Gentoo Installation Handbooks
  • man make.conf
  • Wikipedia
  • Acovea, a benchmarking and test suite that is useful for determining how different compiler flags affect generated code. It is available in Portage: emerge acovea.
  • The Gentoo Forums