Wednesday, July 27, 2011

Finding CPU flags using gcc

Hi all,
One of Gentoo's most attractive features is the ability to specify the cpu CFLAGS, in order to compile all the system to use as much of the hardware as possible.
This leads us to finding the correct cpu flags to include in our /etc/make.conf file.
The approach I was using until now, is to find my cpu flags in the Gentoo wiki page: Safe Cflags. There you can find your cpu by using 'cat /proc/cpuinfo'.
Another approach is to use the -march=native flag, which tells gcc to find the correct CFLAGS for my cpu.
When you compile systems for embedded or other targets, you can't use -march=native, because all the packages will be built for the running cpu and not the target cpu. To compile for the target cpu, you will need to find the flags that suits your target cpu, then apply them in your build environment.

Today I encountered a post from Andy Wilkinson on the Gentoo user mailing list. He describes a very neat trick to find our cpu CFLAGS.
gcc -### -e -v -march=native /usr/include/stdlib.h

This command output will show COLLECT_GCC_OPTIONS which are the options gcc find about your cpu when using -march=native. Here is the output:

COLLECT_GCC_OPTIONS='-e' '-v' '-fPIE' '-pie'
"/usr/libexec/gcc/i686-pc-linux-gnu/4.4.5/cc1" "-quiet" "/usr/include/stdlib.h" "-D_FORTIFY_SOURCE=2" "-march=core2" "-mcx16" "-msahf" "-msse4.1" "--param" "l1-cache-size=32" "--param" "l1-cache-line-size=64" "--param" "l2-cache-size=3072" "-mtune=core2" "-fno-strict-overflow" "-quiet" "-dumpbase" "stdlib.h" "-auxbase" "stdlib" "-fPIE" "-o" "/tmp/cc8bTF68.s" "--output-pch=/usr/include/stdlib.h.gch"

As you see, my cpu is core2 with msse4.1. You also get all the params of the cache size for free.