Introduction
You have used GCC for years. You know roughly what -O2 does. You have fought
cannot find crt1.o at two in the morning. You have built a cross toolchain by
copying somebody's shell script and changing the triple, and it worked, and you
never found out why.
This book explains why, by following each decision GCC makes to the code that
makes it. It covers which program the driver runs, where each header and library
comes from, what a cross build waits for, and what cc1 does between your source
and the assembler. Each chapter covers one mechanism, named in its title, and the chapters
build on each other in order.
GCC's manuals document most options and procedures, and each chapter says where they do, with a link to the page. What the manuals do not show is the code. Every concrete claim in this book links to the line of GCC source that decides it, so a sentence you doubt is one click from the evidence. GCC's own comments often explain a decision better than prose could, and where they do, the book quotes them.
The book is also available to read offline, as an EPUB or a PDF. Both are built from this same source on every deploy.
Who this book is for
The book is for someone comfortable with C, ELF, readelf and the general shape
of a linker. You do not need to have read a compiler book, because terms such as
SSA are explained where a chapter first needs them.
Most chapters need only a compiler you already have. Nearly every mechanism has a
command that shows it working, such as -###, -v, -print-search-dirs,
-dumpspecs or -fdump-tree-all. Parts II and III need a GCC checkout or a
build tree, and the line under each chapter title says what that chapter needs.
How a chapter is laid out
Every chapter has the same shape, so that you can find your way in any of them after reading one. The shape is also how the book separates what the manuals promise from what only the source shows.
- The title names the mechanism. The line under it gives the GCC release and what you need to run the chapter's commands.
- The opening describes a failure or a surprise you may have met, then states what the chapter shows. One sentence names the earlier chapters it builds on.
- Each section opens with its point, then gives the evidence: a listing from GCC's source, whose caption links the exact lines, or a command to run.
- "Three things to carry away" closes the body. Some chapters add "Things that surprise people".
- "Documentation coverage" names the manual pages that document the mechanism, then lists what no manual documents. That list is the part of the book you will not find anywhere else.
- "Next" says what the following chapter takes up.
Each part opens with a short page that lists its chapters, what each one needs, and the terms the part relies on.
Source links: GCC 15.2.0 and four other projects
Every GCC source link points at the release tag releases/gcc-15.2.0 on the
read-only mirror at github.com/gcc-mirror/gcc, and every line number was read
from that tag, not from a working tree. Line numbers move with nearly every
patch, while the code around them rarely changes, so in another release a cited
line is usually a few lines away. Where a mechanism itself changed between major
releases, the sentence that states it says so. A reader on an older compiler is
then warned where they read the claim, not in an appendix they may never reach.
A few chapters cite the projects GCC works with. Their links point at release tags too:
| Project | Release | Cited in |
|---|---|---|
| glibc | 2.42 | Chapters 3.1, 3.3 and 3.5 |
| newlib | 4.5.0 | Chapters 3.4 and 3.6 |
| binutils | 2.45 | Chapter 4.4 |
| DejaGnu | 1.6.3 | Chapters 3.7 and 6.1 |
Commands, output and untested recipes
A command block shows output only when that output was captured, and a caption under it says where. When a block shows no output, the text after it says what the command prints and which source line decides that. Some recipes build GCC, a C library or the manuals, and take hours to run. Each one that was not run end to end carries an "Untested recipe" note. The note says what was checked against the source and what was not, so that you know where to expect trouble before you start the build.
File names before GCC 12: .c, not .cc
GCC 12 renamed nearly every .c file in the compiler to .cc, in a single
commit, 5c69acb3 (Martin Liska, 2022-01-14). So gcc.c became
gcc.cc, gimplify.c became gimplify.cc, and aarch64.c became
aarch64.cc. Blog posts, mailing-list threads and answers written before the
rename use the old names, and so does a GCC 11 or older tree. In those, nearly
every file name differs from this book's by one letter: add or drop the second
c as needed.
The six parts, from using GCC to changing it
The parts go deeper as they go on, because each one moves further from the compiler you have installed. They cover using it, building it, what it ships, what happens inside it, and changing it. You can stop at the end of any part.
Part I, "The driver is not the compiler", is about the program you type. gcc
compiles nothing. It decides which other programs to run and builds each one's
command line. That one fact explains most of what looks arbitrary about GCC from
outside. Part I is the longest part, because almost every path, prefix, library
and header decision lives in the driver.
Part II covers configuring and building GCC itself. Part III covers bootstrapping
a cross toolchain, where the compiler and the C library each need the other to
exist first, and then testing what you built. Part IV covers the runtime
libraries GCC ships: what libgcc is for, the unwinder, and the choice between
static and shared runtimes. Part V goes inside cc1: the three intermediate
representations, the pass manager, and how a machine description becomes an
instruction. Part VI covers GCC as a project: writing tests, its conventions, and
how a patch gets proposed.
Four distinctions the whole book relies on
Four distinctions recur in every part, and most published explanations of GCC get at least one of them wrong. Each one is a place where two mechanisms look like one from outside.
Library search paths. The driver never opens a library file. It emits -l
and -L options and lets ld resolve them. A library search path, in GCC's
sense, is a list of strings that the driver hands to the linker.
Link time and run time. A successful link says nothing about whether the
program will start. At run time the dynamic loader, ld.so, finds shared
libraries through DT_RUNPATH, ld.so.conf and LD_LIBRARY_PATH. The book stops
at the file the linker writes, except in
Chapter 4.4.
Header search and library search. The same prefix relocates both, which makes them look like one mechanism. Different code in different files implements them, with different sysroot rules.
Host programs and target files. Anything under libexec/gcc/ is a host
program, which runs on your machine. Anything under <target>/lib/ is a target
file, which never runs on your machine: it is only linked into what your compiler
produces. Chapter 1.2 is mostly about keeping the
two apart.
1.1 What gcc foo.c runs: cc1, as and collect2
GCC 15.2.0. To run the commands: an installed compiler.
You type gcc hello.c, and an a.out appears. Somewhere in between, your C was
turned into machine code, and the obvious assumption is that gcc did it.
It did not, because gcc compiles nothing. A driver is a program that works
out which other programs to run, builds each one's command line and runs them in
order, and gcc is a driver. Almost every "GCC can't find X" problem is a driver
problem, and the driver prints what it did if you ask it.
-### and -v: printing the commands the driver runs
-### prints every command line the driver would run, fully expanded and
shell-quoted, and then runs none of them. Its sibling -v prints the same
command lines and runs them. -### is the flag to learn before any other. It
turns "GCC is doing something weird" into a concrete argument list that you can
read, diff against a working toolchain and paste back into a shell. The GCC
manual documents both flags under Overall Options.
$ gcc -### hello.c
The output names three or four separate programs, not one. In the diagram
below, each arrow is a real fork and exec:
gcc hello.c
│
├─► cc1 hello.c → /tmp/ccXXXXXX.s the actual C compiler
│ (cc1plus for C++)
├─► as .s → hello.o the assembler, from binutils
│
└─► collect2 hello.o → a.out a wrapper that runs ld
└─► ld
The temporary .s file between cc1 and as is real too, and this command
shows the name that the driver invents for it:
$ gcc -### hello.c 2>&1 | grep -o '/tmp/cc[A-Za-z0-9]*\.s'
It prints a name of the form /tmp/ccXXXXXX.s, which you never chose. cc1 and
as still agree on it, because the driver generated one name and substituted it
into both command lines. Chapter 1.3 explains the
mechanism, and until then the intermediate files between stages are the
driver's bookkeeping, not yours.
Three flags stop the chain early, each at one boundary between stages, which is a quick way to check that the stages are separate. Overall Options documents all three:
| Flag | Stops after |
|---|---|
-E | the preprocessor |
-S | cc1, leaving a .s |
-c | as, leaving a .o |
| (none) | the link |
Where cc1, as and collect2 live
GCC installs cc1, collect2 and its other internal programs in a private
libexec directory, not on $PATH, and as and ld come from binutils. The
driver does not search $PATH for cc1, and could not, so it keeps a search
list of program directories of its own. That list and the directories in the
table below are where to look when the driver cannot find a program.
| Program | What it is | Installed in |
|---|---|---|
gcc, g++ | the driver | $prefix/bin/ |
cc1, cc1plus, lto1 | the real compilers | $prefix/libexec/gcc/<target>/<version>/ |
collect2, lto-wrapper | GCC's own link-time helpers | same libexec directory |
as, ld | binutils | binutils' install, or the tool directory |
All four rows are host programs: they run on your machine, as processes. GCC's
own internal programs go in libexec because they are private implementation
binaries that still have to be exec'd. Putting the target and the release in
the path lets several GCCs coexist. The install manual documents both of GCC's
directories under Configuration: --bindir for the
programs that users call, and --libexecdir for GCC's internal executables.
The driver's list of program directories is separate from its list of library directories, and one command prints both. The GCC manual documents that command under Developer Options:
$ gcc -print-search-dirs
In its output, the programs: line is the executable list and the libraries:
line is the list that resolves crt1.o and -lfoo. Separate code builds the
two lists, and Chapter 1.5 shows how to read
them. There is no third line for headers, for a reason that Chapter 1.5 also
covers.
default_compilers[]: command lines are spec strings, not C code
default_compilers[], the driver's table of compilers, holds strings, not code.
Each string is a template in a small %-escape language that the driver expands
at run time, so the argument lists that -### prints are not written in C
anywhere. The GCC manual documents the language under
Spec Files. Listing 1.1-1 is the entry for a .c file, and
that one string constant is the whole of GCC's knowledge of how to compile C.
{".c", "@c", 0, 0, 1},
{"@c",
/* cc1 has an integrated ISO C preprocessor. We should invoke the
external preprocessor if -save-temps is given. */
"%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
%{!E:%{!M:%{!MM:\
...
%{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
cc1 %(cpp_unique_options) %(cc1_options)}}}\
%{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 1},
Listing 1.1-1: the .c entry in default_compilers[]
(gcc/gcc.cc:1454-1468). Abridged. The omitted middle handles
-save-temps and rejects -traditional.
The literal word cc1 in Listing 1.1-1 tells the driver what to run, because the
program is the first word of an expanded template, not the value of a variable.
The template's last line, %{!fsyntax-only:%(invoke_as)}, pulls in a second
template, invoke_as.
Three consequences of building command lines from templates matter already, although the language itself waits until Chapter 1.3:
- A target customises GCC by replacing a template, not by patching the driver.
Two GCCs built from identical source for different targets can behave
differently, because their target headers
#definedifferent templates. -nostdlib,-nostartfilesand-nodefaultlibsare not implemented in C at all. They are conditionals inside one template string, which is why they compose the way they do, and Chapter 1.10 reads them.- You can replace those templates yourself, per invocation, with
-specs=FILE, without rebuilding anything.
invoke_as: a newline in a spec starts the next program
invoke_as is the template that runs the assembler, and the .c template
expands it unless -fsyntax-only is given, which is why the assembler runs at
all. Inside a template, a newline ends one program's command line, and what
follows it is another program to run. The step from cc1 to as in the diagram
is therefore a newline in a string, not a loop over stages in the driver's C
code.
static const char *invoke_as =
"%{!fwpa*:\
%{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
%{!S:-o %|.s |\n as %(asm_options) %m.s %A }\
}";
Listing 1.1-2: invoke_as, the #else branch (gcc/gcc.cc:1313-1324).
Targets that define AS_NEEDS_DASH_FOR_PIPED_INPUT take the first branch, which
writes %|.s on the as line.
In Listing 1.1-2 the newline is the \n in |\n as, immediately before the
as command. The | in front of it asks for a pipe, and the driver uses one
only under -pipe. Overall Options documents that flag as using "pipes rather
than temporary files" between the stages. Without -pipe the driver drops the
|, runs cc1 to the end, and then runs as on the file that cc1 wrote
(gcc.cc:6157-6166).
Chapter 1.4 follows those files.
Why the driver runs collect2, not ld
On most targets the last program in the chain is not ld but collect2, a GCC
program that then runs ld. collect2 has a job of its own at link time, and
that job needs a compiler, which is why the driver has to tell it which compiler
to use. The default linker name comes from one macro:
#ifndef LINKER_NAME
#define LINKER_NAME "collect2"
#endif
Listing 1.1-3: LINKER_NAME (gcc/gcc.cc:902-904).
collect2's own opening comment says what it is for: "Collect static
initialization info into data structures that can be traversed by C++
initialization and finalization routines" (gcc/collect2.cc:1-2).
Some object formats have no native mechanism for running constructors before
main. On those platforms something has to scan the objects, build a table of
constructor and destructor pointers, and get that table into the image.
collect2 does that scan, generates a small C file containing the tables, and
compiles it.
COLLECT_GCC: how collect2 and lto-wrapper find the same compiler
COLLECT_GCC and COLLECT_GCC_OPTIONS make the driver's link-time helpers run
the same compiler as your command, with the same switches. lto-wrapper, GCC's
other link-time helper, needs a compiler as collect2 does, because it re-runs
code generation at link time for link-time optimisation, and it also needs your
original options. If either helper took whichever gcc came first on $PATH,
the second pass would run with a different prefix, sysroot and search paths, and
on a cross toolchain possibly a different target.
The driver prevents that by putting the answers in the environment before it
spawns anything. COLLECT_GCC holds the full pathname of the running driver,
taken from argv[0]:
obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=") - 1);
Listing 1.1-4: exporting COLLECT_GCC (gcc/gcc.cc:8718).
COLLECT_GCC_OPTIONS holds every switch, each one single-quoted, so the second
pass reconstructs the same paths. This is the whole reason -B, --sysroot and
-L survive into the link step, and it is also why gcc -v output is full of
COLLECT_* lines:
$ gcc -v hello.c 2>&1 | grep '^COLLECT_'
The COLLECT_* lines it prints are already shell-quoted, so they paste into a
terminal. They are the quickest way to reproduce what collect2 was handed.
Without these variables the two helpers behave differently. lto-wrapper
refuses to run, and Listing 1.1-5 is its check for COLLECT_GCC:
collect_gcc = getenv ("COLLECT_GCC");
if (!collect_gcc)
fatal_error (input_location,
"environment variable %<COLLECT_GCC%> must be set");
Listing 1.1-5: lto-wrapper hard-errors (gcc/lto-wrapper.cc:1444-1448).
collect2 is more forgiving, and that makes it the dangerous half of the pair,
because it picks a compiler name of its own:
/* Determine the full path name of the C compiler to use. */
c_file_name = getenv ("COLLECT_GCC");
if (c_file_name == 0)
{
#ifdef CROSS_DIRECTORY_STRUCTURE
c_file_name = concat (target_machine, "-gcc", NULL);
#else
c_file_name = "gcc";
#endif
}
Listing 1.1-6: collect2's fallback (gcc/collect2.cc:1142-1151).
As Listing 1.1-6 shows, a collect2 run without COLLECT_GCC falls back to
<target>-gcc when GCC was built with CROSS_DIRECTORY_STRUCTURE and to plain
gcc otherwise, with no diagnostic. On a cross
toolchain that can pick up a different compiler with different startfile and
sysroot paths, and the only symptom is a link that resolves the wrong
crtbegin.o.
Chapter 1.9 covers the whole environment channel.
When collect2 is missing, the driver runs ld
When the driver cannot find collect2, it runs ld in its place, with no
diagnostic. On a normal Linux toolchain collect2 runs ld, so ld never
appears in the driver's output. When you grep -### output for the link line,
grep for collect2, not for ld. Listing 1.1-7 is the fallback:
/* We'll use ld if we can't find collect2. */
if (! strcmp (linker_name_spec, "collect2"))
{
char *s = find_a_program ("collect2");
if (s == NULL)
set_static_spec_shared (&linker_name_spec, "ld");
}
Listing 1.1-7: the collect2-to-ld fallback (gcc/gcc.cc:9243-9249).
gcc and g++ are the same program
gcc and g++ are not two compilers but the same driver code, with one extra
hook compiled in. The hook, lang_specific_driver, runs on the decoded command
line before anything has acted on it, so it can insert, delete and reorder
options. Those edits are the whole practical difference between the two commands
at link time, and Listing 1.1-8 is the call:
/* Do language-specific adjustment/addition of flags. */
lang_specific_driver (&decoded_options, &decoded_options_count,
&added_libraries);
Listing 1.1-8: the language hook (gcc/gcc.cc:4860-4862).
g++'s implementation does exactly two things: it makes .c files compile as
C++, and it appends the C++ runtime libraries to your link. On the way, it moves
your own -lm and -lc, with no diagnostic. Link C++ objects with gcc, and you
get undefined std:: symbols and no other change. The GCC manual documents the
two effects under Invoking G++, but none of the hook's details,
so Chapter 1.11 takes the hook apart.
Checking a bad link with -### and the -print-* options
When something links wrong, run five driver commands in order and stop at the first surprise. Each asks the driver one question: whether your flag reaches the linker, where it searches, which copy of a file wins, whether a sysroot is in play and which ABI variant you get.
$ gcc -### foo.c # is the flag you passed even reaching the linker?
$ gcc -print-search-dirs # is the directory you expect in `libraries:`?
$ gcc -print-file-name=libfoo.a # which copy of it wins?
$ gcc -print-sysroot # is a sysroot in play at all?
$ gcc -print-multi-directory # are you getting the right ABI variant?
-print-file-name walks the same list the linker is given, so its answer is the
file the link would pick. When the file is not found at all, it prints your
argument back unchanged, which makes it the quickest diagnosis of a missing file.
Chapter 1.5 explains why it works that way.
Three things to carry away
gcc compiles nothing. It decides which programs to run, builds each one's
command line, and runs them. -### shows every command line and runs none.
The command lines are templates, not C code. A target changes what the driver
runs by replacing a template, and so can you, with -specs=FILE.
The driver hands its own identity to its children. COLLECT_GCC and
COLLECT_GCC_OPTIONS make collect2 and lto-wrapper re-run the same compiler
with the same switches.
Things that surprise people
There is no gcc/specs.cc, and there never has been. The spec language lives
in gcc/gcc.cc, where the interpreter is a function called do_spec_1. A great
deal of secondhand documentation names gcc/specs.cc anyway.
Documentation coverage
The observation tools are documented: -### and -v are in
Overall Options (gcc/doc/invoke.texi:1549), the -print-* family
is in Developer Options (:20326), and the spec language has its
own node, Spec Files (:37290). The internals
manual's Collect2 node (gcc/doc/collect2.texi:5) documents how
collect2 finds the real ld.
What is not documented:
- The
COLLECT_GCCchannel, from the driver's side. Neither manual mentions the variable. collect2's fallback to<target>-gccor togcc, whenCOLLECT_GCCis unset.
Next: Chapter 1.2, Build, host and target: which files --sysroot moves,
the vocabulary the rest of Part I is written in: three machine names, and the
difference between a program that runs and an object that only ever gets linked.
1.2 Build, host and target: which files --sysroot moves
GCC 15.2.0. To run the commands: a cross compiler such as arm-linux-gnueabihf-gcc.
You have an ARM cross toolchain. You point --sysroot at your root filesystem,
and the link finds crt1.o there. You point it somewhere else, and crt1.o
moves with it, but the link still finds crtbegin.o in the old place.
A GCC installation holds files for two machines at once: the one that runs the
compiler and the one that runs the code it generates. Almost every configure
flag and command-line option belongs to one of the two. crt1.o and crtbegin.o
are both for the target, but they have different owners. crt1.o belongs to the
C library, which lives in the sysroot, and crtbegin.o belongs to GCC, which
lives under the installation prefix. Once you can say which machine and which
owner a path belongs to, most of GCC's path behaviour stops being arbitrary.
This chapter assumes Chapter 1.1, for the driver and
the programs it runs, such as cc1 and collect2.
--build, --host and --target: native, cross and Canadian cross
GCC's configure takes three machine names, --build, --host and --target,
where almost every other autoconf package takes two. GCC needs --target
because a compiler is the one program whose output is for a machine other than
the one it runs on. Reading any path in a GCC install therefore starts with
asking which machine the file is for. The install manual defines the three
names in one sentence, under Configuration:
The build machine is the system which you are using, the host machine is the system where you want to run the resulting compiler (normally the build machine), and the target machine is the system for which you want the compiler to generate code.
| Flavour | build | host | target |
|---|---|---|---|
| native | x86_64-linux-gnu | same | same |
| cross | x86_64-linux-gnu | same | arm-linux-gnueabihf |
| Canadian cross | x86_64-linux-gnu | x86_64-w64-mingw32 | arm-none-eabi |
A single make therefore produces artifacts for two different machines at once.
Almost everything confusing about GCC's configure flags comes from that fact, so
the question to ask of any flag is whether it is about the machine that runs the
compiler or the machine that runs its output.
You can ask a built compiler which target it is for:
$ arm-linux-gnueabihf-gcc -dumpmachine
It prints the target triple and exits, so it is the quickest check that you are
running the compiler you meant to run. The GCC manual documents -dumpmachine
and the -print-* options under Developer Options.
A target triple names the CPU, the vendor and the operating system, in that
order (config.sub:48-53). The name you configure with may leave a
field out, and config.sub fills it in to make the canonical form, so
x86_64-linux-gnu becomes x86_64-pc-linux-gnu
(Chapter 2.2):
| Triple | CPU | Vendor | Operating system |
|---|---|---|---|
arm-none-eabi | arm | none | eabi |
x86_64-pc-linux-gnu | x86_64 | pc | linux-gnu |
Host code and target code: libexec/ against <target>/lib/
GCC installs two kinds of code: host code, which runs on the machine that runs the compiler, and target code, which is linked into what the compiler produces. The kind decides who builds a file and which directory it lives in, so it is the first thing to settle about any path in an install tree:
| Host code | Target code | |
|---|---|---|
| Examples | gcc, cc1, cc1plus, lto1, collect2, lto-wrapper | libgcc.a, libstdc++.so, crt1.o, crtbegin.o |
| Runs | on your machine, as a process | never by itself, because it is linked into what your compiler produces |
| Built by | the build machine's system compiler | the compiler this build just produced |
| Lives in | bin/, libexec/ | lib/gcc/<t>/<v>/, <t>/lib/, and the sysroot |
libgcc.a shows why target code is easy to misjudge. It is not a library that
GCC uses but one that GCC emits calls into, compiled for a machine that may not
be able to run one instruction of the compiler that built it. When a cross
toolchain "finds the wrong libgcc.a", nothing has gone wrong with GCC's own
installation: the toolchain has picked the wrong artifact for a foreign machine.
One rule, with no exceptions, says which machine each directory serves.
libexec/ and bin/ are host. <target>/lib/ and the sysroot, the target's
stand-in for /, are target. lib/gcc/<target>/<version>/ is a mix: host data
such as the specs file and GCC's own headers, alongside target objects such as
libgcc.a and crtbegin.o.
Most flags affect one side only. -B is the exception, because it is one prefix
applied to three separate search lists at once, and those lists span host and
target. The GCC manual documents all three uses under
Directory Options, and
Chapter 1.5 shows why the result feels blunt.
What a sysroot is: add_sysrooted_prefix
A sysroot is a directory that stands in for / on the target machine. In
the driver it is a string that add_sysrooted_prefix puts in front of certain
absolute paths, so a directory follows --sysroot only if that function
registered it. That function is where to look when a file does not move with the
flag.
Inside a sysroot, usr/include/stdio.h plays the role that
/usr/include/stdio.h plays on the target, and the GCC manual's Directory
Options page gives the same example for --sysroot. A cross compiler needs one
because your own /usr/include/stdio.h describes the C library of your machine,
with the wrong sizeof(long), struct layouts, syscall numbers and #defines for
the target. A cross compile that read it would give no diagnostic, only an
object file that compiles, links and then misbehaves on the device. So the
compiler needs a second / that holds the target's files, and Listing 1.2-1
shows how the driver prepends it to a path:
add_sysrooted_prefix (struct path_prefix *pprefix, const char *prefix,
const char *component,
/* enum prefix_priority */ int priority,
int require_machine_suffix, int os_multilib)
{
if (!IS_ABSOLUTE_PATH (prefix))
fatal_error (input_location, "system path %qs is not absolute", prefix);
if (target_system_root)
{
...
prefix = concat (sysroot_no_trailing_dir_separator, prefix, NULL);
Listing 1.2-1: add_sysrooted_prefix (gcc/gcc.cc:3177-3200).
Abridged; the omitted lines strip a trailing separator and splice in a per-multilib
sysroot suffix.
add_sysrooted_prefix has a sibling, add_prefix, which registers a prefix
the same way but without the sysroot (gcc/gcc.cc:3144). No later
pass rewrites paths, and no flag can apply the sysroot to a prefix that
add_prefix registered. The omitted lines of Listing 1.2-1 also splice in a
per-multilib suffix. A multilib is one of the separate copies of the target
libraries that a toolchain ships, one for each ABI its triple supports
(Chapter 1.6).
The sysroot belongs to libc, the prefix to GCC
The sysroot belongs to the C library, and the prefix, the root that --prefix
names, belongs to GCC. GCC never installs anything into the sysroot, and the C
library never installs anything into the prefix. Almost every question of the
form "why did --sysroot not move this file?" has the same answer: the file is
GCC's, not the C library's.
Sorting the files of a normal link by owner shows the split. The C library's files are in the sysroot, and they are the half that a sysroot moves:
<stdio.h>,<pthread.h>,<fcntl.h>and the rest of the system headerslibc.so,libm.socrt1.o,crti.o,crtn.o
GCC's files are under the prefix, and a sysroot never touches them:
libgcc.a,libgcc_eh.a,libgcc_s.so.1crtbegin.oandcrtend.o, which are part of libgcclibstdc++and its headers, which live in the tooldir, the target's own subtree of the install<stddef.h>,<stdint.h>,<limits.h>and<stdarg.h>, because the C standard requires the compiler to supply them (Chapter 1.8 explains why)
Copying a sysroot from one machine to another therefore does not bring
stdint.h along, because the header is not in the sysroot and is not supposed to
be. The compiler's own headers travel with the compiler.
libsubdir, tooldir and toolexeclibdir: the install directory map
Three autoconf variables, $prefix, $exec_prefix and $libdir, underlie every
path formula in GCC, including the libsubdir, the tooldir and toolexeclibdir.
The configure option that sets a variable therefore moves every directory built
from it, which is how --exec-prefix can put a library's headers and its binary in
different trees.
The install manual documents the option that sets each variable, and its
default, under Configuration:
| Variable | What it is | Default |
|---|---|---|
$prefix | root of the install | --prefix=, else /usr/local |
$exec_prefix | root for machine-dependent files | --exec-prefix=, else $prefix |
$libdir | host libraries | $exec_prefix/lib |
$prefix and $exec_prefix are different variables that default to the same
value (gcc/Makefile.in:662, :673). If you pass
--exec-prefix, paths built from one diverge from paths built from the other.
The libstdc++ install shows the result: it puts its headers under ${prefix}
and its libraries under ${exec_prefix}, so --exec-prefix puts the C++ headers
and the C++ library in different trees.
Chapter 1.12 deals with the consequences.
Two of the directories built from these variables have names of their own in GCC's build files. The libsubdir is GCC's private per-version directory:
libsubdir = $(libdir)/gcc/$(real_target_noncanonical)/$(version)$(accel_dir_suffix)
Listing 1.2-2: libsubdir (gcc/Makefile.in:682).
It expands to something like
/opt/gcc-arm/lib/gcc/arm-linux-gnueabihf/15.2.0/, which holds specs, GCC's
own include/, libgcc.a and crtbegin.o. Because of the $(version)
component, two GCC releases have separate libsubdirs. That lets them coexist, and
it makes mixing GCC 12's headers with GCC 15's cc1 a broken toolchain, not only
an unwise one.
The tooldir is the target's own subtree, and the top-level configure.ac
defines it:
tooldir='${exec_prefix}'/${target_noncanonical}
Listing 1.2-3: tooldir (configure.ac:3121).
It expands to /opt/gcc-arm/arm-linux-gnueabihf/, which holds bin/, lib/,
include/ and sys-include/, a stand-in /usr for the target. A cross
libstdc++ installs there, and so does newlib.
The table adds toolexeclibdir and the sysroot to the map. None of the
directories that GCC installs into is sysrooted, so none of them follows
--sysroot:
| Name | Default | Contains | Sysrooted? |
|---|---|---|---|
| prefix | --prefix | everything GCC installs | no |
| libsubdir | $libdir/gcc/<target>/<ver>/ | GCC's target objects and host data | no |
| tooldir | $exec_prefix/<target>/ | bin/ lib/ include/ sys-include/ | no |
| toolexeclibdir | $tooldir/lib (cross), $libdir (native) | target libraries such as libstdc++.so | no |
| sysroot | --with-sysroot, else $tooldir/sys-root | the C library's files | it is the sysroot |
The install manual documents --with-toolexeclibdir's default as
${gcc_tooldir}/lib (install.texi:2705-2707). The
default for a bare --with-sysroot also sits inside the tooldir, and so inside
$exec_prefix, which is the condition under which a sysroot moves with a
relocated toolchain. The manual states that condition:
If the specified directory is a subdirectory of
${exec_prefix}, then it will be found relative to the GCC binaries if the installation tree is moved.
The driver code that implements that sentence is guarded by a macro that
configure defines only when the condition holds
(gcc/configure.ac:176-182). The driver acts on the macro at
gcc/gcc.cc:5542-5559, and
Chapter 1.5 reads that code.
A cross install under --prefix: host, target and mixed directories
A cross toolchain configured with --prefix=/opt/gcc-arm --target=arm-linux-gnueabihf keeps host and target files in separate
directories, and mixes them only in the libsubdir, lib/gcc/<target>/<ver>/.
The table is the map to check a real compiler's output against:
| Path | Contains | Machine |
|---|---|---|
/opt/gcc-arm/bin/ | arm-linux-gnueabihf-gcc, -g++, -gcc-ar | host |
/opt/gcc-arm/libexec/gcc/<target>/<ver>/ | cc1, cc1plus, lto1, collect2 | host |
/opt/gcc-arm/lib/gcc/<target>/<ver>/ | specs, include/, crtbegin*.o, libgcc.a | mixed |
/opt/gcc-arm/<target>/lib/ | libstdc++.so, newlib's libc.a | target |
/opt/gcc-arm/share/ | docs, man pages | host data |
| the sysroot, wherever it is | libc.so, crt1.o, <stdio.h> | target |
Four commands check the map against an installed cross compiler. The comment on each line says what it prints:
$ arm-linux-gnueabihf-gcc -dumpmachine # the target triple
$ arm-linux-gnueabihf-gcc -print-sysroot # the C library's world; empty = none
$ arm-linux-gnueabihf-gcc -print-search-dirs # install root, programs, target libraries
$ arm-linux-gnueabihf-gcc -v # the configure line it was built with
An empty line from -print-sysroot means the compiler has no sysroot, which is
meaningful rather than broken. Chapter 1.5
explains what it implies.
Why a cross build is circular: libgcc needs the libc headers
A cross build is circular because libgcc and libstdc++ are target libraries
that GCC itself ships, so they belong to GCC and to the target at once. They
need a target compiler and the target's C library, and the C library needs a
compiler in turn. The cycle drives all of Part III, and it closes in four
steps:
- Target libraries need a target compiler, so the build makes one first, an
uninstalled
xgcc. - The libgcc source includes libc headers. The install manual states the need:
"When crossing to GNU/Linux, you need the headers so GCC can build the
exception handling for libgcc." (
install.texi:2765-2766) - libstdc++ needs a libc that it can link against, not only headers, because its configure runs hundreds of link probes.
- The libc itself was built by a compiler.
The conventional way out is to build a deliberately limited GCC first:
binutils → libc headers → minimal GCC (--without-headers)
→ full libc → full GCC (libgcc + libstdc++)
An internal configure variable, inhibit_libc, makes the minimal GCC possible.
With it set, libgcc includes no C library header, although it still calls a few C
library functions, such as malloc and memcpy, through declarations of its own
(gcc/tsystem.h:47-84).
Chapter 3.2 reads the condition that sets it.
--with-headers and --with-libs: copying target files before sysroots
Before sysroots existed, --with-headers and --with-libs pointed GCC at the
target's headers and libraries, and configure copied those files into the
install tree. You will meet both options in old build scripts, and they are the
reason a sysroot toolchain still has header search paths in the tooldir.
Configure does the copy in the top-level configure.ac
(configure.ac:2931). The install manual now marks both
options "Deprecated in favor of --with-sysroot"
(install.texi:2751-2753, :2769-2770).
The paths they left behind are $tooldir/include and $tooldir/sys-include,
which stay on the header search list of a sysroot-only toolchain that never
asked for them. The surviving path is compiled in as TOOL_INCLUDE_DIR
(gcc/Makefile.in:2613), and
Chapter 1.8 returns to it.
Three things to carry away
One install tree holds code for two machines. bin/ and libexec/ run on
yours. <target>/lib/ and the sysroot belong to the target. lib/gcc/<t>/<v>/
holds both, which is why it is the confusing one.
The sysroot belongs to the C library, the prefix belongs to GCC. --sysroot
never moves libgcc, crtbegin.o, libstdc++ or GCC's own headers.
A sysroot is a string, prepended per entry. add_sysrooted_prefix prepends it
and add_prefix does not. Which function registered a directory decides whether
that directory follows --sysroot.
Documentation coverage
The three machine names are defined in the installation manual
(gcc/doc/install.texi:841-844) and again, with the native, cross
and Canadian variants, in the internals manual's
Configure Terms node (gcc/doc/configterms.texi:5).
--with-sysroot is in install.texi (:2709-2731), and
--sysroot is in Directory Options
(gcc/doc/invoke.texi:19484, :19559). The individual install directories have
configure options of their own (install.texi:910-940).
What is not documented:
- That
--sysrootmoves only the C library's half. The manual describes it as "the logical root directory for headers and libraries" (invoke.texi:19560), which reads as if it moved all of them. - The installed tree as a whole: which directories hold host code, which hold target code, and which hold both.
- That
--exec-prefixsplits libstdc++'s headers from its library.
Next: Chapter 1.3, Specs: how the driver writes a command line, the template language behind every command the driver runs.
1.3 Specs: how the driver writes a command line
GCC 15.2.0. To run the commands: an installed compiler for GNU/Linux.
You pass -static-libgcc and the link line changes. You go looking for the code
that implements it, and there is none. There is no if (static_libgcc) anywhere
in the link path, no function that consults a flag and appends a library. What
you find instead is a string:
%{static|static-libgcc|static-pie:-lgcc -lgcc_eh}%{!static:%{!static-libgcc: …
GCC's driver builds every command line by expanding templates written in a small
%-escape language, which works like printf for command lines, with
conditionals and function calls added. Once you can read and write that
language, you can change a toolchain's link behaviour without rebuilding it, and
explain why options such as -static-libgcc and -nostdlib behave the way they
do. The mechanism has three parts: a table of named specs, % directives that
read the table and the command line, and specs files that rewrite the table.
The GCC manual documents the language under Spec Files.
This chapter assumes Chapter 1.1, for -### and the
spec strings in Listings 1.1-1 and 1.1-2, and
Chapter 1.2, for the sysroot, multilibs and
GCC's own library directory, lib/gcc/<target>/<version>/.
The spec table: -dumpspecs, struct spec_list and set_spec
A spec is a named entry in a table that the driver holds in memory: a name,
and the template text currently bound to it. Name references read this table
and specs files write to it, so its layout decides what an override can
change. -dumpspecs, which the GCC manual lists under
Developer Options, prints the whole table, and every line that
starts with * is a name:
$ gcc -dumpspecs | grep '^\*' # every name your driver has
$ gcc -dumpspecs | sed -n '/^\*libgcc:/,/^$/p' # one name and its value
The table is a linked list of struct spec_list. Its comment keeps name and
ptr first so that a target's EXTRA_SPECS can initialise entries, and the
field that %G depends on is ptr_spec:
struct spec_list
{
/* The following 2 fields must be first */
/* to allow EXTRA_SPECS to be initialized */
const char *name; /* name of the spec. */
const char *ptr; /* available ptr if no static pointer */
...
const char **ptr_spec; /* pointer to the spec itself. */
Listing 1.3-1: struct spec_list (gcc/gcc.cc:1685-1700).
An entry does not hold its text. ptr_spec points at the C variable that holds
the text, and the static array static_specs[] seeds the table with one such
pointer per name:
INIT_STATIC_SPEC ("libgcc", &libgcc_spec),
INIT_STATIC_SPEC ("startfile", &startfile_spec),
Listing 1.3-2: two entries from static_specs[]
(gcc/gcc.cc:1729-1730; the array begins at
:1707).
Every change to a spec, from a target's override, a -specs= file or the
driver's own startup rewriting, goes through one function and writes through
that pointer (set_spec, gcc/gcc.cc:2066). Nothing else keeps a
copy of the text, and that indirection is why %G can expand text that appears
nowhere in the source.
Which spec names exist: static_specs[] and EXTRA_SPECS
The spec names that exist before any specs file is read are fixed when GCC is
built, and no external file declares them. Knowing them tells you what a specs
file can override and what a directive such as %G refers to. These are the
names that most specs use, each with the one-letter alias that a spec can write
instead of %(name):
| Name | Alias | Holds |
|---|---|---|
cpp | %C | options for the preprocessor |
cc1 / cc1plus | %1 / %2 | options for the C / C++ compiler proper |
asm | %a | options for the assembler |
link | %l | options for the linker |
lib | %L | the default system libraries, usually -lc |
libgcc | %G | GCC's helper library, -lgcc and related libraries |
startfile | %S | objects linked before yours |
endfile | %E | objects linked after yours |
link_command | none | the whole link template (Listing 1.3-6), of which link is one part |
Another spec uses a name by reference, and a specs file overrides it.
%(link) expands the link spec in place, and %l means the same through its
alias. The names themselves come from three sources, all compiled into the
driver:
| Source | Contributes |
|---|---|
static_specs[] in gcc/gcc.cc:1707 | the universal names above, on every target |
target OS headers, e.g. gcc/config/gnu-user.h | #define STARTFILE_SPEC …, which replaces a default |
target CPU headers, e.g. gcc/config/aarch64/aarch64.h | #define EXTRA_SPECS …, which adds names such as asm_cpu_spec |
Two GCCs built from the same source for different targets therefore behave
differently, because their headers #define different specs. For the same
reason, -dumpspecs output is target-specific: an aarch64-none-elf-gcc and an
x86_64-linux-gnu-gcc list different names.
Reading a %{…} conditional: the libgcc spec
A %{…} conditional tests the command line, and nested conditionals express
every choice a spec makes. Listing 1.1-1 ended with one,
%{!fsyntax-only:%(invoke_as)}, which expands the invoke_as spec unless
-fsyntax-only was given. The libgcc spec from the hook is a larger
example, and reading it shows what -static-libgcc does to the link.
A conditional names an option without its leading dash, so %{static:…} tests
-static, and the forms below write opt for such a name. On a target with a
shared libgcc, the libgcc value, reflowed onto four lines for reading, is
roughly:
%{static|static-libgcc|static-pie:-lgcc -lgcc_eh}
%{!static:%{!static-libgcc:%{!static-pie:
%{!shared-libgcc:-lgcc --as-needed -lgcc_s --no-as-needed}
%{shared-libgcc:-lgcc_s%{!shared: -lgcc}}}}}
-dumpspecs prints the value on one line. A newline in a spec ends one
program's command line, as Chapter 1.1 showed, so a
value written into a specs file belongs on one line.
Two forms make up the whole value. %{opt:X} emits X if -opt was given, and
%{!opt:X} emits it if -opt was not. Everything else is nesting, and three
details make the nesting readable:
|means or. The first line fires if any of-static,-static-libgccor-static-piewas given.- There is no
&&. Nesting negations expresses and-not:%{!opt1:%{!opt2:X}}. - The output half can contain conditionals, because
Xin%{opt:X}is more spec text, expanded recursively. That is why%{shared-libgcc:-lgcc_s%{!shared: -lgcc}}appends-lgcconly when you are not building a shared object.
A third form does not appear in this value, but target specs use it often. A
; separates arms, and an arm with an empty condition is the default, so
%{msoft-float:-soft;:-hard} emits -soft for -msoft-float and -hard
otherwise. Chapter 1.7 shows a glibc startfile spec
that picks among five crt1 variants this way.
Evaluated for each command, the libgcc value gives the static or shared
libgcc that the GCC manual documents for -static-libgcc and -shared-libgcc
under Link Options:
| Your command | libgcc expands to |
|---|---|
gcc foo.o | -lgcc --as-needed -lgcc_s --no-as-needed |
gcc -static-libgcc foo.o | -lgcc -lgcc_eh |
gcc -static foo.o | -lgcc -lgcc_eh |
gcc -shared-libgcc foo.o | -lgcc_s -lgcc |
gcc -shared -shared-libgcc foo.o | -lgcc_s |
libgcc.a holds helpers that each linked object may copy, and libgcc_eh.a and
libgcc_s.so.1 hold the code that must exist once per process.
Chapter 4.2 explains the split.
--as-needed and --no-as-needed are configure's defaults. With GNU ld 2.28 or
later, configure picks --push-state --as-needed and --pop-state instead
(gcc/configure.ac:6574-6587), so that is what a current
GNU/Linux link line shows.
-### prints the link line with this value expanded, and one pipeline picks out
the libgcc options for -static-libgcc:
$ gcc -### -static-libgcc foo.o 2>&1 | tr ' ' '\n' | grep lgcc
It prints -lgcc and -lgcc_eh, the table's -static-libgcc row, chosen by a
conditional and not by C code in the link path.
Why %G names a slot, not a value
%G expands the current value of the libgcc slot, not the text of the
LIBGCC_SPEC macro that the slot started from. The difference matters because
the driver rewrites the slot at startup on targets with a shared libgcc, so the
macro in the source is not what the link uses. The arrow %G → LIBGCC_SPEC in
secondhand explanations is not an equality, because four distinct things share
that name:
| # | Thing | Kind | Where |
|---|---|---|---|
| 1 | LIBGCC_SPEC | a C preprocessor macro, overridable by the target | gcc.cc:878-889 |
| 2 | libgcc_spec | a C variable, initialised from the macro | gcc.cc:1217 |
| 3 | "libgcc" | the name that variable is registered under | gcc.cc:1729 |
| 4 | %G | a directive meaning "expand whatever is registered as libgcc" | gcc.cc:6813 |
The directive's implementation is two lines:
case 'G':
value = do_spec_1 (libgcc_spec, 0, NULL);
Listing 1.3-3: %G (gcc/gcc.cc:6813-6814). do_spec_1 is the
expander.
For libgcc, ptr_spec is &libgcc_spec (Listing 1.3-2), and every set_spec
call writes into that variable. %G reads the same variable, so it sees the
latest value. It is equivalent to %(libgcc), whose handler resolves the name
through the same table (gcc.cc:6931). The variable starts with
the value of the default LIBGCC_SPEC, which holds a single option:
#define LIBGCC_SPEC "-lgcc"
Listing 1.3-4: the default LIBGCC_SPEC (gcc/gcc.cc:887).
On a target configured with ENABLE_SHARED_LIBGCC, the driver walks that string
at startup, looks for the literal -lgcc and replaces it:
const char *p = libgcc_spec;
int in_sep = 1;
/* Transform the extant libgcc_spec into one that uses the shared libgcc
when given the proper command line arguments. */
while (*p)
{
if (in_sep && *p == '-' && startswith (p, "-lgcc"))
{
init_gcc_specs (&obstack,
"-lgcc_s"
Listing 1.3-5: the shared-libgcc rewrite (gcc/gcc.cc:1922-1932).
init_gcc_specs assembles the replacement text
(gcc/gcc.cc:1816-1851). The text depends on
USE_LD_AS_NEEDED and LINK_EH_SPEC, so it differs between targets. That is
why the libgcc value in the conditional section is only roughly right, and why
you run -dumpspecs on your own toolchain.
LINK_COMMAND_SPEC: template order is link order
LINK_COMMAND_SPEC is the template for the whole link, and the order of its
directives is the order of the link command line. It also holds the guards that
-nostdlib and its relatives fail. Reading it shows why your objects sit
between the start files and the end files, and what each of those options
removes. Trimmed to what matters, with a note on each line:
%{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S: ← only when actually linking
%(linker) %l ← collect2/ld, then the link spec
%X %{o*} %{e*} ← your -Wl, options; -o; -e
%{!nostdlib:%{!r:%{!nostartfiles:%S}}} ← startfile: crt1 crti crtbegin
%o ← YOUR object files
%{!nostdlib:%{!r:%{!nodefaultlibs:
%(link_gcc_c_sequence)}}} ← expands to %G %L %G
%{!nostdlib:%{!r:%{!nostartfiles:%E}}} ← endfile: crtend crtn
%{T*} }}}}}}
Listing 1.3-6: LINK_COMMAND_SPEC, abridged
(gcc/gcc.cc:1159-1178).
Through the aliases in the names table, each %G that
%(link_gcc_c_sequence) expands to is the whole libgcc conditional. Three
properties of the link follow from the listing.
Link order. %S, %o, the libraries and %E reach the linker in that
order. The startfile and endfile split exists because %S and %E sit on
opposite sides of your object files, and Chapter 1.7
follows that order through a real link.
Guards. -nostdlib, -nostartfiles, -nodefaultlibs and -r are guards,
not C code: an option that you pass fails its %{!…:} guard, and the text
inside the guard disappears. If you pass -nostartfiles, it removes the %S
line and the %E line: crt1, crti and crtbegin, and also crtend and crtn. In
the abridged listing, -nodefaultlibs guards only the %(link_gcc_c_sequence)
line, so libgcc and the C library go but the start and end files stay.
-nostdlib and -r sit in all three guards, so either one removes all three
lines.
Chapter 1.10 builds the full truth table
and checks it with -###.
Overridable pieces. A target customises one small name, not this whole
string. The %G %L %G order lives in its own spec so that a port can change it,
and the comment above it says so:
/* This is overridable by the target in case they need to specify the
-lgcc and -lc order specially, yet not require them to override all
of LINK_COMMAND_SPEC. */
#ifndef LINK_GCC_C_SEQUENCE_SPEC
#define LINK_GCC_C_SEQUENCE_SPEC "%G %{!nolibc:%L %G}"
#endif
Listing 1.3-7: LINK_GCC_C_SEQUENCE_SPEC
(gcc/gcc.cc:987-992).
%G appears twice in that value, once before %L and once after it.
Chapter 1.7 explains why the C library sits between
two copies of libgcc.
%D, %R, %M and %I: directives that read driver state
The directives %D, %R, %M and %I read the driver's own state: its
library search list, its sysroot, its multilib directory and its header
directories. A spec does not show those values.
Spec Files documents what each directive emits, and the table
adds what it reads and which option prints it.
| Directive | Reads | Emits | Print it with |
|---|---|---|---|
%D | the library search list | one -L per directory | -print-search-dirs |
%R | the sysroot | the bare path | -print-sysroot |
%M | the multilib OS directory | ., ../lib32, ../lib64 | -print-multi-os-directory |
%I | GCC's own header directories | -isystem …/include, …/include-fixed | -print-file-name=include |
%X %Y %Z | your -Wl, / -Wa, / -Wp, options | them, prefix stripped | -### |
Chapter 1.6 explains the multilib directories that %M
names. include-fixed/ holds patched copies of the system's headers, which
Chapter 1.8 explains.
The long comment that defines the language documents %D and %R in the
driver's own words:
%D Dump out a -L option for each directory in startfile_prefixes.
If multilib_dir is set, extra entries are generated with it affixed.
...
%R Output the concatenation of target_system_root and
target_sysroot_suffix.
Listing 1.3-8: two directives, self-documented
(gcc/gcc.cc:592-593 and :599-600).
startfile_prefixes in that comment is the list the table calls the library
search list. -print-search-dirs prints it on its libraries: line, and
Chapter 1.5 shows how the driver builds it.
%R is the sysroot mechanism for specs. Chapter 1.2
showed that a sysroot is a string prepended to certain paths, and %R is where a
spec writes that prepending. A target that wants sysroot-relative link behaviour
puts %R in its spec, and one that does not leaves it out. The implementation is
the concatenation that the comment describes (gcc.cc:6819-6830).
%i, %o, %g and %s: directives that name files
Directives such as %i, %o, %g and %s name files instead of options:
inputs, outputs, temporaries and files found on the library search list. They
put file names on the command lines that -### prints, including the objects
that %o places in the link template.
| Directive | Names |
|---|---|
%i | the input file for this step |
%o | all output files, which in the link are your .o files |
%O | the object suffix, .o |
%s | the name before it, looked up in the library search list |
%g… %u… %U… %j… | temporary files, differing in whether the name is shared or unique |
Chapter 1.1 showed the driver inventing a name for the
scratch .s file that carries assembly from cc1 to as. That name comes from
%|.s and %m.s in Listing 1.1-2. %| and %m act as %g unless -pipe is
given, and with -pipe, %| expands to - and %m to nothing
(gcc.cc:6340-6367). A %g name is shared, so two separate
programs agree on a file that nobody named:
$ gcc -### hello.c 2>&1 | grep -o '/tmp/cc[A-Za-z0-9]*\.s'
The command prints the same /tmp/cc….s name twice, once from the cc1 line
and once from the as line. Chapter 1.4
follows these temporary files.
%s: one search list for libc and libgcc startfiles
%s looks up the word before it in the library search list and substitutes
the full path it finds, so crt1.o%s puts the path of crt1.o on the command
line. One list serves the start files of two owners, the C library and GCC, and
the spec does not say which owner supplies which file. A startfile spec shows the
asymmetry:
crt1.o%s crti.o%s crtbegin.o%s
└─ from libc ─────┘ └─ from libgcc ─┘
All three names are written the same way, yet crt1.o comes from the C
library's sysroot and crtbegin.o from GCC's own library directory,
lib/gcc/<target>/<version>/, next to libgcc. The driver's comment defines %s
as a search of one list:
%s current argument is the name of a library or startup file of some sort.
Search for that file in a standard list of directories
and substitute the full name found.
Listing 1.3-9: %s (gcc/gcc.cc:571-573).
-print-file-name searches the same list for one name, so it shows which
owner's directory supplied each file:
$ gcc -print-file-name=crt1.o # the libc half
$ gcc -print-file-name=crtbegin.o # the libgcc half
If the search fails, -print-file-name prints the bare name back with no
error. Chapter 1.5 uses that echo to tell a
broken sysroot from a broken prefix.
Spec language summary with %(name), %{…} and %:function()
Name references, conditionals and function calls make up the rest of the spec
language, and a specs file can use all three. The driver documents the whole
language in a 230-line comment (gcc/gcc.cc:471-700).
Name references. %(name) expands any name. The one-letter aliases, such as
%G for libgcc, are in the names table.
Conditionals. The %{…} forms, with opt for an option name without its
leading dash, are these:
| Form | Meaning |
|---|---|
%{opt} | emit -opt if it was given |
%{opt*} | emit every switch starting -opt, arguments included |
%{opt:X} | emit X if -opt was given |
%{!opt:X} | emit X if -opt was not given |
%{opt1|opt2:X} | emit X if -opt1 or -opt2 was given |
%{.sfx:X} | emit X if the input file has suffix .sfx |
%{opt1:X;opt2:Y;:Z} | if / else-if / else, with Z as the default arm |
The case '{' branch of the expander hands every conditional to one function,
handle_braces (gcc.cc:6840, :7267). A
backslash escapes a character, so the colon in %{std=iso9899\:1999:X} is part
of the option name. Without the backslash, that colon would end the condition and
start the :X text.
Function calls. %:name(args) calls a function that the expander looks up in
a registry:
static const struct spec_function static_spec_functions[] =
{
{ "getenv", getenv_spec_function },
{ "if-exists", if_exists_spec_function },
...
Listing 1.3-10: the spec-function table
(gcc/gcc.cc:1775-1801), dispatched at
case ':', :6846.
Among the useful ones, %:getenv(VAR SUFFIX), %:if-exists(f) and
%:if-exists-else(a b) pick a file that is present, and
%:include(libgomp.spec) pulls in another specs file mid-expansion.
%:version-compare(...) gates on the OS version, as Darwin's specs do,
%:sanitize(address) tests which sanitizer is on, and %:gt,
%:debug-level-gt and %:dwarf-version-gt compare numbers. The returned
string is processed again as spec text. Used as a predicate,
%{%:function(args):X} emits X when the function returns something non-empty.
The table ends with EXTRA_SPEC_FUNCTIONS, so a port can add its own.
Writing a specs file for -specs=
A specs file passed with -specs= rewrites entries in the spec table, so it
changes a toolchain's behaviour without a rebuild. ARM's nano.specs is one
such file. Each entry replaces the slot it names, so if you add one option under
*link:, the target's link value is lost unless the entry appends with + or
keeps the old value with %rename. The GCC manual documents the file format
under Spec Files, and the -specs= option under
Overall Options.
*libgcc:
-lgcc -lgcc_eh
*startfile:
+ my-extra-crt.o
Listing 1.3-11: a two-entry specs file.
The syntax is *name: alone on a line, the value on the lines that follow, and a
blank line to end the entry. A value that starts with + followed by white
space appends to the old value instead of replacing it, and that test is one
line of C:
*(sl->ptr_spec) = ((spec[0] == '+' && ISSPACE ((unsigned char)spec[1]))
? concat (old_spec, spec + 1, NULL)
: xstrdup (spec));
Listing 1.3-12: replace or append, in set_spec
(gcc/gcc.cc:2106-2108).
Without the white space, set_spec takes the xstrdup branch: the old value is
replaced, and the new one starts with a literal +. + my-extra-crt.o in
Listing 1.3-11 appends to startfile, but +my-extra-crt.o would replace it.
That name also has no %s, so the driver passes my-extra-crt.o as written
instead of searching for it.
Two directives work only in a file, not in a spec. %rename old new moves a
spec's text to a new name (gcc.cc:2454), and %include FILE and
%include_noerr FILE splice in another file (:2411).
%rename keeps the old value under a new name, so the new value can refer to
it. Rename the original out of the way, then reference it:
%rename link old_link
*link:
%(old_link) -extra-flag
Listing 1.3-13: the wrapping idiom.
The new link value expands %(old_link) first and adds -extra-flag after
it, which + -extra-flag would also do. %rename also allows what + cannot,
new text before the old value, because the new value can name the old one at
any position.
A specs file may also create a name that did not exist, because set_spec adds
the entry when it finds none (gcc.cc:2066). A new name has an
effect only when another spec references it with %(name), as the new link
value does with %(old_link). Several -specs= options apply in the order
given, and -### shows the command lines that result:
$ gcc -specs=my.specs -### hello.c # see exactly what your override did
Spec precedence: compiled-in values, the specs file and -specs=
Specs reach the table from four sources, and a later source replaces what an earlier one wrote under the same name. The order decides which value a link uses when a target header, the driver and a specs file all set the same name. From first to last:
-
Compiled-in values. The defaults in
gcc.cc, and the replacements for them in the target's config headers. Both are fixed when GCC is built. -
Driver startup rewrites. The
libgccrewrite of Listing 1.3-5 is the one you are most likely to meet, and it is what makes-static-libgccwork at all. -
An installed
specsfile, in GCC's library directory,lib/gcc/<target>/<version>/(gcc.cc:8496-8499). GCC does not ship one by default, but if one is present it rewrites the toolchain with no diagnostic. -
-specs=FILEon the command line, in command-line order (gcc.cc:8633-8640).
--with-specs bypasses the table, as the section on self specs shows. To find
out whether an installed specs file is in play, look in the directory that
holds libgcc.a:
$ ls "$(dirname "$(gcc -print-libgcc-file-name)")"/specs
ls reports no such file on a toolchain that has none.
Checking specs with -dumpspecs and -###
Two commands answer most questions about specs: -dumpspecs shows what the
table holds, and -### shows what the driver does with it. When the two
disagree, something outside the table is at work, such as a self spec from
--with-specs.
$ gcc -dumpspecs # the whole table, current values
$ gcc -### hello.c # every expanded command line, nothing run
$ gcc -specs=my.specs -### hello.c # what your override actually did
-dumpspecs prints the table only after the driver has initialised it:
case OPT_dumpspecs:
{
struct spec_list *sl;
init_spec ();
for (sl = specs; sl; sl = sl->next)
printf ("*%s:\n%s\n\n", sl->name, *(sl->ptr_spec));
if (link_command_spec)
printf ("*link_command:\n%s\n\n", link_command_spec);
exit (0);
}
Listing 1.3-14: -dumpspecs (gcc/gcc.cc:4216-4226).
init_spec () runs first, with any startup rewrite the target does, such as
Listing 1.3-5, so -dumpspecs shows the live slots, not the macro text in the
source. The printf writes each entry as *name:, the value and a blank line,
which is the specs-file format. An entry copied from the dump can therefore be
edited and passed back with -specs=.
The driver also has a compile-time DEBUG_SPECS macro that prints every
%(name) expansion and every set_spec call
(gcc.cc:2110-2113). It works only in a driver rebuilt with the
macro defined, so it is a last resort.
--with-specs and self specs: options -dumpspecs cannot show
--with-specs adds its options through a self spec, which rewrites the driver's
argument list and never touches the spec table, so -dumpspecs cannot show
them. A toolchain configured this way passes options that no entry in the dump
explains, and -### shows them on each command line.
| Mechanism | What it does | In -dumpspecs? |
|---|---|---|
| built-in specs | the compiled-in table | yes |
--with-specs=… at configure time | rewrites the command line | no |
-specs=FILE at run time | reads a file into the table at startup | not by a plain -dumpspecs |
The install manual documents --with-specs under
Configuration as "additional command line driver SPECS".
--with-specs becomes CONFIGURE_SPECS
(gcc/configure.ac:1084-1089), which lands in an array of self
specs. A self spec is expanded against the driver's own arguments, and its
output rewrites them: it can add a switch, and %<opt removes -opt
(Chapter 1.9).
static const char *const driver_self_specs[] = {
"%{fdump-final-insns:-fdump-final-insns=.} %<fdump-final-insns",
DRIVER_SELF_SPECS, CONFIGURE_SPECS, GOMP_SELF_SPECS, GTM_SELF_SPECS,
Listing 1.3-15: driver_self_specs[] (gcc/gcc.cc:1361-1364),
applied at :8528-8529.
The first entry uses both forms: a conditional that adds a switch, and
%<fdump-final-insns, which removes one. CONFIGURE_SPECS sits in the same
array, so a --with-specs value can do both.
Three things to carry away
Every command line is a template, and the template's order is the command
line's order. Options such as -static-libgcc and -nostdlib are
conditionals in it, not C code.
A spec name is a slot, not a value. %G expands whatever the libgcc slot
holds after startup, which on shared-libgcc targets is not LIBGCC_SPEC's text.
Read -dumpspecs, not the macro.
A specs file rewrites a slot without a rebuild. *name: replaces the value,
+ appends, and %rename keeps the old value for a wrapper. Check the result
with -###.
Things that surprise people
+my-extra-crt.o replaces the value, and + my-extra-crt.o appends.
set_spec appends only when white space follows the +, and otherwise keeps
the + as text (Listing 1.3-12).
An installed specs file in GCC's library directory overrides the built-in
table. The driver reads it at startup with no diagnostic.
--with-specs never appears in -dumpspecs. It rewrites the argument list
through driver_self_specs, so only -### shows its effect.
Documentation coverage
The spec language has its own manual node, Spec Files
(gcc/doc/invoke.texi:37290), which documents the directives. It does not
cover:
- That
%Gexpands a mutable slot rather than the macro's text, and that the slot is rewritten at startup on shared-libgcc targets. The manual describes%Gas processingLIBGCC_SPEC, which is true only before startup. - That an installed
specsfile overrides the built-in table. - That
--with-specsrewrites your command line viadriver_self_specsrather than editing the table, and therefore cannot appear in-dumpspecs. - That a value appends only when its
+is followed by white space. The manual says only that the first character is+(invoke.texi:37340-37341), andset_specalso tests the next character (Listing 1.3-12).
Next: Chapter 1.4, From suffix to compiler: inputs, -x and temporary files,
how the driver decides what each input file is, and how it names the files
between programs.
1.4 Inputs, -x and temporary files: from suffix to compiler
GCC 15.2.0. To run the commands: an installed compiler with g++.
You rename start.S to start.s, and every #define in it stops having any
effect. You compile foo.cpp with gcc -c and it works, but when you link the
same file with gcc, the link fails on undefined std:: symbols. Nobody changed
a flag in either case.
The driver gives every input file a language before it runs anything, and it
reads that language from the end of the file name, never from the contents. The
language selects a spec, and the spec selects the programs. The specs also name
the temporary files that carry one program's output to the next, and the driver
deletes those files when the run ends unless -save-temps keeps them.
This chapter assumes Chapter 1.1, for -###, the .c
row of the compiler table (Listing 1.1-1) and the invoke_as spec (Listing
1.1-2), and Chapter 1.3, for the spec language and its
directives.
-x and add_infile: each input stored with its language
The driver stores every input file together with the language that -x set
before it, or with none. The compiler lookup reads that pair, so the position of
-x on the command line decides which files it covers. The driver reads its
command line in one pass, from left to right, and the input branch in Listing
1.4-1 hands add_infile whatever spec_lang holds at that moment:
for (j = 1; j < decoded_options_count; j++)
{
if (decoded_options[j].opt_index == OPT_SPECIAL_input_file)
{
const char *arg = decoded_options[j].arg;
...
add_infile (arg, spec_lang);
continue;
}
read_cmdline_option (&global_options, &global_options_set,
decoded_options + j, UNKNOWN_LOCATION,
CL_DRIVER, &handlers, global_dc);
}
Listing 1.4-1: inputs and options in one pass (gcc/gcc.cc:5009-5026).
spec_lang is one static variable (gcc.cc:3975), and the
OPT_x case is the one option handler that writes it:
case OPT_x:
spec_lang = arg;
if (!strcmp (spec_lang, "none"))
/* Suppress the warning if -xnone comes after the last input
file, because alternate command interfaces like g++ might
find it useful to place -xnone after each input file. */
spec_lang = 0;
else
last_language_n_infiles = n_infiles;
do_save = false;
break;
Listing 1.4-2: -x (gcc/gcc.cc:4625-4635).
-x therefore applies to every input file after it, up to the next -x, and to
no file before it. -x none clears the language, so later files go back to
their suffixes. The GCC manual documents both rules, with the suffixes and the
language names, under Overall Options. do_save = false
keeps -x off the switch list (gcc.cc:4707-4710), so no spec and
no sub-program sees it, and its only effect is the language stored next to each
file.
A -x with no input file after it has no effect, and the driver warns about it
(gcc.cc:5563-5564). -x none is exempt, because the g++ wrapper
in Listing 1.4-6 puts a -x none after each input file that it wraps, as the
comment in Listing 1.4-2 explains.
The input list holds more than input files. -Wl,, -Xlinker and -l go in
with the language "*", which means "linker input"
(gcc.cc:4429-4471), so a -lfoo keeps its position among your
object files. Chapter 1.7 shows where that position
ends up.
default_compilers[] and lookup_compiler: the last matching row wins
default_compilers[] is the table that maps an input file to a spec, and
lookup_compiler searches it from the last row back, so the last matching row
wins. The lookup decides what a -x name means, what a suffix means, and what
happens to a file that matches nothing. The comment on struct compiler states
the two rules: a file with no matching suffix "will be passed unchanged to the
loader", and "If multiple entries match a file, the last matching one is used"
(gcc.cc:1410-1417).
The table has two kinds of row. A suffix row such as {".c", "@c", ...} maps a
suffix to a language name. A language row such as {"@c", "<spec>", ...} holds
that language's spec. Listing 1.1-1 showed both rows for C. In lookup_compiler,
watch the two for loops, which start at the last row, and the recursive call at
the end, which follows a suffix row to its language row:
/* If this was specified by the user to be a linker input, indicate that. */
if (language != 0 && language[0] == '*')
return 0;
/* Otherwise, look for the language, if one is spec'd. */
if (language != 0)
{
for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
if (cp->suffix[0] == '@' && !strcmp (cp->suffix + 1, language))
...
error ("language %s not recognized", language);
return 0;
}
/* Look for a suffix. */
for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
...
if (cp >= compilers)
{
if (cp->spec[0] != '@')
/* A non-alias entry: return it. */
return cp;
/* An alias entry maps a suffix to a language.
Search for the language; pass 0 for NAME and LENGTH
to avoid infinite recursion if language not found. */
return lookup_compiler (NULL, 0, cp->spec + 1);
}
return 0;
Listing 1.4-3: lookup_compiler, abridged (gcc/gcc.cc:9364-9432).
Followed for one file, the function makes its decisions in this order:
- A linker input (
"*") gets no compiler. - A
-xlanguage wins.-x csearches for the row named@c, and the suffix is never examined. - Otherwise the suffix decides. Both loops start at the last row and go backwards, which is how "the last matching one is used" is implemented.
- A suffix row whose spec starts with
@is an alias, so the lookup starts again with the language name.
The argument to -x is therefore a row name without its @, and the valid
languages are the @ rows in your driver, not a list in the manual.
When nothing matches, the driver records the file "as explicit linker input"
(gcc.cc:9131-9135), so a file with no known suffix goes
straight to the linker. With -c nothing links, and the driver only warns that
the linker input is unused (gcc.cc:9293-9308). Two commands
show both branches:
$ gcc -### -c foo.txt # no cc1 line, only the warning
$ gcc -### -x c foo.txt # the suffix no longer decides
The first prints no cc1 line, only the warning. In the second, -x c takes
the language branch of Listing 1.4-3, so the suffix no longer decides.
.s against .S: the suffix decides where the pipeline starts
.s and .S map to different language rows, and each row starts the pipeline
at a different program. Of the two, only the .S row runs the preprocessor, so
a file renamed from start.S to start.s goes straight to as, and its
#define lines stop having any effect. Listing 1.4-4 shows both rows:
{".s", "@assembler", 0, 0, 0},
{"@assembler",
"%{!M:%{!MM:%{!E:%{!S:as %(asm_debug) %(asm_options) %i %A }}}}", 0, 0, 0},
{".sx", "@assembler-with-cpp", 0, 0, 0},
{".S", "@assembler-with-cpp", 0, 0, 0},
{"@assembler-with-cpp",
...
"%(trad_capable_cpp) -lang-asm %(cpp_options) -fno-directives-only\
%{E|M|MM:%(cpp_debug_options)}\
%{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
as %(asm_debug) %(asm_options) %m.s %A }}}}"
...
Listing 1.4-4: assembly with and without the preprocessor
(gcc/gcc.cc:1493-1510). The omitted #ifdef uses %|.s instead of
%m.s for assemblers that need - to read a pipe.
@assembler runs one program, as, on %i, the input file itself.
@assembler-with-cpp runs the preprocessor first, writes %|.s, and then runs
as on that file. The other rows read the same way, by the first program that
each one runs:
| Suffix | Language row | First program | Source |
|---|---|---|---|
.c | @c | cc1, which preprocesses internally | Listing 1.1-1 |
.i | @cpp-output | cc1 -fpreprocessed | gcc.cc:1490-1492 |
.h | @c-header | cc1, writing %i.gch | gcc.cc:1472-1489 |
.S, .sx | @assembler-with-cpp | the preprocessor, then as | Listing 1.4-4 |
.s | @assembler | as | Listing 1.4-4 |
- | none | the preprocessor, and only with -E | gcc.cc:1469-1471 |
The last row matches only the file name -, and its spec refuses to run without
-E:
%{!E:%e-E or -x required when input is from standard input}
The message names the other way out. With -x c, the lookup takes the language
branch of Listing 1.4-3 and never reaches the - row, so gcc -E -x c - works.
lang-specs.h: the C++ rows and their #C++ placeholders
The C++ rows of the compiler table come from the C++ front end's
lang-specs.h, which the build adds at the end of default_compilers[].
Placeholder rows at the start of the table stand in for a front end that was not
built. That layout decides what gcc foo.cpp does on any driver: it runs
cc1plus where C++ was built, and reports a missing C++ compiler where it was
not.
The C rows live in gcc.cc, and every other language's rows come from its front
end. The table ends with #include "specs.h" (gcc.cc:1512),
a file generated at build time with one #include per front end's
lang-specs.h (gcc/Makefile.in:2619-2625). configure lists a
front end's file only if that language is in --enable-languages
(gcc/configure.ac:7321-7327). C++ contributes suffix rows
such as {".cpp", "@c++", 0, 0, 0} and an @c++ row whose spec runs cc1plus
and then %(invoke_as) (gcc/cp/lang-specs.h:27-121). The same
suffixes also appear at the top of default_compilers[], with a spec that
starts with #:
/* Add lists of suffixes of known languages here. If those languages
were not present when we built the driver, we will hit these copies
and be given a more meaningful error than "file not used since
linking is not done". */
...
{".cc", "#C++", 0, 0, 0}, {".cxx", "#C++", 0, 0, 0},
{".cpp", "#C++", 0, 0, 0}, {".cp", "#C++", 0, 0, 0},
Listing 1.4-5: the placeholder rows (gcc/gcc.cc:1429-1437).
specs.h comes last and the search runs backwards, so a built front end's rows
match first and hide the placeholders. On a driver built without C++, .cpp
reaches the #C++ row, and the driver reports "%s: %s compiler not installed on this system" (gcc.cc:9062-9067). There is no @c++
placeholder, so -x c++ on that driver fails with "language %s not recognized" instead.
Both drivers use this one table, so gcc foo.cpp runs cc1plus just as
g++ foo.cpp does:
$ gcc -### foo.cpp ; g++ -### foo.cpp # same input, different link
The compile lines name the same program, and the link lines differ, because
g++ adds -lstdc++ before the specs run. The missing -lstdc++ is the gcc
link failure in the opening, and Chapter 1.11
shows how g++ adds it. The GCC manual documents both halves under
Invoking G++.
g++ and -x c++: wrapping .c, .i and .h inputs
g++ wraps every .c, .i and .h input in a -x option for the matching
C++ language, with a -x none after it, so the generic driver compiles those
files as C++. The wrapping, and the rule for when g++ skips it, explain why your
own -x before a list of C files covers only the first one. The GCC manual says
under Invoking G++ that g++ treats .c, .h and .i files as C++ "unless -x
is used", and the lang_specific_driver of g++ does the wrapping:
/* Wrap foo.[chi] files in a language specification to
force the gcc compiler driver to run cc1plus on them. */
if (args[i] & LANGSPEC)
{
...
case 'c':
generate_option (OPT_x, "c++", 1, CL_DRIVER,
&new_decoded_options[j++]);
break;
...
new_decoded_options[j++] = decoded_options[i];
generate_option (OPT_x, "none", 1, CL_DRIVER,
&new_decoded_options[j]);
}
Listing 1.4-6: g++ puts -x c++ before a C file and -x none after it
(gcc/cp/g++spec.cc:340-365).
g++ foo.c therefore reaches the generic driver as -x c++ foo.c -x none. A
.i file gets -x c++-cpp-output and a .h file gets -x c++-header. The
-x none stops the wrapper from leaking onto the next file, and Listing 1.4-2
exempts it from the "after last input file" warning.
A comment says the wrapping is skipped "if a specified -x option is currently
active" (g++spec.cc:264-265), but the code does less.
Any -x sets a flag (:204), and the next input file clears
it (:258-262), so only the first file after your -x is
exempt.
%g, %u, %U and %j: temporary names as spec directives
Spec directives name the temporary files that pass between programs: %g,
%u, %U and %j, from the list in Chapter 1.3. The
directive that a spec uses decides whether two commands share a file name, which
is why all inputs in one run share a .s file but not a .o file. %| and %m
act as %g unless -pipe is in effect, and the GCC manual documents all six
under Spec Files. The spec that names each input's object file
shows them at work:
"%a %Y %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}";
Listing 1.4-7: where the object file gets its name (gcc/gcc.cc:1311).
With -c the object is the output you asked for: your -o, or %b%O, the input
base name plus .o. Without -c it is a temporary: %u%O creates a new name
with the object suffix, and %d marks it for deletion. %w marks the same name
as this input's output, so %o passes it to the link.
The .s file uses %|.s and %m.s (Listing 1.1-2), which act as %g.s. The
difference between %g and %u is one test in the code that hands out names:
for (t = temp_names; t; t = t->next)
if (t->length == suffix_length
&& strncmp (t->suffix, suffix, suffix_length) == 0
&& t->unique == (c == 'u' || c == 'U' || c == 'j'))
break;
/* Make a new association if needed. %u and %j
require one. */
if (t == 0 || c == 'u' || c == 'j')
{
...
temp_filename = make_temp_file (t->suffix);
...
Listing 1.4-8: one name per suffix, or a new one each time
(gcc/gcc.cc:6492-6528).
The list temp_names keeps one entry per suffix for %g, and one per suffix for
the %u family. %g reuses its entry, %u puts a new name in its entry each
time, and %U reads the name that the last %u with that suffix wrote. The
default ASM_FINAL_SPEC shows why %U exists: with -gsplit-dwarf it runs
objcopy on %U%O, the object that %u%O named a moment before
(gcc.cc:711-720).
Only driver::finalize resets temp_names (gcc.cc:11349), so
nothing clears it during a run. "Chosen once per compilation", in the comment on
%g (gcc.cc:500-502), therefore means once per driver run. All
inputs in one command share one .s name, and each input gets its own .o
name:
$ gcc -### a.c b.c 2>&1 | grep -o '/tmp/cc[A-Za-z0-9]*\.[so]'
The same .s path appears for both inputs, and the two .o paths differ.
Sharing is safe because execute waits for every command it starts
(gcc.cc:3458-3467). The .o files must all exist when the
linker runs, so they cannot share.
%j usually names no real file. It expands to the host's bit bucket, /dev/null
by default (gcc/system.h:740-742), when that is writable and
-save-temps is off (gcc.cc:6319-6339). cc1_options uses it for
-fsyntax-only, which still needs an -o (gcc.cc:1296).
The name itself comes from libiberty's make_temp_file. It takes the directory
from TMPDIR, TMP or TEMP, then tries P_tmpdir, /var/tmp, /tmp and .
(libiberty/make-temp-file.c:131-147). It adds cc, six random
characters and the suffix, and creates the file with mkstemps
(:203-222). Of those variables, the GCC manual documents only
TMPDIR, under Environment Variables.
%d, %w and the delete queues: cleanup on success and failure
The driver deletes the names that %g, %u and %d mark at the end of every
run, whether or not a step failed. After a failure it also deletes the outputs
that %w marks, so a failed compile leaves neither its temporaries nor a
half-written output behind. To keep the intermediate files, ask for them with
-save-temps.
Each marked name goes into one of two queues. The comment above store_arg says
that a DELETE_ALWAYS file "should be deleted eventually" and a
DELETE_FAILURE file "should be deleted if this compilation fails"
(gcc.cc:2191-2196). %g, %u and %d feed the first queue, and
%w, the output mark, feeds the second (gcc.cc:5774). At the
end of the run the driver empties both:
if (seen_error ())
delete_failure_queue ();
delete_temp_files ();
Listing 1.4-9: cleanup in driver::final_actions (gcc/gcc.cc:9318-9320).
delete_temp_files runs whether or not a step failed, and
delete_failure_queue runs only when seen_error () is true. The driver does
not always wait for the end of the run. When the commands for one input fail, it
deletes that input's outputs at once (gcc.cc:9137-9146),
and a fatal signal empties both queues too (gcc.cc:8133-8138).
-pipe: %| and %m replace the temporary file with a pipe
-pipe changes two directives, %| and %m, so that cc1 writes to a pipe and
as reads its standard input, with no temporary .s file between them. The GCC
manual documents the option under Overall Options as using
"pipes rather than temporary files" between the stages. When it is in effect,
%| expands to - and %m expands to nothing (gcc.cc:6340-6367).
The | that Chapter 1.1 pointed out in invoke_as
becomes a pipe only under -pipe, as the code that reads it says: "A `|' before
the newline means use a pipe here, but only if -pipe was specified. Otherwise,
execute now and don't pass the `|' as an arg" (gcc.cc:6157-6166).
cc1 gets -o -, and on the as line %m.s leaves nothing, while %|.s
leaves a - on targets that define AS_NEEDS_DASH_FOR_PIPED_INPUT. -###
shows the result:
$ gcc -### -pipe -c foo.c
Each command that feeds the next one ends in a | in that output
(gcc.cc:3369-3372). -save-temps wins over -pipe: the driver
warns that -pipe is ignored and turns pipes off
(gcc.cc:5472-5478).
-save-temps: the same directives, predictable names
-save-temps adds no new directive. It changes what %g, %u and %U produce,
so the temporaries stay on disk under names you can predict. In that mode the
driver builds each name from the auxiliary-output prefix, the base name and the
suffix, and clears the deletion mark (gcc.cc:6408-6490).
The prefix is the one that cc1 receives as -dumpdir. The GCC manual documents
-save-temps, and its =cwd and =obj forms, under
Developer Options.
-save-temps also changes the C pipeline, and the comment over the @c spec
explains the part that Listing 1.1-1 left out:
/* cc1 has an integrated ISO C preprocessor. We should invoke the
external preprocessor if -save-temps is given. */
...
%{save-temps*|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
%(cpp_options) -o %{save-temps*:%b.i} %{!save-temps*:%g.i} \n\
cc1 -fpreprocessed %{save-temps*:%b.i} %{!save-temps*:%g.i} \
%(cc1_options)}\
Listing 1.4-10: -save-temps splits the preprocessor out
(gcc/gcc.cc:1456-1465).
-save-temps therefore runs one more process per C file: the preprocessor writes
%b.i, and cc1 -fpreprocessed reads it. The C++ row does the same with %b.ii
(cp/lang-specs.h:111-114).
$ gcc -save-temps -c foo.c && ls foo.* # the temporaries, kept
foo.i and foo.s appear next to foo.o. With -c and no -o, the driver sets
no prefix, so each name is the input's base name plus a suffix.
A predictable name can collide with the input. Compile foo.s with
-x assembler-with-cpp -save-temps, and the preprocessed output from %|.s would
also be foo.s. When the name the driver built is the input file, by name or by
device and inode number, it uses a random temporary name instead
(gcc.cc:6448-6489). The GCC manual calls this "sensible
enough to avoid overwriting an input source file"
(invoke.texi:21304-21306).
-dumpdir and -dumpbase: the a- prefix on kept files
The driver names each kept file from a prefix and a base name, which -dumpdir
and -dumpbase set. Since GCC 11, a run that links takes the prefix from the
output's base name, so plain gcc -save-temps foo.c keeps a-foo.i rather than
foo.i. Run the -save-temps command again without -c:
$ gcc -save-temps foo.c && ls a-foo.*
The kept files are a-foo.i, a-foo.s and a-foo.o, because when the driver
links, "the .o outputs that would have been temporary become aux outputs"
(gcc.cc:5152-5154). Each auxiliary output, such as a
kept temporary or a .dwo file, gets the base name of the link output and a
dash as a prefix, and with no -o that base name is a
(gcc.cc:5325-5326). The GCC manual documents this naming at
length under Overall Options, in the entries for -o,
-dumpbase and -dumpdir.
The comment that specifies the scheme shows the same prefix without
-save-temps, on the .dwo files that -gsplit-dwarf writes:
When compiling and linking, no -dump* nor -save-temps=*, .o
outputs are temporary, aux outputs land in the dir of the output,
prefixed with the basename of the linker output:
...
# gcc b.c d.c [-o a.out] -gsplit-dwarf
-> cc1 -dumpdir a- -dumpbase b.c -dumpbase-ext .c # a-b.dwo
&& cc1 -dumpdir a- -dumpbase d.c -dumpbase-ext .c # a-d.dwo
&& link ... [-o a.out]
Listing 1.4-11: from the comment that specifies the naming scheme
(gcc/gcc.cc:5123-5135). The whole comment is
:5093-5224.
cc1 and cc1plus receive the result as -dumpdir, -dumpbase and
-dumpbase-ext, which a spec function, %:dumps, writes into cc1_options
(gcc.cc:1273-1288). The driver also appends -dumpdir to
COLLECT_GCC_OPTIONS (gcc.cc:5666-5684), so
'-dumpdir' 'a-' shows up in that environment variable too, where
Chapter 1.9 reads it.
$ gcc -### foo.c 2>&1 | grep -o -- '-dumpdir [^ ]*'
The -dumpdir argument is a-, because the command links and names no
output. %b, and %g in -save-temps mode, read this prefix
(gcc.cc:489-497), and three cases change it:
- When the output has the same base name as the single input, there is no prefix.
gcc -save-temps foo.c -o fookeepsfoo.iandfoo.s(gcc.cc:5358-5376). -dumpdir PFXsets the prefix.-save-temps=cwdand-save-temps=objset it too, and "the one that appears last prevails" (gcc.cc:5093-5094).-dumpbase NAMEsets the base name. With several inputs, the driver adds it to the prefix instead (gcc.cc:5094-5096).
Before GCC 11.
-save-tempsnamed every file after the input and put it in the current directory. In GCC 10.5.0, plain-save-tempssetSAVE_TEMPS_CWD(gcc/gcc.c:4149-4152), and%bwas the input base name unless-save-temps=objand-osupplied a prefix (gcc/gcc.c:5370-5378, and the GCC 10 manual atinvoke.texi:16320-16328). In GCC 15.2.0,gcc -save-temps foo.cwritesa-foo.*, andgcc -save-temps -c src/foo.c -o build/foo.owritesbuild/foo.iwhere GCC 10 wrote./foo.i. A script that collects.ifiles from the current directory breaks across that boundary.
-fno-rtti on a C file: the driver passes it and cc1 warns
The driver accepts an option if any front end knows it, and leaves the language
check to the compiler that the suffix chose. -fno-rtti on a C file therefore
gets a warning from cc1 and nothing from the driver. The split matters because
the suffix chooses the compiler, so an option can reach a compiler that does not
understand it.
The driver reads every option against the full option table, which the build
generates from each front end's .opt files
(Chapter 2.4 shows how). An option that is not a
driver option goes to a callback with this policy:
/* At this point, non-driver options are accepted (and expected to
be passed down by specs) unless marked to be rejected by the
driver. Options to be rejected by the driver but accepted by the
compilers proper are treated just like completely unknown
options. */
Listing 1.4-12: the driver accepts every front end's options
(gcc/gcc.cc:3959-3963).
After that, the driver checks only that some spec mentions the option
(gcc.cc:9463-9476), and rejects the rest as unrecognized
(gcc.cc:8770-8787). -fno-rtti on a C file passes, because
cc1_options passes %{f*} (gcc.cc:1290). cc1 then checks the
option against its own language, and only warns:
else if (ok_langs[0] != '\0')
/* Eventually this should become a hard error IMO. */
warning (0, "command-line option %qs is valid for %s but not for %s",
text, ok_langs, bad_lang);
Listing 1.4-13: the wrong-language warning (gcc/opts-global.cc:111-114).
$ gcc -c -fno-rtti foo.c # cc1 warns, the driver does not
The warning names the languages from the option's entry, C++ ObjC++ for
frtti (gcc/c-family/c.opt:2296-2297). The exception is .S: when
cc1 preprocesses assembly with -lang-asm, it accepts every C-family option
with no diagnostic, "since the driver may pass them through"
(gcc/c-family/c-opts.cc:267-274).
Three things to carry away
The suffix picks a row, and the row picks the programs. -x replaces the
suffix for every later file until -x none, and a name with no known suffix goes
to the linker.
Temporary files are spec directives. %g gives one name per suffix for the
whole run, %u a new name each time, and %U the last %u. The driver deletes
them at the end, even after a failure.
-save-temps and -dumpdir decide the kept names. Since GCC 11, a
compile-and-link run prefixes them with the output's base name, a- by default.
Things that surprise people
gcc -save-temps foo.c writes a-foo.i, not foo.i. Add -c, or name the
output foo, to get foo.i.
g++ -x c a.c b.c compiles b.c as C++. g++ skips its -x c++ wrapper
only for the first file after your -x. Check it with g++ -### -x c a.c b.c.
gcc -c notes.txt compiles nothing and does not fail. If the file exists, the
driver only warns that a linker input is unused.
A driver without C++ gives two different errors. gcc foo.cpp says the C++
compiler is not installed. gcc -x c++ foo.cpp says the language is not
recognized.
Documentation coverage
The suffix list and -x are in Overall Options
(gcc/doc/invoke.texi:1549, -x at :1700). Auxiliary output names are
documented at length under -o (:1768), -dumpbase (:1839) and
-dumpdir (:1962). -pipe is at :2251 and -save-temps at :21299. The
Spec Files node (gcc/doc/invoke.texi:37290) documents %d,
%g, %u, %U, %j, %| and %m (:37457-37505), and Environment Variables
documents TMPDIR (:38043).
What is not documented:
- That the compiler table is searched from its last row, and that its first rows are placeholders that turn a missing front end into "compiler not installed".
- That
-x LANGlooks up a row named@LANG, so the valid languages are the ones your driver was built with. - That "once per compilation" for
%gmeans once per driver run, so every input shares the%g.sfile. - That temporaries are deleted when a step fails. The Spec Files node says
%dfiles are deleted "if GCC exits successfully" (invoke.texi:37458-37460). The code deletes them in both cases. - That
-save-tempsruns the preprocessor as a separate process for C and C++. - That a missing
-ocounts asawhen the driver builds the prefix. The manual states the rule in terms of the output name, and thea-prefix appears only in the source comment (gcc.cc:5161-5164). - That
g++wraps.c,.iand.hinputs in-x c++…-x none, and that your own-xexempts only the next file. The manual says these files are C++ "unless -x is used" (invoke.texi:2364-2365), as if one-xcovered them all. - That the driver accepts any front end's option and leaves the language check to the compiler.
Next: Chapter 1.5, How the driver builds its search lists: -B and --sysroot,
how the driver finds cc1, as and the other programs that these rows name,
and every file that a spec asks for with %s.
1.5 How the driver builds its search lists: -B and --sysroot
GCC 15.2.0. To run the commands: an installed compiler, and a cross compiler such as arm-linux-gnueabihf-gcc.
Your cross compiler cannot find crt1.o. You add --sysroot=/arm-rootfs, and
now it can. crtbegin.o is missing too, so you try the same flag on it, and
it is still missing: --sysroot has no effect on it.
Both files reach the link line through the same directive, %s, and the driver
looks both up in the same list, startfile_prefixes. One follows your sysroot
and the other ignores it, because two functions register the entries of that
list, add_prefix and add_sysrooted_prefix, and only the second prepends the
sysroot. The order of the registrations is the search order, and -B,
--sysroot and the configure options each touch a different part of it.
This chapter assumes Chapter 1.1 for -### and the
programs the driver runs, and Chapter 1.2 for
add_sysrooted_prefix, the libsubdir and the tooldir. It also assumes
Chapter 1.3 for the %s, %D and %R directives, and
for a spec name as a slot whose value can change.
exec_prefixes for programs, startfile_prefixes for files
The driver keeps one search list for the host programs it runs, exec_prefixes,
and another for target files such as crt1.o and libraries,
startfile_prefixes. A flag can feed one list, the other or both, so the first
question to ask of a flag that moves a search path is which list it feeds. A
third list, for headers, is covered in
Chapter 1.8. -print-search-dirs prints the
first two:
$ gcc -print-search-dirs
It prints each list on a line of its own, under the name in the last column:
| List | Finds | Printed as |
|---|---|---|
exec_prefixes | host programs: cc1, as, ld, collect2 | programs: |
startfile_prefixes | target files: crt*.o and every -l | libraries: |
The two lists live in separate variables. -L feeds only startfile_prefixes,
and -B feeds all three lists, which makes it the blunt instrument. The GCC
manual documents both flags under Directory Options, and
-print-search-dirs with the other -print-* options under
Developer Options. Despite its name, exec_prefixes is a driver
list, not the configure variable $exec_prefix, which
Chapter 1.2 describes as the root for
machine-dependent files.
Every -L option that the driver generates for the linker comes out of
startfile_prefixes, through one directive, %D:
%D Dump out a -L option for each directory in startfile_prefixes.
If multilib_dir is set, extra entries are generated with it affixed.
Listing 1.5-1: %D (gcc/gcc.cc:592-593; handler at
:6250).
For -l, the driver's library search path is therefore not a path it searches
but a list it converts into -L options. The driver never opens a library file:
it emits -l and -L and lets ld resolve them. It does walk the list itself
for a startfile named with %s, which is how it finds crt1.o and
crtbegin.o. -print-file-name walks it too, so that it can report what ld
would conclude.
The order startfile_prefixes is built in
The driver builds startfile_prefixes at startup, and the order of the calls
that register its entries is the search order. The entries come from six places,
from the command line to the target's configuration, and the place an entry
comes from decides both its rank and whether --sysroot moves it:
-Bprefixes, from the command line (gcc.cc:4590).GCC_EXEC_PREFIX, from the environment (gcc.cc:4784).LIBRARY_PATH, from the environment, for native compilers only (gcc.cc:4923).- The relocated install prefix, computed from
argv[0](gcc.cc:4818-4835). - The tool directory,
$prefix/<target>/lib/(gcc.cc:5537-5539). - Either
STARTFILE_PREFIX_SPEC(gcc.cc:8579-8587) or theSTANDARD_STARTFILE_PREFIX*chain (gcc.cc:8590-8630), never both.
The internals manual documents this order, not the user manual. Its entry at
gcc/doc/tm.texi:570 begins "Here is the order of prefixes tried for
startfiles" and lists the prefixes with their conditions. Of the manual
references in Part I, info gccint 'Target Macros' Driver is the one to keep at
hand.
-B wins, and nothing can sort before it
-B adds its argument to all three search lists at the driver's highest
priority, so a -B directory is searched before anything from the environment
or the configuration. That reach is why -B fixes problems you did not know you
had and breaks things you did not expect. In the option's handler, watch the
three add_prefix calls at the end and the comment on a missing directory
separator:
case OPT_B:
{
size_t len = strlen (arg);
/* Catch the case where the user has forgotten to append a
directory separator to the path. Note, they may be using
-B to add an executable name prefix, eg "i386-elf-", in
order to distinguish between multiple installations of
GCC in the same directory. Hence we must check to see
if appending a directory separator actually makes a
valid directory name. */
if (!IS_DIR_SEPARATOR (arg[len - 1])
&& is_directory (arg))
{
...
}
add_prefix (&exec_prefixes, arg, NULL,
PREFIX_PRIORITY_B_OPT, 0, 0);
add_prefix (&startfile_prefixes, arg, NULL,
PREFIX_PRIORITY_B_OPT, 0, 0);
add_prefix (&include_prefixes, arg, NULL,
PREFIX_PRIORITY_B_OPT, 0, 0);
}
Listing 1.5-2: -B (gcc/gcc.cc:4590-4619).
The three add_prefix calls are the whole of -B's definition. It is not a
library path option or an executable path option, but one prefix applied to
programs, link inputs and headers at once.
The driver appends the trailing / only when the result names a directory, and
the comment gives the reason. A -B argument without a trailing separator can be
a legitimate executable name prefix, such as i386-elf-. The driver must
therefore check that appending a separator names a real directory before it
appends one. If you write -B/opt/alt and /opt/alt exists, you get
/opt/alt/. If it does not exist, the driver takes your programs to be called
/opt/altcc1 and so on.
PREFIX_PRIORITY_B_OPT is the highest priority there is, and the enum that
defines it has exactly two members:
/* Ranking of prefixes in the sort list. -B prefixes are put before
all others. */
enum path_prefix_priority
{
PREFIX_PRIORITY_B_OPT,
PREFIX_PRIORITY_LAST
};
Listing 1.5-3: the priority enum (gcc/gcc.cc:3120-3127).
Every environment contribution and every compiled-in default lands at
PREFIX_PRIORITY_LAST, where entries are ordered only by when they were added.
-B therefore beats the environment, the environment beats the compiled-in
defaults, and there is no way to express "before -B".
-B does not move C++ header search. It adds GCC's own header directories,
which is enough to change which <stdint.h> a compile uses but not which
<vector>. Chapter 1.8 and
Chapter 1.12 explain that asymmetry. The
driver's -B is also unrelated to the linker's -Bstatic.
make_relative_prefix: relocating a moved toolchain from argv[0]
The driver recomputes its install prefix from argv[0] on every run, using
libiberty's make_relative_prefix. An installed GCC tree moved to another
directory therefore keeps working, and RPATH plays no part in it. The relocated
install prefix is also the entry that finds crtbegin.o, the file that ignored
--sysroot:
gcc_libexec_prefix = standard_libexec_prefix;
#ifndef VMS
/* FIXME: make_relative_prefix doesn't yet work for VMS. */
if (!gcc_exec_prefix)
{
gcc_exec_prefix = get_relative_prefix (decoded_options[0].arg,
standard_bindir_prefix,
standard_exec_prefix);
gcc_libexec_prefix = get_relative_prefix (decoded_options[0].arg,
standard_bindir_prefix,
standard_libexec_prefix);
if (gcc_exec_prefix)
xputenv (concat ("GCC_EXEC_PREFIX=", gcc_exec_prefix, NULL));
}
Listing 1.5-4: relocation (gcc/gcc.cc:4822-4835). get_relative_prefix
is make_relative_prefix from libiberty, assigned at
:4816.
The three arguments give where the driver was configured to be installed,
standard_bindir_prefix and standard_exec_prefix, and where it was started
from, decoded_options[0].arg, which is argv[0]. The function applies the
same relative relationship to the new location. If you configured with
--prefix=/opt/gcc-arm and the binary is now at /home/me/toolchain/bin/gcc,
gcc_exec_prefix is computed as /home/me/toolchain/lib/gcc/. The GCC
manual states the rule under GCC_EXEC_PREFIX in
Environment Variables. When that variable is not set, GCC
"attempts to figure out an appropriate prefix to use based on the pathname it is
invoked with".
The xputenv call near the end exports the result as GCC_EXEC_PREFIX, whether
or not you set that variable yourself. Relocation and the environment variable
are therefore one mechanism, and the driver's own comment a few lines later says
so:
/* From this point onward, gcc_exec_prefix is non-null if the toolchain
is relocated. The toolchain was either relocated using GCC_EXEC_PREFIX
or an automatically created GCC_EXEC_PREFIX from
decoded_options[0].arg. */
Listing 1.5-5: the driver's summary of its own state
(gcc/gcc.cc:4855-4858).
Setting GCC_EXEC_PREFIX yourself pre-empts the computation, because the code
in Listing 1.5-4 runs only when gcc_exec_prefix is null.
Chapter 1.9 covers the variable.
Relocating the sysroot: only under $exec_prefix
Relocation moves GCC's own tree, but in general it does not move the sysroot.
The driver relocates a sysroot only when it was configured inside
$exec_prefix, so the configure line decides whether a prebuilt cross toolchain
unpacked in a new directory takes its sysroot along. The install manual states
the condition under Configuration:
If the specified directory is a subdirectory of
${exec_prefix}, then it will be found relative to the GCC binaries if the installation tree is moved.
When the condition holds, configure defines an extra macro and the driver
relocates the sysroot too (gcc/configure.ac:176-182, acted on at
gcc/gcc.cc:5542-5559). A bare --with-sysroot, with no
argument, defaults to $exec_prefix/<target>/sys-root
(gcc/configure.ac:169-170), which meets the condition. The
default is therefore relocatable, and an explicit --with-sysroot=/arm-rootfs
is not.
The tool directory $prefix/<target>/: never sysrooted
The tool directory, or tooldir, $prefix/<target>/, goes on both lists
through add_prefix, not add_sysrooted_prefix, so --sysroot never moves it.
For a bare-metal toolchain it is the most important entry on the library list, because
newlib installs its libraries there. Two calls register it:
add_prefix (&exec_prefixes,
concat (tooldir_prefix, "bin", dir_separator_str, NULL),
"BINUTILS", PREFIX_PRIORITY_LAST, 0, 0);
add_prefix (&startfile_prefixes,
concat (tooldir_prefix, "lib", dir_separator_str, NULL),
"BINUTILS", PREFIX_PRIORITY_LAST, 0, 1);
Listing 1.5-6: the tool directory (gcc/gcc.cc:5534-5539).
The first call puts $prefix/<target>/bin/ on the program list, and the second
puts $prefix/<target>/lib/ on the library list. Because neither applies the
sysroot, -lc works with no -L and no sysroot once newlib is installed in
$prefix/<target>/lib/. For the same reason, a cross install finds
libstdc++.so there rather than in the sysroot, whatever --sysroot you pass.
The last argument of the library call, 1, marks the entry as an OS multilib
prefix, which changes how the driver expands it.
Chapter 1.6 explains that expansion.
The STANDARD_STARTFILE_PREFIX chain and the cross-compiler gate
The last step of the order adds either the target's STARTFILE_PREFIX_SPEC or
the STANDARD_STARTFILE_PREFIX chain. The chain runs only for a native compiler
or a compiler with a configured sysroot. A cross compiler with no sysroot
therefore gets no /lib and no /usr/lib, which is why its libraries: line
can look short. If the target defines STARTFILE_PREFIX_SPEC, the spec wins
outright:
/* Look for startfiles in the standard places. */
if (*startfile_prefix_spec != 0
&& do_spec_2 (startfile_prefix_spec, NULL) == 0
&& do_spec_1 (" ", 0, NULL) == 0)
{
for (const char *arg : argbuf)
add_sysrooted_prefix (&startfile_prefixes, arg, "BINUTILS",
PREFIX_PRIORITY_LAST, 0, 1);
}
Listing 1.5-7: the STARTFILE_PREFIX_SPEC branch
(gcc/gcc.cc:8579-8587).
The spec's entries go through add_sysrooted_prefix, so they follow --sysroot.
Without the spec, the standard chain runs, behind a guard:
/* We should eventually get rid of all these and stick to
startfile_prefix_spec exclusively. */
else if (*cross_compile == '0' || target_system_root)
Listing 1.5-8: the gate (gcc/gcc.cc:8588-8590).
The first condition holds for a native compiler, and the second when a sysroot is
configured. The gate is deliberate, because searching the host's /usr/lib for
target libraries gives file in wrong format errors from the linker or, worse,
a link that succeeds against the wrong objects.
The machine-dependent part of the chain also differs between native and cross
compilers. MD_EXEC_PREFIX, MD_STARTFILE_PREFIX and MD_STARTFILE_PREFIX_1
are #undef'd outright for a cross compiler, with the comment "Don't use these
prefixes for a cross compiler" (gcc/gcc.cc:1620-1624).
/lib/ and /usr/lib/ under the sysroot: why crt1.o moves
Inside the gate, the driver registers the two standard prefixes, /lib/ and
/usr/lib/, with add_sysrooted_prefix, so --sysroot=/arm-rootfs turns
/lib/ into /arm-rootfs/lib/. That call is the whole sysroot mechanism for
libraries, and it is why crt1.o follows --sysroot. The comment above the
calls ties the sysroot to relocation as well:
/* Sysrooted prefixes are relocated because target_system_root is
also relocated by gcc_exec_prefix. */
if (*standard_startfile_prefix_1)
add_sysrooted_prefix (&startfile_prefixes,
standard_startfile_prefix_1, "BINUTILS",
PREFIX_PRIORITY_LAST, 0, 1);
if (*standard_startfile_prefix_2)
add_sysrooted_prefix (&startfile_prefixes,
standard_startfile_prefix_2, "BINUTILS",
PREFIX_PRIORITY_LAST, 0, 1);
Listing 1.5-9: where the sysroot gets glued on
(gcc/gcc.cc:8621-8630).
The macros behind the two variables default to the usual system library directories:
#ifndef STANDARD_STARTFILE_PREFIX_1
#define STANDARD_STARTFILE_PREFIX_1 "/lib/"
#endif
#ifndef STANDARD_STARTFILE_PREFIX_2
#define STANDARD_STARTFILE_PREFIX_2 "/usr/lib/"
#endif
Listing 1.5-10: the two standard prefixes
(gcc/gcc.cc:1613-1618).
The GCC manual documents the same rewrite for --sysroot under
Directory Options, as dir/usr/lib in place of /usr/lib. No
other code applies the sysroot, and nothing can apply it to an entry after the
entry is registered. The entries registered with plain add_prefix, which are
-B, GCC_EXEC_PREFIX, the relocated install prefix and the tool directory,
are therefore never sysrooted.
crt1.o and crtbegin.o take the two routes. crt1.o lives in the sysroot's
/usr/lib, which Listing 1.5-9 registers. crtbegin.o lives in the libsubdir,
which the relocated install prefix reaches through add_prefix. Both use the
same %s and the same list, and the function that registered each directory
decides how the file answers --sysroot.
--sysroot=%R: the driver passes the sysroot to ld
When ld supports it, the driver passes the sysroot to ld as --sysroot=, so
that ld's own built-in search directories and any =-prefixed path inside a
linker script become sysroot-relative. The sysrooted prefixes are therefore not
the only route from --sysroot to the link. The driver adds this one by
rewriting the link spec at startup:
#ifdef HAVE_LD_SYSROOT
/* Pass the --sysroot option to the linker, if it supports that. If
there is a sysroot_suffix_spec, it has already been processed by
this point, so target_system_root really is the system root we
should be using. */
if (target_system_root)
{
obstack_grow (&obstack, "%(sysroot_spec) ", strlen ("%(sysroot_spec) "));
obstack_grow0 (&obstack, link_spec, strlen (link_spec));
set_spec ("link", XOBFINISH (&obstack, const char *), false);
}
#endif
Listing 1.5-11: prepending the sysroot to the link spec
(gcc/gcc.cc:8554-8566).
Listing 1.5-11 shows a spec name acting as a slot, as
Chapter 1.3 describes for %G: the driver rewrites the
link slot at startup, by name, through set_spec. The text it prepends refers
to another spec, which is one line:
#ifndef SYSROOT_SPEC
# define SYSROOT_SPEC "--sysroot=%R"
#endif
Listing 1.5-12: SYSROOT_SPEC (gcc/gcc.cc:1189-1191).
%R expands to the sysroot, so --sysroot=/arm-rootfs on your command line
becomes --sysroot=/arm-rootfs on ld's command line. -### shows the link
command without running it:
$ gcc --sysroot=/arm-rootfs -### hello.c 2>&1 | grep -o '\-\-sysroot=[^ "]*'
Among the matches is the --sysroot=/arm-rootfs on the link command, which %R
put there through the link spec. A compiler configured for an ld without
--sysroot support skips the rewrite in Listing 1.5-11.
Choosing among --prefix, --with-sysroot, --sysroot and -B
--prefix, --with-sysroot, --with-build-sysroot, --sysroot and -B all
look like "where GCC looks for things", but they are five different mechanisms.
Three are set at configure time and two at usage time. They move different
trees, so the question to settle before reaching for one is whose files need to
move. The install manual documents the configure-time flags under
Configuration, and the table adds whose tree each one moves:
| Flag | When | Moves | Whose tree |
|---|---|---|---|
--prefix | configure | where GCC installs itself | GCC's own tree |
--with-sysroot | configure | the default target root for libc | C library's tree |
--with-build-sysroot | configure | libc's location during the build only | C library's tree |
--sysroot | usage | overrides the configured sysroot for one run | C library's tree |
-B | usage | three search lists at once | both |
--sysroot overwrites target_system_root (gcc.cc:4559),
which every add_sysrooted_prefix call and every %R then picks up. One
--sysroot therefore moves both the sysrooted prefixes and the --sysroot= that
ld receives.
--with-build-sysroot: a sysroot used only while building
--with-build-sysroot sets the sysroot used only while building the target
libraries, and it leaves no trace in the installed compiler. The option explains
a category of cross-build bug: a libstdc++ that lacks features although the
build reported no error. The configure code is literal:
AC_ARG_WITH(build-sysroot,
[...],
[if test x"$withval" != x ; then
SYSROOT_CFLAGS_FOR_TARGET="--sysroot=$withval"
fi], ...)
Listing 1.5-13: --with-build-sysroot (gcc/configure.ac:140-146).
The option appends --sysroot= to the command line that the build uses to
compile libgcc and libstdc++. The configure script of libstdc++ runs several
hundred compile-and-link probes against the target C library, and when those
probes cannot link, the features they test configure themselves as not
available. The result is a libstdc++ with missing features rather than a build
failure, which is why the build needs the option.
Chapter 3.3 returns to it.
Which prefix supplied a file: -print-file-name and -print-search-dirs
-print-file-name and -print-search-dirs show which prefix supplied a file,
so they turn a missing crt1.o or crtbegin.o into a lookup. On a cross
toolchain, four commands cover the sysroot, the two lists and one startfile from
each owner:
$ arm-linux-gnueabihf-gcc -print-sysroot # the baked-in sysroot
$ arm-linux-gnueabihf-gcc -print-search-dirs # the two lists
$ arm-linux-gnueabihf-gcc -print-file-name=crt1.o # the libc half
$ arm-linux-gnueabihf-gcc -print-file-name=crtbegin.o # the libgcc half
-print-file-name looks the name up with find_file, and its behaviour on
failure is the whole body of that function:
find_file (const char *name)
{
char *newname = find_a_file (&startfile_prefixes, name, R_OK, true);
return newname ? newname : name;
}
Listing 1.5-14: find_file (gcc/gcc.cc:8068-8072).
If the file is not found, -print-file-name prints your argument back
unchanged, with no error and exit status 0. -print-libgcc-file-name is the same
lookup, not a separate mechanism: it is one assignment,
print_file_name = "libgcc.a" (gcc/gcc.cc:4298). Different files
come from different owners, so the name that comes back unchanged points at the
tree to fix:
| Symptom | Diagnosis |
|---|---|
crt1.o printed back unchanged | the sysroot is wrong |
crtbegin.o printed back unchanged | the prefix or -B is wrong |
libraries: short on a cross compiler | no sysroot configured (Listing 1.5-8) |
-print-search-dirs looks right, link still fails | multilib expansion (Chapter 1.6) |
-print-search-dirs prints exactly three lines, one for each printf in its
handler:
printf (_("install: %s%s\n"),
gcc_exec_prefix ? gcc_exec_prefix : standard_exec_prefix,
gcc_exec_prefix ? "" : machine_suffix);
printf (_("programs: %s\n"),
build_search_list (&exec_prefixes, "", false, false));
printf (_("libraries: %s\n"),
build_search_list (&startfile_prefixes, "", false, true));
Listing 1.5-15: -print-search-dirs (gcc/gcc.cc:8795-8805).
install: is the resolved install root, and programs: and libraries: are
exec_prefixes and startfile_prefixes. Three facts decide how to read them:
- There is no
headers:line.cc1builds and prints the header search list, so no driver option can print it, and Chapter 1.8 shows how to askcc1. - The sysroot is already in the
libraries:entries, becauseadd_sysrooted_prefixprepended it when the list was built. An entry that does not start with your sysroot will never follow it. - The multilib suffixes are not in the entries, because the driver expands each
entry at lookup time, as Chapter 1.6 explains. A
directory can appear in
libraries:and still not be the one a given-mflag searches.
Three environment variables, GCC_EXEC_PREFIX, COMPILER_PATH and
LIBRARY_PATH, feed the same lists, and nothing on your command line shows
them. When a toolchain behaves differently in CI than on your desk, compare the
lists with and without them:
$ gcc -print-search-dirs
$ env -u GCC_EXEC_PREFIX -u COMPILER_PATH -u LIBRARY_PATH gcc -print-search-dirs
If the two outputs differ, one of the variables is set in that environment. Chapter 1.9 explains what each one adds.
Three things to carry away
The driver never opens a library file. It turns startfile_prefixes into
-L options and lets ld resolve every -l. It also walks the list itself, for
a %s startfile and for -print-file-name.
-B feeds all three lists, at the highest priority. It moves programs, link
inputs and GCC's headers at once.
A cross compiler with no sysroot gets no /lib and no /usr/lib. That gate
protects you from linking against the host's libraries.
Documentation coverage
The internals manual documents the startfile prefix order, with its conditions,
at gcc/doc/tm.texi:570. The GCC manual documents -B and
--sysroot under Directory Options
(gcc/doc/invoke.texi:19484), -print-search-dirs and -print-file-name under
Developer Options, and relocation under GCC_EXEC_PREFIX in
Environment Variables. The install manual documents the
configure-time flags under Configuration, from
gcc/doc/install.texi.
Four things are not documented:
- That
add_prefixversusadd_sysrooted_prefixis what decides whether a directory follows--sysroot. The manual lists which prefixes get "any sysroot modifications" per entry, which is the same information, but it never says the mechanism is per-entry and irreversible. - That
-print-search-dirsshows the list before multilib expansion. - That
-print-search-dirshas noheaders:line, and that no driver option prints header paths. - That
-print-file-namereturns its argument unchanged when the file is not found. The manual says only that it prints the full name of the file that would be used (invoke.texi:21572-21575).
Next: Chapter 1.6, Multilib and multiarch: several ABIs under one
triple, why the directory in libraries: is not
necessarily the directory that gets searched.
1.6 Multilib and multiarch: several ABIs under one triple
GCC 15.2.0. To run the commands: an installed x86-64 compiler, and a bare-metal ARM cross compiler for the Cortex-M4 example.
You pass -m32, with no extra -L and no other flag. The link still picks up a
32-bit libgcc.a and a 32-bit libc.so, out of an installation whose default
is 64-bit.
On a bare-metal toolchain you pass -mcpu=cortex-m4 -mfloat-abi=hard, and the
same mechanism fails. The link succeeds, and the binary is built against the
wrong float ABI.
One target triple can have several mutually incompatible ABIs. Multilib is how one toolchain ships a separate copy of every target library for each of them, and each copy is called a variant. The driver tries every search prefix up to four ways, adding the variant's directory names, and then walks the prefixes once more with no variant. That last walk is why the Cortex-M4 link succeeds instead of failing. Multiarch, Debian's layout of one library directory per triple, is a separate scheme that shares the same search code.
This chapter assumes Chapter 1.2, for the sysroot
and add_sysrooted_prefix, Chapter 1.3, for spec text and
its if/else form, and Chapter 1.5, for the prefix
lists that the driver searches and the add_prefix calls that build them.
MULTILIB_OPTIONS: one library build per option combination
MULTILIB_OPTIONS lists the options that select a variant, and the build
compiles the target libraries once for each combination of them that can be
used together. The driver then has to pick the matching set of libraries on
every invocation, and the -m32 and Cortex-M4 links both depend on that choice.
The internals manual documents the variable under
Target Makefile Fragments:
Write options that are mutually incompatible side by side, separated by a slash. Write options that may be used together separated by a space. The build procedure will build all combinations of compatible options.
For example, if you set
MULTILIB_OPTIONStom68000/m68020 msoft-float,Makefilewill build special versions oflibgcc.ausing the following sets of options:-m68000,-m68020,-msoft-float,-m68000 -msoft-float, and-m68020 -msoft-float.
One variable setting gives five variants of libgcc.a, and the other target
libraries multiply the same way. libstdc++, libatomic, newlib's libc.a and
every crt*.o are each built and installed once per variant.
Checking the variants with -print-multi-lib and -print-multi-directory
-print-multi-lib lists every variant that a toolchain has, while
-print-multi-directory names the one variant that a set of options selects.
A wrong-library link raises both questions, and two more: the name of the
variant's directory under OS conventions, and the file that the search found.
Each of these commands answers one question, as its comment says:
$ gcc -print-multi-lib # every variant this toolchain HAS
$ gcc -m32 -print-multi-directory # GCC-side dir for THIS invocation
$ gcc -m32 -print-multi-os-directory # OS-side dir for THIS invocation
$ gcc -m32 -print-file-name=libgcc.a # which variant actually won
-print-multi-lib prints one line per variant, in the format that its manual
entry gives: the directory name, a ;, then the switches that select the
variant. Each switch has @ in place of -, and there are no spaces between
the switches. For a toolchain with 32-bit and x32 variants, the output is shaped
like this:
.;
32;@m32
x32;@mx32
print_multilib_info prints these lines from the driver's table of variants,
multilib_select (gcc/gcc.cc:10042). The table has a
format of its own, in which a directory may carry a multiarch name after a :
(gcc/gcc.cc:9750-9761). The printed lines stop at the :.
If the variant you want is missing from -print-multi-lib, the library was
never built, and no -B or --sysroot can make the driver find it. You need a
toolchain built with that variant, or you need to build one. Make this check
first, because it is faster than reasoning about paths. A short list usually
means that GCC was configured with --disable-multilib, which gcc -v shows.
The install manual documents that option under Configuration.
-print-multi-directory and -print-multi-os-directory print the directory of
the selected variant, or . when there is no variant
(gcc/gcc.cc:8858-8865, :8888-8895). The GCC manual
documents every -print-* option in this chapter under
Developer Options.
multilib_dir and multilib_os_dir: one variant, two directory names
Each variant has two directory names: multilib_dir inside GCC's own install
tree, and multilib_os_dir inside the sysroot and other directories that follow
OS convention. Most of the confusion about multilibs comes from this split.
lib/gcc/<t>/<v>/32/ and <sysroot>/usr/lib32/ hold the same variant, so a
search by hand for a missing library has to look in both:
| GCC-side | OS-side | |
|---|---|---|
| Applies to | directories inside GCC's install, such as lib/gcc/<t>/<v>/<dir>/ | directories that follow OS convention, such as the sysroot's /lib and /usr/lib |
| Typical value | 32 | ../lib32 |
| Fragment variable | MULTILIB_DIRNAMES | MULTILIB_OSDIRNAMES |
| Driver variable | multilib_dir | multilib_os_dir |
| Print with | -print-multi-directory | -print-multi-os-directory |
The driver holds the two names, and a third for multiarch, in three variables.
The comment on each says that set_multilib_dir sets it from the compilation
options:
/* Subdirectory to use for locating libraries. Set by
set_multilib_dir based on the compilation options. */
static const char *multilib_dir;
/* Subdirectory to use for locating libraries in OS conventions. Set by
set_multilib_dir based on the compilation options. */
static const char *multilib_os_dir;
/* Subdirectory to use for locating libraries in multiarch conventions. Set by
set_multilib_dir based on the compilation options. */
static const char *multiarch_dir;
Listing 1.6-1: the three subdirectory variables
(gcc/gcc.cc:1666-1679).
There are two names, three with multiarch, because GCC and the distribution each
own a directory layout. GCC owns its own tree, so it may name its variants
however it likes. Whoever built the distribution decides the sysroot's layout:
/usr/lib32 on one, Debian's /usr/lib/i386-linux-gnu on another, /usr/lib64
on a third. The target's build configuration maps GCC's convention onto the
OS's.
set_multilib_dir chooses all three names once per invocation, by matching the
command-line switches against the table of variants
(gcc/gcc.cc:9764). The table is itself a spec, named
multilib, and is stored as a string in the spec table like any other
(gcc.cc:1733). The driver builds that string at run time,
because it can be too long for some compilers' string limits
(gcc.cc:1326-1330).
Spec text reads the OS-side name through %M, one of the directives from
Chapter 1.3 that read driver state. It expands to
multilib_os_dir, or to . when there is no variant:
case 'M':
if (multilib_os_dir == NULL)
obstack_1grow (&obstack, '.');
else
obstack_grow (&obstack, multilib_os_dir,
strlen (multilib_os_dir));
Listing 1.6-2: %M, the OS-side directory in spec text
(gcc/gcc.cc:6805-6811).
for_each_path: the four ways each prefix is tried
for_each_path tries every prefix on a search list up to four ways, in a fixed
order, and it is where the variant's directory names enter the search. Each
attempt is a block with its own comment inside the function
(gcc/gcc.cc:2778). Watch the fourth, because it is where
multilib_dir and multilib_os_dir part ways.
/* Look first in MACHINE/VERSION subdirectory. */
if (!skip_multi_dir)
{
memcpy (path + len, multi_suffix, suffix_len + 1);
Listing 1.6-3: attempt one, machine and version plus multilib_dir
(gcc/gcc.cc:2838-2841).
/* Some paths are tried with just the machine (ie. target)
subdir. This is used for finding as, ld, etc. */
if (!skip_multi_dir
&& pl->require_machine_suffix == 2)
Listing 1.6-4: attempt two, the machine name only
(gcc/gcc.cc:2847-2850).
/* Now try the multiarch path. */
if (!skip_multi_dir
&& !pl->require_machine_suffix && multiarch_dir)
Listing 1.6-5: attempt three, multiarch (gcc/gcc.cc:2858-2860).
/* Now try the base path. */
if (!pl->require_machine_suffix
&& !(pl->os_multilib ? skip_multi_os_dir : skip_multi_dir))
{
const char *this_multi;
...
if (pl->os_multilib)
{
this_multi = multi_os_dir;
Listing 1.6-6: attempt four, the bare prefix plus multilib_os_dir
(gcc/gcc.cc:2868-2884).
In Listing 1.6-6, a per-prefix flag, pl->os_multilib, chooses between
multi_os_dir and multi_dir. The flag is the last argument to add_prefix,
and Listing 1.5-6 in Chapter 1.5 registers the
tool directory with a final argument of 1. That argument marks the tool
directory as an OS-convention prefix, so the driver appends ../lib32 to it
rather than 32. A 32-bit variant therefore expands differently on the two
kinds of prefix:
$prefix/lib/gcc/<target>/<ver>/32/ ← multilib_dir, on a GCC-convention prefix
<sysroot>/usr/lib/../lib32/ ← multilib_os_dir, on an OS-convention prefix
The driver does not normalise .. away, so /usr/lib/../lib32/ is the real
shape of the path. That is why -print-multi-os-directory prints values such as
../lib32, and why an strace of a link shows paths that look wrong but are
correct.
Attempt two, require_machine_suffix == 2 in Listing 1.6-4, adds the machine
name only, and the driver uses it to find as and ld. It is how a toolchain
finds $prefix/<target>/bin/as with no version component, and it applies to
exec_prefixes, not to libraries.
The fallback pass in for_each_path: why a wrong-ABI link succeeds
The fallback pass is a second walk over the whole prefix list in
for_each_path, this time with no variant directories. It is why a link can
succeed against the wrong ABI, as the Cortex-M4 link does. Listing 1.6-7 starts
the second walk, and its comment says that it skips the directories already
tried:
/* Run through the paths again, this time without multilibs.
Don't repeat any we have already seen. */
if (multi_dir)
{
free (CONST_CAST (char *, multi_dir));
multi_dir = NULL;
...
}
else
skip_multi_dir = true;
Listing 1.6-7: the second pass (gcc/gcc.cc:2902-2914).
GCC makes the second walk on purpose, so that a target can ship only the default
variant of a library rather than every combination. That matters on ARM, where
the -mcpu and float-ABI axes multiply into an enormous number of combinations.
A wrong-ABI link happens when the variant directory holds no copy of a library.
The search then falls through to the default directory, and ld receives an
archive that it reads without complaint. Sometimes the link prints a diagnostic
about incompatible attributes, but on many targets it prints none.
The internals manual documents both walks, and a ! that turns the second one
off. A target for which falling through is worse than failing puts the ! at
the start of its MULTILIB_OSDIRNAMES entry:
If the osdir part begins with a
!, GCC will not search in the non-multilib directory and use exclusively the multilib directory. Otherwise, the compiler will examine the search path for libraries and crt files twice; the first time it will add multilib to each directory in the search path, the second it will not.
When a link may have fallen back, do not reason about directories. Ask the driver which file it found and which variant the options select:
$ gcc -mcpu=cortex-m4 -mfloat-abi=hard -print-file-name=libgcc.a
$ gcc -mcpu=cortex-m4 -mfloat-abi=hard -print-multi-directory
If the second command prints a variant directory and the first prints a path that does not contain it, the search fell through to the default variant.
-print-multiarch: per-triple directories, separate from multilib
-print-multiarch prints the multiarch directory name that the options select,
such as x86_64-linux-gnu. Multiarch is Debian's scheme of one library
directory per triple, so that several architectures' libraries can coexist in
one filesystem. It is independent of multilib, because a configuration can use
multiarch with no multilibs, but it shares the search code and has its own
attempt in for_each_path (Listing 1.6-5).
$ gcc -print-multiarch # e.g. x86_64-linux-gnu
When there is no multiarch directory, -print-multiarch prints an empty line,
not the . that -print-multi-directory and -print-multi-os-directory print
(gcc.cc:8867-8874). The difference matters when a script reads the
output.
A variant can have both a multiarch directory and an OS multilib directory. The internals manual fixes the order in which the driver searches them:
Each multiarch subdirectory will be searched before the corresponding OS multilib directory, for example
/lib/i386-linux-gnubefore/lib/../lib32.
SYSROOT_SUFFIX_SPEC: a different sysroot for each variant
SYSROOT_SUFFIX_SPEC lets a target give each variant a sysroot of its own,
instead of subdirectories inside one sysroot. The two schemes behave
differently under -print-sysroot, so it matters which one a target uses.
Subdirectories in one sysroot. The common scheme keeps every variant in a
single sysroot and appends the OS-side directory to paths inside it. One
/arm-rootfs then contains both usr/lib and usr/lib32.
One sysroot per variant. Some targets append a suffix to the sysroot itself,
computed from the options by SYSROOT_SUFFIX_SPEC. gcc.cc declares that spec
with an empty default (gcc.cc:1229, :1193-1195).
The GCC manual documents that such a suffix exists, and --no-sysroot-suffix to
turn it off, under Directory Options. MIPS is the canonical
user:
#undef SYSROOT_SUFFIX_SPEC
#define SYSROOT_SUFFIX_SPEC \
"/%{mmicromips:micro}mips%{mel|EL:el}-" MIPS_SYSVERSION_SPEC \
"%{msoft-float:-soft;:-hard}" \
"%{!mips32r6:%{!mips64r6:%{mnan=2008:-nan2008}}}%{muclibc:-uclibc}"
Listing 1.6-8: MIPS computing a sysroot suffix from the variant options
(gcc/config/mips/mti-linux.h:29-33).
Listing 1.6-8 is ordinary spec text, with the if/else form from
Chapter 1.3, so --sysroot=/opt/rootfs -EL -msoft-float
searches /opt/rootfs/mipsel-r2-soft/…. The driver evaluates the suffix once at
startup (gcc.cc:8542-8552). It then appends the suffix inside
add_sysrooted_prefix (gcc.cc:3194-3196), so that function, from
Chapter 1.2, joins three pieces rather than two:
the sysroot, the suffix and the prefix. On such a target the suffix has three
consequences:
-
-print-sysrootprints the suffixed path. Its output changes with-ELor-msoft-float, so do not cache it. Chapter 1.14 reads the code, in Listing 1.14-2. -
--with-sysrootgives only the base. The sysroot is not one root filesystem but a family of them. The suffix does not appear in the configure line, sogcc -vdoes not show it. -
The startfile prefix varies too. The same target makes the startfile prefix multilib-conditional, through the
STARTFILE_PREFIX_SPECbranch from Chapter 1.5:#undef STARTFILE_PREFIX_SPEC #define STARTFILE_PREFIX_SPEC \ "%{mabi=32: /usr/local/lib/ /lib/ /usr/lib/} \ %{mabi=n32: /usr/local/lib32/ /lib32/ /usr/lib32/} \ %{mabi=64: /usr/local/lib64/ /lib64/ /usr/lib64/}"Listing 1.6-9: MIPS replacing the standard prefix chain (
gcc/config/mips/mti-linux.h:37-41).
Header search gets the same treatment through SYSROOT_HEADERS_SUFFIX_SPEC,
which MIPS defines as the same spec (mti-linux.h:35). The driver
processes that spec at gcc.cc:8568-8577.
t-* fragments and genmultilib: declaring the variant set
A target declares its variant set in its t-* makefile fragment, through the
MULTILIB_* variables, and a shell script, genmultilib, compiles that
declaration into the driver. If you build a toolchain rather than use one, the
fragment is where you change the variant set. The internals manual documents
every variable, and the last column gives its line in fragments.texi:
| Variable | Declares | fragments.texi |
|---|---|---|
MULTILIB_OPTIONS | the option axes, with / between exclusive options and a space between combinable ones | :64 |
MULTILIB_DIRNAMES | the GCC-side directory name per variant | :86 |
MULTILIB_MATCHES | option spellings that map to the same variant | :106 |
MULTILIB_EXCEPTIONS | combinations not to build | :114 |
MULTILIB_REQUIRED | the whitelist form of the same idea | :129 |
MULTILIB_REUSE | serve an unbuilt option set from an existing variant | :152 |
MULTILIB_EXTRA_OPTS | options forced into every variant build | :184 |
MULTILIB_OSDIRNAMES | the OS-side name, optionally :multiarch after a colon | :192 |
The x86-64 GNU/Linux fragment sets three of these variables. It computes each value instead of listing it:
comma=,
MULTILIB_OPTIONS = $(subst $(comma),/,$(TM_MULTILIB_CONFIG))
MULTILIB_DIRNAMES = $(patsubst m%, %, $(subst /, ,$(MULTILIB_OPTIONS)))
MULTILIB_OSDIRNAMES = m64=../lib64$(call if_multiarch,:x86_64-linux-gnu)
MULTILIB_OSDIRNAMES+= m32=$(if $(wildcard $(shell echo $(SYSTEM_HEADER_DIR))/../../usr/lib32),../lib32,../lib)$(call if_multiarch,:i386-linux-gnu)
MULTILIB_OSDIRNAMES+= mx32=../libx32$(call if_multiarch,:x86_64-linux-gnux32)
Listing 1.6-10: the multilib variables of x86-64 GNU/Linux
(gcc/config/i386/t-linux64:33-38).
The six lines hold three pieces of indirection. The option list comes from
TM_MULTILIB_CONFIG, which config.gcc sets from the triple, so
x86_64-linux-gnu and i686-linux-gnu get different axes from the same
fragment. if_multiarch emits the :name part only on a multiarch-enabled
configuration, so the same line serves Debian and Fedora. The m32 line probes
the filesystem at build time for usr/lib32, and falls back to ../lib when
it is absent. A comment above the variables gives the reason:
On Debian, Ubuntu and other derivative distributions, the 32bit libraries are found in /lib32 and /usr/lib32, /lib64 and /usr/lib64 are symlinks to /lib and /usr/lib, while other distributions install libraries into /lib64 and /usr/lib64. The LSB does not enforce the use of /lib64 and /usr/lib64, it doesn't tell anything about the 32bit libraries on those systems.
genmultilib writes the variant set into a generated header, multilib.h
(gcc/Makefile.in:2476-2483). The driver includes that header
with a comment about its position:
#include "multilib.h" /* before tm.h */
Listing 1.6-11: multilib.h, included before tm.h
(gcc/gcc.cc:37).
Pruning multilibs in GCC also prunes them in newlib when newlib is built in a
combined tree, with its directories beside gcc/
(Chapter 3.6). In such a tree, newlib and
anything else built with it take their variant set from
xgcc -print-multi-lib. A --disable-multilib GCC therefore produces a
single-variant newlib, whether or not you asked for one.
Three things to carry away
A variant has two directory names, not one. multilib_dir and
multilib_os_dir play different roles, and a flag set when a prefix was
registered decides which one that prefix gets.
Every prefix is tried up to four ways, then once more with no variant. That last pass is why a wrong-ABI link can succeed with no error.
Check that the variant exists before you debug a path. If
gcc -print-multi-lib does not list it, no search order will find it.
Documentation coverage
Multilib is the best-documented mechanism in Part I. The internals manual's
Target Makefile Fragments node covers the fragment variables,
including the two-pass walk (gcc/doc/fragments.texi:205-210)
and the ! prefix that disables it. It also gives the multiarch ordering
(:218-220) and says that MULTILIB_OSDIRNAMES
subsumes MULTIARCH_DIRNAME (:212-216). The GCC manual
documents the -print-multi-* options under
Developer Options (gcc/doc/invoke.texi:20326).
What is not documented is the consequence rather than the mechanism:
- That the fallback pass turns a missing variant into a wrong-library link rather than an error.
- That
-print-search-dirsshows the prefix list before the multilib expansion, so its output is not the set of directories that the driver searches.
Next: Chapter 1.7, The link line: crt*.o files, -lgcc and their order,
what all these paths are searched for.
1.7 The link line: crt*.o files, -lgcc and their order
GCC 15.2.0. To run the commands: an installed compiler for GNU/Linux.
You link with gcc -v and read the collect2 command at the end of the output.
Five object files with crt in their names sit around your own objects, in an
order that nothing on the line explains, and -lgcc appears twice.
Neither is an accident. One spec, LINK_COMMAND_SPEC, writes the whole link
line, and the order of its directives is the link order. The startup files come
from two unrelated providers, the C library and GCC's libgcc, so a missing one
points at the sysroot or at the prefix depending on its owner. libgcc appears on
both sides of the C library on purpose, because the C library can call into it.
This chapter assumes Chapter 1.1, for -### and
collect2, Chapter 1.2, for the sysroot and the
installation prefix, and Chapter 1.3, for the spec
language, %G and Listings 1.3-5, 1.3-6 and 1.3-9. It also uses the library
search list of Chapter 1.5, with %D,
add_sysrooted_prefix and Listings 1.5-9 and 1.5-14, and the multilib
subdirectory from Chapter 1.6.
crt1.o to crtn.o: the order of a glibc link line
On a glibc target, the startup objects run from crt1.o to crtn.o, with three
before your own objects and two after them. Two providers supply them, the C
library and GCC's libgcc, and the diagram marks which file comes from which:
crt1.o crti.o crtbegin.o …your objects… crtend.o crtn.o
└────── libc ─────┘└ libgcc ┘ └ libgcc ┘ └ libc ┘
The libraries form a second sequence, in which libgcc appears on both sides of
the C library. On the link line this sequence sits between your objects and
crtend.o, not after crtn.o:
-lgcc -lc -lgcc
To see both sequences on your own toolchain, print the link command without
running it. Search for collect2 rather than ld, because on most targets the
driver runs collect2, which then runs ld
(Chapter 1.1):
$ gcc -### hello.c 2>&1 | grep collect2
LINK_COMMAND_SPEC: the whole link line in one spec
LINK_COMMAND_SPEC is the one spec that writes the whole link command, and the
position of each directive in it is the position of its output on the link line.
Chapter 1.3 read it as an example of spec syntax, in
Listing 1.3-6. Annotated with what each slot adds to the link line, it shows
where the startup files, your objects and the libraries go:
%{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S: ← only when actually linking
%(linker) ← collect2 (or ld)
%{flto} %{fno-lto} %{flto=*} %l ← target link flags
%X %{o*} %{e*} … ← -Wl, options, -o, -e …
%{!nostdlib:%{!r:%{!nostartfiles:%S}}} ← crt1.o crti.o crtbegin.o
%{static|no-pie|static-pie:} %@{L*} %(link_libgcc)
%o ← YOUR object files
%{!nostdlib:%{!r:%{!nodefaultlibs:
%(link_ssp) %(link_gcc_c_sequence)}}} ← libgcc + libc + libgcc
%{!nostdlib:%{!r:%{!nostartfiles:%E}}} ← crtend.o crtn.o
%{T*} \n%(post_link) }}}}}}
Listing 1.7-1: LINK_COMMAND_SPEC, abridged
(gcc/gcc.cc:1159-1178).
%S, %o, the libraries and %E reach the linker in that order. The startup
files are split into a startfile spec and an endfile spec only because %S and
%E sit on opposite sides of %o. The %{!nostdlib:…}, %{!nostartfiles:…}
and %{!nodefaultlibs:…} wrappers in Listing 1.7-1 are the -no* guards that
Chapter 1.3 named. Chapter 1.10 reads
the full truth table off their nesting.
The %(link_libgcc) slot immediately before your objects is where the search
list of Chapter 1.5 reaches the linker. Its
default value is one directive, %D, which expands to one -L option per
directory in the driver's prefix list. That one directive is the whole
connection between the prefix list and the linker's search path:
#ifndef LINK_LIBGCC_SPEC
/* Generate -L options for startfile prefix list. */
# define LINK_LIBGCC_SPEC "%D"
#endif
Listing 1.7-2: where the -L flags come from
(gcc/gcc.cc:1180-1183).
crt1.o from libc, crtbegin.o from libgcc: one search list
crt1.o comes from the C library and crtbegin.o from libgcc, but the driver
finds both through one search list. The spec text therefore does not show which
provider a file has. The C library's files move with the sysroot and libgcc's
with the installation prefix, and that split decides what to fix when a link
cannot find a startup file:
| Files | Provider | Installed under | Moved by |
|---|---|---|---|
crt1.o, Scrt1.o, gcrt1.o, crti.o, crtn.o | the C library | the sysroot's /usr/lib | --with-sysroot, --sysroot |
crtbegin*.o, crtend*.o | GCC's libgcc | $prefix/lib/gcc/<t>/<v>/ | --prefix, -B |
Both halves are written the same way in the spec, because %s only means "look
this name up in the library search list" (Listing 1.3-9). The libc half is found
because /lib/ and /usr/lib/ are registered with add_sysrooted_prefix
(Listing 1.5-9), and that call is where the sysroot is added to the path. The
libgcc half is found through prefixes derived from the driver's own location,
which are never sysrooted.
The diagnosis therefore takes one command for each half. -print-file-name
walks the same search list, and when it finds no file it prints its argument
back unchanged (Listing 1.5-14):
$ gcc -print-file-name=crt1.o # the libc half
$ gcc -print-file-name=crtbegin.o # the libgcc half
| Echoed back verbatim | Means |
|---|---|
crt1.o | your sysroot is wrong |
crtbegin.o | your prefix or -B is wrong |
STARTFILE_SPEC: the crt0 default and the gnu-user.h override
The default STARTFILE_SPEC in the driver is built on crt0, and the familiar
crt1.o, crti.o and crtbegin.o of a glibc link come from one target
family's override. To find the startup files of your own target, read its
override, which for GNU user space is in gcc/config/gnu-user.h. The default in
gcc.cc is one conditional:
/* config.h can define STARTFILE_SPEC to override the default crt0 files. */
#ifndef STARTFILE_SPEC
#define STARTFILE_SPEC \
"%{!shared:%{pg:gcrt0%O%s}%{!pg:%{p:mcrt0%O%s}%{!p:crt0%O%s}}}"
#endif
Listing 1.7-3: the default STARTFILE_SPEC
(gcc/gcc.cc:891-895). The default ENDFILE_SPEC, at
:897-900, is the empty string.
That default is a historical fallback that almost no target uses. GNU user space installs its own startfile spec over it:
#define GNU_USER_TARGET_STARTFILE_SPEC \
"%{shared:; \
pg|p|profile:%{static-pie:grcrt1.o%s;:gcrt1.o%s}; \
static:crt1.o%s; \
static-pie:rcrt1.o%s; \
" PIE_SPEC ":Scrt1.o%s; \
:crt1.o%s} " \
GNU_USER_TARGET_CRTI " \
%{static:crtbeginT.o%s; \
shared|static-pie|" PIE_SPEC ":crtbeginS.o%s; \
:crtbegin.o%s} \
...
Listing 1.7-4: the glibc startfile spec
(gcc/config/gnu-user.h:51-65, installed over the default at
:66-67).
This spec is the best example in the tree of the ;-separated
if/else-if/else form from Chapter 1.3. Its first
selection has six arms, and each one picks a single crt1 variant or none:
| You passed | You get |
|---|---|
-shared | nothing (the empty first arm) |
-pg, -p or -profile | gcrt1.o, or grcrt1.o with -static-pie |
-static | crt1.o |
-static-pie | rcrt1.o |
whatever PIE_SPEC matches | Scrt1.o |
| otherwise | crt1.o |
A second, independent selection picks crtbeginT.o, crtbeginS.o or
crtbegin.o. Because both selections depend on the flags,
gcc -static -### hello.c and gcc -shared -### hello.c produce link lines
that share almost no startup objects, and "the crt1 file" is not a well-defined
phrase.
The matching ENDFILE_SPEC mirrors the whole structure
(gcc/config/gnu-user.h:75-85). The crti.o in the
startfile spec and the crtn.o in the endfile spec come from two one-line
macros:
#define GNU_USER_TARGET_CRTI "crti.o%s"
#define GNU_USER_TARGET_CRTN "crtn.o%s"
Listing 1.7-5: GNU_USER_TARGET_CRTI and GNU_USER_TARGET_CRTN
(gcc/config/gnu-user.h:43-44).
extra_parts: when libgcc supplies crti.o
extra_parts declares which crt* files a target's libgcc provides, and on
many bare-metal targets the list includes crti.o. On such a target a missing
crti.o means your prefix is wrong, not your sysroot, so the
-print-file-name diagnosis for a glibc link does not apply. Check what your
libgcc installed before you blame either setting.
Each target's list is in libgcc/config.host. For example,
arm*-*-eabi* gets extra_parts="crtbegin.o crtend.o crti.o crtn.o"
(libgcc/config.host:584). libgcc's makefile turns
extra_parts into EXTRA_PARTS (libgcc/Makefile.in:59-61)
and installs them into inst_libdir, which is libsubdir plus the multilib
subdirectory from Chapter 1.6:
inst_libdir = $(libsubdir)$(MULTISUBDIR)
Listing 1.7-6: where libgcc's objects land
(libgcc/Makefile.in:315; the install rule is install-leaf at
:1188).
libgcc computes libsubdir from real_host_noncanonical, not from a target
variable (libgcc/Makefile.in:204), because libgcc is
configured with --host=<GCC's target>. Whenever a path formula in a target
library says "host", read "GCC's target". The same convention returns in
Chapter 1.12, in the install paths of
libstdc++.
What libgcc is: the library the compiler emits calls into
libgcc is GCC's own runtime support library, and the compiler emits calls into
it whether or not you asked for it. Those calls explain both of its surprises on
the link line: it appears twice, and a -nostdlib link still needs it. The
calls go to four kinds of helper:
- integer division and modulo helpers on targets without the instruction, such
as
__divdi3and__udivsi3 - the
__aeabi_*helpers on Arm EABI targets such asarm-none-eabi, whose names come from Arm's run-time ABI document rather than from GCC (gcc/config/arm/arm.cc:2573-2666, explained in Chapter 4.1) - soft-float emulation
- the stack unwinder used by C++ exceptions and by
__attribute__((cleanup))
Dropping the standard libraries does not stop the compiler from emitting a call
to __aeabi_idiv, so you still need -lgcc under -nostdlib. The GCC
manual's -nostdlib entry under Link Options gives the same
advice. The most common result of leaving it out is a bare-metal link that
fails on an undefined __aeabi_* or __udivsi3.
Chapter 1.10 covers what a link still
needs once you have taken the runtime away.
Why -lgcc appears twice: LINK_GCC_C_SEQUENCE_SPEC
The default library sequence is -lgcc -lc -lgcc because the C library can call
into libgcc, for __divdi3 on a target without a division instruction, for the
unwinder or for soft-float helpers. With static archives the linker resolves
left to right, and it takes from an archive only the members it needs at the
moment it reads that archive. A reference that libc.a creates after libgcc.a
has been scanned would go unresolved, so libgcc is repeated after libc:
-lgcc -lc -lgcc
│ │ └── libgcc AGAIN, after libc
│ └──────── libc
└──────────────── libgcc
One spec writes that sequence, and its comment says why it is a spec of its own
rather than a part of LINK_COMMAND_SPEC:
/* This is overridable by the target in case they need to specify the
-lgcc and -lc order specially, yet not require them to override all
of LINK_COMMAND_SPEC. */
#ifndef LINK_GCC_C_SEQUENCE_SPEC
#define LINK_GCC_C_SEQUENCE_SPEC "%G %{!nolibc:%L %G}"
#endif
Listing 1.7-7: the double libgcc
(gcc/gcc.cc:987-992). %G is the libgcc spec, %L the lib
spec.
Two families of targets replace the default. GNU/Linux keeps -lgcc -lc -lgcc
for a dynamic link. With -static or -static-pie it uses
--start-group %G %L --end-group instead
(gcc/config/gnu-user.h:112-117), so libgcc appears once, and
the group makes the linker rescan both archives until no new reference is left.
Bare-metal Arm always uses the group, because newlib's printf can reach the
unwinder through libgcc's division helpers, and the unwinder calls abort in
libc (gcc/config/arm/unknown-elf.h:91-96).
-nolibc drops %L %G, the -lc and the second -lgcc, and keeps the leading
-lgcc, because in Listing 1.7-7 the %{!nolibc:…} wraps %L %G and not the
first %G. The GCC manual documents -nolibc and the rest of the -no* family
under Link Options.
%G and %L: what the libgcc and lib specs expand to
%G and %L name the libgcc and lib specs, and neither always expands to
the single option its name suggests. On a shared-libgcc target %G depends on
the static and shared options of the link, and %L has a default that most
targets override. Two links from the same toolchain can therefore name
different libraries.
The driver rewrites the libgcc slot at startup (Listing 1.3-5), into a nested
conditional that chooses between -lgcc -lgcc_eh,
-lgcc --as-needed -lgcc_s --no-as-needed and -lgcc_s -lgcc, depending on
-static, -static-libgcc and -shared-libgcc. With a recent GNU ld,
--push-state --as-needed … --pop-state takes the place of --as-needed …
--no-as-needed. These two commands therefore give different answers on the
same toolchain:
$ gcc -### foo.o 2>&1 | tr ' ' '\n' | grep lgcc
$ gcc -### -static foo.o 2>&1 | tr ' ' '\n' | grep lgcc
Without -static the output names -lgcc_s, and with -static it names
-lgcc_eh in its place, as the table of cases in
Chapter 1.3 shows.
The lib spec has a default too: -lc, -lc_p under profiling, and nothing
when building a shared object. Most targets override it in their config/*.h:
/* config.h can define LIB_SPEC to override the default libraries. */
#ifndef LIB_SPEC
#define LIB_SPEC "%{!shared:%{g*:-lg} %{!p:%{!pg:-lc}}%{p:-lc_p}%{pg:-lc_p}}"
#endif
Listing 1.7-8: the default LIB_SPEC (gcc/gcc.cc:754-757).
Checking the -no* flags on the link line with -###
-nostdlib, -nostartfiles and -nodefaultlibs each fail one or more guards in
LINK_COMMAND_SPEC, and the text inside a failed guard leaves the link line.
Comparing the -### output with and without each flag shows which pieces go,
and it is the quickest way to learn the template. The last command prints the
template as your driver holds it:
$ gcc -### hello.c # baseline
$ gcc -### -nostdlib hello.c # crt*.o and -lc/-lgcc gone
$ gcc -### -nostartfiles hello.c # crt*.o gone, -lc/-lgcc kept
$ gcc -### -nodefaultlibs hello.c # crt*.o kept, -lc/-lgcc gone
$ gcc -dumpspecs | grep -A2 '^\*link_command'
Each piece that disappears sat inside a %{!…:} guard that the flag fails.
Three things to carry away
The startup files come from two providers. crt1.o, crti.o and crtn.o
are the C library's, crtbegin.o and crtend.o are libgcc's, and on some
bare-metal targets crti.o is libgcc's too.
-lgcc appears twice on purpose. libc can call into libgcc, and the linker
takes from a static archive only what is undefined when it reads that archive.
The compiler emits calls into libgcc whatever you link. That is why a
-nostdlib link still needs -lgcc.
Things that surprise people
g++ moves your -lm and -lc. It takes them out of wherever you put them
and emits them again after -lstdc++, with no diagnostic. On a target where
every library is a static archive, that move changes symbol resolution
(Chapter 1.11).
-r fails the same guards as -nostdlib. A relocatable link never gets the
runtime, because %{!r: appears in each of the three guards in Listing 1.7-1.
-static-libstdc++ is not on the link line on most targets. The C++ driver
consumes it and puts -Wl,-Bstatic … -Wl,-Bdynamic around one -l instead,
so search the link line for Bstatic, not for the option
(Chapter 1.11).
ENDFILE_SPEC is empty by default. A link line with no crtend.o may be
correct for your target, if the target keeps that default.
A successful link says nothing about run time. Finding libstdc++.so.6 or
libc.so.6 when the program starts is the job of the target's dynamic loader,
through DT_RUNPATH, ld.so.conf and LD_LIBRARY_PATH. Link-time search and
run-time search are unrelated systems that happen to involve some of the same
file names.
Documentation coverage
The GCC manual documents -nostdlib and the other -no* options under
Link Options (gcc/doc/invoke.texi:19067). The internals
manual has a chapter on libgcc,
The GCC low-level runtime library (gcc/doc/libgcc.texi:6).
What is not documented:
- Why
-lgccappears twice. The spec is in the source, but the rationale is not, and you have to reconstruct it. The nearest thing is the comment in Listing 1.7-7, which explains why the ordering is overridable rather than why it is what it is. - That the default
STARTFILE_SPECis built oncrt0, and that the familiar crt1/crti/crtbegin shape is a per-target-family override. Every secondhand account of GCC's link order presents one target's spec as universal. - That
crti.omay come from libgcc rather than libc, which inverts the-print-file-namediagnosis on bare-metal targets.
Next: Chapter 1.8, Where <stdint.h> comes from: the headers GCC ships,
the same question for headers.
1.8 Where <stdint.h> comes from: the headers GCC ships
GCC 15.2.0. To run the commands: an installed compiler, with g++ for the C++ search list.
You are building a sysroot for a cross target. You have copied in glibc's
headers, you have stdio.h, pthread.h and fcntl.h, and you check for
stdint.h and it is not there. You go looking for the glibc build step that
produces it, and there is none.
<stdint.h> is not the C library's header but the compiler's, and it lives
under GCC's own prefix, in $prefix/lib/gcc/<target>/<version>/include/. So do
<stddef.h>, <limits.h>, <stdarg.h> and about a dozen others. GCC searches
its own directories before the sysroot, and some of its headers then bring in
the C library's header of the same name with #include_next. The first command
prints the directory, and the second lists what GCC installed there:
$ gcc -print-file-name=include
$ ls "$(gcc -print-file-name=include)"
This chapter assumes Chapter 1.1, for the driver and
cc1, and Chapter 1.2, for the libsubdir, the
tooldir and the rule that the sysroot belongs to the C library and the prefix
belongs to GCC. That rule holds for headers without exception. The chapter also
uses %I from Chapter 1.3, -B and include_prefixes
from Chapter 1.5, and multiarch from
Chapter 1.6. It is the compile-time counterpart of
Chapter 1.7, which asks the same question of the link
line.
Freestanding headers such as <stdint.h>: why GCC provides them
The freestanding headers are a small core set that the C standard requires the compiler itself to provide. A conforming implementation must work in a freestanding environment, where by definition there is no C library to supply headers, so these headers must be available when nothing else is. That requirement is why they sit under GCC's prefix and not in the sysroot. The standard defines two kinds of execution environment:
| Environment | Means | __STDC_HOSTED__ |
|---|---|---|
| Hosted | a full OS with a complete C library: files, threads, <stdio.h> | 1 |
| Freestanding | bare metal, kernels, early boot: no OS, maybe no libc at all | 0 |
The GCC manual lists the freestanding set, standard by standard, under
Language Standards Supported by GCC. GCC keeps the sources
under gcc/ginclude/, and a makefile variable, USER_H, lists the
ones that get installed:
USER_H = $(srcdir)/ginclude/float.h \
$(srcdir)/ginclude/iso646.h \
$(srcdir)/ginclude/stdarg.h \
$(srcdir)/ginclude/stdbool.h \
$(srcdir)/ginclude/stddef.h \
$(srcdir)/ginclude/varargs.h \
$(srcdir)/ginclude/stdfix.h \
$(srcdir)/ginclude/stdnoreturn.h \
$(srcdir)/ginclude/stdalign.h \
$(srcdir)/ginclude/stdatomic.h \
$(srcdir)/ginclude/stdckdint.h \
$(EXTRA_HEADERS)
Listing 1.8-1: the headers GCC installs (gcc/Makefile.in:473-484).
The last entry, $(EXTRA_HEADERS), is where a target adds headers of its own,
which is how <arm_neon.h> and <immintrin.h> get there. <stdint.h> and
<limits.h> are not in the list, because the build installs them by separate
rules, which the #include_next section reads.
Before GCC 14.
<stdckdint.h>is not there. C23's checked integer arithmetic header arrived in GCC 14:gcc/ginclude/stdckdint.hdoes not exist atreleases/gcc-13.3.0and does atreleases/gcc-14.3.0.
Each of these headers encodes something only the compiler knows, such as type widths, alignment rules, calling conventions or instruction sets, so a C library cannot get them right for an arbitrary compiler. The table gives what each header provides and why it must be the compiler's:
| Header | Provides | Why it must be the compiler's |
|---|---|---|
<stddef.h> | size_t, ptrdiff_t, NULL, offsetof, wchar_t | These are compiler properties, and offsetof is __builtin_offsetof |
<stdarg.h> | va_list, va_start, va_arg, va_end | Expands to __builtin_va_*: the varargs ABI is generated code, not a library |
<stdint.h> | int32_t, uint64_t, INTPTR_MAX, … | Must match the target data model: ILP32, LP64, LLP64 |
<limits.h> | INT_MAX, CHAR_BIT, LONG_MIN | Derived from the target's integer widths |
<float.h> | FLT_MANT_DIG, DBL_MAX, … | Derived from the target's floating-point formats |
<stdbool.h> | bool, true, false | Maps to the built-in _Bool |
<stdalign.h> | alignas, alignof | Maps to _Alignas and _Alignof |
<stdatomic.h> | atomic_int, atomic_load, … | Atomics are codegen plus libatomic, not libc |
<iso646.h> | and, or, not, … | Pure macros, with nothing for a libc to contribute |
| arch intrinsics | <arm_neon.h>, <immintrin.h>, … | One-to-one mappings onto instructions the back end knows |
C23 made bool, alignas, alignof and noreturn keywords, so
<stdbool.h>, <stdalign.h> and <stdnoreturn.h> are now largely vestigial,
but they still exist and still come from GCC. <stdbit.h> is C23 too, but it is
not one of GCC's headers. In GCC 15.2.0 it exists only as a libstdc++
C-compatibility header
(libstdc++-v3/include/c_compatibility/stdbit.h), not in
gcc/ginclude/. Run ls on your own -print-file-name=include rather than
trusting any list, including Listing 1.8-1.
include-fixed/: system headers patched by fixincludes at build time
include-fixed/ holds patched copies of the system's headers, and include/
holds GCC's own. Both sit in the libsubdir, and both come before the sysroot in
the search order. include-fixed/ is a snapshot taken when GCC was built, so a
header the compile takes from it can be stale against a sysroot updated later.
fixincludes is a build-time pass that copies the system headers it finds
and mechanically repairs constructs GCC dislikes, such as ancient K&R
declarations and macros that break under a modern preprocessor. Its output is
include-fixed/. The machinery lives in fixincludes/, and its
README describes the workflow, which is a rule database compiled by AutoGen:
If you are having some problem with a system header that is either broken by the manufacturer, or is broken by the fixinclude process, then you will need to alter or add information to the include fix definitions file,
inclhack.def.
If your sysroot's headers were updated after GCC was built, you compile against
a patched version of a header that no longer exists. On a modern glibc or musl
target include-fixed/ is usually near-empty. The machinery is mostly
historical, but on older or unusual targets it can matter a great deal.
The compiled-in list of header directories has separate entries for
include-fixed/, and they have their own multilib behaviour:
#ifdef FIXED_INCLUDE_DIR
/* This is the dir for fixincludes. */
#ifndef SYSROOT_HEADERS_SUFFIX_SPEC
{ FIXED_INCLUDE_DIR, "GCC", 0, 0, 0, 2 },
#endif
{ FIXED_INCLUDE_DIR, "GCC", 0, 0, 0,
/* A multilib suffix needs adding if different multilibs use
different headers. */
Listing 1.8-2: the include-fixed entries
(gcc/cppdefault.cc:75-83).
The trailing 2 is the multilib field, and it means "append the multiarch
path". The three-way split of Chapter 1.6, between
GCC's multilib directory, the OS one and the multiarch one, therefore reaches
into header search too.
cpp_include_defaults: the header search order, GCC's directories first
cpp_include_defaults is the compiled-in array that sets the header search
order, and it lists GCC's own directories before the C library's.
#include <limits.h> therefore finds GCC's copy first, and that copy decides
whether to bring in the C library's as well. gcc -v -E prints the list, and
the cpp manual documents this use of -v under Search Path:
$ gcc -v -E - < /dev/null
For an arm-none-eabi toolchain installed in /opt/gcc-arm, the <...> part of
the list has four entries. GCC's own include/ and include-fixed/ come first,
the tooldir's include/ next, and the C library's directory in the sysroot last:
#include <...> search starts here:
/opt/gcc-arm/lib/gcc/arm-none-eabi/15.2.0/include ← GCC's own
/opt/gcc-arm/lib/gcc/arm-none-eabi/15.2.0/include-fixed ← fixincludes output
/opt/gcc-arm/arm-none-eabi/include ← tooldir
<sysroot>/usr/include ← the C library's
End of search list.
The array is defined at gcc/cppdefault.cc:38, and the search
order is its declaration order. The entries run from the C++ header directories
at the top down to the native system directory, whose comment says where it
ranks:
#ifdef NATIVE_SYSTEM_HEADER_DIR
/* /usr/include comes dead last. */
{ NATIVE_SYSTEM_HEADER_DIR, NATIVE_SYSTEM_HEADER_COMPONENT, 0, 0, 1, 2 },
{ NATIVE_SYSTEM_HEADER_DIR, NATIVE_SYSTEM_HEADER_COMPONENT, 0, 0, 1, 0 },
#endif
Listing 1.8-3: the last entries in the list
(gcc/cppdefault.cc:98-102).
The compiler's makefile #defines the macros that fill in the main entries,
and the table gives the directory that each one names:
| Macro | Directory |
|---|---|
GCC_INCLUDE_DIR | $libsubdir/include, GCC's own |
FIXED_INCLUDE_DIR | $libsubdir/include-fixed |
TOOL_INCLUDE_DIR | $tooldir/include (gcc/Makefile.in:2613) |
NATIVE_SYSTEM_HEADER_DIR | /usr/include, sysrooted |
GPLUSPLUS_INCLUDE_DIR | the C++ headers (Chapter 1.12) |
TOOL_INCLUDE_DIR is where a bare-metal C library such as newlib installs its
headers (Chapter 3.4). A pure-sysroot
toolchain that never asked for it still searches it. The pre-sysroot
--with-headers option of Chapter 1.2 copies the
headers into a different directory, $tooldir/sys-include.
add_sysroot: which header directories follow --sysroot
add_sysroot is a field in each entry of cpp_include_defaults that says
whether --sysroot applies to that directory. The decision is therefore made per
directory, and no flag can change it after the fact. GCC's own header
directories are not sysrooted but relocated with the compiler, which is why
--sysroot cannot move <stdint.h>. The field's declaration reads:
const char add_sysroot; /* FNAME should be prefixed by
cpp_SYSROOT. */
Listing 1.8-4: the field (gcc/cppdefault.h:48-49).
The code that builds the search path in incpath.cc branches on the field for
each directory. The else if is the branch to read:
/* Should this directory start with the sysroot? */
if (sysroot && p->add_sysroot)
{
...
str = concat (sysroot_no_trailing_dir_separator, p->fname, NULL);
...
}
else if (!p->add_sysroot && relocated
&& !filename_ncmp (p->fname, cpp_PREFIX, cpp_PREFIX_len))
{
Listing 1.8-5: sysroot or relocate, per directory
(gcc/incpath.cc:181-193).
GCC's own header directories take the else if branch. If such a path starts
with the configure-time prefix and the compiler has been relocated, the run-time
prefix is substituted for it. The branch is the rule that these headers are
GCC's and not the C library's, stated in code. It is also the consumer of the
set_std_prefix call that Chapter 1.9 shows in
Listing 1.9-2.
The split parallels add_prefix against add_sysrooted_prefix for libraries in
Chapter 1.5, but the implementation is separate.
Header search and library search are two mechanisms that the same prefix
relocates.
#include_next: how GCC's headers wrap the C library's
#include_next is the GNU extension that lets one of GCC's headers wrap the C
library's header of the same name. GCC's copy adds what the compiler knows, and
the C library's copy still contributes its own definitions. <stdint.h> and
<limits.h> work this way when the system has its own copy, and -H shows the
chain on any compiler. The cpp manual documents the directive under
Wrapper Headers.
#include <foo.h> searches the path from the beginning, and
#include_next <foo.h> searches only the directories after the one where the
current file was found. A header can therefore include the next file of the same
name further down the search path, one layer below itself, without knowing where
that layer is and without the risk of including itself.
<stdint.h>: wrapped when hosted, self-contained when freestanding
<stdint.h> is the clearest wrapper, because its shipped source holds the whole
hosted and freestanding split. A hosted compile defers to the system's copy. A
freestanding compile may have no system copy at all, so it falls back to
stdint-gcc.h, a self-contained version that GCC ships alongside:
#ifndef _GCC_WRAP_STDINT_H
#if __STDC_HOSTED__
...
# include_next <stdint.h>
...
#else
# include "stdint-gcc.h"
#endif
#define _GCC_WRAP_STDINT_H
#endif
Listing 1.8-6: stdint-wrap.h, abridged, without the lines that define
__STDC_LIMIT_MACROS for C++11 and silence a -Wpedantic warning about
include_next (gcc/ginclude/stdint-wrap.h).
The #if __STDC_HOSTED__ test meets the freestanding requirement in eight
lines. Whether this wrapper becomes include/stdint.h at all is a separate,
build-time decision. USE_GCC_STDINT comes from configure, and the install rule
copies the wrapper when it is wrap and the self-contained version when it is
provide:
if [ $(USE_GCC_STDINT) = wrap ]; then \
cp $(srcdir)/ginclude/stdint-wrap.h include/stdint.h; \
...
elif [ $(USE_GCC_STDINT) = provide ]; then \
cp $(T_STDINT_GCC_H) include/stdint.h; \
Listing 1.8-7: wrap or provide (gcc/Makefile.in:3514-3524).
The value of USE_GCC_STDINT comes from configure (:816).
<limits.h> is assembled, not shipped
<limits.h> is a wrapper too, but there is no single gcc/limits.h in the tree
to read, because the build concatenates the installed file from three
fragments. A filesystem test at build time decides which fragments go in:
if $(LIMITS_H_TEST) ; then \
cat $(srcdir)/limitx.h $(T_GLIMITS_H) $(srcdir)/limity.h > tmp-xlimits.h; \
else \
cat $(T_GLIMITS_H) > tmp-xlimits.h; \
fi; \
Listing 1.8-8: building limits.h (gcc/Makefile.in:3528-3532).
LIMITS_H_TEST is one line, and it tests for the system's own limits.h:
LIMITS_H_TEST = [ -f $(BUILD_SYSTEM_HEADER_DIR)/limits.h ]
Listing 1.8-9: LIMITS_H_TEST (gcc/Makefile.in:591).
If the system has its own limits.h, the installed file is the wrapper form:
the prologue limitx.h, GCC's own limits, and the epilogue limity.h. If it
does not, the file is GCC's limits alone, with no #include_next at all. The
fragments say so themselves:
/* This administrivia gets added to the beginning of limits.h
if the system has its own version of limits.h. */
Listing 1.8-10: the prologue's comment (gcc/limitx.h:24-25). The
matching comment in gcc/limity.h:1-2 says "the end of limits.h".
limitx.h does not use #include_next itself, so the prologue reaches the
system's limits.h through one more file. It includes syslimits.h from its
own directory:
/* Use "..." so that we find syslimits.h only in this same directory. */
#include "syslimits.h"
Listing 1.8-11: the hop to syslimits.h (gcc/limitx.h:33-34).
syslimits.h is a copy of gsyslimits.h
(gcc/Makefile.in:3540), and its body is only these lines:
#define _GCC_NEXT_LIMITS_H /* tell gcc's limits.h to recurse */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic" // include_next
#include_next <limits.h>
#pragma GCC diagnostic pop
#undef _GCC_NEXT_LIMITS_H
Listing 1.8-12: gsyslimits.h (gcc/gsyslimits.h:6-11).
The extra file exists because include-fixed/ may contain a patched
syslimits.h instead, which is one of fixincludes' jobs. The hop gives the build
a place to intervene without touching limits.h itself.
Checking #include_next with -H
-H prints the include tree, one dot of indentation per nesting level, so each
#include_next hop shows up one level deeper. Which headers are wrappers varies
by target, so run -H on your own compiler rather than trusting a table. The
cpp manual documents -H under Invocation.
$ echo '#include <limits.h>' | gcc -H -E -x c - > /dev/null
The tree shows GCC's limits.h at depth one, syslimits.h below it and the
sysroot's limits.h below that, which is the hop of Listing 1.8-11 made
visible. Roughly, <stddef.h>, <stdarg.h>, <stdbool.h>, <iso646.h> and
the arch intrinsics are standalone, with no #include_next.
Checking header search with -print-file-name=include and -v -E
-print-file-name=include and gcc -v -E answer the two questions behind a
missing or wrong header: where GCC's own headers are, and which directories the
compile searches, in order. With ls, -H and a grep, they make five
commands to run on any toolchain:
$ gcc -print-file-name=include # GCC's own header dir
$ ls "$(gcc -print-file-name=include)" # what it actually ships
$ gcc -v -E - < /dev/null # the full search list
$ echo '#include <limits.h>' | gcc -H -E -x c - >/dev/null # the include_next chain
$ echo '#include <stdint.h>' | gcc -E -x c - | grep -m1 stdint
The last command shows which file a single #include resolved to. Of the
others, gcc -v -E - < /dev/null is the only way to see the whole list. -
reads an empty program from standard input, -E stops after preprocessing, and
-v lets you see cc1's standard error. The list comes from cc1, not from
the driver, and cc1 prints it only when it is verbose:
/* If verbose, print the list of dirs to search. */
if (verbose)
{
fprintf (stderr, _("#include \"...\" search starts here:\n"));
...
fprintf (stderr, _("End of search list.\n"));
Listing 1.8-13: the verbose printout
(gcc/incpath.cc:391-405).
Before GCC 15. The printout has one section fewer. GCC 15 added a fifth include chain for C23's
#embed, somerge_include_chainsnow sysroot-expands the quote, bracket, system, after and embed chains (gcc/incpath.cc:359-363), and the verbose output gained an#embed <...> search starts here:block (:408).INC_EMBEDis absent at every release tag through 14.3.0 and present at 15.2.0.
For C++ you must name the language with -x c++, because standard input has no
extension to infer a language from. The list then starts with the
include/c++/... directories:
$ g++ -v -E -x c++ /dev/null
If the include/c++/... entries begin with your sysroot path, the toolchain was
configured for sysroot-relative C++ headers. If they do not, they are
prefix-relative, and --sysroot never moves them.
Chapter 1.12 explains the difference.
Three things to carry away
<stdint.h> is the compiler's, not the C library's. It lives under
lib/gcc/<target>/<version>/include/, and gcc -print-file-name=include prints
that directory.
GCC's header directories come before the system's. In a hosted build GCC's copy defers to the system's. In a freestanding build GCC's copy is the whole answer.
include-fixed/ is a snapshot taken when GCC was built. It can be stale
against a sysroot you updated later.
Things that surprise people
Do not look in the sysroot for stdint.h. It is not there and it is not
supposed to be. gcc -print-file-name=include is where to look.
Copying a sysroot does not copy GCC's headers. A sysroot is complete for libc but useless on its own, because the compiler's own headers travel with the compiler.
GCC's headers are version-locked. The path contains <version>
(Listing 1.2-2), so two GCC releases have separate copies. Mixing GCC 12's
headers with GCC 15's cc1 is a broken toolchain, not only an unwise one.
-nostdinc removes GCC's headers too, not only the system directories
(gcc/c-family/c.opt:2523). On bare metal you almost always
want them back:
$ gcc -nostdinc -isystem "$(gcc -print-file-name=include)" …
-ffreestanding changes nothing about header search. Its entry in c.opt
has one line of help text:
ffreestanding
C ObjC C++ ObjC++
Do not assume that standard C libraries and \"main\" exist.
Listing 1.8-14: the ffreestanding entry
(gcc/c-family/c.opt:1986-1988).
It changes what the compiler may assume. It stops printf("x\n") from becoming
puts("x"), relaxes the requirements on main and sets __STDC_HOSTED__ to
0, but it moves no directory. Chapter 1.10
puts it side by side with -nostdlib and -nostdinc, the two options it is most
often confused with. On a hosted target, the first command below shows
__STDC_HOSTED__ defined to 1, and the second shows it defined to 0:
$ gcc -dM -E - < /dev/null | grep __STDC_HOSTED__
$ gcc -ffreestanding -dM -E - < /dev/null | grep __STDC_HOSTED__
-B moves GCC's header directories. A -B<dir> adds
<dir>/<target>/<version>/include and .../include-fixed to the header search,
because -B feeds include_prefixes (Listing 1.5-2) and %I expands that list:
info.option = "-isystem";
info.append = "include";
...
for_each_path (&include_prefixes, false, info.append_len,
spec_path, &info);
Listing 1.8-15: %I emitting GCC's header directories
(gcc/gcc.cc:6604-6612).
So -B can change which <stdint.h> you compile against, but not which
<vector> you get, because only GCC's own two directories are in
include_prefixes.
Documentation coverage
The GCC manual documents -nostdinc and -I, -isystem and -idirafter under
Directory Options (gcc/doc/invoke.texi:19484). The
preprocessor manual documents them too, along with #include_next and -H.
-ffreestanding is under C Dialect Options
(gcc/doc/invoke.texi:2665).
What is not documented:
- That
<limits.h>is assembled from three fragments at build time, and that which form you get depends on a filesystem test. Thesyslimits.hhop in particular exists only in the source. - That the sysroot decision is per include-directory, carried in a struct field, and therefore not something a flag can change after the fact.
- That GCC's own header directories are relocated rather than sysrooted. The
else ifin Listing 1.8-5 is the precise statement of why--sysrootcannot move them.
Next: Chapter 1.9, How GCC_EXEC_PREFIX and LIBRARY_PATH move the search paths,
the environment variables that move both search lists without appearing on any
command line.
1.9 How GCC_EXEC_PREFIX and LIBRARY_PATH move the search paths
GCC 15.2.0. To run the commands: an installed compiler.
The build works on your machine and fails in CI. The source is the same, the compiler version is the same, and you have checked the command line three times.
Check the environment next, because the variables that move GCC's search paths
do not appear on any command line you can read. They fall into three groups, by
who sets them and who reads them. You set the first group to move the driver's
search lists. You set the second group too, but the driver never reads it and
cc1 does. The driver sets the third group, so that its own subprocesses agree
with it:
| Group | Set by | Read by | Variables |
|---|---|---|---|
| In | you | the driver | GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH |
| Past the driver | you | cc1 | CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH, OBJC_INCLUDE_PATH |
| Out | the driver | its children | COLLECT_GCC, COLLECT_GCC_OPTIONS, COLLECT_LTO_WRAPPER, COLLECT_AS_OPTIONS |
This chapter assumes Chapter 1.1 for collect2,
lto-wrapper and COLLECT_GCC, Chapter 1.3 for spec
directives such as %<, and Chapter 1.4
for -dumpdir. It also assumes Chapter 1.5 and
Chapter 1.8, because the first two groups feed
the lists those chapters build: the driver's prefix lists and cc1's include
chains.
Driver variables: GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH
The driver reads four variables, GCC_EXEC_PREFIX, COMPILER_PATH,
LIBRARY_PATH and LPATH, and adds their directories to the search lists that
-B and the compiled-in defaults also fill. They are the first suspects when
the driver finds a different program or library on two machines. Each one feeds
a different part of the lists, and a cross compiler ignores two of them:
| Variable | Feeds | Works on a cross compiler? |
|---|---|---|
GCC_EXEC_PREFIX | programs and libraries, plus header search | yes |
COMPILER_PATH | programs and headers | yes |
LIBRARY_PATH | libraries | no, native only |
LPATH | as LIBRARY_PATH, legacy | no, native only |
Listing 1.5-3 in Chapter 1.5 settles their priority. Its enum has two values,
and GCC_EXEC_PREFIX, COMPILER_PATH and LIBRARY_PATH all land at the lower
one, PREFIX_PRIORITY_LAST. -B therefore beats the environment, the
environment beats the compiled-in defaults, and nothing can sort before a -B.
The GCC manual documents the first three variables, and that order, under
Environment Variables. It does not mention LPATH.
LIBRARY_PATH and LPATH: ignored by a cross compiler
A cross compiler ignores LIBRARY_PATH and LPATH, because the driver reads
each of them only when it was built as a native compiler. If LIBRARY_PATH has
no effect on your arm-linux-gnueabihf-gcc, one clause of the driver is the
reason:
temp = env.get (LIBRARY_PATH_ENV);
if (temp && *cross_compile == '0')
Listing 1.9-1: the native-only guard (gcc/gcc.cc:4923-4924). LPATH
gets the same treatment at :4956-4957.
*cross_compile == '0' means "this is a native compiler", so a cross compiler
skips the variable and prints no diagnostic. Use -B or -L instead. The
manual's LIBRARY_PATH entry states the same condition in one clause: "When
configured as a native compiler".
GCC_EXEC_PREFIX and COMPILER_PATH have no such guard, so they work on a
cross compiler (gcc.cc:4889). The name in Listing 1.9-1 is
LIBRARY_PATH_ENV, a macro rather than a literal, so a port can rename the
variable, and some do (gcc.cc:209-211).
GCC_EXEC_PREFIX: relocation for programs, libraries and headers
GCC_EXEC_PREFIX is the relocation mechanism of Chapter 1.5, seen from outside
the driver. Its documented default is $prefix/lib/gcc/, but when it is unset,
the driver derives it from argv[0] and exports it anyway, as Listing
1.5-4 shows. Setting it by hand only pre-empts that computation. Whoever sets
it, the variable does three things:
set_std_prefix (gcc_exec_prefix, len);
add_prefix (&exec_prefixes, gcc_libexec_prefix, "GCC",
PREFIX_PRIORITY_LAST, 0, 0);
add_prefix (&startfile_prefixes, gcc_exec_prefix, "GCC",
PREFIX_PRIORITY_LAST, 0, 0);
Listing 1.9-2: what GCC_EXEC_PREFIX feeds (gcc/gcc.cc:4879-4884).
The two add_prefix calls put the relocated prefixes on exec_prefixes and
startfile_prefixes, the program and library search lists. The
set_std_prefix call is the one that is easy to miss, because it moves header
search too. It tells gcc/prefix.cc what to substitute for the configure-time
prefix in compiled-in directory names, and the manual's GCC_EXEC_PREFIX entry
documents that substitution. That is how a relocated toolchain finds its own
<stdint.h>, and Chapter 1.8 shows the code that consumes the substitution.
Two smaller behaviours come with the variable. A small block recognises a
trailing /lib/gcc/ and shortens the length before use, so pointing the
variable at either $prefix/ or $prefix/lib/gcc/ behaves the same
(gcc.cc:4864-4877). The variable relocates the sysroot too, but
only if the toolchain was configured with the sysroot inside $exec_prefix
(gcc.cc:5542-5559), the condition that Chapter 1.5 covers.
-no-canonical-prefixes: relocating from the symlink's directory
-no-canonical-prefixes changes which function computes the relative prefix,
so a driver reached through a symlink resolves to the symlink's directory
rather than to the real one. It belongs with GCC_EXEC_PREFIX because it
changes the same relocation computation. The GCC manual documents the option
under Directory Options:
if (decoded_options[j].opt_index == OPT_no_canonical_prefixes)
{
get_relative_prefix = make_relative_prefix_ignore_links;
break;
}
Listing 1.9-3: -no-canonical-prefixes (gcc/gcc.cc:4807-4816).
The comment above this code explains why the option is handled early, before normal option processing: the prefixes it affects are needed to build the default search paths. It is the only option in the driver treated that way.
Checking the driver variables with env -u and -print-search-dirs
Comparing gcc -print-search-dirs with and without GCC_EXEC_PREFIX,
COMPILER_PATH and LIBRARY_PATH shows whether the environment moves a search
list. Run the pair first whenever a toolchain behaves differently in two
places, such as your machine and CI:
$ gcc -print-search-dirs
$ env -u GCC_EXEC_PREFIX -u COMPILER_PATH \
-u LIBRARY_PATH gcc -print-search-dirs
If the two outputs differ, one of the three variables is set in that
environment, and the programs: or libraries: line that changed shows which
list it moved.
The driver rewrites COMPILER_PATH and LIBRARY_PATH for collect2
Before it runs collect2 or ld, the driver overwrites COMPILER_PATH and
LIBRARY_PATH with its own final prefix lists. A child process therefore sees
the resolved lists, including everything that -B and the compiled-in defaults
contributed, and not the value the shell exported. The rewrite takes two calls:
/* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
for collect. */
putenv_from_prefixes (&exec_prefixes, "COMPILER_PATH", false);
putenv_from_prefixes (&startfile_prefixes, LIBRARY_PATH_ENV, true);
Listing 1.9-4: propagation to subprocesses
(gcc/gcc.cc:9275-9278).
Reading LIBRARY_PATH inside a build script that GCC invoked therefore reports
the driver's lists, not the shell's value. This shows up in configure scripts
and in Makefiles driven from a compiler wrapper, where the value looks like a
user setting and is not.
CPATH and the *_INCLUDE_PATH variables: read by cc1, not the driver
CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH and OBJC_INCLUDE_PATH move
header search, but nothing in gcc/gcc.cc reads them. They reach cc1 in the
environment that the driver passes on, so no driver option shows their effect.
cc1 reads them while it builds its include chains:
/* CPATH and language-dependent environment variables may add to the
include chain. */
add_env_var_paths ("CPATH", INC_BRACKET);
add_env_var_paths (lang_env_vars[idx], INC_SYSTEM);
Listing 1.9-5: the header variables
(gcc/incpath.cc:505-508), in register_include_chains. The table
of language variables is at :494-496.
CPATH joins the bracket chain, where -I directories go. The language variable
joins the system chain, where -isystem directories go, and idx selects it by
the language cc1 is compiling. Both calls come before GCC's own directories and
the system's are added, so both variables win over the defaults. The same
Environment Variables node documents this mapping to -I and
-isystem, and the empty-element rule, from gcc/doc/cppenv.texi.
Two consequences follow for debugging. -print-search-dirs cannot show these
variables, and the env -u diff of the driver variables does not unset them.
Ask cc1 instead: gcc -v -E - < /dev/null prints them with the rest of the
header search list. An empty element means the current directory
(gcc/incpath.cc:115-116), so a trailing : that a shell script
left on CPATH puts . on the header search list.
COLLECT_* variables: how collect2 and lto-wrapper re-enter the driver
The COLLECT_* variables flow the other way: the driver sets them and its
children read them. Two of those children re-enter the driver, as Chapter 1.1
describes, so they need to know which driver to run and with which switches.
collect2 must compile the constructor tables it generates, and lto-wrapper
must re-run code generation at link time with the original options.
COLLECT_GCC and COLLECT_GCC_OPTIONS carry those two answers, so when a link
goes wrong they show what the inner driver was told.
COLLECT_GCC: the path of the outer driver
COLLECT_GCC holds the full pathname of the running driver, taken from
argv[0] rather than from progname. The comment above the code gives the
reason:
/* Set up to remember the pathname of gcc and any options
needed for collect. We use argv[0] instead of progname because
we need the complete pathname. */
void
driver::putenv_COLLECT_GCC (const char *argv0) const
{
obstack_init (&collect_obstack);
obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=") - 1);
obstack_grow (&collect_obstack, argv0, strlen (argv0) + 1);
Listing 1.9-6: exporting COLLECT_GCC
(gcc/gcc.cc:8710-8721).
progname would give gcc. argv[0] gives the path that was invoked, which is
the only thing that identifies this installation among several on one machine.
lto-wrapper and collect2, the two consumers of COLLECT_GCC, disagree about
what to do when it is missing. Chapter 1.1 shows both code paths
(lto-wrapper.cc:1444-1448 and collect2.cc:1142-1151):
| Consumer | Behaviour when unset |
|---|---|
lto-wrapper | hard error: "environment variable COLLECT_GCC must be set" |
collect2 | falls back to <target>-gcc in a cross-directory build, otherwise to gcc |
The collect2 fallback is the dangerous one on a cross toolchain. A collect2
invoked without COLLECT_GCC can pick up a different compiler, and with it a
different sysroot, different startfile prefixes and a different crtbegin.o.
The link succeeds and the binary is wrong, with no diagnostic.
COLLECT_GCC_OPTIONS: the outer driver's switches, quoted
COLLECT_GCC_OPTIONS holds every switch of the outer driver, and each of its
arguments, single-quoted one by one. A value looks like this:
COLLECT_GCC_OPTIONS='-B' '/opt/alt/' '--sysroot=/arm-rootfs' '-O2' '-dumpdir' 'a-'
The function that builds it states its contract in its comment:
/* Store switches not filtered out by %<S in spec in COLLECT_GCC_OPTIONS
and place that in the environment. */
static void
set_collect_gcc_options (void)
Listing 1.9-7: set_collect_gcc_options
(gcc/gcc.cc:5610-5614).
The variable is therefore not the command line as typed, because the driver
leaves out the switches that a %<S directive removed. %<S is the spec directive that
removes the switch -S (Chapter 1.3), and the loop that
fills the variable skips such switches explicitly:
/* Ignore elided switches. */
if ((switches[i].live_cond
& (SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC))
== SWITCH_IGNORE)
continue;
Listing 1.9-8: %<S filtering (gcc/gcc.cc:5634-5638).
The driver rebuilds the variable before every subprocess rather than taking a
snapshot at startup, so each value reflects the spec state at that moment
(gcc.cc:5841 and :6169). It also
holds switches that nobody typed, such as -dumpdir and other options
synthesised along the way. A COLLECT_GCC_OPTIONS line therefore holds
switches that are not in the command line you typed. Embedded single quotes are
escaped as '\'' in the loop that follows the lines of Listing 1.9-7, which
makes the whole line safe to paste into a shell.
COLLECT_GCC_OPTIONS carries path flags into the inner driver
COLLECT_GCC_OPTIONS is what lets path flags survive the recursion into
collect2 and back. A -B, --sysroot or -L on the command line lands in
the variable. When collect2 re-invokes the driver with those options, the
inner driver therefore rebuilds the same prefix lists and the same sysroot as
the outer one. Together with the rewrite of COMPILER_PATH and
LIBRARY_PATH in Listing 1.9-4, it keeps every process in the tree in
agreement about where files live. Without it, a -B would apply to the compile
and not to the link, with no diagnostic.
COLLECT_LTO_WRAPPER, COLLECT_AS_OPTIONS and COLLECT_NO_DEMANGLE
Three more variables complete the family. The driver sets COLLECT_LTO_WRAPPER
and COLLECT_AS_OPTIONS for its children, and COLLECT_NO_DEMANGLE is the only
member of the family that you would ever set deliberately:
| Variable | Purpose | Set at |
|---|---|---|
COLLECT_LTO_WRAPPER | path to lto-wrapper | gcc.cc:8726-8745 |
COLLECT_AS_OPTIONS | accumulated -Xassembler / -Wa, options | gcc.cc:6094-6112 |
COLLECT_NO_DEMANGLE | suppresses symbol demangling in collect2 | you, by hand |
COLLECT_NO_DEMANGLE is the odd one out because it is an input. collect2
reads it (collect2.cc:895) and then re-exports it, so that a
nested invocation inherits it (:898).
collect2 also reads COLLECT_LTO_WRAPPER, and stops with an error if it is
absent, but only when collect2 handles link-time optimisation itself. That
happens when the link runs without the linker plugin, so collect2 sees no
-plugin, and an object holds IR (collect2.cc:597-614). IR is
GCC's intermediate representation, which cc1 writes into the object file
under -flto. Chapter 1.13 explains both
routes, with the linker plugin and without it.
Checking the COLLECT_* variables with gcc -v
gcc -v prints every variable that the driver sets, because the function that
sets them echoes each one under -v. That makes -v the quickest way to see
what collect2 and lto-wrapper were handed:
void
env_manager::xput (const char *string)
{
if (m_debug)
fprintf (stderr, "env_manager::xput (%s)\n", string);
if (verbose_flag)
fnotice (stderr, "%s\n", string);
Listing 1.9-9: why -v echoes the environment
(gcc/gcc.cc:126-132).
The verbose_flag test is the echo. Filtering the -v output of a link for
lines that start with COLLECT_ shows the variables the driver set:
$ gcc -v hello.c 2>&1 | grep '^COLLECT_'
The first line is COLLECT_GCC=, followed by COLLECT_LTO_WRAPPER= when the
command links and the driver finds lto-wrapper
(gcc.cc:8730-8733). A fresh COLLECT_GCC_OPTIONS= line
then comes immediately before every subprocess, one for each rebuild of the
variable. The lines are already shell-quoted, so they paste into a terminal and
reproduce what collect2 was handed.
Setting COLLECT_GCC or COLLECT_GCC_OPTIONS yourself has an effect only when
you run collect2 or lto-wrapper directly, which can help when debugging a
link. Before a normal gcc run, exporting them accomplishes nothing, because
the driver overwrites both before it spawns anything.
Three things to carry away
-B outranks GCC_EXEC_PREFIX, COMPILER_PATH and LIBRARY_PATH. The
prefix lists have two priority levels, and -B has the higher one.
LIBRARY_PATH does nothing on a cross compiler. One *cross_compile == '0'
guard skips it, and the driver prints no diagnostic.
COLLECT_GCC and COLLECT_GCC_OPTIONS make path flags survive the recursion
into collect2. Without them, a collect2 can use the wrong compiler, with no
diagnostic.
Documentation coverage
GCC_EXEC_PREFIX, COMPILER_PATH and LIBRARY_PATH are documented, in the
Environment Variables node (gcc/doc/invoke.texi:37984, with the
individual items at :38057, :38092 and :38099). The header variables are in
the same node, from gcc/doc/cppenv.texi (included at invoke.texi:38155),
including the empty-element rule.
What is not documented:
- That the driver never reads the header variables, so no driver option shows their effect.
- The
COLLECT_*family that the driver exports. The Environment Variables node covers what you may set, and the outward channel is in the source only. collect2's fallback to<target>-gccorgccwhenCOLLECT_GCCis unset.- That the driver overwrites
COMPILER_PATHandLIBRARY_PATHbefore spawning the linker, so their values inside a child process are the driver's, not yours. - That switches removed by
%<Sare absent fromCOLLECT_GCC_OPTIONS.
Next: Chapter 1.10, Turning the runtime off: -nostdlib and
-ffreestanding, what -nostdlib and its
relatives take off the link line, and what you then owe.
1.10 -nostdlib and -ffreestanding: turning the runtime off
GCC 15.2.0. To run the commands: an installed compiler, and arm-none-eabi-gcc for the bare-metal examples.
You are bringing up firmware on a Cortex-M part. There is no operating system,
no glibc and no crt1.o that knows how to call main, so you reach for
-nostdlib. The link then fails on an undefined reference to __aeabi_idiv,
a symbol you have never typed, from a library you thought you had switched off.
-nostdlib is not one mechanism. In the link spec it is three %{!…:} guards,
and in the g++ driver it is one case label. Where those guards sit decides
what each option of the family removes, so the truth table can be read from the
source instead of memorised from the manual. -nostdlib also does not stop the
compiler from emitting calls into libgcc, and whatever it removes, your startup
code and link line must now supply. Three options with similar names,
-ffreestanding, -nostdinc and -nostdinc++, act before the link and leave
it alone.
This chapter assumes Chapter 1.1 for -###, and
Chapter 1.3 for the spec language and its %{…}
conditionals. It takes apart the link line that
Chapter 1.7 built, and uses its Listing 1.7-1 of
LINK_COMMAND_SPEC, its startfile and endfile specs and its double -lgcc. It
also uses the search lists of Chapter 1.5, the
multilib selection of Chapter 1.6 and the include table
cpp_include_defaults of Chapter 1.8.
The -nostdlib family in common.opt: Driver and no variable
-nostdlib and the four other options of its family have no C variable
anywhere in the compiler. They exist as strings that a spec conditional such as
%{!nostdlib:…} can match, which is why they compose cleanly and why a search
of the source for flag_nostdlib finds nothing. Each is declared with the
single flag Driver and nothing else:
nodefaultlibs
Driver
nostartfiles
Driver
nolibc
Driver
nostdlib
Driver
nostdlib++
Driver
Listing 1.10-1: the whole declaration of every option in the -nostdlib family
(gcc/common.opt:3782-3795).
No declaration has a Var(...), an Init(...) or help text. An option with
Driver and no Var therefore cannot be tested with an if anywhere in the
compiler.
-nostdlib++ was added in GCC 13, so it does not exist if you are on GCC 12 or
earlier. The option is absent from gcc/common.opt at releases/gcc-11.4.0
and releases/gcc-12.3.0, and present from releases/gcc-13.3.0 onward.
-nolibc and -nostdlib go back much further.
The guards in LINK_COMMAND_SPEC: the truth table is their nesting
The truth table of the -nostdlib family follows from three lines of
LINK_COMMAND_SPEC, each holding one slot guarded three deep. The outer two
guards are the same on all three lines, and only the inner one differs.
Chapter 1.7 showed the whole template as Listing
1.7-1, and these are its guarded slots:
%{s} %{t} %{u*} %{z} %{Z} %{!nostdlib:%{!r:%{!nostartfiles:%S}}} \
...
%{!nostdlib:%{!r:%{!nodefaultlibs:%(link_ssp) %(link_gcc_c_sequence)}}}\
%{!nostdlib:%{!r:%{!nostartfiles:%E}}} %{T*} \n%(post_link) }}}}}}"
Listing 1.10-2: the three guarded slots, at gcc/gcc.cc:1168,
:1176 and :1177.
Reading the guards from the outside in gives the slots that each option suppresses. An option suppresses a slot when its name sits in one of that line's guards:
| Option | Suppresses %S (startfiles) | Suppresses %(link_gcc_c_sequence) | Suppresses %E (endfiles) |
|---|---|---|---|
-nostartfiles | yes | no | yes |
-nodefaultlibs | no | yes | no |
-nostdlib | yes | yes | yes |
-r | yes | yes | yes |
The GCC manual documents the first three rows, with -nolibc and
-nostdlib++, under Link Options. The -r row follows from
the outer guards, which are %{!nostdlib:%{!r: on every line, so -r and
-nostdlib are indistinguishable in these slots. A relocatable link therefore
never gets the runtime. If you pass -r and find crtbegin.o missing, this
guard is the cause. The behaviour is correct, because a partial link must not
drag in startup code that will be linked again later.
-nostartfiles and -nodefaultlibs differ only in which lines carry their
inner guard. -nostartfiles sits in the guards of the %S and %E lines, and
-nodefaultlibs in the guard of the library line. Nothing enforces this
symmetry, which comes only from the option name written inside each %{!…:}.
Checking -nostdlib, -nostartfiles and -nodefaultlibs with -###
Each row of the truth table can be checked with -###, which prints the
command lines the driver would run and then stops. Diffing that output with and
without each option shows which crt* files and -l options leave the link
line. The GCC manual documents -### under Overall Options,
and these commands filter its output down to the crt files and -l options:
$ gcc -### hello.c 2>&1 | tr ' ' '\n' | grep -E 'crt|^-l' | sort > full
$ gcc -### -nostdlib hello.c 2>&1 | tr ' ' '\n' | grep -E 'crt|^-l' | sort > nostdlib
$ gcc -### -nostartfiles hello.c 2>&1 | tr ' ' '\n' | grep -E 'crt|^-l' | sort > nostart
$ gcc -### -nodefaultlibs hello.c 2>&1 | tr ' ' '\n' | grep -E 'crt|^-l' | sort > nodeflibs
$ diff full nostart # only crt* lines disappear
$ diff full nodeflibs # only -l* lines disappear
$ diff full nostdlib # both
$ gcc -### -r hello.c 2>&1 | tr ' ' '\n' | grep -cE 'crt|^-l' # 0, same as -nostdlib
Listing 1.10-3: deriving the truth table experimentally.
The first diff shows only crt* lines leaving, the second only -l lines,
and the third both. Under -r the last command counts no crt file and no
-l option, the same result as -nostdlib. The sort matters, because
-nodefaultlibs also changes the order of what is left.
The -no* link options change no search path, because they remove text from a
command line and never touch where the driver looks. -print-search-dirs and
-print-file-name=crt1.o give the same answers with and without each of them.
%S, %E and %G %L %G: what each guard removes
The three guards remove the directives %S, %E and %(link_gcc_c_sequence),
not named files, so what an option takes off the link line depends on what the
target's specs expand to. %S and %E are the startfile and endfile specs from
Chapter 1.7, and the library slot is a sequence that
holds more than -lc. Knowing each expansion tells you what a -nostdlib link
has to put back.
The default startfile spec is built on crt0, and the default endfile spec is
empty (gcc/gcc.cc:891-895, :897-900). The
familiar crt1.o crti.o crtbegin.o shape is the GNU userspace override. What
-nostartfiles removes is therefore target-specific: on glibc it is five
objects, and on a target that never defined STARTFILE_SPEC it may be one.
The library slot holds %(link_gcc_c_sequence), which is not -lc. Its
default is a macro that a target can override:
#ifndef LINK_GCC_C_SEQUENCE_SPEC
#define LINK_GCC_C_SEQUENCE_SPEC "%G %{!nolibc:%L %G}"
#endif
Listing 1.10-4: LINK_GCC_C_SEQUENCE_SPEC (gcc/gcc.cc:987-992).
%G is libgcc and %L is libc, so the sequence is -lgcc -lc -lgcc, the
double libgcc that Chapter 1.7 explains.
-nodefaultlibs removes the whole expression, while -nolibc removes only
%L %G, the -lc and the second -lgcc, and keeps the leading -lgcc. That
makes -nolibc the option for a link that has its own libc but still wants the
compiler's helper routines. The definition is byte-identical in every release
from GCC 11 to 15.2.0.
-nostdlib removes -lgcc, not the calls into libgcc
-nostdlib removes -lgcc from the link line, but not the calls to libgcc
that the compiler has already emitted into your object files. Those calls are
why the firmware link fails on __aeabi_idiv. An undefined __aeabi_idiv or
__udivsi3 after a -nostdlib link is the most common consequence of the
option, and it always has the same fix: put -lgcc back by hand.
The compiler emits a libgcc call when the target has no instruction for what
you wrote: a 64-bit divide on a 32-bit machine, a soft-float multiply, an
unaligned wide load or a switch lowered to a table helper. On Arm the helpers
are the __aeabi_* family, and elsewhere they have names such as __divdi3,
__udivsi3 and __muldf3. The GCC manual's -nostdlib entry under
Link Options gives the same warning and tells you to add
-lgcc back. nm -u shows the calls in an object file before any link runs:
$ arm-none-eabi-gcc -c -O2 -mcpu=cortex-m0 div.c
$ arm-none-eabi-nm -u div.o | grep aeabi
Listing 1.10-5: the calls survive -nostdlib because they were emitted at compile
time, long before the link line existed.
If div.c contains a division, nm -u lists the __aeabi_* helpers that
div.o calls among its undefined symbols, although no link has run yet. A
working bare-metal link is therefore almost never bare -nostdlib. It puts
libgcc back by hand, next to its own linker script and startup object:
$ arm-none-eabi-gcc -nostdlib -T link.ld start.o main.o -lgcc
-print-libgcc-file-name prints the full path of the libgcc.a that -lgcc
finds with the options you give it. The GCC manual documents it for this case
under Developer Options:
$ arm-none-eabi-gcc -mcpu=cortex-m4 -mfloat-abi=hard -print-libgcc-file-name
The path goes through the multilib selection of
Chapter 1.6, so the answer changes with -mcpu and
-mfloat-abi. A libgcc.a from the wrong variant links and then misbehaves.
-lstdc++ comes from the g++ driver, not from a spec
-lstdc++ is not in any spec, so no %{!…:} guard can remove it. The g++
driver adds it before the specs run, and checks the -no* options itself to
decide whether to add it. It checks a different set of options from the spec
guards, so a g++ link has a fourth column that the truth table does not
predict:
case OPT_nostdlib__:
args[i] |= SKIPOPT;
/* FALLTHRU */
case OPT_nostdlib:
case OPT_nodefaultlibs:
library = -1;
break;
Listing 1.10-6: the C++ side of the family (gcc/cp/g++spec.cc:170-176).
Setting library to -1 means "never link the C++ runtime", according to the
comment on its values (gcc/cp/g++spec.cc:92-97). Three
consequences follow that the spec guards do not predict.
-nostartfiles does not suppress -lstdc++, because it is not in that case
list. The startfiles and the C++ runtime are decided by two unrelated pieces of
code, and this is where the symmetry of the truth table breaks.
-r still sets library to -1, by a different route. It is absent from
Listing 1.10-6 but present a few lines further down, in the list with -c,
-S and -E (g++spec.cc:215-225). The comment there gives the
reason: "Don't specify libraries if we won't link, since that would cause a
warning."
-nostdlib++ disappears from the command line. The SKIPOPT on the first line
of Listing 1.10-6 deletes it from the option array, and the /* FALLTHRU */
gives it the same library = -1 as -nostdlib. Unlike -nostdlib, it never
reaches the specs, so it drops the C++ runtime and leaves -lc and -lgcc in
place. Chapter 1.11 reads that state machine in
full.
-nostdlib, -ffreestanding, -nostdinc: related names, unrelated stages
-nostdlib, -ffreestanding and -nostdinc have related names but act at
three different stages, and none of them implies another. The names invite
confusion, but each option is implemented in a different part of the compiler
and changes something different:
| Option | Stage | What it changes |
|---|---|---|
-nostdlib | link | text on the linker command line |
-ffreestanding | compile | what the compiler may assume about libc and main |
-nostdinc / -nostdinc++ | preprocess | the header search list |
You can #include <stdio.h> under -nostdlib and fail only at link, and you
can pass -ffreestanding and see no change in the link line. The GCC manual
keeps them apart too: -ffreestanding is under
C Dialect Options, and -nostdinc and -nostdinc++ are
under Directory Options. -ffreestanding and -nostdinc are
both handled in gcc/c-family/c-opts.cc, and each does more than its name
suggests.
-ffreestanding sets flag_hosted and flag_no_builtin
-ffreestanding sets two flags, flag_hosted and flag_no_builtin, and the
second has the more visible effects. The common account says only that it sets
flag_hosted to 0, but the manual's entry under
C Dialect Options says that the option "implies
-fno-builtin". The source sets the two flags together:
case OPT_ffreestanding:
value = !value;
/* Fall through. */
case OPT_fhosted:
flag_hosted = value;
flag_no_builtin = !value;
break;
Listing 1.10-7: gcc/c-family/c-opts.cc:498-504.
__STDC_HOSTED__ is defined from flag_hosted, which also relaxes the
requirements on main. flag_no_builtin stops the compiler from turning
printf("x\n") into puts("x"), or memcpy into inline moves. Two further
effects of -ffreestanding sit in the same file: loop pattern recognition is
disabled (c-opts.cc:935-939), and the -Wmain default
flips (:947-954). -ffreestanding is therefore closer to
-fno-builtin than to -nostdlib.
-nostdinc removes GCC's own headers too
-nostdinc removes every standard include directory, GCC's own include
directory among them, so <stdint.h> goes along with <stdio.h>. The whole
implementation is one file-static bool and the if that tests it. The option
sets the bool:
case OPT_nostdinc:
std_inc = false;
break;
Listing 1.10-8: gcc/c-family/c-opts.cc:639-641.
The bool is passed as the stdinc parameter of register_include_chains
(gcc/c-family/c-opts.cc:867-868). There it gates one call:
/* Finally chain on the standard directories. */
if (stdinc)
add_standard_paths (sysroot, iprefix, imultilib, cxx_stdinc);
Listing 1.10-9: the entire implementation of -nostdinc
(gcc/incpath.cc:512-514).
add_standard_paths walks cpp_include_defaults, the table from
Chapter 1.8 that holds both /usr/include and
GCC's own lib/gcc/<target>/<version>/include. One if skips the whole table,
and with it the directory holding <stddef.h>, <stdint.h> and <stdarg.h>,
which Chapter 1.8 showed the compiler is required to provide. The useful form
is therefore almost always a pair, which drops the system headers and keeps the
compiler's own:
$ gcc -nostdinc -isystem "$(gcc -print-file-name=include)" -c foo.c
Listing 1.10-10: drop the system headers, keep the compiler's own.
The -isystem directory survives because it goes on a chain that is merged
after add_standard_paths would have run. -v prints the search list that
results, so you can confirm what -nostdinc leaves:
$ echo 'int main(void){return 0;}' | gcc -nostdinc -E -v -x c - 2>&1 | sed -n '/search starts here/,/End of search/p'
The list that sed prints holds neither GCC's own include directory nor
/usr/include, because the if in Listing 1.10-9 skipped the table that names
them. Adding the -isystem of Listing 1.10-10 puts GCC's own directory back.
-nostdinc++ is narrower. It sets std_cxx_inc to false, which arrives as
cxx_stdinc and suppresses only the entries whose cplusplus field is
non-zero (gcc/incpath.cc:176-177). Those are the C++
directories in Chapter 1.8's table, so the C headers stay.
After -nostdlib: _start, constructors, -lgcc and a libc
A -nostdlib link leaves four jobs to you that the startfiles and the default
libraries used to do. The first two produce a program that links, runs and
does the wrong thing, rather than one that fails to build:
-
An entry point. The linker's default is
_start, notmain. Nothing now callsmain, sets up the stack or zeroes.bss. -
Static initialisation. The compiler puts constructors in
.init_array, but something must run them at startup. Where a target uses.init_array,crtstuff.cleaves that to the C library: "If we are using .init_array, there is nothing to do" (libgcc/crtstuff.c:687). The C library's startup code begins in thecrt1.othat-nostartfilesremoves. Without it, C++ constructors for file-scope objects and C__attribute__((constructor))functions never run, with no diagnostic. -
libgcc. Add
-lgccby hand, because the calls that the compiler emitted into libgcc survive-nostdlib. -
A C library. Supply one, or write code that needs none.
-nolibcis the middle ground, which keeps-lgccand drops-lc.
Three things to carry away
-nostdlib is three spec guards and one case label. -nostartfiles and
-nodefaultlibs fail some of the same guards, and -r fails all three.
Removing -lgcc does not remove the calls to it. The compiler emitted them
when it compiled your code, so a bare-metal link still needs libgcc.
-nostdlib, -ffreestanding and -nostdinc act at three different stages.
The stages are link, compile and preprocess, and none of the three options
implies another.
Things that surprise people
The -no* link options change no search path. Removing -lc does not
remove <sysroot>/usr/lib from the search list. Chapter 1.7's rule holds: the
driver emits text, and ld resolves it.
-nostdlib and -ffreestanding are often used together and do not
overlap. A hermetic build needs all three,
-nostdlib -ffreestanding -nostdinc, plus explicit -I, -L and --sysroot.
A missing constructor is a -nostartfiles bug. If your C++ globals are
uninitialised and nothing crashed, look for the startup objects on the link
line, crt1.o among them on glibc, before looking anywhere else.
-nolibc exists. A link with -nodefaultlibs and -lgcc added back by
hand gets what -nolibc gives in one option, except that -nodefaultlibs also
drops %(link_ssp), which -nolibc keeps.
Documentation coverage
The GCC manual documents the link options in the Link Options
node (gcc/doc/invoke.texi:19067), and it documents what each one
suppresses. -ffreestanding is under C Dialect Options,
and -nostdinc under Directory Options.
What is not documented:
- That the link options are pure spec conditionals with no C variable. The manual
describes the effect, but nothing says that the implementation is three
%{!…:}guards. That fact is what lets you predict the interactions instead of memorising them. - That
-ris equivalent to-nostdlibfor all three slots. You can only get this by reading the%{!r:in Listing 1.10-2. - That
-nostdincremoves GCC's own headers as well as the system's. The manual implies it: only the-I,-iquote,-isystemand-idirafterdirectories are searched (gcc/doc/cppdiropts.texi:142-147). But neither the manual nor the help text, "standard system include directories", names GCC's ownincludedirectory. Listing 1.10-9 states it. - That
-lstdc++is removed by a different mechanism, and therefore that the truth table has an asymmetric fourth column. Nothing in the manual connects the two families.
Next: Chapter 1.11, How g++ injects -lstdc++,
the function that puts -lstdc++ on a g++ link and moves your -lm.
1.11 How g++ injects -lstdc++
GCC 15.2.0. To run the commands: an installed compiler with g++.
You have a project of C object files, and nothing in it is C++. You link it with
g++, because that is what the build system uses, and you pass -lm -lz because
you need the maths library and zlib. The link line that comes out has -lstdc++
on it, and your -lm has moved: you typed it before -lz, and it comes out after
-lstdc++.
g++ runs the same driver code as gcc, with one extra function called before
any option is acted on. That function may rewrite the option array: insert
options, delete them and reorder them. Everything surprising about C++ linking
happens in those few hundred lines of gcc/cp/g++spec.cc, and the manual
documents only their outcome.
This chapter assumes Chapter 1.1, for -### and the
call to lang_specific_driver in Listing 1.1-8, and
Chapter 1.3, for specs and -dumpspecs. It also assumes
Chapter 1.7, for the link line that the generic driver
builds from LINK_COMMAND_SPEC, and
Chapter 1.10, for -nostdlib,
-nostartfiles and the truth table of their spec guards.
lang_specific_driver: the g++ hook called before any option acts
lang_specific_driver is the hook that makes g++ differ from gcc. It runs
before the driver acts on any option, so it can rewrite your command line before
anything reads it. The generic driver first decodes argv into an array of
struct cl_decoded_option, then makes the call that Chapter 1.1 showed as
Listing 1.1-8:
/* Do language-specific adjustment/addition of flags. */
lang_specific_driver (&decoded_options, &decoded_options_count,
&added_libraries);
Listing 1.11-1: the call to the language hook
(gcc/gcc.cc:4860-4862).
All three arguments are passed by address because they are out-parameters. The
hook may replace the array, change its length, and report how many libraries it
added. Every front end links its own lang_specific_driver: the C one does
nothing, and the C++ one is in gcc/cp/g++spec.cc.
The GCC manual documents the outcome under Invoking G++: g++
"automatically specifies linking against the C++ library", and gcc does not.
The manual gives no conditions, so the sections that follow read them from
g++spec.cc.
Because the hook runs first, -lstdc++ is an ordinary -l by the time the
specs run, no different from one you typed. No spec mentions it, so searching
-dumpspecs output for stdc++ finds nothing.
library and the per-argument bits: what the hook records
The hook keeps its decision about the C++ runtime in one int, library, and
what it saw in each option in an array of bits. The options that turn injection
on and off move library, and the reordering of -lm and -lc reads the bits.
The comment above library is the only place its four values are documented:
/* What action to take for the c++ runtime library:
-1 means we should not link it in.
0 means we should link it if it is needed.
1 means it is needed and should be linked in.
2 means it is needed but should be linked statically. */
int library = 0;
Listing 1.11-2: gcc/cp/g++spec.cc:92-97.
The default is 0, "link it if it is needed", and the first pass over the
options exists to move it off zero. Because the start value is the "maybe" state
and not "no", most transitions go from 0 to 1. They are guarded by
if (library == 0), so that an earlier -1 is never overwritten.
The bits live in a parallel array, args, with one int per option. Each
#define names one bit, and its comment says what the bit records:
/* This bit is set if we saw a `-xfoo' language specification. */
#define LANGSPEC (1<<1)
/* This bit is set if they did `-lm' or `-lmath'. */
#define MATHLIB (1<<2)
/* This bit is set if they did `-lc'. */
#define WITHLIBC (1<<3)
/* Skip this option. */
#define SKIPOPT (1<<4)
/* Add -lstdc++exp for experimental features that need library support. */
#define EXPERIMENTAL (1<<5)
Listing 1.11-3: the per-argument bits (gcc/cp/g++spec.cc:26-35).
The hook sets and tests four of those five bits. EXPERIMENTAL is never used:
the #define is its only occurrence in the file, at every release from 13.3.0
to 15.2.0. The hook tracks -fcontracts with a separate
bool need_experimental instead. EXPERIMENTAL is one of two pieces of unused
state in the file, and the other is saw_time in the reordering of -lm and
-lc. Both matter only so that you stop looking for the code that sets them.
What turns -lstdc++ injection on
Two paths move library from 0 to 1: an -l option that the hook does not
recognise, and an input file that is not a header. Both are broader than "link
the C++ runtime when a C++ source is on the command line", and they explain the
-lstdc++ on the all-C link of the opening example.
Any -l other than -lm and -lc
The hook recognises two libraries by name, MATH_LIBRARY and c, and treats
every other -l as one that might need the C++ runtime. MATH_LIBRARY is "m"
by default:
case OPT_l:
if (strcmp (arg, MATH_LIBRARY) == 0)
{
args[i] |= MATHLIB;
need_math = 0;
}
else if (strcmp (arg, "c") == 0)
args[i] |= WITHLIBC;
else
/* Unrecognized libraries (e.g. -lfoo) may require libstdc++. */
library = (library == 0) ? 1 : library;
break;
Listing 1.11-4: gcc/cp/g++spec.cc:178-189.
Every library other than those two is unknown, and an unknown library might need
the C++ runtime, so g++ -lz foo.o links libstdc++ because of -lz. The
comment in Listing 1.11-4 is the hook's only justification. -Xlinker and -Wl,
do the same (gcc/cp/g++spec.cc:207-213), with a comment that spells
out the reasoning: "Arguments that go directly to the linker might be .o files,
or something, and so might cause libstdc++ to be needed."
Any input other than .h, .hpp and other headers
An input file sets library to 1 unless its name ends in a header suffix. The
test is negative, so the rule is not "a C++ source file on the command line":
the hook never looks for a C++ extension. Listing 1.11-5 shows four of the nine
suffixes it compares:
/* If we don't know that this is a header file, we might
need to be linking in the libraries. */
if (library == 0)
{
if ((len <= 2 || strcmp (arg + (len - 2), ".H") != 0)
&& (len <= 2 || strcmp (arg + (len - 2), ".h") != 0)
&& (len <= 4 || strcmp (arg + (len - 4), ".hpp") != 0)
...
&& (len <= 3 || strcmp (arg + (len - 3), ".hh") != 0))
library = 1;
}
Listing 1.11-5: abridged from gcc/cp/g++spec.cc:277-291.
The nine suffixes are .H, .h, .hpp, .hp, .hxx, .h++, .HPP, .tcc
and .hh. g++ foo.o, g++ foo.a and g++ foo.s therefore all link the C++
runtime, because none of those names ends in one of them.
The two paths together give the rule: g++ links libstdc++ unless you gave
it nothing but headers or an option turns the runtime off. The driver errs towards linking
on purpose, because a missing -lstdc++ gives a confusing undefined-symbol
error, while a spurious one costs a DT_NEEDED entry.
Three -### commands check the input-file rule and its limits. Each splits the
printed commands into words and counts the words that contain stdc:
$ g++ -### foo.o 2>&1 | tr ' ' '\n' | grep -c stdc # 1: input file rule
$ g++ -### foo.hh 2>&1 | tr ' ' '\n' | grep -c stdc # 0: header, no link anyway
$ gcc -### foo.o -lz 2>&1 | tr ' ' '\n' | grep -c stdc # 0: gcc injects nothing
Listing 1.11-6: the injection rules, one command each.
The object file gets its -lstdc++ from the input-file rule. The header gets
none, and would not be linked in any case. gcc adds nothing even with -lz on
the line, because only the g++ hook injects the C++ runtime.
What turns -lstdc++ injection off: -nostdlib and -c
Two lists of options set library to -1, which turns injection off:
the -nostdlib family, and the options under which no link happens. Chapter
1.10 read the spec guards that -nostdlib trips on the link line. Listing 1.11-7
is its C++ half, which Chapter 1.10 also showed as Listing 1.10-6:
case OPT_nostdlib__:
args[i] |= SKIPOPT;
/* FALLTHRU */
case OPT_nostdlib:
case OPT_nodefaultlibs:
library = -1;
break;
Listing 1.11-7: gcc/cp/g++spec.cc:170-176.
A separate case list holds the options under which no link happens at all, and
its comment gives the reason:
case OPT_c:
case OPT_r:
case OPT_S:
case OPT_E:
case OPT_M:
case OPT_MM:
case OPT_fsyntax_only:
/* Don't specify libraries if we won't link, since that would
cause a warning. */
library = -1;
break;
Listing 1.11-8: gcc/cp/g++spec.cc:215-225.
Listing 1.11-8 is why g++ -c foo.cc produces no unused-argument warning, and
why -r lands at -1 even though it is absent from Listing 1.11-7.
-nostartfiles is in neither list, so it does not suppress -lstdc++. A g++
link has a -lstdc++ column that the truth table of Chapter 1.10 does not
predict, because these two case lists decide it, not the %{!…:} guards in
LINK_COMMAND_SPEC.
-nostdlib++ is the one option in Listing 1.11-7 that disappears from the
command line. It takes SKIPOPT before it falls through, so the hook deletes it
from the array (gcc/cp/g++spec.cc:368-369) and it never reaches the
specs. It removes the C++ runtime and leaves -lc and -lgcc in place, which is
what its name promises and what -nostdlib cannot do. The GCC manual documents
the option under Link Options in one line: "Do not implicitly link
with standard C++ libraries."
-nostdlib++ does not exist in GCC 12 and earlier. It arrived in GCC 13, along
with -lstdc++exp, and the same commit took g++spec.cc from 436 to 460 lines,
so every line number in this chapter differs before GCC 13. Before GCC 12 the
file is g++spec.c, not .cc.
g++ moves -lm and -lc after -lstdc++
g++ takes -lm and -lc out of their place on the command line and re-emits
them after -lstdc++, which is the move in the opening example. The hook copies
the options into a new array one at a time. While library is above 0, two
checks in that loop pull out the first -lm and the first -lc as they pass.
The comment above the checks gives the reason:
/* Make sure -lstdc++ is before the math library, since libstdc++
itself uses those math routines. */
if (!saw_math && (args[i] & MATHLIB) && library > 0)
{
--j;
saw_math = &decoded_options[i];
}
if (!saw_libc && (args[i] & WITHLIBC) && library > 0)
{
--j;
saw_libc = &decoded_options[i];
}
Listing 1.11-9: gcc/cp/g++spec.cc:326-338.
The --j is the removal. The loop has already written the option to
new_decoded_options[j], so decrementing j lets the next iteration overwrite
it. A pointer keeps the option, and the end of the hook re-emits it after the
runtime:
if (saw_math)
new_decoded_options[j++] = *saw_math;
else if (library > 0 && need_math)
{ ... generate_option (OPT_l, MATH_LIBRARY, ...) ... }
if (saw_time)
new_decoded_options[j++] = *saw_time;
if (saw_libc)
new_decoded_options[j++] = *saw_libc;
Listing 1.11-10: the re-emission (gcc/cp/g++spec.cc:430-443).
The move changes the link, and g++ prints no diagnostic for it:
g++ -lm foo.o links foo.o -lstdc++ -lm. On a target where every library is a
static archive, ld resolves symbols from left to right, so the order decides
which symbols the link pulls in. The comment gives a sound reason, because
libstdc++.a has undefined references into libm. The cost is that no
g++ command line can put -lm before -lstdc++. If you need that order, link
with gcc or ld and name the C++ runtime yourself.
When you pass no -lm, the else if branch of Listing 1.11-10 adds one. The
branch is gated on need_math, which is (MATH_LIBRARY[0] != '\0')
(gcc/cp/g++spec.cc:129). A port that folds the maths routines
into libc defines MATH_LIBRARY "", so its link line has no -lm. Check
MATH_LIBRARY before you conclude that a new target's link line is too short.
The saw_time slot for -lrt is dead code. saw_time is initialised to NULL
(gcc/cp/g++spec.cc:118-119) and read in Listing 1.11-10, but no
line in the file assigns it, because there is no TIMELIB bit to go with
MATHLIB and WITHLIBC. It is unassigned at every release from 11.4.0 to
15.2.0, so exactly two of your options are ever moved: -lm and -lc.
One -### command shows the move. It prints each -l option of the commands
the driver would run, in order, with any word that contains stdc:
$ g++ -### -lm -lz foo.o 2>&1 | tr ' ' '\n' | grep -E '^-l|stdc'
Listing 1.11-11: watch -lm come out after -lstdc++, and -lz stay where you put
it.
In the output, -lz stays where you put it, and -lm comes after -lstdc++,
where Listing 1.11-10 re-emits it.
-static-libstdc++ changes no path and no filename
-static-libstdc++ leaves the library name, the search order and every -L as
they were, and wraps the one -lstdc++ in a pair of linker state changes. The
GCC manual documents the contract under Link Options: the option
makes g++ link libstdc++ statically, "without necessarily linking other
libraries statically". The wrap is how g++ keeps that promise:
… -Wl,-Bstatic -lstdc++ -Wl,-Bdynamic -lm -lc
-Wl,-Bstatic switches ld to archive preference and -Wl,-Bdynamic switches
it back, so the preference covers exactly one library. The hook emits the two
halves around the -l, and Listing 1.11-12 is the opening half:
#ifdef HAVE_LD_STATIC_DYNAMIC
if (library > 1 && !static_link)
{
generate_option (OPT_Wl_, LD_STATIC_OPTION, 1, CL_DRIVER,
&new_decoded_options[j]);
j++;
}
#endif
Listing 1.11-12: the opening half (gcc/cp/g++spec.cc:384-391),
whose mirror image at :421-428 emits the closing LD_DYNAMIC_OPTION.
library > 1 is the 2 state, and !static_link skips the wrap under plain
-static, where the whole link is archive-only already. The option that sets
state 2 also deletes itself, on most targets:
case OPT_static_libstdc__:
library = library >= 0 ? 2 : library;
#ifdef HAVE_LD_STATIC_DYNAMIC
/* Remove -static-libstdc++ from the command only if target supports
LD_STATIC_DYNAMIC. When not supported, it is left in so that a
back-end target can use outfile substitution. */
args[i] |= SKIPOPT;
#endif
break;
Listing 1.11-13: gcc/cp/g++spec.cc:235-243.
The library >= 0 guard keeps g++ -c -static-libstdc++ at -1, because -c
got there first. The #ifdef means that on a target without
HAVE_LD_STATIC_DYNAMIC the option is not deleted, so it survives into the
specs for the port to act on. That conditional is why two targets disagree about
whether the option appears in -v output.
-static-libstdc++ needs libstdc++.a in the same search path as the shared
library, because the search does not change, only ld's preference between .a
and .so. If you ship a cross toolchain with a shared-only libstdc++, the option
gives you the shared library with no diagnostic, and the link succeeds.
On most targets the option itself does not appear on the link line, because the
hook deleted it. Search -v output for Bstatic, not for -static-libstdc++:
$ g++ -### -static-libstdc++ foo.o 2>&1 | tr ' ' '\n' | grep -E 'Bstatic|Bdynamic|stdc'
Listing 1.11-14: the option is gone, and its effect is two -Wl, options.
The output shows -Bstatic before -lstdc++ and -Bdynamic after it, and no
-static-libstdc++. On another linker the pair is spelled differently, because
configure picks the spelling by target, in a case "$target"
(gcc/configure.ac:4231-4250) followed by three
AC_DEFINEs (:4253-4259):
| Value | Target |
|---|---|
-Bstatic / -Bdynamic | GNU ld and Solaris (the default) |
-bstatic / -bdynamic | AIX |
-aarchive_shared / -adefault | HP-UX (non-GNU ld) |
LIBSTDCXX and -stdlib=: which C++ library g++ links
LIBSTDCXX is the macro that names the library g++ injects, so a port can
change it. Two options change the library for one command: -fcontracts adds
-lstdc++exp in front of it, and -stdlib=libc++ replaces it with clang's
runtime. Listing 1.11-15 gives the default of LIBSTDCXX and of the two macros
next to it:
#ifndef LIBSTDCXX
#define LIBSTDCXX "stdc++"
#endif
#ifndef LIBSTDCXX_PROFILE
#define LIBSTDCXX_PROFILE LIBSTDCXX
#endif
#ifndef LIBSTDCXX_STATIC
#define LIBSTDCXX_STATIC NULL
#endif
Listing 1.11-15: gcc/cp/g++spec.cc:44-52.
-p and -pg set saw_profile_flag, and the hook then names
LIBSTDCXX_PROFILE (gcc/cp/g++spec.cc:407-410).
LIBSTDCXX_STATIC is not a replacement but an extra library, appended after the
main one when the link is static (:413-419). An RTOS or
bare-metal port uses it to add its own support archive. If a link line on an
unusual target does not say -lstdc++, one of these three macros is why.
-fcontracts adds -lstdc++exp ahead of the main library
(gcc/cp/g++spec.cc:378-383). Those lines run before the
-Wl,-Bstatic of Listing 1.11-12, so -static-libstdc++ does not cover
libstdc++exp.
The GCC manual documents -stdlib= under C++ Dialect Options:
the option selects the headers and the runtime library, libstdc++ or libc++.
-stdlib=libc++ switches to clang's library and emits -lc++ and -lc++abi
(gcc/cp/g++spec.cc:392-406). The hook skips the ABI library when
the port sets LIBCXXABI to NULL. The comment on that macro gives the case: a
platform may forward the ABI library from libc++ or combine it some other way.
The option exists only if GCC was configured for it (ENABLE_STDLIB_OPTION),
which Chapter 1.12 covers.
added_libraries and the no input files check
added_libraries counts the -l options that the hook added, so that plain
g++ with no arguments fails with no input files. Without the count, the
driver would see the libraries that the hook had added, conclude that it had
inputs, and attempt a link. The hook hands the count back through the third
out-parameter of Listing 1.11-1, and the generic driver reads it once:
if (n_infiles == added_libraries)
fatal_error (input_location, "no input files");
Listing 1.11-16: gcc/gcc.cc:8970-8971.
That comparison is the only use of the count, and the reason
lang_specific_driver has to report what it did as well as doing it.
Three things to carry away
g++ is the C driver plus one hook. lang_specific_driver rewrites the
option array before the driver acts on any option.
Injection is the default, not the exception. An -l the hook does not
recognise, or any input that is not a header, adds -lstdc++.
Your -lm and -lc move. The hook re-emits them after -lstdc++. On a
target with a separate maths library it also adds a -lm you did not ask for.
Things that surprise people
gcc never injects anything. Link C++ objects with gcc and you get
undefined std:: symbols. At link time that is the practical difference between
the two drivers, not a different compiler or different code generation.
g++ -lz foo.o links the C++ runtime, even though nothing in it is C++.
Only -lm and -lc move. Every other option keeps its position.
-nostartfiles does not suppress -lstdc++. The spec guards and the C++
hook check two different lists of options.
Documentation coverage
The options are documented: -static-libstdc++ and -nostdlib++ under
Link Options (gcc/doc/invoke.texi:19416, :19262), and -stdlib=
under C++ Dialect Options (:3748). No manual documents the
mechanism:
- The injection's conditions have no texi node. The manual states only the
outcome:
g++"automatically specifies linking against the C++ library" (gcc/doc/invoke.texi:2360-2362). It does not say under what conditions. Thelibrarystate machine exists only as the source comment in Listing 1.11-2. - The
-lfoorule is undocumented. Linking any third-party library throughg++guarantees the C++ runtime. - The input-file rule is undocumented. It tests for header suffixes, not for a C++ source, and Listing 1.11-5 is the only statement of it.
- The
-lmand-lcreordering is undocumented. No manual says thatg++moves two of your options, andg++prints no diagnostic when it does. -static-libstdc++'s mechanism is undocumented. The manual describes the option, but not that it becomes-Wl,-Bstatic…-Wl,-Bdynamicand leaves the command line, nor theHAVE_LD_STATIC_DYNAMICconditional that decides whether it leaves.
For the mechanism, the comments in g++spec.cc are the specification.
Next: Chapter 1.12, Which libstdc++, and which <vector>,
the file that the injected -lstdc++ finds and the <vector> you compiled
against.
1.12 Which libstdc++, and which <vector>
GCC 15.2.0. To run the commands: a C++ cross compiler such as arm-linux-gnueabihf-g++, and a target root filesystem for --sysroot.
You have a cross toolchain and a root filesystem for the target. You pass
--sysroot=/arm-rootfs, and the rootfs contains /usr/include/c++/15 and
/usr/lib/libstdc++.so.6. Yet g++ -v -E -x c++ /dev/null shows a <vector>
from a directory under your compiler's install prefix. You try -B to fix it,
and nothing changes.
Neither half of libstdc++ is in the sysroot, by design. The headers and the
library both live relative to where the compiler is installed, and --sysroot
is about the C library. Exactly one configure-time route makes the headers
sysroot-relative, and you have to ask for it.
Chapter 1.11 put -lstdc++ on the link line.
This chapter answers two further questions: which file that -l resolves to,
and which <vector> you compiled against. Different mechanisms answer them,
although the same prefix moves both.
This chapter assumes Chapter 1.2 for the three
machine names and the tooldir, and Chapter 1.5
for the driver's prefix lists, add_prefix against add_sysrooted_prefix, and
Listings 1.5-8 and 1.5-9. It uses the multilib expansion of
Chapter 1.6, and cpp_include_defaults, its
add_sysroot field and %I from Chapter 1.8.
It also uses GCC_EXEC_PREFIX and LIBRARY_PATH from
Chapter 1.9, -nostdinc++ from
Chapter 1.10 and -stdlib= from
Chapter 1.11.
-lstdc++, <vector> and libstdc++.so: three separate decisions
Three questions about the C++ runtime look like one, and three separate
mechanisms answer them: whether -lstdc++ goes on the link line, where
#include <vector> comes from, and which libstdc++.so the -l finds.
--sysroot affects each mechanism differently, as the last column shows, so a
fix has to start from the right question:
| Question | Answered by | Sysroot-aware? |
|---|---|---|
Should -lstdc++ be on the link line? | the g++ driver (Chapter 1.11) | no, pure option rewriting |
Where does #include <vector> come from? | GCC's compiled-in include table | only if configured for it |
Which libstdc++.so does that -l find? | the driver's prefix list → -L flags → ld | yes, but the sysroot usually loses |
The third row follows from a rule of Chapter 1.5:
the driver never opens libstdc++.so. It emits one -l and a list of -L
options and lets ld resolve them, so the question of which library is the
question of which directory comes first.
Where a cross install puts libstdc++
A cross build, one whose host and target differ, installs libstdc++ into the
tooldir, the target's own subtree of the install, and not into the sysroot or
$prefix/lib. The driver must later search the same places, so these two
install paths are the reference for every search question about libstdc++:
| Artefact | Install location |
|---|---|
| Headers | $prefix/$target_alias/include/c++/$version |
libstdc++.{a,so} | $exec_prefix/$target_alias/lib[/$multi_os_dir] |
The install manual gives the library directory under Configuration,
as the default of --with-toolexeclibdir: ${gcc_tooldir}/lib. For the headers it
says only that the default "differs between cross and native configurations".
Both paths come from one autoconf macro, GLIBCXX_EXPORT_INSTALL_INFO
(libstdc++-v3/acinclude.m4:729). The file changes between
point releases and in vendor forks, so read it at the releases/gcc-15.2.0 tag
when you follow these line numbers. The macro computes the header directory
first. In the default case, where $version_specific_libs and $gxx_include_dir
are both no, it puts include/c++/${gcc_version} under
${prefix}/${target_alias} when $with_cross_host is set to something other
than no, and under ${prefix} otherwise:
# Default case for install directory for include files.
if test $version_specific_libs = no && test $gxx_include_dir = no; then
gxx_include_dir='include/c++/${gcc_version}'
if test -n "$with_cross_host" &&
test x"$with_cross_host" != x"no"; then
gxx_include_dir='${prefix}/${target_alias}/'"$gxx_include_dir"
else
gxx_include_dir='${prefix}/'"$gxx_include_dir"
fi
fi
Listing 1.12-1: the header install directory
(libstdc++-v3/acinclude.m4:760-769).
The library directory follows. Its comment states the policy, and the formula
puts the tooldir under ${exec_prefix}:
# Calculate glibcxx_toolexecdir, glibcxx_toolexeclibdir
# Install a library built with a cross compiler in tooldir, not libdir.
if test x"$glibcxx_toolexecdir" = x"no"; then
if test -n "$with_cross_host" &&
test x"$with_cross_host" != x"no"; then
glibcxx_toolexecdir='${exec_prefix}/${host_alias}'
case ${with_toolexeclibdir} in
no)
glibcxx_toolexeclibdir='${toolexecdir}/lib'
;;
Listing 1.12-2: the library install directory
(libstdc++-v3/acinclude.m4:784-793).
$exec_prefix and ${host_alias} in the libstdc++ install paths
The libstdc++ install paths use two variables that are easy to misread:
$exec_prefix, which can differ from $prefix, and ${host_alias}, which in a
target library names GCC's target. Both decide where the files land, and a
misreading of either shows only after a build has gone wrong.
$prefix and $exec_prefix are different variables that default to the same
value, which is why the difference goes unnoticed. Listing 1.12-1 builds the
header path from ${prefix}, and Listing 1.12-2 builds the library path from
${exec_prefix}. If you pass --exec-prefix, your C++ headers and your C++
library land in different trees from one configure run, with no warning. The
install manual documents both options under Configuration,
where --exec-prefix is the root for architecture-dependent files.
${host_alias} in a target library means GCC's target. Target libraries are
configured with --host=<target triple>, because from libstdc++'s point of view
the machine it will run on is GCC's target. ${exec_prefix}/${host_alias} in
Listing 1.12-2 is therefore $exec_prefix/<target>, the tooldir, and libgcc
uses the same convention with real_host_noncanonical. Whenever a path formula
inside a target library says "host", read "GCC's target": the three machines of
Chapter 1.2, seen from the other end.
gcc_gxx_include_dir: the driver's copy of the C++ header path
The driver must search where the install rules put libstdc++, so
gcc/configure.ac computes the header path a second time, as
gcc_gxx_include_dir. For the library it computes no path, and adds the
tooldir's lib/ directory to its search list instead. The comment at the top of
Listing 1.12-3 states the rule that the two copies follow:
# This logic must match libstdc++-v3/acinclude.m4:GLIBCXX_EXPORT_INSTALL_INFO.
if test x${gcc_gxx_include_dir} = x; then
if test x${enable_version_specific_runtime_libs} = xyes; then
gcc_gxx_include_dir='${libsubdir}/include/c++'
else
libstdcxx_incdir='include/c++/$(version)'
if test x$host != x$target; then
libstdcxx_incdir="$target_alias/$libstdcxx_incdir"
fi
gcc_gxx_include_dir="\$(libsubdir)/\$(libsubdir_to_prefix)$libstdcxx_incdir"
fi
Listing 1.12-3: the driver's half (gcc/configure.ac:213-223).
The duplication spans three files, not two. libstdc++'s copy of the comment
names a third, config/gxx-include-dir.m4, that must be kept consistent too
(acinclude.m4:727-728). A change to one of the three needs
the same change in the other two, or the headers install where the driver will
not look.
The library half is one call, on startfile_prefixes, the driver's library
search list:
add_prefix (&startfile_prefixes,
concat (tooldir_prefix, "lib", dir_separator_str, NULL),
"BINUTILS", PREFIX_PRIORITY_LAST, 0, 1);
Listing 1.12-4: the tooldir on the library search list (gcc/gcc.cc:5537-5539).
Listing 1.12-4 calls add_prefix, not add_sysrooted_prefix, and that one call
is why --sysroot does not move your C++ library. Listing 1.5-9 in
Chapter 1.5 registers /lib/ and /usr/lib/
through add_sysrooted_prefix, which prepends target_system_root to each
prefix (gcc/gcc.cc:3177-3205). add_prefix prepends nothing.
--sysroot and the C++ headers: the per-entry add_sysroot flag
The C++ headers follow --sysroot only if configure set the add_sysroot flag
on their entry in the compiled-in include table, cpp_include_defaults.
Configure sets the flag only for a --with-gxx-include-dir path inside the
--with-sysroot path, and that is the one configure-time route to
sysroot-relative headers. Each entry carries its own flag, so the setting is per
directory, not global:
const char add_sysroot; /* FNAME should be prefixed by
cpp_SYSROOT. */
Listing 1.12-5: the per-entry sysroot flag (gcc/cppdefault.h:48-49).
For the C++ directories, the field's value is a configure-time macro,
GPLUSPLUS_INCLUDE_DIR_ADD_SYSROOT:
#ifdef GPLUSPLUS_INCLUDE_DIR
/* Pick up GNU C++ generic include files. */
{ GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1,
GPLUSPLUS_INCLUDE_DIR_ADD_SYSROOT, 0 },
#endif
Listing 1.12-6: the C++ header entry (gcc/cppdefault.cc:43-47).
Because the decision is in the table, per entry, no command-line flag can change
it after the fact. --sysroot supplies the string, and whether a given directory
uses it was decided when GCC was configured. The macro's value comes from
gcc_gxx_include_dir_add_sysroot, which starts at zero
(gcc/configure.ac:211) and is set to 1 in exactly one place:
elif test "${with_sysroot+set}" = set; then
gcc_gxx_without_sysroot=`expr "${gcc_gxx_include_dir}" : "${with_sysroot}"'\(.*\)'`
if test "${gcc_gxx_without_sysroot}"; then
gcc_gxx_include_dir="${gcc_gxx_without_sysroot}"
gcc_gxx_include_dir_add_sysroot=1
fi
fi
Listing 1.12-7: the one place that sets the flag (gcc/configure.ac:224-230).
The elif is the else-branch of if test x${gcc_gxx_include_dir} = x in
Listing 1.12-3, so it runs only when you passed --with-gxx-include-dir.
Without that option the default branch runs, the path is prefix-relative, and the
flag stays 0. With it, configure factors the sysroot out only if your path
starts with the text of --with-sysroot's value, because the expr is a string
match, not a path comparison. The two conditions give four configurations:
| Configuration | include/c++/15 resolves to | Follows --sysroot? |
|---|---|---|
plain cross, no --with-gxx-include-dir | $prefix/$target/include/c++/$ver, relocatable | no |
--with-sysroot=S only | same as above | no |
--with-sysroot=S --with-gxx-include-dir=S/usr/include/c++/15 | <sysroot>/usr/include/c++/15 | yes |
--with-gxx-include-dir=/opt/foo, no overlap with the sysroot | /opt/foo, absolute | no |
Only the third row gives the sysroot-native layout, and it needs both options, with one path textually inside the other. The default gives relocatability instead, which is usually worth more.
The default include/c++: relocated with the installed prefix
The default include/c++ directories are relocated with the compiler rather
than sysrooted, which is why --sysroot cannot move them. When the compiler has
been relocated, add_standard_paths rewrites a standard directory that is not
sysrooted and starts with the configure-time prefix, so that it starts at the
run-time prefix instead. The comment in Listing 1.12-8 names that prefix:
else if (!p->add_sysroot && relocated
&& !filename_ncmp (p->fname, cpp_PREFIX, cpp_PREFIX_len))
{
static const char *relocated_prefix;
char *ostr;
/* If this path starts with the configure-time prefix,
but the compiler has been relocated, replace it
with the run-time prefix. The run-time exec prefix
is GCC_EXEC_PREFIX. Compute the path from there back
to the toplevel prefix. */
Listing 1.12-8: the relocation branch (gcc/incpath.cc:192-201).
A default cross build takes this branch, so if you move the installed toolchain,
the C++ headers follow it. The path is recomputed from GCC_EXEC_PREFIX
(Chapter 1.9) rather than stored as an absolute
string. The sysroot branch and this one exclude each other by construction, so
GCC's own header directories are relative to a prefix discovered at run time,
never to the sysroot.
-B cannot move the C++ headers either, which is why the -B of the opening
example changed nothing. -B feeds include_prefixes, and %I turns that list
into -isystem <B>/<target>/<version>/include and .../include-fixed, GCC's own
header directories from Chapter 1.8. The C++
directories are not in that set, so -B changes which <stdint.h> you get but
not which <vector>. The GCC manual documents the translation into -isystem in
its -B item, under Directory Options.
-nostdinc++ and -isystem =: sysroot-relative C++ headers
-nostdinc++ and an =-prefixed -isystem replace the C++ headers of one
compilation with sysroot-relative ones, whatever GCC's configuration. You can
therefore test a sysroot-resident header set against a compiler that was not
configured for one. -nostdinc++ drops the compiled-in C++ directories, and a
leading = or $SYSROOT on any -I, -isystem or -idirafter path expands to
the sysroot.
The GCC manual documents the = rule and -nostdinc++ under
Directory Options.
add_sysroot_to_chain applies the = and $SYSROOT rule to the include chains:
if (p->user_supplied_p)
{
if (p->name[0] == '=')
p->name = concat (sysroot, p->name + 1, NULL);
if (startswith (p->name, "$SYSROOT"))
p->name = concat (sysroot, p->name + strlen ("$SYSROOT"), NULL);
}
Listing 1.12-9: the = rewrite (gcc/incpath.cc:333-339),
applied to the quote, bracket, system, after and #embed chains at
:356-364.
The user_supplied_p test limits the rewrite to paths you passed on the command
line, so it never touches the compiled-in table. To check the C++ headers in a
sysroot against such a compiler, drop the compiled-in C++ directories and name
the sysroot's own:
$ arm-linux-gnueabihf-g++ --sysroot=/arm-rootfs \
-nostdinc++ -isystem =/usr/include/c++/15 -E -v -x c++ /dev/null
Listing 1.12-10: -nostdinc++ drops the compiled-in C++ directories (Chapter 1.10),
= supplies sysroot-relative ones.
The -v output then lists /arm-rootfs/usr/include/c++/15 among the search
directories and none of the compiled-in C++ directories, because -nostdinc++
removed those and Listing 1.12-9 expanded the =. The command names one
directory, so any other C++ header directory that your rootfs needs, such as a
separate per-target one, gets its own -isystem = option.
--sysroot and libstdc++.so: searched, but the tooldir copy wins
--sysroot adds the sysroot to the link-time search for libstdc++.so, through
two mechanisms, but the copy in the tooldir usually wins. The tooldir
prefix of Listing 1.12-4 is not sysrooted, and it holds the file that GCC
installed. A libstdc++.so in the target's root filesystem therefore rarely
decides which library a cross link uses.
Sysrooted startfile prefixes. The driver registers /lib/ and /usr/lib/
(gcc/gcc.cc:1613-1618) through add_sysrooted_prefix
(:8621-8630), which prepends target_system_root.
The linker is told. If ld supports it, the driver prepends
%(sysroot_spec), which is --sysroot=%R
(gcc/gcc.cc:1189-1191), to the whole link spec
(:8554-8564). ld's own built-in search directories and any
=-prefixed path in a linker script then become sysroot-relative too.
A sysroot copy wins only if one is there and it sorts before the tooldir entry, which the order of Chapter 1.5 does not do by default. Arranging that is usually the wrong move, because it leaves two candidates and a search-order question to answer.
The sysrooted prefixes sit behind a gate: a cross compiler configured with no
sysroot gets no /lib or /usr/lib prefixes at all. Listing 1.5-8 in Chapter 1.5 is
the gate, and that chapter explains why the gate is correct. Ports that define
STARTFILE_PREFIX_SPEC take the earlier branch instead
(gcc.cc:8579-8587), and that branch wins outright over the /lib/ and
/usr/lib/ chain.
Configure flags that move libstdc++: --with-gxx-include-dir and others
Four configure flags move the C++ library or its headers, and each must be honoured twice: by
libstdc++'s install rules and by the driver's compiled-in defaults.
--with-toolexeclibdir shows what happens when only the install rules honour a
flag. The install manual documents --with-gxx-include-dir and
--enable-version-specific-runtime-libs on the same
Configuration page as --with-toolexeclibdir, but not the
"Follows --sysroot?" column:
| Flag | Moves | Default | Follows --sysroot? |
|---|---|---|---|
--with-gxx-include-dir=DIR | libstdc++ headers | $prefix/$target_alias/include/c++/$ver | only via Listing 1.12-7 |
--with-gxx-libcxx-include-dir=DIR | libc++ headers, and gates -stdlib= | $prefix/$target_alias/include/c++/v1 | same mechanism |
--enable-version-specific-runtime-libs | headers and libraries into libsubdir | off | never |
--with-toolexeclibdir=DIR | where cross-built libraries install | $tooldir/lib | never |
--with-gxx-libcxx-include-dir. Besides naming the libc++ header directory,
the flag decides whether -stdlib= exists at all: =no disables the option, a
path enables it, and leaving it unset enables it only on recent Darwin
(gcc/configure.ac:255-274). If -stdlib=libc++ is rejected
as an unknown option, this flag is the reason, and the -lc++ and -lc++abi
emission of Chapter 1.11 is unreachable without
it. The libc++ header entry is a separate row in the same include table,
distinguished by cplusplus == 2 (cppdefault.cc:58-62)
and selected by flag_stdlib_kind at incpath.cc:176-177.
--enable-version-specific-runtime-libs. The flag moves both halves out of
the tooldir into GCC's versioned directory: headers to ${libsubdir}/include/c++
and libraries to ${libdir}/gcc/${host_alias}/${gcc_version}$(MULTISUBDIR)
(acinclude.m4:771-782). It applies only if you did not pass
--with-gxx-include-dir, as the && in Listing 1.12-1 shows. A version-specific
layout can never be sysroot-relative either, because Listing 1.12-7 is in the
branch it does not take.
--with-toolexeclibdir. The flag moves the install but not the search, so it
can produce a working build and a broken compiler. libstdc++'s configure consumes
it (acinclude.m4:790-797), and the library installs
where you said. Listing 1.12-4, however, builds the driver's prefix from
tooldir_prefix and the target triple, and this flag does not parameterise it.
If you point the flag somewhere unusual, the build installs libstdc++.so there
and g++ then fails to find it, unless you also supply -L or -B.
Checking libstdc++ and <vector> with -print-file-name and -v
-print-file-name=libstdc++.so and -v -E answer the two questions about the
C++ runtime on an installed toolchain: which file the -l resolves to, and
which C++ header directories the compiler searches. Listing 1.12-11 puts them in
a sequence with four other queries, to run when a link picks up the wrong C++
runtime:
$ arm-linux-gnueabihf-g++ -print-sysroot # empty means: none configured
$ arm-linux-gnueabihf-g++ -print-search-dirs # raw prefix lists, pre-expansion
$ arm-linux-gnueabihf-g++ -print-file-name=libstdc++.so # which file the -l resolves to
$ arm-linux-gnueabihf-g++ -print-file-name=libstdc++.a # ditto for -static-libstdc++
$ arm-linux-gnueabihf-g++ -mcpu=cortex-a9 -print-multi-os-directory
$ arm-linux-gnueabihf-g++ -v -E -x c++ /dev/null # the C++ header search list
Listing 1.12-11: the six questions, in the order you should ask them.
The GCC manual documents the -print-* options under
Developer Options, down to the empty answer from
-print-sysroot when no sysroot is configured. -print-file-name echoes its
argument back unchanged when the file was not found
(Chapter 1.5), so libstdc++.so coming back
verbatim means "not found", not "found in the current directory".
In the output of -v -E, check whether the include/c++/… lines begin with your
sysroot path. If they do, GCC was configured with a
--with-gxx-include-dir inside --with-sysroot. If they do not, no --sysroot
value will move them.
-print-search-dirs prints prefixes before multilib expansion, so its output is
not the set of directories that a given -mcpu searches. The four-way expansion
of Chapter 1.6 happens later, inside for_each_path
(gcc/gcc.cc:2778), with the variant that set_multilib_dir
chose (:9764). -print-file-name performs the whole search,
so its answer is the one to trust.
Three things to carry away
Neither half of libstdc++ is in the sysroot, by design. The headers and the library are found relative to the compiler's install.
--sysroot moves the C++ headers only if configure decided so. That needs
--with-gxx-include-dir with a path that starts with the --with-sysroot value.
The sysroot's libstdc++.so usually loses. The copy GCC installed sits in the
tooldir, which is not sysrooted and is searched before the sysroot's directories.
Things that surprise people
$prefix/$target/lib is not sysrooted, is where a cross libstdc++ lives, and
is searched regardless of --sysroot.
-B does not move C++ header search. It moves GCC's own headers, which is
enough to change <stdint.h> and not <vector>.
A cross ignores LIBRARY_PATH. The guard is *cross_compile == '0'
(Chapter 1.9). Do not debug a cross with it.
A successful link says nothing about whether the program runs. Link-time
search and run-time search are unrelated systems. -L and the prefix lists
resolve the -l, while DT_NEEDED, DT_RUNPATH, ld.so.conf and
LD_LIBRARY_PATH decide whether the target finds libstdc++.so.6 at exec time.
Getting the first right tells you nothing about the second.
Documentation coverage
Three of the four configure flags are on the install manual's
Configuration page (gcc/doc/install.texi), where
--with-toolexeclibdir is at install.texi:2705-2707.
--with-gxx-libcxx-include-dir is in no manual in GCC 15.2.0. The search-path
ordering is in the internals manual's Driver node
(gcc/doc/tm.texi, "Here is the order of prefixes tried for
startfiles").
What is not documented:
--with-gxx-include-dir's interaction with--with-sysroot. The case table of configurations exists only as the shell code in Listing 1.12-7, andconfigure --helpdoes not hint at it.- That the sysroot decision is per include directory, carried in the
add_sysrootfield (Listing 1.12-5) and therefore unchangeable by any flag. The corollary, that GCC's own directories are relocated rather than sysrooted (Listing 1.12-8), is the precise reason--sysrootcannot move them, and the source is the only place that states it. - That
--with-toolexeclibdirmoves the install without moving the search. The option is documented, but the asymmetry is not. - That the path logic is duplicated across three files. Only the in-tree comments say so, and they are the only warning you get.
Next: Chapter 1.13, What -flto does to the link,
what the option adds to the link line and who runs lto1.
1.13 What -flto does to the link
GCC 15.2.0. To run the commands: an installed compiler.
You add -flto to a build, and the link starts to print a warning: "using serial
compilation of 8 LTRANS jobs". The warning comes from a program called
lto-wrapper, and nothing in your makefile runs it. Run the link again with -v
and the collect2 line has more strangers on it: a -plugin option that names a
shared object, and a row of -plugin-opt= options. Then look at a link from a build
that never mentioned -flto. If your GCC's configure found GNU ld 2.21 or newer,
the -plugin option is there too.
-flto acts at both ends of a build. At compile time,
cc1 writes GCC's intermediate representation (IR) into each object. At the
link, the driver puts GCC's linker plugin on the collect2 line, and the plugin,
or collect2 itself when there is no plugin, runs lto-wrapper. lto-wrapper
runs the driver once more, to compile the IR into the objects that the linker
gets in the end. When configure found GNU ld 2.21 or newer, the plugin goes on
every link, because an object with IR and no machine code needs LTO even at a
link that never asked for it.
This chapter assumes Chapter 1.1 for collect2,
lto-wrapper, COLLECT_GCC and the driver's table of compilers, and
Chapter 1.3 for the spec language. It also uses
exec_prefixes from Chapter 1.5,
LINK_COMMAND_SPEC and the order of the link line from
Chapter 1.7, and the COLLECT_* family from
Chapter 1.9.
The driver's side of LTO ends at two interfaces. How a linker loads a plugin and
calls it is the binutils plugin API, which binutils owns, and GCC's plugin uses
two of its hooks. Inside the link, lto1 runs a WPA step, which splits the IR
into partitions, and LTRANS steps, which compile one partition each. What lto1
does in those steps is GCC's own subject, and the internals manual describes
lto1 in its LTO chapter.
.gnu.lto_ sections: the IR in slim and fat objects
-flto makes cc1 write the IR into the object file, in sections whose names
start with .gnu.lto_. The GCC manual documents the IR in the object under
Optimize Options. These sections are what the plugin and
collect2 look for at the link, and whether the object also holds machine code
decides which links can use it. The prefix is a macro, and its comment says how
the rest of each name is built:
/* The string that is the prefix on the section names we make for lto.
For decls the DECL_ASSEMBLER_NAME is appended to make the section
name for the functions and static_initializers. For other types of
sections a '.' and the section type are appended. */
#define LTO_SECTION_NAME_PREFIX ".gnu.lto_"
Listing 1.13-1: the IR section prefix
(gcc/lto-section-names.h:23-27).
One of those sections, .gnu.lto_.opts, holds the options that compiled the
object, and lto-wrapper reads them back at link time. The writer quotes them in
the same format as COLLECT_GCC_OPTIONS
(gcc/lto-opts.cc:34-36, :57-69).
A fat object holds the IR and ordinary machine code, so any link can use it. A
slim object holds the IR and no machine code, so only an LTO link can use it.
The -ffat-lto-objects item in Optimize Options documents
both kinds, and a slim default "on targets with linker plugin support".
-ffat-lto-objects has no Init in gcc/common.opt:1718-1720, so it
starts off and slim is the default. The option code turns it on in one case:
if (!opts->x_flag_fat_lto_objects
&& (!HAVE_LTO_PLUGIN
|| (opts_set->x_flag_use_linker_plugin
&& !opts->x_flag_use_linker_plugin)))
{
if (opts_set->x_flag_fat_lto_objects)
error_at (loc, "%<-fno-fat-lto-objects%> are supported only with "
"linker plugin");
opts->x_flag_fat_lto_objects = 1;
}
Listing 1.13-2: the fallback to fat objects
(gcc/opts.cc:1225-1234).
HAVE_LTO_PLUGIN is a configure-time value that says whether the linker can load
GCC's plugin, and it also selects what the driver adds to the link line. A slim
object is the default whenever the linker can load the plugin, unless you pass
-fno-use-linker-plugin, and fat objects are the fallback for a linker that
cannot.
Before GCC 4.9. Objects are fat by default.
-ffat-lto-objectsisInit(1)atreleases/gcc-4.8.0(gcc/common.opt:1121-1123), and has noInitatreleases/gcc-4.9.0(gcc/common.opt:1162-1164).
A slim object also gets one ordinary symbol, __gnu_lto_slim. The comment above
the code that emits it says what the symbol is for:
/* Let linker plugin know that this is a slim object and must be LTOed
even when user did not ask for it. */
if (flag_generate_lto && !flag_fat_lto_objects)
{
#if defined ASM_OUTPUT_ALIGNED_DECL_COMMON
ASM_OUTPUT_ALIGNED_DECL_COMMON (asm_out_file, NULL_TREE, "__gnu_lto_slim",
HOST_WIDE_INT_1U, 8);
Listing 1.13-3: the slim marker (gcc/toplev.cc:546-561).
Abridged. Two other branches emit the same symbol for other targets.
"Even when user did not ask for it" is the reason the driver puts the plugin on
links with no -flto. A slim object can arrive in a library that somebody else
built, at a link with no -flto on it. That link must still optimise the
object, because the object has no other code. readelf shows the IR sections
and the marker in an object of your own:
$ gcc -flto -c foo.c bar.c
$ readelf -S foo.o | grep '\.gnu\.lto_' # the IR sections
$ readelf -s foo.o | grep __gnu_lto_slim # only in a slim object
LINK_PLUGIN_SPEC and HAVE_LTO_PLUGIN: when the driver adds -plugin
The driver adds -plugin to the link line through LINK_PLUGIN_SPEC, and the
configured value of HAVE_LTO_PLUGIN decides on which links. At level 2, the
value for GNU ld 2.21 or newer, that is every link, with or without -flto,
which explains a -plugin option on a link from a build that never mentioned
LTO. Chapter 1.7 abridged LINK_COMMAND_SPEC
straight after %(linker), and the full template has LINK_PLUGIN_SPEC in that
place:
#define LINK_COMMAND_SPEC "\
%{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S:\
%(linker) " \
LINK_PLUGIN_SPEC \
"%{flto|flto=*:%<fcompare-debug*} \
%{flto} %{fno-lto} %{flto=*} %l " LINK_PIE_SPEC \
Listing 1.13-4: the start of LINK_COMMAND_SPEC, unabridged
(gcc/gcc.cc:1160-1165).
LINK_PLUGIN_SPEC has three definitions, and HAVE_LTO_PLUGIN selects one.
Levels 1 and 2 differ only in PLUGIN_COND and PLUGIN_COND_CLOSE, the
condition that wraps the -plugin options, and level 0 gets a spec that rejects
-fuse-linker-plugin:
#if HAVE_LTO_PLUGIN > 0
/* The linker used has full plugin support, use LTO plugin by default. */
#if HAVE_LTO_PLUGIN == 2
#define PLUGIN_COND "!fno-use-linker-plugin:%{!fno-lto"
#define PLUGIN_COND_CLOSE "}"
#else
...
#define PLUGIN_COND "fuse-linker-plugin"
#define PLUGIN_COND_CLOSE ""
#endif
#define LINK_PLUGIN_SPEC \
"%{" PLUGIN_COND": \
-plugin %(linker_plugin_file) \
-plugin-opt=%(lto_wrapper) \
-plugin-opt=-fresolution=%u.res \
" LTO_PLUGIN_SPEC "\
%{flinker-output=*:-plugin-opt=-linker-output-known} \
%{!nostdlib:%{!nodefaultlibs:%:pass-through-libs(%(link_gcc_c_sequence))}} \
}" PLUGIN_COND_CLOSE
#else
/* The linker used doesn't support -plugin, reject -fuse-linker-plugin. */
#define LINK_PLUGIN_SPEC "%{fuse-linker-plugin:\
%e-fuse-linker-plugin is not supported in this configuration}"
#endif
Listing 1.13-5: LINK_PLUGIN_SPEC (gcc/gcc.cc:1076-1100).
Abridged by one comment.
Configure sets HAVE_LTO_PLUGIN from the linker it found, and only if it built the
plugin (gcc/configure.ac:4327-4382, with the version tests at
:4362-4373). The three values give three
kinds of link line:
HAVE_LTO_PLUGIN | Linker that configure found | -plugin on the link line |
|---|---|---|
| 2 | GNU ld or gold 2.21 or newer, or mold | always, unless -fno-use-linker-plugin or -fno-lto |
| 1 | gold 2.20 | only with -fuse-linker-plugin |
| 0 | any other | never, and -fuse-linker-plugin is an error |
The -fuse-linker-plugin item in Optimize Options documents
the first row as a default: the option is on when GCC "was configured for use
with a linker supporting plugins". The FIXME above PLUGIN_COND records the
history of that default: "For slim LTO we will need to enable plugin
unconditionally" (gcc.cc:1068-1073). The plugin costs little
when no input holds IR, because its all-symbols-read hook returns at once if it
claimed no file (lto-plugin/lto-plugin.c:780-781).
$ gcc -### hello.c 2>&1 | grep -o -- '-plugin [^ ]*'
$ gcc -### hello.c 2>&1 | grep -o -- '-plugin-opt=[^ ]*'
On a level-2 toolchain, the first command prints the plugin's full path, though nothing in the command asks for LTO.
-plugin and -plugin-opt=: the pieces of LINK_PLUGIN_SPEC
The -plugin and -plugin-opt= options on an LTO link's collect2 line come
from LINK_PLUGIN_SPEC. One of its pieces gives the linker the plugin's path.
Three more give the plugin the path of lto-wrapper, a file for the symbol
resolution and a second copy of the default libraries. The search for the
plugin's path also explains the fatal error that a link without -flto can
raise when the plugin is missing.
-plugin %(linker_plugin_file) is the plugin's full path. The driver looks it
up when it is about to run the link. Two parts of the code decide the result: the
find_a_file call on exec_prefixes, and the fatal_error when that call finds
nothing:
#if HAVE_LTO_PLUGIN == 2
if (!switch_matches (fno_use_linker_plugin,
fno_use_linker_plugin
+ strlen (fno_use_linker_plugin), 0))
#else
...
#endif
{
char *temp_spec = find_a_file (&exec_prefixes,
LTOPLUGINSONAME, R_OK,
false);
if (!temp_spec)
fatal_error (input_location,
"%<-fuse-linker-plugin%>, but %s not found",
LTOPLUGINSONAME);
linker_plugin_file_spec = convert_white_space (temp_spec);
}
Listing 1.13-6: finding the plugin (gcc/gcc.cc:9252-9270).
Abridged. Level 1 tests for -fuse-linker-plugin instead.
exec_prefixes is the program list of Chapter 1.5,
the one that finds cc1 and collect2, so -B moves the plugin too. The file
name is liblto_plugin.so unless the host's entry in config.host changes it
(gcc/config.host:77). The plugin installs into the same
libexec/gcc/<target>/<version>/ directory as cc1
(lto-plugin/Makefile.am:8, :17).
-plugin-opt=%(lto_wrapper) is the path of lto-wrapper. The driver finds it
at start-up and exports the same string as COLLECT_LTO_WRAPPER
(gcc.cc:8726-8745). It searches only when it can link, because
-c, -S and -E set have_c (gcc.cc:4995-5005), and have_c
skips the search.
-plugin-opt=-fresolution=%u.res names a temporary file. The plugin writes the
linker's symbol resolution into it before it runs lto-wrapper
(lto-plugin.c:801), and passes the option on with the other
-plugin-opt= values (:1458-1466).
%:pass-through-libs(%(link_gcc_c_sequence)) lists libgcc and the C library a
second time, for the plugin. The spec function's comment gives the purpose:
/* %:pass-through-libs spec function. Finds all -l options and input
file names in the lib spec passed to it, and makes a list of them
prepended with the plugin option to cause them to be passed through
to the final link after all the new object files have been added. */
Listing 1.13-7: the comment on %:pass-through-libs
(gcc/gcc.cc:10827-10830).
The order matters because the linker takes from an archive only what is
undefined when it reads that archive, as Chapter 1.7 showed. The objects that
lto-wrapper makes arrive only after the linker has read -lgcc and -lc.
Each -l in Listing 1.7-7 therefore becomes a -plugin-opt=-pass-through=-l…
option, and the plugin gives those libraries to the linker again after the new
objects (lto-plugin.c:889-904). It skips this step for
gold 1.11 or newer, which does not need it.
The last LTO piece is in LINK_COMMAND_SPEC itself, where %{flto} %{fno-lto} %{flto=*} copy your LTO options onto the linker's command line. The comment
above the template says who has to deal with them: "We pass any -flto flags on
to the linker, which is expected to understand them. In practice, this means it
had better be collect2." (gcc.cc:1156-1157). collect2 reads
them and then removes them, under the comment "Do not pass LTO flag to the
linker." (collect2.cc:1282-1287).
lto-wrapper with and without the linker plugin
lto-wrapper runs after the linker has read the inputs, and one of two programs
starts it, depending on whether -plugin is on the link line. With it, the
linker loads liblto_plugin.so, and the plugin runs lto-wrapper from inside
the link. Without it, collect2 runs lto-wrapper between two links of its own.
The route decides whether IR inside an archive reaches lto1.
liblto_plugin.so: claiming IR files and running lto-wrapper
The linker loads liblto_plugin.so, calls its one exported function, and then
calls the plugin back at two points: for each input file, and once when it has
read every symbol. The plugin claims the inputs that hold IR at the first hook and
runs lto-wrapper at the second. Its header comment gives this contract from
GCC's side:
/* The plugin has only one external function: onload. A linker passes it an array of
function that the plugin uses to communicate back to the linker.
With the functions provided by the linker, the plugin can be notified when
the linker first analyzes a file and pass a symbol table back to the linker. The plugin
is also notified when all symbols have been read and it is time to generate
machine code for the necessary symbols.
Listing 1.13-8: the plugin's two hooks
(lto-plugin/lto-plugin.c:19-25).
In the first hook, the plugin looks in each input for a section whose name starts
with .gnu.lto_.symtab (lto-plugin.c:1097). If it finds one, it
claims the file and gives the linker the symbols from the IR. Archive members are
inputs too, and the plugin records each one as archive@offset
(:1229-1241). The second hook runs lto-wrapper and reads
what it prints:
errmsg = pex_run (pex, 0, new_argv[0], new_argv, NULL, NULL, &t);
check (errmsg == NULL, LDPL_FATAL, "could not run lto-wrapper");
check (t == 0, LDPL_FATAL, "could not run lto-wrapper");
wrapper_output = pex_read_output (pex, 0);
check (wrapper_output, LDPL_FATAL, "could not read lto-wrapper output");
add_output_files (wrapper_output);
t = pex_get_status (pex, 1, &status);
check (t == 1, LDPL_FATAL, "could not get lto-wrapper exit status");
check (WIFEXITED (status) && WEXITSTATUS (status) == 0, LDPL_FATAL,
"lto-wrapper failed");
Listing 1.13-9: the plugin runs lto-wrapper
(lto-plugin/lto-plugin.c:735-747).
new_argv[0] is the first -plugin-opt= value, the lto-wrapper path from
Listing 1.13-5. The other options and the claimed files go into a temporary file,
and lto-wrapper gets that file as one @ argument
(lto-plugin.c:680-700). The plugin reads lto-wrapper's standard
output one line at a time and gives each line to the linker as a new input file
(:629-662). It also tells lto-wrapper what the linker makes, as
-flinker-output=exec, pie, dyn, rel or nolto-rel
(:808-833). Link Options in the GCC manual
documents -flinker-output and these values.
The plugin also reads the environment. It relies on the driver's COLLECT_*
variables from Chapter 1.9, which reach it through collect2 and the linker:
char *collect_gcc_options = getenv ("COLLECT_GCC_OPTIONS");
if (collect_gcc_options)
{
/* Support -fno-use-linker-plugin by failing to load the plugin
for the case where it is auto-loaded by BFD. */
if (strstr (collect_gcc_options, "'-fno-use-linker-plugin'"))
return LDPS_ERR;
Listing 1.13-10: the plugin refuses to load
(lto-plugin/lto-plugin.c:1620-1626).
The comment records a second way in: BFD can load the plugin with no -plugin
option. On that route only the plugin itself can honour
-fno-use-linker-plugin, so it returns LDPS_ERR and refuses to load.
collect2 without -plugin: link, run lto-wrapper, link again
Without -plugin, collect2 does the plugin's job itself, after a first link.
If any object file holds a .gnu.lto_ section, it runs lto-wrapper from
COLLECT_LTO_WRAPPER and links again, with the objects that lto-wrapper
printed in place of the IR objects (collect2.cc:597-638). It reads
object files only, so on this route IR inside an archive never reaches lto1.
collect2 turns its own LTO code off when it sees -plugin on its command line
(collect2.cc:953-958, :1032-1033). The same test
makes it run the linker that configure recorded as the plugin linker, unless a
-fuse-ld= option names another (:783-787,
configure.ac:2787-2794).
A comment in collect2.cc gives the order. By the time collect2 does the
plugin's job, "at least one linker run has been performed without the use of any
LTO info" (collect2.cc:562-563). The test that collects the
IR objects is where archives drop out:
/* LTO objects must be in a known format. This check prevents
us from accepting an archive containing LTO objects, which
gcc cannot currently handle. */
if (which_pass == PASS_LTOINFO)
{
if(is_lto_object_file (prog_name)) {
add_lto_object (<o_objects, prog_name);
}
return;
Listing 1.13-11: no archives on this route
(gcc/collect2.cc:2352-2360).
The comment names the reason: an archive containing LTO objects is something "gcc cannot currently handle". The machine code of a fat archive member links instead of its IR.
lto-wrapper re-runs the driver from COLLECT_GCC
lto-wrapper compiles nothing itself. It runs the driver named in COLLECT_GCC
again, with -xlto -c and the options merged from your objects and your link,
and prints the names of the objects that come out. Because the inner run is an
ordinary driver run, the driver's search lists and specs apply to it as they
apply to any compile.
Its header comment says that it "is passed a gcc, a list of gcc arguments and a
list of object files containing IL". GCC's comments call the IR IL. The same
comment says that it "prints a list of output files on stdout"
(gcc/lto-wrapper.cc:23-26). The gcc and its arguments come from
COLLECT_GCC and COLLECT_GCC_OPTIONS. Listing 1.1-5 showed that lto-wrapper
stops without the first, and it stops without the second too
(lto-wrapper.cc:1449-1452).
lto-wrapper merges options from two sources. COLLECT_GCC_OPTIONS holds the
link command's, and the .gnu.lto_.opts section of each IR object holds that
object's compile command, which find_and_merge_options reads
(lto-wrapper.cc:1155-1168). The manual gives the merge rules for
users, starting with "Generally, options specified at link time override those
specified at compile time" (gcc/doc/invoke.texi:14999-15001).
Then lto-wrapper builds a driver command:
/* Initalize the common arguments for the driver. */
obstack_init (&argv_obstack);
obstack_ptr_grow (&argv_obstack, collect_gcc);
obstack_ptr_grow (&argv_obstack, "-xlto");
obstack_ptr_grow (&argv_obstack, "-c");
append_compiler_options (&argv_obstack, fdecoded_options);
append_linker_options (&argv_obstack, decoded_options);
Listing 1.13-12: the command lto-wrapper runs
(gcc/lto-wrapper.cc:1534-1541).
collect_gcc is the value of COLLECT_GCC, so the command starts with the same
driver you typed. -xlto -c, the merged compile options and your link options
follow, and lto-wrapper runs the result
(lto-wrapper.cc:1930-1931). -xlto selects one more entry in the
driver's table of compilers. Listing 1.1-1 showed the @c entry, and the LTO
front end adds this one:
/* LTO contributions to the "compilers" array in gcc.cc. */
{"@lto", "lto1 %(cc1_options) %i %{!fsyntax-only:%(invoke_as)}",
/*cpp_spec=*/NULL, /*combinable=*/1, /*needs_preprocessing=*/0},
Listing 1.13-13: the @lto entry
(gcc/lto/lang-specs.h:21-24).
The inner run rebuilds its prefix lists from the -B and --sysroot in your
options, as Chapter 1.9 described. It finds lto1 on the program list as it
finds cc1, and runs invoke_as from Listing 1.1-2. The %{!fwpa*: at the top
of invoke_as is for this run: the driver runs no assembler for the WPA step.
-flto= and the make jobserver: how many LTRANS jobs run
lto-wrapper decides how many LTRANS jobs run at once from two inputs: the
-flto= value in the merged options, and whether it finds a make jobserver. A
plain -flto with no jobserver runs them one at a time, and a serial run of more
than one partition prints the "using serial compilation" warning.
lto-wrapper reads -flto= from the merged options, so a value from compile time
counts. A -flto= on the link command wins: "Override IL file settings with a
linker -flto= option." (lto-wrapper.cc:1582-1584). A plain
-flto sets no job count (:1640-1666), and lto-wrapper then
looks for a make jobserver:
else
{
jobserver_info jinfo;
if (jobserver && !jinfo.is_active)
{
/* Fall back to auto parallelism. */
jobserver = 0;
auto_parallel = 1;
}
else if (!jobserver && jinfo.is_active)
{
parallel = 1;
jobserver = 1;
}
}
Listing 1.13-14: the jobserver test
(gcc/lto-wrapper.cc:1692-1706).
The if branch above it handles -flto-partition=none and incremental links,
with one lto1 run and no parallel step
(lto-wrapper.cc:1684-1691). Every other case ends in one cell
of this table:
| Option | make jobserver found | No jobserver |
|---|---|---|
-flto | the jobserver | serial |
-flto=N | the jobserver | N jobs |
-flto=auto | the jobserver | one job for each CPU thread |
-flto=jobserver | the jobserver | as -flto=auto |
The -flto item in Optimize Options documents what -flto=N,
-flto=jobserver and -flto=auto ask for. Three cells of the table are not in
it: the serial plain -flto, the jobserver that wins over N, and the fallback
of -flto=jobserver.
The jobs run through make, and lto-wrapper checks that make --version, or
$MAKE --version, works (lto-wrapper.cc:1386-1402). If it does
not, the jobs run one at a time (:1708-1710). The choice becomes a
-fwpa= option for the inner driver (:1892-1917). When the WPA step
makes more than one partition and parallel is still 0, lto-wrapper warns:
else if (parallel == 0)
{
warning (0, "using serial compilation of %d LTRANS jobs", nr);
print_lto_docs_link ();
}
Listing 1.13-15: the serial-compilation warning
(gcc/lto-wrapper.cc:2030-2034).
The diagnostic carries the name lto-wrapper because the program takes its name
from its own argv[0] (lto-wrapper.cc:2299-2302). The fix is
-flto=auto, or a jobserver.
Before GCC 10. A plain
-fltonever uses the jobserver. The test arrived in GCC 10 (lto-wrapper.c:1476-1480atreleases/gcc-10.1.0), and the same block atreleases/gcc-9.1.0has no such test (lto-wrapper.c:1288-1293).
Before GCC 12. The serial run prints no warning. The warning is present at
releases/gcc-12.1.0(lto-wrapper.cc:1971-1975) and absent atreleases/gcc-11.1.0.
$ gcc -flto=auto -v foo.o bar.o -o prog 2>&1 | grep 'LTO parallelism'
With no jobserver, that prints the thread count lto-wrapper chose
(lto-wrapper.cc:1904-1906).
Why gcc-ar, gcc-nm and gcc-ranlib exist
gcc-ar, gcc-nm and gcc-ranlib run the real ar, nm or ranlib with a
--plugin option that names GCC's plugin. They exist because a slim object has
no machine code and its symbols are in an IR section. A tool that builds an
archive's symbol index, or lists an object's symbols, must read that section.
The internals manual states the requirement: slim objects "require that tools
like ar and nm understand symbol tables of LTO sections"
(gcc/doc/lto.texi:39-44).
What a plain ar or nm does when it cannot read them is binutils' behaviour,
and binutils is the authority on it. On GCC's side, the -ffat-lto-objects item
in Optimize Options names the three wrappers as the way to
pass the right options to these tools. The first line of gcc-ar.cc says what
they are: "Wrapper for ar/ranlib/nm to pass the LTO plugin."
(gcc/gcc-ar.cc:1).
One source file makes all three programs, because the makefile copies gcc-ar.cc
to gcc-nm.cc and gcc-ranlib.cc and compiles each with a different
PERSONALITY (gcc/Makefile.in:2529-2547). Each one finds the
plugin, finds the real tool, and runs the tool with two more arguments at the
front:
nargv = XCNEWVEC (const char *, ac + j + 1); /* +j plugin args +1 for NULL. */
nargv[0] = exe_name;
#if HAVE_LTO_PLUGIN > 0
nargv[1] = "--plugin";
nargv[2] = plugin;
#endif
for (k = 1; k < ac; k++)
nargv[j + k] = av[k];
Listing 1.13-16: gcc-ar adds --plugin
(gcc/gcc-ar.cc:229-236).
j counts the plugin arguments. When HAVE_LTO_PLUGIN is 0, j is 0 and the
wrapper adds nothing (gcc-ar.cc:129-134).
gcc-ar does not use the driver's search lists, and builds its own from its own
location: the target's tool bin directory, then
libexec/gcc/<target>/<version>/, where the plugin is
(gcc-ar.cc:105-119). It looks for the plugin on that list
only (:189-197). For the tool it then tries $PATH, and on a
cross toolchain it looks there for <target>-ar, not ar
(:199-214). A -B option puts a directory in front of both
searches (:149-187).
The same -ffat-lto-objects item in the manual names a second way to get the
same effect (gcc/doc/invoke.texi:15231-15234). It relies on
binutils loading the plugin by itself:
Note that modern binutils provide plugin auto-load mechanism. Installing the linker plugin into
$libdir/bfd-pluginshas the same effect as usage of the command wrappers (gcc-ar,gcc-nmandgcc-ranlib).
Where binutils looks for such plugins, and which versions do it, is binutils' business. Listing 1.13-10 shows that GCC's plugin expects to be loaded that way.
$ ar rcs plain.a foo.o && nm plain.a # depends on what binutils loads
$ gcc-ar rcs lto.a foo.o && gcc-nm lto.a # passes --plugin itself
Checking an LTO link with -v: one command line per layer
On the plugin route, -v makes every layer of an LTO link print a command line,
because each layer finds -v in COLLECT_GCC_OPTIONS. -### is no
substitute, because it runs nothing: it shows the plugin options and nothing
that runs inside the link. The layers print in this order:
- The driver prints the
collect2command line, with the options of Listing 1.13-5. - The plugin prints the
lto-wrappercommand line that it builds (lto-plugin.c:714-719). It becomes verbose when it finds'-v'inCOLLECT_GCC_OPTIONS(:1634-1636). lto-wrapperprints its own command line (lto-wrapper.cc:1670-1679), then the driver command it runs. That second line shows only@and a file name, becauselto-wrapperpasses the arguments in a response file (collect-utils.cc:153-195).- The inner driver prints its
lto1command lines in full. It got-vbecause-vis a driver option (common.opt:3883-3884), andlto-wrapperpasses driver options on (lto-wrapper.cc:829-832).
$ gcc -v -flto foo.o bar.o -o prog 2>&1 | grep -E 'lto-wrapper|lto1'
Three things to carry away
A slim object holds IR and no machine code, and it is the default. Only an LTO link can use it, which is why the plugin has to be on the link line.
The driver puts the plugin on the link line, not your makefile. On a level-2 toolchain it is on every link, and it does nothing when no input holds IR.
lto-wrapper is the driver calling itself. It runs COLLECT_GCC with
-xlto -c and the options from your objects and your link, and the linker gets the
objects it prints.
Things that surprise people
A link without -flto can fail for want of the LTO plugin. On a level-2
toolchain, the driver looks for liblto_plugin.so on every link. If the file is
missing, the driver stops with a fatal error that names -fuse-linker-plugin, an
option you never typed (Listing 1.13-6). -fno-lto removes -plugin from the link
line but does not stop the search. Only -fno-use-linker-plugin does.
A broken LTO setup still links when the objects are fat. The internals manual
says that "any mistake in the toolchain leads to LTO information not being used".
It adds that "the user is not informed that the optimization has been disabled"
(gcc/doc/lto.texi:52-57). If you need to know, check the -v
output for an lto1 line.
Documentation coverage
-flto, -fuse-linker-plugin and -ffat-lto-objects are documented in
Optimize Options (gcc/doc/invoke.texi:12669, items at :14922,
:15197 and :15216), and -flinker-output in Link Options (:19096). The
-ffat-lto-objects item names the three wrappers and bfd-plugins
(:15222-15234). The internals manual has an LTO chapter
(gcc/doc/lto.texi:7).
What is not documented:
- That a level-2 toolchain puts
-pluginon every link, with or without-flto. The-fuse-linker-pluginitem says only that the option "is enabled by default" with a plugin-capable linker (invoke.texi:15211-15213). - That a missing plugin fails a link that never asked for LTO, and that
-fno-ltodoes not prevent the failure. - The
-plugin-opt=-pass-through=copies of libgcc and the C library. - That
lto-wrapperruns the driver again with-xlto -c. - That a plain
-fltowith nomakejobserver runs serially. The manual says only that GCC "tries to automatically detect a running GNU make's job server" (invoke.texi:15144-15145). - That
gcc-arsearches its own prefixes, not the driver's program list.
The internals manual also disagrees with the source in two places:
- It says that GCC "does not use the linker plugin by default", and that
collect2examines the objects (lto.texi:539-545). In GCC 15.2.0, that is the route forHAVE_LTO_PLUGIN0 or 1 only. It also says thatcollect2"invokeslto1" (lto.texi:84-87). Two programs sit between them,lto-wrapperand the driver. - It says that objects are fat by default "if no plugin support is detected for
arandnmwhen GCC is configured" (lto.texi:46-48). The code testsHAVE_LTO_PLUGIN(Listing 1.13-2), which configure derives from the linker alone (configure.ac:4362-4373).
Next: Chapter 1.14, -print-*, -v and -dumpspecs: asking a built
compiler, every question in this part as one
procedure.
1.14 -print-*, -v and -dumpspecs: asking a built compiler
GCC 15.2.0. To run the commands: an installed compiler, plus a working one to diff it against.
Something is wrong with a build. A header resolves to the wrong file, a -l
picks up a library from a directory you have never heard of, or a flag you passed
appears to do nothing. The temptation is to read the documentation and reason
about what should happen.
Ask the compiler instead, because a built compiler reports what it did. Each chapter of Part I showed the commands that observe its own mechanism. This chapter collects them in the order that finds a fault fastest, for when you do not yet know which mechanism is at fault. Each check links to the chapter that explains what it shows, so you can start here and read only the chapter that your fault leads to.
-print-* options: which one answers which question
The table pairs each question about the driver's decisions with the command that
answers it, a -print-* option or one of a few others such as -###, -v and
-dumpspecs. Its last column names the chapter that shows what the source does
behind each answer. Use the table when the fault already points at one decision,
and the seven checks from -### to -dumpspecs when it does not. The GCC manual
documents every option in it: -### and -v under
Overall Options, -dM under
Preprocessor Options, and the rest under
Developer Options.
| You want to know | Command | Explained in |
|---|---|---|
| What commands would this run? | gcc -### foo.c | Chapter 1.1 |
Which file would -lfoo or crt1.o resolve to? | gcc -print-file-name=libfoo.a | Chapter 1.5 |
| Where does it look for programs and libraries? | gcc -print-search-dirs | Chapter 1.5 |
| Where does it look for headers? | gcc -v -E - < /dev/null | Chapter 1.8 |
| Is the environment moving a list? | env -u GCC_EXEC_PREFIX … gcc -print-search-dirs | Chapter 1.9 |
| Is a sysroot in play? | gcc -print-sysroot | this chapter |
| What was this compiler configured with? | gcc -v | this chapter |
| Which target is this? | gcc -dumpmachine | Chapter 1.2 |
Which ABI variant do these -m flags select? | gcc -m32 -print-multi-directory | Chapter 1.6 |
| Which variants exist at all? | gcc -print-multi-lib | Chapter 1.6 |
| What are the driver's command-line templates? | gcc -dumpspecs | Chapter 1.3 |
| Every predefined macro? | gcc -dM -E - < /dev/null | Chapter 2.6 |
From -### to -dumpspecs: seven checks, one mechanism each
The checks run from gcc -###, which shows whether a flag reaches the right
program, to gcc -dumpspecs, which shows the templates behind each command line,
and then repeat for C++. Each check rules out one mechanism at the cost of one
command, so run them in order when you do not know where the fault is.
-
Does the flag arrive? Run
gcc -### foo.cand read the line for the program that should get the flag:collect2for the link,cc1for the compiler. A flag that is missing there was removed by a spec or never recognised. See Chapter 1.1. -
Which file wins? Run
gcc -print-file-name=NAMEfor each library and startup file in doubt. An answer that is only the bare name means not found, and the owner of that file is the suspect: the sysroot forcrt1.o, the prefix or-Bforcrtbegin.o. See Chapter 1.5. -
Is it the right variant? Run
gcc -print-multi-directorywith your-mflags, then check that-print-multi-liblists that variant. A missing variant links against the default one, with no error. See Chapter 1.6. -
Is the environment involved? Diff
-print-search-dirswith and withoutGCC_EXEC_PREFIX,COMPILER_PATHandLIBRARY_PATH. See Chapter 1.9. -
Is it a header?
gcc -v -Eprints the header search list, andgcc -H -Eprints the chain of#include_nexthops. See Chapter 1.8. -
Is it a spec? Run
gcc -dumpspecs, and look for a strayspecsfile.--with-specsnever shows in-dumpspecs, so read the configure line fromgcc -vtoo. See Chapter 1.3. -
Is it C++? Ask the flag, file and header questions again, for
-lstdc++on the link line,-print-file-name=libstdc++.so, andg++ -v -E -x c++ /dev/null. See Chapter 1.11 and Chapter 1.12.
maybe_print_and_exit: two -print-* options, one answer
Every -print-* option is handled in one function,
driver::maybe_print_and_exit, which prints an answer and returns before any
compiling starts. A command that asks two of these questions at once therefore
gets one answer, so ask each in its own command.
driver::maybe_print_and_exit () const
{
if (print_search_dirs)
...
if (print_file_name)
...
Listing 1.14-1: driver::maybe_print_and_exit
(gcc/gcc.cc:8793-8959, abridged), called from
gcc.cc:8301.
The function checks its flags in a fixed order, so the one answer comes from the option it checks first, whatever the order on your command line (Listing 1.14-1). Because every one of these options ends in this function, half of them carry the same "and don't do anything else" wording in the manual.
-print-sysroot: empty output means no sysroot
Empty output from gcc -print-sysroot means that no sysroot was configured, and
that is an answer, not a failure. For a cross compiler, the missing sysroot has a
further consequence: such a compiler gets no /lib or /usr/lib search entries
at all. Chapter 1.5 shows the single line of code
that decides this, and explains why it is correct rather than unhelpful.
$ gcc -print-sysroot
The GCC manual documents the empty answer under
Developer Options, and warns that the printed path comes
"possibly with an extra suffix that depends on compilation options".
maybe_print_and_exit prints target_system_root, with target_sysroot_suffix
appended whenever a suffix is set:
if (print_sysroot)
{
if (target_system_root)
{
if (target_sysroot_suffix)
printf ("%s%s\n", target_system_root, target_sysroot_suffix);
else
printf ("%s\n", target_system_root);
}
Listing 1.14-2: -print-sysroot (gcc/gcc.cc:8876-8886).
On targets that define SYSROOT_SUFFIX_SPEC, of which MIPS is the canonical
case, the answer changes with -EL or -msoft-float, so do not cache it in a
build script. Chapter 1.6 explains the mechanism.
gcc -v: the configure line a compiler was built with
With no source file, gcc -v prints the version, the thread model and the
complete configure line that the compiler was built with. Read that line when a
check traces a fault to a decision made at configure time, such as the sysroot or
the multilib set. The line is a string constant in a generated header, fixed at
build time (gcc/gcc.cc:225), and the driver prints it as stored
(:7710).
Configuring again in the same build tree appends : (reconfigured) and the new
arguments to the old line (gcc/configure.ac:2222-2231). In
either form, look in the line for the options that explain what the other checks
found:
--with-sysroot, explained in Chapter 1.5--with-specs, explained in Chapter 1.3--enable-languages, and any--with-archor--with-cpudefaults--disable-multilib, which explains a suspiciously short-print-multi-lib
Diffing -### output against a working toolchain
When one toolchain works and another does not, diff their -### output rather
than reading either one. -### suits this, because it prints each command line,
quoted, and runs nothing. It is therefore safe on a broken toolchain, and its
output diffs cleanly against a working one. With a source file, -v prints the
same command lines as it runs them, plus every COLLECT_* variable the driver
exports.
$ gcc -v hello.c # run everything, printing each command line
$ gcc -### hello.c # print the command lines, quoted, run nothing
-### writes to standard error, so a pipe needs 2>&1. Piped through grep,
or run with the flag under test, it answers narrower questions:
$ gcc -### hello.c 2>&1 | grep collect2 # just the link line
$ gcc -### -nostdlib hello.c # confirm what a flag removed
$ gcc -specs=my.specs -### hello.c # confirm what an override did
To compare two toolchains, run the same command with each driver and give both
outputs to diff, because the lines that differ hold the fault:
$ diff <(/opt/good/bin/gcc -### hello.c 2>&1) <(/opt/bad/bin/gcc -### hello.c 2>&1)
Three things to carry away
A built compiler answers from the same lists the real run uses. Every
-print-* option answers and exits before any compiling starts.
A bare name back means not found. -print-file-name echoes its argument when
the search fails, and the owner of that file is the suspect.
Diff -###, do not read it. Against a toolchain that works, the difference is
the fault.
Documentation coverage
The GCC manual documents these options well. -### and -v are in
Overall Options (gcc/doc/invoke.texi:1549), the -print-*
family is in Developer Options (:20326), and -B,
--sysroot and the search options are in Directory Options
(:19484).
What is not documented:
- That two
-print-*options in one command give one answer, chosen by the order of the checks in Listing 1.14-1. - The gaps for each option, which the chapter that explains it lists:
Chapter 1.3 for
-dumpspecs, and Chapter 1.5 for-print-file-nameand-print-search-dirs.
Next: Chapter 2.1, How config.gcc picks your part of a GCC
checkout, the first chapter of Part II, where
configure and make take the decisions that Part I observed.
2.1 How config.gcc picks your part of a GCC checkout
GCC 15.2.0. To run the commands: a GCC checkout, and an arm-none-eabi-gcc cross compiler.
You clone GCC to read the backend of your x86-64 compiler, and there is no
gcc/config/x86_64/. You look for the rule that builds __aeabi_uldivmod for
your arm-none-eabi toolchain, and gcc/config/arm/t-bpabi is one line about a
header. The checkout has 38 top-level directories, 1,051 files directly in
gcc/ and 52 directories in gcc/config/, and most of them do not apply to the
compiler you build (top level, gcc/,
gcc/config/).
One shell script, gcc/config.gcc, turns --target= into the list of backend
files, headers, macros and makefile fragments that your compiler is built from.
The tree is arranged so that this script, and its twin libgcc/config.host, can
make that choice. Read with the two scripts in mind, the layout is not
arbitrary.
This chapter assumes Chapter 1.2, for build, host
and target, and for the split between host code and target code, and
Chapter 1.3, for the spec language. It also uses -### and
-v from Chapter 1.1, the multilib fragments of
Chapter 1.6, and the Configured with: line that
Chapter 1.14 reads.
Makefile.def: the top level is a list of modules
The top level of a GCC checkout builds modules, and Makefile.def is the list
of them. The top level is shared with other projects, so the list names many
modules that a GCC checkout does not contain, and the top-level configure
keeps only those whose directory is present. That presence test decides which
top-level directories matter for your build, and which ones you can add.
The internals manual says that the top-level directory "contains several files
and directories that are shared with other software distributions such as that
of GNU Binutils" (sourcebuild.texi:23-26). The more than
forty modules in Makefile.def that a GCC checkout does not contain include
bfd, gas, ld, gdb, gmp and mpfr as host modules, and newlib,
libgloss and winsup as target modules (Makefile.def:36,
:48, :97, :182,
:200-201). libgloss is newlib's companion library of
board-specific startup code and input/output support, which
Chapter 3.4 describes. The loop in the
top-level configure that drops the absent ones tests each directory for a
configure script:
# Quietly strip out all directories which aren't configurable in this tree.
# This relies on all configurable subdirectories being autoconfiscated, which
# is now the case.
...
configdirs_all="$configdirs"
configdirs=
for i in ${configdirs_all} ; do
if test -f ${srcdir}/$i/configure ; then
configdirs="${configdirs} $i"
fi
done
Listing 2.1-1: modules that are not in the tree disappear, abridged
(configure.ac:2755-2773). The same check runs for build and
target modules.
The directory names are the module names, so you add a module to the build by
adding its directory. The install manual relies on this when it tells you to put
bfd, gas and ld, or gmp, mpfr and mpc, next to gcc/ and build them
together, under Downloading GCC (install.texi:698-713). A
checkout with other projects' directories added beside gcc/ is a combined
tree, and Chapter 3.6 uses one to build newlib
inside a GCC build.
Each module in Makefile.def has a kind: build, host or target. Sorted by that
kind, the directories that a GCC checkout does contain, apart from .github and
.forgejo, fall into five groups:
Kind in Makefile.def | Directories in GCC 15.2.0 |
|---|---|
| host | gcc, c++tools, gnattools, gotools, libcc1, libcody, libdecnumber, lto-plugin |
| build and host | fixincludes, libcpp, libiberty |
| host and target | libbacktrace, libgrust, zlib |
| target | libgcc, libstdc++-v3, libatomic, libgomp, libitm, libquadmath, libsanitizer, libssp, libvtv, libada, libgfortran, libgo, libgm2, libgcobol, libobjc, libphobos, libffi |
| none | config, contrib, include, INSTALL, maintainer-scripts |
Sources: the build_modules, host_modules and target_modules entries of
Makefile.def:27-212.
A directory with two kinds is built once for each. zlib, for example, is a
host module that the compiler uses for LTO data
(sourcebuild.texi:152-154, Makefile.def:141)
and also a target module (:204). The last row holds the
shared Autoconf macros and makefile fragments (config/), the libiberty
headers (include/), and scripts. Chapter 2.3
shows the order in which make builds the modules.
The set of directories also changes between releases. Three top-level directories appeared or went between GCC 12 and GCC 15, so a search in a tree of another release can find nothing:
-
GCC 14 removed
intl/. Commitfbe4e643("intl: remove, in favor of out-of-tree gettext") deleted it. It is present atreleases/gcc-13.3.0. -
GCC 13 added
libgm2/. It is absent atreleases/gcc-12.1.0, and present atreleases/gcc-13.1.0with the Modula-2 front end ingcc/m2/. -
GCC 15 added
libgcobol/. It and the COBOL front end ingcc/cobol/are absent atreleases/gcc-14.3.0and present atreleases/gcc-15.1.0.
Why libgcc/ is not inside gcc/: target_subdir
libgcc/ sits beside gcc/, and not inside it, because the two are built for
different machines by different compilers. gcc is a host module and libgcc
is a target module (Makefile.def:49, :183), and
a module's kind decides where it is built and which compiler builds it. A comment
in the shared Autoconf macros gives the rule, one build subdirectory per machine,
with target_subdir for the target modules:
dnl # GCC & friends build 'build', 'host', and 'target' tools. These must
dnl # be separated into three well-known subdirectories of the build directory:
dnl # build_subdir, host_subdir, and target_subdir. The values are determined
dnl # here so that they can (theoretically) be changed in the future. They
dnl # were previously reproduced across many different files.
...
build_subdir="build-${build_noncanonical}"
...
target_subdir=${target_noncanonical}
Listing 2.1-2: one build subdirectory per machine, abridged
(config/acx.m4:66-101).
For an arm-none-eabi cross built on x86-64 Linux, libgcc is therefore
configured and built in arm-none-eabi/libgcc/ under the build directory, the
directory where you run the top-level configure. When the build and host
machines are the same and gcc/ is in the tree, the compiler that builds
libgcc is the one that the gcc module built before it. The top-level
configure sets CC_FOR_TARGET to gcc/xgcc -B$$r/$(HOST_SUBDIR)/gcc/
(configure.ac:4059), and it reports that choice before
anything is built:
$ ../gcc/configure --target=arm-none-eabi 2>&1 | grep 'where to find the target cc'
The line reports that compiler as "just compiled"
(config/acx.m4:562-577). For a Canadian cross the macro
takes a compiler that is already installed instead.
gcc/ is configured once, for the host, and compiled by the host's compiler.
libgcc must be configured for the target and compiled by a compiler that does
not exist until gcc/ is built. A directory inside gcc/ cannot have both
properties. Every other target library in the module table has the same
constraint, so every one is a top-level directory.
The internals manual still lists crtstuff.c and unwind-dw2.c as files
"under the gcc directory" that belong to runtime libraries
(sourcebuild.texi:316-320). In GCC 15.2.0 they are in
libgcc/, and gcc/ has neither (libgcc/crtstuff.c,
libgcc/unwind-dw2.c).
The split still leaves libgcc reading files from the gcc build directory,
such as libgcc.mvars. Its makefile names that directory gcc_objdir
(libgcc/Makefile.in:25, :184). Like the other
target modules, libgcc is configured only after the gcc module is built
(Makefile.in:67908), and
Chapter 2.3 shows where that dependency comes
from.
Inside gcc/: config-lang.in, c-family/ and common/
gcc/ holds the compiler: the driver, the front ends, the middle end and the
backends. Only some of these have a subdirectory, so the layout tells you where
to start a search. The subdirectories fall into three groups: front ends, which
a config-lang.in file marks, code that several programs share, in c-family/
and common/, and everything else.
gcc/ has 24 subdirectories and 1,051 files of its own (tree). The
middle end and the target-independent half of the back end are among the files,
not in a subdirectory. gimplify.cc, passes.cc, cfgexpand.cc, ira.cc and
final.cc sit directly in gcc/, beside the driver's gcc.cc, and Part V
walks through them.
Front ends. A subdirectory of gcc/ is a front end if it contains
config-lang.in. gcc/configure finds them with one glob,
for lang in ${srcdir}/*/config-lang.in
(gcc/configure.ac:7287), sources each file
(:7337), and adds its Make-lang.in to the makefile
(:7358-7363). In GCC 15.2.0, 13 directories qualify: ada, c,
cobol, cp, d, fortran, go, jit, lto, m2, objc, objcp and
rust. Chapter 2.2 covers how
--enable-languages selects among them.
Shared code. c-family/ holds the parts of the C, C++ and Objective-C
front ends that are the same. The makefile calls them "object files
shared by all C-family front ends" (gcc/Makefile.in:1313-1314),
and both cc1 and cc1plus link them (c/Make-lang.in:53-56,
cp/Make-lang.in:93-94). common/ holds code that the driver and the
compilers share. A target that needs a hook in both places puts it in
common/config/<cpu>/ (sourcebuild.texi:201-205), so the ARM
version is gcc/common/config/arm/arm-common.cc, not a file in
gcc/config/arm/.
Everything else. config/ holds the backends. doc/ holds the Texinfo
manuals, ginclude/ the freestanding headers that GCC installs, po/ the
message catalogues, and testsuite/ the compiler's tests
(sourcebuild.texi:207-235). The objects of analyzer/,
rtl-ssa/ and sym-exec/ are part of OBJS, the compiler's own object list
(gcc/Makefile.in:1382-1848). text-art/ goes into libcommon.a,
which is "potentially used by all host binaries"
(:1850-1878).
gcc/config/: one directory per CPU type
gcc/config/ has one subdirectory for each CPU type, and the operating-system
headers that several CPUs share sit at its top level. A triple picks one CPU
directory and some of those shared headers, so this layout is what config.gcc
chooses from. The README in the directory states the rule in five lines:
This directory contains machine-specific files for the GNU C compiler.
It has a subdirectory for each basic CPU type.
The only files in this directory itself
are some .h files that pertain to particular operating systems
and are used for more than one CPU type.
Listing 2.1-3: the layout of gcc/config/ (gcc/config/README:1-5).
The rule holds for 49 of the 52 directories. mingw/, vms/ and vxworks/
are operating-system directories, and the top level of gcc/config/ now has
.cc, .opt and t-* files as well as headers (tree). The
headers there form the operating-system layer, such as elfos.h, linux.h,
newlib-stdint.h and rtems.h.
The directory is named after the CPU type, which is not always the first field
of the triple. That is why there is no gcc/config/x86_64/: x86_64-*-* uses
i386/ (config.gcc:413-414), powerpc*-*-* uses rs6000/
(:524-525), and amdgcn* uses gcn/ (:361-362).
Inside one CPU directory, the file names follow a convention that config.gcc
and gcc/configure rely on. If a file with the expected name exists, it is used
unless the target says otherwise. The table gives the expected names for ARM,
the variable that each one fills, and where its default is set:
File in gcc/config/arm/ | Variable | Where the default comes from |
|---|---|---|
arm.h | tm_file | config.gcc:602 |
arm-protos.h | tm_p_file | config.gcc:603-606, if the file exists |
arm.cc | out_file | gcc/configure.ac:1946-1947 |
arm.md | md_file | gcc/configure.ac:1943-1944 |
arm.opt | extra_options | config.gcc:629-632, if the file exists |
arm-modes.def | extra_modes | config.gcc:624-628, if the file exists |
arm-d.h | tm_d_file | config.gcc:608-612, if the file exists |
t-arm | tmake_file | gcc/configure.ac:1949-1951, unless the target sets it |
The other 131 files in the directory are named explicitly somewhere: headers in
the target's entry, extra .md files in t-arm, built-in tables and scheduling
models (tree).
Before GCC 12. The
out_filedefault was$cpu_type/$cpu_type.c, as atreleases/gcc-11.1.0(gcc/configure.ac:1783). Commit5c69acb3("Rename .c files to .cc files.") renamed the sources, and atreleases/gcc-12.1.0the default is$cpu_type/$cpu_type.cc(gcc/configure.ac:1852). The comment at the top ofconfig.gccstill says.c(config.gcc:96-97).
config.gcc: a shell script that configure sources
config.gcc is a shell fragment that gcc/configure sources, so it runs in
configure's own shell, with configure's variables in scope. It is not a configure
test and not a makefile, and gcc/configure later substitutes the variables it
sets, such as tmake_file and tm_defines, into gcc/Makefile. Listing 2.1-4
shows where it is sourced, after one file for each of the other two machines:
# --------------------------------------------------------
# Build, host, and target specific configuration fragments
# --------------------------------------------------------
# Collect build-machine-specific information.
. ${srcdir}/config.build || exit 1
# Collect host-machine-specific information.
. ${srcdir}/config.host || exit 1
target_gtfiles=
# Collect target-machine-specific information.
. ${srcdir}/config.gcc || exit 1
Listing 2.1-4: the three machine files (gcc/configure.ac:1918-1931).
The three files match the three machines, and the internals manual says that
config.gcc "is usually needed" while the other two are "rarely needed"
(sourcebuild.texi:285-293). The file's own header says why
it is a separate file: "Putting it in a separate shell file lets us skip running
autoconf when modifying target-specific information"
(config.gcc:21-25). The same header lists every variable that the
file reads and sets, with a description of each, and that list is the closest
thing to a specification the file has (config.gcc:30-212).
The 6,162 lines of config.gcc run in seven steps, in a fixed order, and each
step can override the ones before it. The arm-none-eabi example refers to the
steps by number:
- The CPU type is the first field of the triple, cut with
sed 's/-.*$//'(config.gcc:339). - A
caseon the triple sets the CPU type where it differs, and the per-CPU variables: objects, installed headers, extra.optfiles (:341-600). - The file-name defaults from the table above (
:602-632). - A
casefor operating-system families such as*-*-linux*and*-*-elf(:725-1175). - The large
casewith one entry per supported triple pattern (:1188-3645). - A
casethat validates--with-cpu,--with-arch,--with-floatand the others for each target (:4247-5867). - A loop that turns the accepted
--with-*values intoconfigure_default_options(:6116-6144).
Following arm-none-eabi through config.gcc
Following --target=arm-none-eabi through the seven steps of config.gcc shows
how one triple becomes four decisions: the headers, the makefile fragments, the
macros and the default CPU. Every target goes through the same steps, so the
example is also a guide to reading the entry for your own triple.
Step 1 gives cpu_type=arm. Step 2 matches arm*-*-* and adds the ARM objects,
arm_neon.h and its siblings as installed headers, and arm-c.o for the C and
C++ compilers (config.gcc:375-385). Step 3 sets tm_file=arm/arm.h
and finds arm/arm-protos.h. Step 4 matches nothing, because no
operating-system entry matches eabi. Step 5 decides the triple, in the entry
of Listing 2.1-5, where the lines to watch are the tm_file and tmake_file
assignments and target_cpu_cname:
arm*-*-eabi* | arm*-*-symbianelf* | arm*-*-rtems* | arm*-*-fuchsia*)
case ${target} in
arm*eb-*-eabi*)
tm_defines="${tm_defines} TARGET_BIG_ENDIAN_DEFAULT=1"
esac
default_use_cxa_atexit=yes
tm_file="elfos.h arm/unknown-elf.h arm/elf.h arm/bpabi.h"
tmake_file="${tmake_file} arm/t-arm arm/t-arm-elf"
target_cpu_cname="arm7tdmi"
case ${target} in
arm*-*-eabi*)
tm_file="$tm_file newlib-stdint.h"
tmake_file="${tmake_file} arm/t-bpabi"
use_gcc_stdint=wrap
;;
...
esac
tm_file="${tm_file} arm/aout.h arm/arm.h"
;;
Listing 2.1-5: the arm-none-eabi entry, abridged
(gcc/config.gcc:1497-1530). The omitted branches are for Fuchsia,
RTEMS and Symbian.
The headers. The entry replaces tm_file instead of adding to it. The
result layers three sources: the object-file format (elfos.h, from the top of
gcc/config/), the ARM ELF and EABI headers, and the C library's integer types
(newlib-stdint.h). arm/arm.h goes last. A later step puts vxworks-dummy.h
in front of every ARM, x86, MIPS, PowerPC, SH and SPARC target
(config.gcc:5883-5888). So the list that leaves config.gcc
is:
vxworks-dummy.h elfos.h arm/unknown-elf.h arm/elf.h arm/bpabi.h newlib-stdint.h arm/aout.h arm/arm.h
gcc/configure then appends defaults.h, and initfini-array.h or
tm-dwarf2.h when other options ask for them
(gcc/configure.ac:1953-1960, :2209). The
list becomes the generated tm.h. Chapter 2.4
shows that file.
The makefile fragments. tmake_file collects arm/t-arm, arm/t-arm-elf
and arm/t-bpabi. Configure keeps only the names that exist as files under
gcc/config/ (gcc/configure.ac:2406-2414). A
--with-multilib-list=aprofile or rmprofile adds arm/t-multilib
(config.gcc:4488-4539). The install manual documents the two
values under Configuration: they build multilibs for the A
profile and for the R and M profiles. Chapter 1.6
shows what that fragment's variables do.
The macros. tm_defines holds "target macros to define for all
compilations" (config.gcc:70). Each one becomes a #define
in the generated tm.h (gcc/mkconfig.sh:57-62). For
arm-none-eabi the list holds only the entries that all targets get: the C
library codes LIBC_GLIBC=1 to LIBC_MUSL=4 (config.gcc:697)
and HEAP_TRAMPOLINES_INIT=0 (:1177-1186). The big-endian
triple armeb-none-eabi adds TARGET_BIG_ENDIAN_DEFAULT=1, in the first lines
of Listing 2.1-5. In config.gcc, that one macro is the whole difference between
the two triples.
The default CPU. The entry sets target_cpu_cname="arm7tdmi", and step 6
accepts eight --with-* options for ARM (config.gcc:4402).
The install manual documents all eight under Configuration, and
says that the --with-cpu= value "will be used as the default value of the
-mcpu= switch". Step 6 ends with with_cpu=${with_cpu:-$target_cpu_cname}
(:4541), so if you did not pass --with-cpu, with_cpu is
now arm7tdmi.
The loop in step 7 records the value in configure_default_options, which
gcc/configure writes into the generated configargs.h
(gcc/configure.ac:2242-2250). The backend's arm.h turns it
back into a driver option, in its OPTION_DEFAULT_SPECS:
{"cpu", "%{!march=*|march=unset:"\
"%{!mcpu=*|mcpu=unset:%<march=* %<mcpu=* -mcpu=%(VALUE)}}" }, \
Listing 2.1-6: the cpu entry of OPTION_DEFAULT_SPECS
(gcc/config/arm/arm.h:400-401).
The driver expands these entries at start-up, with %(VALUE) replaced by the
configured value (gcc/gcc.cc:8519-8523,
:5874-5920). In the spec language of
Chapter 1.3, the entry says: if the command line has no
-march= and no -mcpu=, add -mcpu=arm7tdmi. cc1_options passes every -m
switch to the compiler (gcc.cc:1288). So an arm-none-eabi toolchain
configured with neither --with-cpu nor --with-arch compiles for ARM7TDMI
unless you say otherwise, and one line in Listing 2.1-5 made that choice.
The same value also reaches cc1 by a second path. config.gcc copies it into
target_cpu_default (config.gcc:5900-5908,
:6146-6154), the generated tm.h defines it as
TARGET_CPU_DEFAULT (gcc/mkconfig.sh:51-54), and arm.cc
uses it "If the user did not specify a processor or architecture"
(gcc/config/arm/arm.cc:3424-3434). That path matters only
when you run cc1 without the driver.
gcc/Makefile: where config.gcc's choices become paths
The variables that config.gcc sets end in gcc/Makefile, where
gcc/configure substitutes each one, most of them as paths into the source
tree. From there they are the build's input, and you can read them back before
anything is compiled. Listing 2.1-7 shows the substitutions and the line that
includes the target's t-* fragments:
tmake_file=@tmake_file@
...
out_file=$(srcdir)/config/@out_file@
out_object_file=@out_object_file@
common_out_file=$(srcdir)/common/config/@common_out_file@
...
md_file=$(srcdir)/common.md $(srcdir)/config/@md_file@
tm_file_list=@tm_file_list@
...
tm_defines=@tm_defines@
...
# target overrides
-include $(tmake_file)
Listing 2.1-7: the target's files in gcc/Makefile.in, abridged
(gcc/Makefile.in:599-611, :2004-2005).
out_file is the backend's .cc file, and md_file is the backend's machine
description after the target-independent common.md. common_out_file is the
target's file under gcc/common/config/, where a hook that the driver and the
compilers share lives. The t-* fragments are included into the makefile
itself, after the front ends' fragments, so a target can change any variable
that gcc/Makefile.in defines.
To read the choice back, run the top-level configure in a build directory,
then configure only the gcc module with the configure-gcc target of the
generated top-level makefile (Makefile.in:12099). Grep its
output and its makefile:
$ make configure-gcc 2>&1 | grep -A10 '^Using'
$ grep -E '^(out_file|md_file|tmake_file|tm_file_list|tm_defines)=' gcc/Makefile
The first command shows the lines that gcc/configure prints about its choice:
Using `<srcdir>/config/arm/arm.cc' for machine-specific logic., the same
line for arm.md, and the target macro files one per line
(gcc/configure.ac:1963-1964, :2000-2007). The
second shows the values substituted into the variables of Listing 2.1-7.
libgcc/config.host: a second selection, for libgcc
libgcc/config.host selects for libgcc what config.gcc selects for the
compiler, from a separate libgcc/config/ tree. The run-time functions that a
target program links come from this side, so a search for the rule that builds
__aeabi_uldivmod starts here, not in gcc/config/arm/.
config.gcc's header asks you to keep the two files in step: "When you change
the cases in the OS or target switches, consider updating ../libgcc/config.host
also" (config.gcc:27-28). The header of config.host explains
why its case reads a different variable:
This file bears an obvious resemblance to gcc/config.gcc. The cases should be kept similar, to ease moving library-specific settings from config.gcc to this file. That is also why tmake_file is left as tmake_file, rather than hmake_file, even though this library switches on ${host}.
libgcc switches on ${host} because it is configured as a target module: for
the library, the host is the machine it runs on, and that machine is your
target. libgcc/configure.ac calls AC_CANONICAL_HOST and sources
config.host (libgcc/configure.ac:156, :471).
The arm*-*-eabi* entry of config.host adds crtbegin.o, crtend.o,
crti.o and crtn.o, the soft-float fragments and the ARM unwinder header
(libgcc/config.host:578-595).
Both files name a fragment called arm/t-bpabi, and they are not the same file.
gcc/configure looks for it under gcc/config/, and libgcc/configure under
libgcc/config/ (libgcc/configure.ac:685-694). The
compiler's copy, the one a search in gcc/config/arm/ finds, is one line:
EXTRA_HEADERS += $(srcdir)/ginclude/unwind-arm-common.h
Listing 2.1-8: the whole of gcc/config/arm/t-bpabi (gcc/config/arm/t-bpabi:1).
The library's copy is where the EABI run-time functions come from. Its second
line is the rule for __aeabi_uldivmod, with the other functions that
bpabi.S provides:
# Add the bpabi.S functions.
LIB1ASMFUNCS += _aeabi_lcmp _aeabi_ulcmp _aeabi_ldivmod _aeabi_uldivmod
# Add the BPABI C functions.
LIB2ADD += $(srcdir)/config/arm/bpabi.c \
$(srcdir)/config/arm/unaligned-funcs.c
LIB2ADD_ST += $(srcdir)/config/arm/fp16.c
LIB2ADDEH = $(srcdir)/config/arm/unwind-arm.c \
$(srcdir)/config/arm/libunwind.S \
$(srcdir)/config/arm/pr-support.c $(srcdir)/unwind-c.c
Listing 2.1-9: the start of libgcc/config/arm/t-bpabi
(libgcc/config/arm/t-bpabi:1-12).
When a target-specific question is about code that runs on the target, start in
libgcc/config/<cpu>/. When it is about how the compiler behaves, start in
gcc/config/<cpu>/. Chapter 4.1 explains
what goes into libgcc.
Checking the target selection with -### and gcc -v
An installed arm-none-eabi-gcc shows two results of config.gcc with no build
tree: the default CPU, on the cc1 line that -### prints, and the configure
arguments, which gcc -v prints. The GCC manual documents both options under
Overall Options: -v prints the commands that the driver runs,
and -### prints them without running them. With any C file as foo.c, the
default CPU appears on the cc1 line:
$ arm-none-eabi-gcc -### -c foo.c 2>&1 | grep -o -- '-mcpu=[^ ]*'
On a toolchain configured with neither --with-cpu nor --with-arch, Listing
2.1-6 makes this print -mcpu=arm7tdmi. If you pass -mcpu= or -march=
yourself, the default does not apply, and the command prints only your own
option.
gcc -v reads back what configure recorded. It prints the target and the
configure line, from the print_configuration function
(gcc/gcc.cc:7709-7710):
$ arm-none-eabi-gcc -v
The Configured with: line records the top-level configure's arguments as
typed. gcc/configure writes them into the same generated configargs.h as the
default CPU (gcc/configure.ac:2244), and
Chapter 1.14 reads that line for the flags
it records.
The Target: line is not the ${target} that config.gcc switches on
(config.gcc:30). Chapter 2.2
explains the two names, and why neither line shows the canonical triple.
Three things to carry away
gcc/config.gcc turns the triple into file names. It picks the CPU
directory, the header list, the makefile fragments, the macros and the default
--with-* values, in a fixed order where later steps override earlier ones.
A top-level directory is a module, built for one machine. libgcc/ is
outside gcc/ because it is a target module, compiled by the compiler that
gcc/ produces.
The triple is read twice. gcc/config.gcc chooses for the compiler, and
libgcc/config.host chooses for libgcc, from two different config/ trees.
Things that surprise people
There is no gcc/config/x86_64/. The x86-64 backend is in
gcc/config/i386/, and the PowerPC backend is in gcc/config/rs6000/.
Every ARM compiler includes a VxWorks header. vxworks-dummy.h is first in
the header list of arm-none-eabi, so that shared ARM code can test VxWorks
markers safely (config.gcc:5878-5881).
A misspelled t-* fragment is dropped without a message. gcc/configure
keeps a tmake_file entry only if the file exists
(gcc/configure.ac:2409-2412).
The --with-* validation step changes the build on ARM. Its comment says
that it "should set nothing besides supported_defaults"
(config.gcc:4240-4244). The ARM branch adds multilib
fragments and headers, and sets --with-float=soft for the built-in multilib
profiles (config.gcc:4488-4539).
Documentation coverage
The internals manual describes the tree in its
Source Tree Structure and Build System chapter
(gcc/doc/sourcebuild.texi:5). The Top Level node lists the
top-level directories (:21), Subdirectories lists those of
gcc/ (:183), System Config covers config.build,
config.host and config.gcc (:282), and
Anatomy of a Target Back End lists the files of a
gcc/config/<machine>/ directory (:789). The install manual's
Downloading GCC page documents building binutils, GMP, MPFR and
MPC in the same tree (install.texi:698-713), and its
Configuration page documents --with-cpu
(install.texi:1681).
Where the internals manual is out of date for GCC 15.2.0:
- The Top Level list still has
intl(sourcebuild.texi:64-66), which GCC 14 removed, and has no entry forlibgrust. - The Subdirectories list omits
c-family,analyzer,rtl-ssa,sym-execandtext-art. - The Back End node names the backend source
machine.c(:799). The default ismachine.ccsince GCC 12. - The Library Files node places
crtstuff.candunwind-dw2.cundergcc/(:316-320). They are inlibgcc/. - The Configuration nodes name
acconfig.h(:243) andconfigure.frag(:278). Neither file is ingcc/in GCC 15.2.0.
What is not documented:
- What
config.gccsets. The System Config node is a FIXME (:298-299) that points at the comment at the top of the file, and that comment is the only description. - How the top-level build system works. The manual says it "is documented in a
separate manual, included with GNU Binutils" (
:157-160). A GCC checkout does not contain that manual. - That
Makefile.defnames modules the checkout does not contain, and thatconfiguredrops them without a message. - That
libgcc/config.hostmakes a second, separate selection, with fragment names that repeat those ingcc/config/. - That an
arm-none-eabitoolchain defaults to-mcpu=arm7tdmi. Thearm-*-eabientry of the target notes (install.texi:4102) does not say so, and the--with-cpuentry does not say what happens without it.
Next: Chapter 2.2, What configure does with your triple,
what happens to the triple before config.gcc sees it, and which of its two
names ends up on your compiler.
2.2 What configure does with your triple
GCC 15.2.0. To run the commands: a GCC checkout, and the cross compiler arm-eabi-gcc for -dumpmachine and -v.
A tutorial tells you to configure GCC with --target=arm-eabi, and the build
finishes. The driver in bin/ is arm-eabi-gcc, but your Makefile asks for
arm-none-eabi-gcc. You run ./config.sub arm-eabi to see what GCC made of the
name, and it prints arm-unknown-eabi. That makes three spellings of one
target: the one you typed, the one config.sub made, and the arm-none-eabi
that your Makefile and your binutils use.
configure keeps two forms of every machine name: the canonical form that
config.sub makes, for matching, and the form you typed, which autoconf calls
the alias, for naming. The case statements that decide what to build read the
first. Every directory, program name and tool lookup reads the second.
This chapter assumes Chapter 1.2, for build, host
and target and for the tooldir, and Chapter 1.5,
for how the driver searches the tooldir and for Listing 1.5-6. It also uses
collect2 from Chapter 1.1, specs from
Chapter 1.3, the multilib table and MULTILIB_OSDIRNAMES
from Chapter 1.6, and config.gcc and the
config-lang.in files from Chapter 2.1.
config.sub and config.guess: from alias to canonical triple
config.sub turns each machine name that configure receives into a canonical
triple, and config.guess names the build machine when you give no --build.
The rules in config.sub explain why arm-eabi becomes arm-unknown-eabi, and
the triple they produce is the one that GCC's per-target case patterns match.
The install manual documents the canonicalisation under
Configuration: a name "may be canonical or it may be more or
less abbreviated", and config.sub "produces canonical versions".
With no --build, configure first asks config.guess to name the machine it
runs on, then passes the answer to config.sub
(configure:2411-2417). For the target, it passes your --target
value to config.sub (configure:2505-2509). The script's header
comment states its contract, a triple of CPU, manufacturer and operating system,
or in some cases a newer four-part form that adds the kernel:
# The goal of this file is to map all the various variations of a given
# machine specification into a single specification in the form:
# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
# or in some cases, the newer four-part form:
# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
# It is wrong to echo any other type of specification.
Listing 2.2-1: the goal of config.sub (config.sub:48-53).
config.sub needs no build tree, so you can run it from the top of any GCC
checkout:
$ ./config.sub arm-eabi
$ ./config.sub arm-none-eabi
$ ./config.sub x86_64-linux-gnu
With the config.sub in GCC 15.2.0, whose timestamp is 2021-10-27
(config.sub:7), the three commands print arm-unknown-eabi,
arm-none-eabi and x86_64-pc-linux-gnu. Only arm-none-eabi comes back as
typed.
arm-eabi has two fields, and when the second field is not a known
manufacturer, config.sub reads it as the operating system. The CPU then has no
vendor, the code's name for the manufacturer field, so the script supplies one.
In the abridged listing, watch the basic_os=$field2 line and the
vendor=unknown default:
*-*)
# Second component is usually, but not always the OS
case $field2 in
...
*)
basic_machine=$field1
basic_os=$field2
;;
...
# Recognize the basic CPU types without company name.
*)
cpu=$basic_machine
vendor=unknown
;;
...
echo "$cpu-$vendor-${kernel:+$kernel-}$os"
Listing 2.2-2: how arm-eabi becomes arm-unknown-eabi, abridged
(config.sub:169-197, :963-967,
:1877).
eabi passes the OS check (config.sub:1712-1713), and the table
that picks a vendor from the OS has no entry for it (:1799-1875),
so the vendor stays unknown. Nothing in config.sub turns arm-eabi into
arm-none-eabi. The none is not a keyword: in arm-none-eabi it is the vendor
field. The three-field branch keeps arm-none as CPU and vendor
(config.sub:140-158), and the split of arm-none into the two
leaves none as typed (:938-944).
x86_64-linux-gnu also has no vendor field, but its last two fields form a known
two-part OS, linux-gnu (config.sub:143-150). A bare x86_64
gets the vendor pc, for a reason its comment gives: the word unknown tends to
confuse beginning users (config.sub:946-952). The result is
x86_64-pc-linux-gnu, which is also what config.guess prints on an x86_64
GNU/Linux machine (config.guess:1110-1122).
$target and $target_noncanonical: one for matching, one for names
configure keeps both forms of the target name: $target holds the canonical
triple, and $target_noncanonical holds your spelling. Each consumer in the
tree reads one of the two, so the variable it reads decides whether arm-eabi
and arm-none-eabi look the same to it.
$target is the output of config.sub (configure:2519),
and $target_alias is the --target value as you typed it.
$target_noncanonical is the alias, with a fallback for the case where you
typed nothing:
dnl # _GCC_TOPLEV_NONCANONICAL_TARGET
dnl # $target_alias or $host_noncanonical if blank.
dnl # Used when we would use $target_alias, but empty is not OK.
AC_DEFUN([_GCC_TOPLEV_NONCANONICAL_TARGET],
[AC_REQUIRE([_GCC_TOPLEV_NONCANONICAL_HOST]) []dnl
case ${target_alias} in
"") target_noncanonical=${host_noncanonical} ;;
*) target_noncanonical=${target_alias} ;;
esac
]) []dnl # _GCC_TOPLEV_NONCANONICAL_TARGET
Listing 2.2-3: target_noncanonical (config/acx.m4:29-38).
The host and build macros above it follow the same pattern
(config/acx.m4:8-26). At the end of the chain, an empty --build
falls back to the canonical $build. On a native build where you typed no
machine name at all, all three noncanonical names are therefore the config.sub
form of what config.guess printed.
gcc/configure.ac states the purpose of the second form in one comment:
"Determine the noncanonical target name, for directory use"
(gcc/configure.ac:41-42). The rule holds across the tree:
| Consumer | Form it reads | Source |
|---|---|---|
| "is this a cross compiler?" | canonical | configure.ac:209-215, gcc/configure.ac:2546-2549 |
per-target case patterns, such as unsupported languages | canonical | configure.ac:918-922 |
backend selection in config.gcc | canonical | gcc/config.gcc:1497 |
the tooldir, $exec_prefix/<alias> | as typed | configure.ac:3121 |
lib/gcc/<alias>/ and libexec/gcc/<alias>/ | as typed | gcc/Makefile.in:682-684 |
| the build-tree directory of the target libraries | as typed | config/acx.m4:100-101 |
the driver's own target name, spec_machine | as typed | gcc/Makefile.in:2605 |
collect2's <alias>-ld | as typed | gcc/Makefile.in:2558 |
The lib/gcc/<alias>/ and libexec/gcc/<alias>/ directories use
real_target_noncanonical, which is "Normally
identical to target_noncanonical, except for compilers built as accelerator
targets" (gcc/Makefile.in:65-67).
The split has a reason on each side. A pattern such as arm*-*-eabi* needs three
fields, so only the canonical form can match it. A directory name has no such
need, so GCC keeps your spelling. The cost is that --target=arm-eabi and
--target=arm-none-eabi canonicalise to arm-unknown-eabi and arm-none-eabi,
which both match arm*-*-eabi*. The two select the same backend, and they
install into two different trees.
The cross test meets two spellings of one canonical name. It compares canonical
names, so --host=x86_64-linux-gnu --target=x86_64-pc-linux-gnu is a native
build.
program_prefix: how a cross build gets <alias>- names
A cross build installs its programs under <alias>- names with no option,
because the generated configure sets program_prefix to the target alias and a
dash when you give none of the program-name options. GCC turns that default off
for a native build with a guard that compares spellings, not canonical names, so
a native build can still get a prefix.
Three configure options rename the programs that make install writes to
bin/. --program-prefix=foo- installs gcc as foo-gcc,
--program-suffix=-15 installs it as gcc-15, and --program-transform-name=
applies a sed script to each name. The install manual documents the three
under Configuration (gcc/doc/install.texi:998-1038).
The default prefix comes from code that autoconf writes into configure for
AC_CANONICAL_SYSTEM and AC_ARG_PROGRAM (configure.ac:80-81).
A search of the text of configure.ac finds only the guard in Listing 2.2-5, so
the code to read is in the generated configure:
# The aliases save the names the user supplied, while $host etc.
# will get canonicalized.
test -n "$target_alias" &&
test "$program_prefix$program_suffix$program_transform_name" = \
NONENONEs,x,x, &&
program_prefix=${target_alias}-
Listing 2.2-4: the default program prefix (configure:2533-2538).
NONE, NONE and s,x,x, are the defaults of the three program-name options
(configure:930-932), so the prefix applies when you give a
target and set none of the three options. The alias is your spelling, so
--target=arm-eabi gives arm-eabi-.
Autoconf would do this for a native build too, whenever --target is on the
command line. GCC's top level stops it one step earlier:
dnl Autoconf 2.5x and later will set a default program prefix if
dnl --target was used, even if it was the same as --host. Disable
dnl that behavior. This must be done before AC_CANONICAL_SYSTEM
dnl to take effect.
test "$host_noncanonical" = "$target_noncanonical" &&
test "$program_prefix$program_suffix$program_transform_name" = \
NONENONEs,x,x, &&
program_transform_name=s,y,y,
Listing 2.2-5: no default prefix when host and target match
(configure.ac:71-78).
s,y,y, is a sed command that changes nothing, so its only effect is to make
the test in Listing 2.2-4 fail. The guard compares the noncanonical names, not
the canonical ones that the cross test compares.
Configure natively on a machine that config.guess calls x86_64-pc-linux-gnu,
pass --target=x86_64-linux-gnu and no --host, and the two spellings differ.
The guard does not fire, and the prefix applies. The canonical names match, so
the result is a native compiler installed as x86_64-linux-gnu-gcc.
The top level then hands the finished sed script to every subdirectory as
--program-transform-name. It also replaces s,x,x, with s,y,y,, "because we
want to override the logic in subdir configure scripts to choose
program_transform_name" (configure.ac:3623-3637). The
override matters because gcc/configure carries its own copy of Listing 2.2-4
(gcc/configure:3540-3543).
In gcc/, the script becomes the installed names:
GCC_INSTALL_NAME := $(shell echo gcc|sed '$(program_transform_name)')
GCC_TARGET_INSTALL_NAME := $(target_noncanonical)-$(shell echo gcc|sed '$(program_transform_name)')
...
FULL_DRIVER_NAME=$(target_noncanonical)-gcc-$(version)$(exeext)
Listing 2.2-6: the driver's installed names, abridged
(gcc/Makefile.in:876-877, :1925).
install-driver installs GCC_INSTALL_NAME, then links <alias>-gcc-15.2.0
next to it. On a native build only, it also links GCC_TARGET_INSTALL_NAME
(gcc/Makefile.in:4173-4191). The test it uses for "native" is
the absence of gcc-cross, which only the cross build makes
(gcc/Makefile.in:2219, :2448-2450). The version
link takes $(target_noncanonical) directly, so no transformation renames it.
Sub-configures see --target=$(target_alias)
Every directory that the top level configures gets its target as
--target=$(target_alias) from the generated Makefile, not from your command
line. target_alias holds your spelling, so every directory sees the name as you
typed it, and every directory runs config.sub on it again.
The top level drops every option that starts with --t, --ho, --bu or
--program-, and forwards most others, such as --enable-languages and
--disable-multilib, as you typed them (configure.ac:3579-3610).
The generated Makefile adds the machine names back. In it, target_alias is
@target_noncanonical@ (Makefile.tpl:48-51), and every
sub-configure gets --target= with that value
(Makefile.tpl:1203-1204).
For a target library, the Makefile also passes the target alias as --host
(Makefile.tpl:1488-1493), because a target library runs on the
target. Chapter 2.3 covers the module lists that
these rules come from.
After the top-level configure succeeds, the generated Makefile shows both
forms:
$ ../gcc/configure --target=arm-eabi --prefix=/opt/arm
$ grep -E '^target(_alias)?=' Makefile
From Listing 2.2-2 and the Makefile.tpl lines, target_alias holds arm-eabi
and target holds arm-unknown-eabi.
-dumpmachine, the tooldir and collect2 read the alias
-dumpmachine and gcc -v report a built compiler's target as you spelled it,
not in canonical form, and the tooldir and collect2 find the target's tools by
the same spelling. Those lookups decide whether an arm-eabi compiler finds
binutils that were installed under arm-none-eabi names.
-dumpmachine prints "the compiler's target machine" and exits, and the GCC
manual documents it under Developer Options. The driver gets its
target name from -DDEFAULT_TARGET_MACHINE, which the Makefile sets to
$(target_noncanonical) (gcc/Makefile.in:2604-2605):
static const char *spec_machine = DEFAULT_TARGET_MACHINE;
static const char *spec_host_machine = DEFAULT_REAL_TARGET_MACHINE;
...
case OPT_dumpmachine:
printf ("%s\n", spec_machine);
exit (0);
Listing 2.2-7: what -dumpmachine prints, abridged
(gcc/gcc.cc:335-336, :4231-4233).
gcc -v prints the same string on its Target: line, and the configure
arguments on the next line (gcc/gcc.cc:7709-7710). Those
arguments are the top-level command line as typed, $0 and then "$@"
(configure.ac:42-64):
$ arm-eabi-gcc -dumpmachine
$ arm-eabi-gcc -v 2>&1 | grep -E '^(Target|Configured with):'
For the arm-eabi build, -dumpmachine prints arm-eabi, and Configured with: repeats --target=arm-eabi. A canonical name shows up only on a native
build with no machine options, because there you typed no spelling and the alias
falls back to the output of config.guess.
spec_machine also names the tooldir in the driver's program search
(gcc/gcc.cc:5523-5539, Listing 1.5-6). The driver asks that
list for the name that the spec gives, a plain as, and never for <alias>-as
(gcc/gcc.cc:3097-3118). When no prefix holds one, it runs the
bare name and lets the PATH decide (gcc/gcc.cc:3295-3302,
:3438-3441).
collect2, unlike the driver, adds the target name itself. On a cross compiler,
it builds the linker's name from TARGET_MACHINE, which is
$(target_noncanonical) (gcc/Makefile.in:2558):
for (i = 0; i < USE_LD_MAX; i++)
#ifdef CROSS_DIRECTORY_STRUCTURE
/* lld and mold are platform-agnostic and not prefixed with target
triple. */
if (!(i == USE_LLD_LD || i == USE_MOLD_LD))
full_ld_suffixes[i] = concat (target_machine, "-", ld_suffixes[i],
NULL);
else
#endif
full_ld_suffixes[i] = ld_suffixes[i];
Listing 2.2-8: collect2 names <alias>-ld (gcc/collect2.cc:867-876).
collect2 searches the PATH for that name last, after the compiler's own
directories (gcc/collect2.cc:1107-1110). The top-level configure
uses the same alias to find the target tools for the build. It tries a list of
tool directories that includes $prefix/<alias>/bin, then <alias>-as on the
PATH (config/acx.m4:113-118, :257-292,
configure.ac:4040).
The --target you give GCC must therefore be spelled the same as the one you
gave binutils. An arm-eabi driver looks for as in $prefix/arm-eabi/bin/,
and its collect2 looks for arm-eabi-ld on the PATH. If your binutils use
the arm-none-eabi names, neither lookup finds them.
--program-prefix does not change these lookups. It renames what
make install writes to bin/, and the installed driver and collect2 never
read it. One build-time rule does: on a cross build with no binutils in the
tree, gcc/Makefile.in names the target ar, ranlib and strip by running
the script over the bare names (gcc/Makefile.in:513-551).
config.gcc reads both names: the alias keeps pentium4
config.gcc reads the alias as well as the canonical triple, because
canonicalisation can discard information that the alias carries. A pentium4
target shows both halves: the canonical form picks the backend, and the alias
supplies the processor that becomes the compiler's default.
config.sub turns a pentium4 CPU into i786
(config.sub:1079-1081), so --target=pentium4-linux-gnu
canonicalises to i786-unknown-linux-gnu. The canonical form still selects the
32-bit x86 backend, and config.gcc then reads the alias to recover the
processor:
# Set arch and cpu from ${target} and ${target_noncanonical}. Set cpu
# to generic if there is no processor scheduler model for the target.
...
i686-*-* | i786-*-*)
case ${target_noncanonical} in
...
pentium4-*|pentium4m-*)
arch=pentium4
cpu=pentium4
Listing 2.2-9: the alias picks the default processor, abridged
(gcc/config.gcc:3714-3715, :3775-3776,
:3871-3873).
--with-arch and --with-cpu give a compiler its default processor options,
and the install manual documents them under Configuration. With
neither option, the arch and cpu values that Listing 2.2-9 sets become the
defaults (gcc/config.gcc:4018-4027, :4105-4124).
pentium4 thus becomes this compiler's default --with-arch and --with-cpu
value, and neither option appears on its Configured with: line. The rest of
config.gcc is the subject of Chapter 2.1.
--enable-languages: config-lang.in and noconfigdirs
The top level reads a config-lang.in fragment for every language, and a
language that --enable-languages does not take loses its directories. The
triple reaches this option too, because a case on the canonical $target can
mark a language unsupported. The install manual documents the option under
Configuration (gcc/doc/install.texi:2094-2112).
--enable-languages takes a comma-separated list of the compilers to build,
with their run-time libraries. Its special values are all, for every available
language, and default. In gcc/, grep ^language= */config-lang.in lists
the others. A loop in the top-level configure.ac sources every
gcc/*/config-lang.in and reads five variables from each
(configure.ac:2340-2360). Go's fragment shows four of them:
language="go"
compilers="go1\$(exeext)"
target_libs="target-libgo target-libffi target-libbacktrace"
lang_dirs="gotools"
gtfiles="\$(srcdir)/go/go-lang.cc \$(srcdir)/go/go-c.h"
# Do not build by default.
build_by_default="no"
Listing 2.2-10: a language fragment (gcc/go/config-lang.in:27-37).
With no --enable-languages, and no deprecated LANGUAGES variable in the
environment, the list is default (configure.ac:2222-2227).
default takes each language whose build_by_default is yes
(:2380-2382). The code that removes the directories of a language
that is not taken has one arm for unsupported and one for no:
case $add_this_lang in
unsupported)
# Remove language-dependent dirs.
disabled_target_libs="$disabled_target_libs $target_libs"
noconfigdirs="$noconfigdirs $lang_dirs"
;;
no)
# Remove language-dependent dirs; still show language as supported.
disabled_target_libs="$disabled_target_libs $target_libs"
noconfigdirs="$noconfigdirs $lang_dirs"
potential_languages="${potential_languages}${language},"
;;
Listing 2.2-11: a disabled language removes its directories
(configure.ac:2528-2539).
A disabled target library stays only if an enabled language also lists it
(configure.ac:2562-2570). With --enable-languages=c,c++, the
build therefore drops target-libgo and gotools, but keeps any library that Go
shares with an enabled language. The comment that declares the two lists says
that "Noconfigdirs are removed loudly", unlike skipdirs, which configure
removes with no message (configure.ac:225-227).
One source of unsupported is a case on the canonical $target, such as the
one that marks Go unsupported on Darwin, Cygwin, MinGW and BPF
(configure.ac:918-922). A language that you named but that cannot
be built stops configure with "The following requested languages could not be
built" (configure.ac:2612-2616).
--disable-multilib: the top level, config-ml.in and multilib.h
--disable-multilib acts in three places: the top level, each target library's
config-ml.in, and the multilib.h table that the driver reads. In gcc/, the
rule that writes multilib.h has a second condition, so on some targets the
variants that GCC builds go but the OS library directory names stay. The
install manual gives the option one sentence: it stops GCC
building the extra library variants (gcc/doc/install.texi:1298-1302).
At the top level, the default is on. If you give neither form, the top level
adds --enable-multilib to every target library's configure line
(configure.ac:3714-3717). If you give --disable-multilib, it
reaches the target libraries like any other forwarded option. On a native x86_64
GNU/Linux build with neither form, configure first checks that -m32 links, and
stops with an error that suggests --disable-multilib if it does not
(configure.ac:3694-3712).
In each target library, config-ml.in does all of its work inside one
if [ "${enable_multilib}" = yes ] (config-ml.in:177-178). When
the switch is on, it asks the newly built compiler for the variant list:
multidirs=
for i in `${CC-gcc} --print-multi-lib 2>/dev/null`; do
dir=`echo $i | sed -e 's/;.*$//'`
...
done
# Target libraries are configured for the host they run on, so we check
# $host here, not $target.
Listing 2.2-12: target libraries take the variants from the new compiler,
abridged (config-ml.in:217-232).
The comment states the same rule as the --host that the Makefile passes to a
target library: in a target library's configure, $host is the target machine.
With --disable-multilib, the library builds the default variant only.
In gcc/, the switch reaches multilib.h, the table that
Chapter 1.6 showed the driver reading. The rule that
generates it has a second condition:
s-mlib: $(srcdir)/genmultilib Makefile
if test @enable_multilib@ = yes \
|| test -n "$(MULTILIB_OSDIRNAMES)"; then \
$(SHELL) $(srcdir)/genmultilib \
"$(MULTILIB_OPTIONS)" \
...
"@enable_multilib@" \
> tmp-mlib.h; \
else \
$(SHELL) $(srcdir)/genmultilib '' '' '' '' '' '' '' '' \
"$(MULTIARCH_DIRNAME)" '' no \
> tmp-mlib.h; \
fi
Listing 2.2-13: --disable-multilib and MULTILIB_OSDIRNAMES, abridged
(gcc/Makefile.in:2480-2500).
When the target's fragment sets MULTILIB_OSDIRNAMES, genmultilib still gets
the full option list, but with no as its last argument. Its header comment
states the effect: with anything but yes there, every GCC multilib directory
name becomes . (gcc/genmultilib:91-92). The OS directory
survives next to each . (:400-402).
x86_64 GNU/Linux is such a target. It sets MULTILIB_OSDIRNAMES, with
m64=../lib64 (gcc/config/i386/t-linux64:36), so
--disable-multilib there removes the variants that GCC builds and keeps the OS
library directory names. Some targets also choose their multilib fragment by the
switch: RISC-V GNU/Linux adds riscv/t-linux-multilib only when it is yes
(gcc/config.gcc:2522-2528).
Three things to carry away
$target is for case patterns, and $target_noncanonical names everything
on disk. config.sub output selects the backend. Your spelling names the
programs, the tooldir and lib/gcc/<alias>/.
A cross build gets <alias>- names from autoconf, with no option. The
guard against a prefix on a native build compares spellings, not canonical names.
Every tool lookup uses the alias. The tooldir, -dumpmachine, collect2's
<alias>-ld and configure's search for <alias>-as all read it, and
--program-prefix changes none of them.
Things that surprise people
config.sub arm-eabi prints arm-unknown-eabi. No step in the script
produces arm-none-eabi from a two-part name.
--target=arm-eabi and --target=arm-none-eabi build the same compiler into
different trees. Both canonical forms match arm*-*-eabi*, and every
directory name uses the spelling.
A native build can get a program prefix. --target=x86_64-linux-gnu with no
--host, on a machine that config.guess calls x86_64-pc-linux-gnu, gives
x86_64-linux-gnu-gcc.
gcc -v does not canonicalise. Configured with: is the command line as
typed, and Target: is the alias.
Documentation coverage
The install manual's Configuration page
(gcc/doc/install.texi:727) defines build, host and target, and says that
config.sub "produces canonical versions" of configuration names
(:835-867). The same page documents the program-name options (:998-1038),
--disable-multilib (:1298) and --enable-languages (:2094). The internals
manual's Configure Terms node (gcc/doc/configterms.texi:5)
says that --target=foo-bar gives a compiler called foo-bar-gcc (:40-45).
It also says that a target library's host is the target (:47-55).
-dumpmachine is in Developer Options
(gcc/doc/invoke.texi:21649).
Each option has an entry, but no entry says which form of the name the rest of the build uses.
What is not documented:
- That
configurekeeps the canonical name for matching and your spelling for every directory and program name. - That the default
<alias>-prefix comes from autoconf, and that GCC's guard against it compares spellings. - That
-dumpmachineprints the alias. The manual's example,i686-pc-linux-gnu(invoke.texi:21650-21651), reads like a canonical name. - That the driver looks for a plain
asand falls back to thePATH, whilecollect2looks for<alias>-ld. - That
--disable-multilibkeeps the OS directory names of a target that setsMULTILIB_OSDIRNAMES.
What the manual says that GCC 15.2.0 does not do:
- "As currently implemented, this option only takes effect for native builds;
cross compiler binaries' names are not transformed even when a transformation
is explicitly asked for by one of these options" (
install.texi:1029-1031). Listing 2.2-4 skips its default when you give any of the three options. The top level then passes the resulting script togcc/, for a cross build as for a native one. By that trace,--program-prefix=foo-installs a cross driver asfoo-gcc.
Next: Chapter 2.3, Makefile.def and AutoGen: how make orders the
build, how AutoGen turns Makefile.def into the
top-level Makefile, and the order in which make builds the directories that
the top-level configure set up.
2.3 Makefile.def and AutoGen: how make orders the build
GCC 15.2.0. To run the commands: a GCC checkout, and binutils for arm-none-eabi installed under $HOME/cross.
Cross-compiler recipes tell you to run make all-gcc first and
make all-target-libgcc later. Look for either target in a checkout, and
gcc/Makefile.in defines neither. The top-level Makefile.in defines both,
among nearly 70,000 lines, and its first line says that a program wrote it. If
you add a rule there by hand, the next regeneration deletes it without a warning.
The top-level build order is data: Makefile.def lists the modules and the
edges between them. AutoGen expands that list into the top-level Makefile.in,
configure deletes the modules you do not build, and make walks what is left
as a graph.
This chapter assumes Chapter 1.2, for build, host
and target, the Canadian cross and the uninstalled xgcc. It also uses the
specs file of Chapter 1.3, the -B search lists of
Chapter 1.5 and the multilib variants of
Chapter 1.6. From Part II, it assumes
Chapter 2.1, for the top-level directory map and for
why libgcc/ is not under gcc/, and
Chapter 2.2, for how
--enable-languages drops modules.
Makefile.def and Makefile.tpl: the AutoGen input for Makefile.in
Makefile.def and Makefile.tpl are the two files from which AutoGen, a
template processor separate from Autoconf and Automake, writes the top-level
Makefile.in. Makefile.def holds records, such as the lists of modules, and
Makefile.tpl holds make syntax with macros that loop over those records. The
top level therefore has three files where an Automake project has two, and a
change to the build order starts in one of the two inputs. The first lines of the
definitions file say how they fit together:
#! /usr/bin/autogen
AutoGen definitions Makefile.tpl;
// Makefile.in is generated from Makefile.tpl by 'autogen Makefile.def'.
Listing 2.3-1: the head of the definitions file (Makefile.def:1-4).
A record in Makefile.def looks like target_modules = { module= libgcc; ... };,
and the macros in Makefile.tpl are written [+ ... +]. The template also
contains Scheme functions (Makefile.tpl:1940-2039), which is why
the install manual lists Guile next to AutoGen. Its Prerequisites
page says that both are "Necessary to regenerate the top level Makefile.in file
from Makefile.tpl and Makefile.def".
The loop that writes the all-target rule shows how records become make syntax.
It writes one all-target line per target module:
.PHONY: all-target
[+ FOR target_modules +][+ IF bootstrap +]
@if target-[+module+]-no-bootstrap[+ ENDIF bootstrap +]
all-target: maybe-all-target-[+module+][+ IF bootstrap +]
@endif target-[+module+]-no-bootstrap[+
ENDIF bootstrap +][+ ENDFOR target_modules +]
Listing 2.3-2: the template loop for all-target
(Makefile.tpl:903-908).
@if target-libvtv-no-bootstrap
all-target: maybe-all-target-libvtv
@endif target-libvtv-no-bootstrap
all-target: maybe-all-target-libssp
all-target: maybe-all-target-newlib
@if target-libgcc-no-bootstrap
all-target: maybe-all-target-libgcc
@endif target-libgcc-no-bootstrap
Listing 2.3-3: what the loop wrote, in the checked-in file
(Makefile.in:1335-1342).
A flag in a record changes the output. libgcc and libvtv carry
bootstrap=true in Makefile.def, so their lines are fenced by @if. libssp
and newlib do not, so their lines are bare.
autogen Makefile.def: regenerating the top-level Makefile.in
In a normal build tree, nothing runs autogen Makefile.def, because configure
disables the template rule that would regenerate the top-level Makefile.in. A
hand edit of Makefile.in therefore lasts until the next person runs autogen,
and an edit of Makefile.def changes nothing until then. The rule is in the
template:
# Rebuilding Makefile.in, using autogen.
AUTOGEN = autogen
$(srcdir)/Makefile.in: @MAINT@ $(srcdir)/Makefile.tpl $(srcdir)/Makefile.def
cd $(srcdir) && $(AUTOGEN) Makefile.def
Listing 2.3-4: regeneration (Makefile.tpl:2136-2139).
configure replaces @MAINT@ with # unless you give it
--enable-maintainer-mode (configure.ac:4139-4147). The # turns the
prerequisites into a comment, so the rule never runs. The install manual
documents that option under Configuration, for "the build rules
that regenerate the Autoconf and Automake output files", and does not name this
rule.
A hand edit of Makefile.in does take effect, because the next rule rebuilds
Makefile from it through config.status
(Makefile.tpl:2141-2143). For a change that lasts, edit
Makefile.def or Makefile.tpl, run autogen Makefile.def in the source
directory, and commit the regenerated Makefile.in with your change.
@if gcc and @endif gcc: how configure prunes the Makefile
@if gcc and @endif gcc are not make syntax but markers for the top-level
configure. For a module that stays in the build, configure deletes the marker
lines and keeps the lines between them. For a module that it dropped from the
build, it deletes the lines between them too, so that module has no rules at all in your
Makefile.
configure deletes the markers while it writes its one output file,
AC_CONFIG_FILES([Makefile]), through three sed scripts
(configure.ac:4226-4234). It builds the scripts from its module
lists. Before that, it removes from those lists every module that
--enable-languages or the target excluded
(configure.ac:2716-2744), and every module whose source
directory is not in the tree (:2755-2782). For each host module
that is left, it adds these commands:
extrasub_host="$extrasub_host
/^@if $module\$/d
/^@endif $module\$/d
/^@unless $module\$/,/^@endunless $module\$/d
/^@if $module-$host_bootstrap_suffix\$/d
/^@endif $module-$host_bootstrap_suffix\$/d
/^@unless $module-$host_bootstrap_suffix\$/,/^@endunless $module-$host_bootstrap_suffix\$/d"
Listing 2.3-5: per-module commands for host modules
(configure.ac:3378-3384). The build and target lists get the
same commands at :3356-3362 and
:3400-3406.
Those commands handle the modules that are still in the build. One final sweep then removes every fence that is left, with the lines inside it:
# Do the final fixup along with target modules.
extrasub_target="$extrasub_target
/^@if /,/^@endif /d
/^@unless /d
/^@endunless /d"
Listing 2.3-6: the final sweep (configure.ac:3409-3413).
$bootstrap_suffix is bootstrap or no-bootstrap
(configure.ac:3180-3189). Bootstrap, which builds GCC with
itself three times, is on by default only when build, host and target are the
same (configure.ac:1532-1541). A cross build therefore
keeps the -no-bootstrap blocks and drops the per-stage rules, which
Chapter 2.5 covers.
The top-level configure does not configure the subdirectories. Each one is
configured by a configure-<module> rule, when make first needs it. The comment
in configure.ac says that configure removes their Makefiles "so that the
top-level Makefile reconfigures them, like we used to do when configure itself
was recursive" (configure.ac:3317-3321).
build_modules, host_modules, target_modules: directory, CC and --host
build_modules, host_modules and target_modules are the three lists in
Makefile.def, and every module is in one or more of them. The list that a
module is in decides how the top level builds and configures it, which is why a
target library is configured with the target as its host. In the abridged
records below, libiberty and libcpp appear twice, as build modules and as
host modules:
build_modules= { module= libiberty; };
...
build_modules= { module= libcpp;
extra_configure_flags='--disable-nls am_cv_func_iconv=no';};
...
host_modules= { module= gcc; bootstrap=true;
extra_make_flags="$(EXTRA_GCC_FLAGS)";
extra_configure_flags='@gcc_host_pie@'; };
...
host_modules= { module= libcpp; bootstrap=true; };
...
host_modules= { module= libiberty; bootstrap=true;
extra_configure_flags='@extra_host_libiberty_configure_flags@';};
...
target_modules = { module= libstdc++-v3;
bootstrap=true;
lib_path=src/.libs;
raw_cxx=true; };
...
target_modules = { module= newlib; };
target_modules = { module= libgcc; bootstrap=true; no_check=true;
missing=TAGS;
missing=install-dvi; };
Listing 2.3-7: the three lists, abridged (Makefile.def:27-185).
The build list is :27-34, the host list :36-167 and
the target list :169-212.
The list decides three things: the directory in the build tree, the compiler in
CC, and the --host that the module's own configure receives.
| List | Directory in the build tree | CC in its environment | Its configure gets |
|---|---|---|---|
build_modules | build-<build>/ | CC_FOR_BUILD | --host=<build> |
host_modules | the top of the build tree | CC | --host=<host> |
target_modules | <target>/ | CC_FOR_TARGET | --host=<target> |
The directories come from GCC_TOPLEV_SUBDIRS
(config/acx.m4:84-101). The host directory becomes host-<host>/
in a few cases, for example when you configure inside the source directory. The
compilers come from BUILD_EXPORTS, HOST_EXPORTS and BASE_TARGET_EXPORTS,
and the --host values from the template arguments
(Makefile.tpl:154-158, :199-201 and
:304-308 for the compilers,
:1343-1344, :1359 and
:1491 for --host).
To its own configure, a target library runs on the target, so the target is
its host. The generated rule for libgcc shows that --host, and it shows the
other step that every target module takes before it configures:
configure-target-libgcc:
@r=`${PWD_COMMAND}`; export r; \
...
$(CC_FOR_TARGET) --print-multi-lib > $(TARGET_SUBDIR)/libgcc/multilib.tmp 2> /dev/null; \
...
$(NORMAL_TARGET_EXPORTS) \
echo Configuring in $(TARGET_SUBDIR)/libgcc; \
...
$(TARGET_CONFIGARGS) --build=${build_alias} --host=${target_alias} \
--target=${target_alias} \
|| exit 1
Listing 2.3-8: configure-target-libgcc, abridged
(Makefile.in:49946-49979).
The rule runs the target compiler to get the multilib list. It reconfigures the
module when that list changes, so a change to the multilib variants of
Chapter 1.6 reaches every target library. It also means
that configure-target-libgcc cannot start until the target compiler exists.
The build copy of a module such as libcpp exists because a generator links it.
build/genmatch runs on the build machine during the build, and it links the
build machine's libcpp (gcc/Makefile.in:3324-3328,
:3336). The host copy is linked into cc1.
Chapter 2.4 covers the generators.
CC_FOR_TARGET: the xgcc that the build just made
CC_FOR_TARGET is the compiler that configures and builds every target library.
When build and host are the same and the tree builds gcc, it is the xgcc that
the build has made, with a -B that points into the compiler's own build
directory. That choice is why no target library can be configured before the
compiler is built. The value starts as one line of the top-level configure.ac:
GCC_TARGET_TOOL(cc, CC_FOR_TARGET, CC, [gcc/xgcc -B$$r/$(HOST_SUBDIR)/gcc/])
Listing 2.3-9: the in-tree default (configure.ac:4059).
The macro decides whether to use that default. Watch the first if, which
compares build with host, and the case on configdirs:
if test "x${build}" != "x${host}" ; then
if expr "x[$]$2" : "x/" > /dev/null; then
# We already found the complete path
ac_dir=`dirname [$]$2`
AC_MSG_RESULT(pre-installed in $ac_dir)
else
# Canadian cross, just use what we found
AC_MSG_RESULT(pre-installed)
fi
else
ifelse([$4],,,
[ok=yes
case " ${configdirs} " in
*" patsubst([$4], [/.*], []) "*) ;;
*) ok=no ;;
esac
...
if test $ok = yes; then
# An in-tree tool is available and we can use it
$2='$$r/$(HOST_SUBDIR)/$4'
AC_MSG_RESULT(just compiled)
Listing 2.3-10: GCC_TARGET_TOOL, abridged (config/acx.m4:553-577).
Read it with the three flavours of Chapter 1.2 in mind. A Canadian cross takes the first branch, and a native or a cross build takes the second:
- On a Canadian cross, build and host differ. The new
xgccruns on the host, so the build machine cannot run it. The macro keeps the target compiler thatconfigurefound installed (configure.ac:4031). - Otherwise,
patsubstcuts the default at its first/to getgcc. Ifgccis inconfigdirs, the value becomes$$r/$(HOST_SUBDIR)/gcc/xgcc -B$$r/$(HOST_SUBDIR)/gcc/, andconfigureprints "just compiled" for it.
$$r is the top of the build tree: each module recipe starts with
r=`${PWD_COMMAND}` (Listing 2.3-8). The top-level Makefile adds
$(STAGE_CC_WRAPPER) in front (Makefile.tpl:591). The
value then reaches each target module twice: as CC in the environment of its
configure (Makefile.tpl:308) and as CC= on its make command
line (Makefile.tpl:787).
The compiler's own directory, gcc/, gets a different variable.
EXTRA_GCC_FLAGS passes GCC_FOR_TARGET to its make
(Makefile.tpl:826-827), and gcc/Makefile.in uses it to run
the new xgcc, for example to dump specs. The comment above EXTRA_GCC_FLAGS
says "gcc builds a library, libgcc.a" (Makefile.tpl:820-822).
The comment is out of date: in GCC 15.2.0, libgcc is a target module
(Listing 2.3-7), and the quickstrap target in gcc/Makefile.in hands over to
the top-level all-target-libgcc (gcc/Makefile.in:2212-2215).
-B into gcc/: why libgcc copies its files back
The -B in CC_FOR_TARGET makes the new xgcc look for its own files in
gcc/, the compiler's directory in the build tree. The target libraries need
files from libgcc as well, and libgcc builds in a directory of its own, so it
copies its results back into gcc/. The libgcc edges that
lang_env_dependencies gives the target libraries wait for that copy.
The GCC manual documents -B under Directory Options, as the option
that says "where to find the executables, libraries, include files, and data
files of the compiler itself". Chapter 1.5 showed
that -B feeds the program, startfile and header search lists at once, so
-B$$r/gcc/ makes xgcc find its own cc1 and headers in the build directory.
gcc/Makefile.in also writes a specs file there, "to make -B./ read these
specs over installed ones" (gcc/Makefile.in:2441-2444).
The files that the target libraries need from libgcc include libgcc.a and
crtbegin.o, and libgcc builds them in <target>/libgcc/, not in gcc/. Its
all target copies them back:
all: all-multi
# Now that we have built all the objects, we need to copy
# them back to the GCC directory. Too many things (other
# in-tree libraries, and DejaGNU) know about the layout
# of the build tree, for now.
$(MAKE) install-leaf DESTDIR=$(gcc_objdir) \
slibdir= libsubdir= MULTIOSDIR=$(MULTIDIR)
Listing 2.3-11: libgcc installs into the compiler's build directory
(libgcc/Makefile.in:116-122). gcc_objdir is
../../gcc from the library's directory (:25).
After that step, every later xgcc -B$$r/gcc/ link finds libgcc without an
installed toolchain.
dependencies in Makefile.def: hard edges and soft maybe- edges
Each dependencies record in Makefile.def is one edge between two make
targets, and a record marked hard=true is a hard edge. A hard edge stops the
build when the module it names is missing, and a soft edge lets the build do
without it. Soft edges are what let one top level build both a combined tree,
with binutils beside GCC, and a GCC checkout alone. The records start at the
comment // Inter-module dependencies (Makefile.def:354),
and the compiler's own edges look like this:
dependencies = { module=all-gcc; on=all-libiberty; hard=true; };
...
dependencies = { module=all-gcc; on=all-build-libcpp; };
dependencies = { module=all-gcc; on=all-zlib; };
dependencies = { module=all-gcc; on=all-libbacktrace; hard=true; };
dependencies = { module=all-gcc; on=all-libcpp; hard=true; };
dependencies = { module=all-gcc; on=all-libcody; hard=true; };
dependencies = { module=all-gcc; on=all-libdecnumber; hard=true; };
Listing 2.3-12: edges into all-gcc, abridged (Makefile.def:378-394).
The edges into configure-gcc are at :367-377.
The template's comment defines the two kinds:
# There are two types of dependencies here: 'hard' dependencies, where one
# module simply won't build without the other; and 'soft' dependencies, where
# if the depended-on module is missing, the depending module will do without
# or find a substitute somewhere (perhaps installed). Soft dependencies
# are made here to depend on a 'maybe-' target. If you're not sure,
# it's safer to use a soft dependency.
Listing 2.3-13: hard and soft (Makefile.tpl:1933-1938).
The generated file has all-gcc: all-libcpp for the hard edge
(Makefile.in:68206) and all-gcc: maybe-all-zlib for a soft one
(:68186). A maybe- target is how a soft edge survives a missing
module:
.PHONY: all-gcc maybe-all-gcc
maybe-all-gcc:
@if gcc-bootstrap
all-gcc: stage_current
@endif gcc-bootstrap
@if gcc
TARGET-gcc=all
maybe-all-gcc: all-gcc
all-gcc: configure-gcc
Listing 2.3-14: maybe-all-gcc (Makefile.in:12432-12440),
expanded from the template at Makefile.tpl:1265-1275.
maybe-all-gcc always exists, with no recipe. Only inside @if gcc does it
gain a prerequisite on all-gcc. When configure prunes a module, its maybe-
target stays as an empty target, and a soft edge to it does nothing. A hard edge
names all-libcpp itself, so if libcpp is pruned, make has no rule for it
and stops.
A combined tree shows a soft edge at work. configure-gcc waits for all-gas
and all-ld (Makefile.def:374-375), and gcc's configure uses
../gas/as-new when it finds a configured gas beside it
(gcc/configure.ac:2697-2700). With binutils sources in the tree,
the compiler is configured against the assembler it will drive. Without them,
the edge is empty and configure looks for an installed assembler.
lang_env_dependencies: what every target library waits for
Target libraries get most of their edges from defaults in the template, and
lang_env_dependencies records adjust those defaults for one module at a time.
By default, a target library waits for the compiler, for libgcc, and for the C
library when it is in the tree. A record can exempt a module from the libgcc
edge or the C-library edge, or add an edge to libstdc++-v3. Together they fix the order in which the target libraries are configured. The comment above the records
states the defaults:
// Target modules. These can also have dependencies on the language
// environment (e.g. on libstdc++). By default target modules depend
// on libgcc and newlib/libgloss.
lang_env_dependencies = { module=libitm; cxx=true; };
lang_env_dependencies = { module=libffi; cxx=true; };
lang_env_dependencies = { module=newlib; no_c=true; };
lang_env_dependencies = { module=libgloss; no_c=true; };
lang_env_dependencies = { module=libgcc; no_gcc=true; no_c=true; };
// libiberty does not depend on newlib or libgloss because it must be
// built newlib on some targets (e.g. Cygwin). It still needs
// a dependency on libgcc for native targets to configure.
lang_env_dependencies = { module=libiberty; no_c=true; };
lang_env_dependencies = { module=libgcobol; cxx=true; };
Listing 2.3-15: lang_env_dependencies (Makefile.def:647-659).
In that comment, newlib is a C library, and libgloss is its companion
library of startup code and input/output support, with pieces for each board or
debug monitor (Chapter 3.4). The template
turns the flags into edges, here for a build that does not bootstrap:
@if gcc-no-bootstrap[+ FOR target_modules +][+ IF (not (lang-dep "no_gcc")) +]
configure-target-[+module+]: maybe-all-target-libgcc[+
ENDIF +][+ ENDFOR target_modules +]
@endif gcc-no-bootstrap
[+ FOR target_modules +][+ IF (not (lang-dep "no_c")) +]
configure-target-[+module+]: maybe-all-target-newlib maybe-all-target-libgloss[+
ENDIF +][+ IF (lang-dep "cxx") +]
configure-target-[+module+]: maybe-all-target-libstdc++-v3[+
ENDIF +]
[+ ENDFOR target_modules +]
Listing 2.3-16: the default edges between target modules
(Makefile.tpl:2108-2118).
Another loop, before the explicit edges in the template, gives every target
module an edge to the compiler: configure-target-<module>: maybe-all-gcc
(Makefile.tpl:1927-1930). Together, the loops give these
rules:
- Every target library waits for the compiler. No flag removes that edge.
- Every target library except
libgccwaits forlibgcc.no_gccis set only onlibgcc. - Every target library except
libgcc,newlibandlibglosswaits for the C library, if the C library is in the tree. libitm,libffiandlibgcobolalso wait forlibstdc++-v3.
newlib has no_c but not no_gcc, so it waits for libgcc. The generated
file has configure-target-newlib: maybe-all-target-libgcc
(Makefile.in:69375), so in a tree with newlib in it,
libgcc is built before newlib. Chapter 3.2
explains how libgcc builds before a C library exists, and
Chapter 3.6 covers what the top level hands to
both of them.
The edges land on configure-target-*, not on all-target-*, because a target
library's configure runs CC_FOR_TARGET (Listing 2.3-8). The compiler and its
runtime must exist before that step, not only before compilation. The other
edges between target modules are explicit records, for example
configure-target-libstdc++-v3 on configure-target-libgomp
(Makefile.def:675).
The libiberty record in Listing 2.3-15 does nothing, because libiberty is not
in target_modules. configure.ac says "Note that libiberty is not a target
library" (configure.ac:146-148).
all-host and all-target: the module graph of a cross build
all-host and all-target have no order between them, so the edges between
modules decide the whole order of a cross build. make with no target runs
all, and for a build that does not bootstrap, all asks for those two targets
(Makefile.tpl:876-877). The install manual's
Building a cross compiler section gives the resulting order in four
steps: host tools, binutils if they are in the tree, the compiler, and then the
run-time libraries.
In the graph, arrows point from what is built first to what waits for it. Watch
<target>/libgcc, which sits between the compiler and the C library:
build-<build>/libiberty --> build-<build>/libcpp ------------+ soft
libiberty --> libcpp ----------------------------------------+ hard
libdecnumber, libbacktrace, libcody -------------------------+ hard
fixincludes, lto-plugin, zlib -------------------------------+ soft
gmp, mpfr, mpc, isl, gas, ld (only if in the tree) ----------+ soft
|
v
gcc (xgcc, cc1, ...)
|
v
<target>/libgcc
|
v
<target>/newlib --> <target>/libgloss
(only if in the tree) |
v
<target>/libstdc++-v3, <target>/libgomp, ...
The host libraries come before the compiler that links them. Under make -j,
modules with no path between them can build at the same time.
Checking the build order: make all-gcc against make
The edges are in your build tree as soon as configure has run, so grep on
the generated Makefile checks the build order before anything is built. The
commands below configure an arm-none-eabi cross compiler, read two sets of
edges, and then build in the order that cross recipes use: make all-gcc,
make all-target-libgcc, then plain make.
Untested recipe. The results described below come from the source that the citations show. The commands were not run.
The commands assume a cross binutils for the target, with its as, ld, ar
and ranlib in $HOME/cross/arm-none-eabi/bin. The install manual's
Building a cross compiler section names that directory,
<prefix>/<target>/bin, for binutils that are not in the GCC source tree.
$ mkdir build && cd build
$ ../gcc/configure --target=arm-none-eabi --prefix=$HOME/cross \
--enable-languages=c,c++
$ grep -c '^@if ' Makefile # 0: Listing 2.3-6
$ grep -E '^(all-gcc|configure-target-libgcc):' Makefile
$ make -j8 all-gcc
$ make -j8 all-target-libgcc
$ make -j8
The grep -c line prints 0, because the final sweep of Listing 2.3-6 removes
every @if line. The grep -E line prints the edges into all-gcc, with
all-libcpp among the hard ones. For configure-target-libgcc it prints the
rule, which has no prerequisites of its own, and one edge, to maybe-all-gcc.
That edge comes from the gcc-no-bootstrap loop
(Makefile.tpl:1927-1930), which survives because a cross
build does not bootstrap.
make -n does not show the order, so read the edges with grep instead. GNU
make runs a recipe line that mentions $(MAKE) even under -n, and each module
rule does its cd and its $(MAKE) in one line
(Makefile.in:12441-12446). The configure-<module>
recipe before it is only printed. In a tree that is not built yet, make -n
therefore stops at the first cd into a directory that no configure created.
make all-gcc configures and builds the build modules and host modules that
all-gcc depends on, then gcc itself. It configures no target module, because
no edge in Listing 2.3-12 or in the records of
Makefile.def:366-413 names one. The host modules that do wait
for target libraries are gnattools and gotools
(Makefile.def:417-418, :430), and all-gcc
does not depend on them.
make all-target-libgcc follows Listing 2.3-8. It runs all-gcc again through
maybe-all-gcc, then runs xgcc --print-multi-lib, configures
arm-none-eabi/libgcc with --host=arm-none-eabi, builds it, and copies it back
into gcc/ (Listing 2.3-11).
Plain make then reaches every remaining target module, libstdc++-v3 among
them, and what those modules need from a C library is Part III's subject. The
split between the first two commands and the third is what Part III's stage 1
compilers rest on. A stage 1 compiler is the first GCC build of a cross recipe. It starts with
make all-gcc, before any C library exists, and it is not the stage1 of a
native bootstrap.
Chapter 3.1 explains why a cross
toolchain needs the split.
gcc/Makefile.in is written by hand, not by Automake
gcc/Makefile.in is written by hand, like the Makefile.in of several library
directories, while others, such as libstdc++-v3, generate theirs with
Automake. With AutoGen at the top level, a GCC tree therefore has three ways to
make a Makefile.in. The way a directory uses decides what you edit to
change its build.
The gcc/ directory has no Makefile.am (the gcc/ tree), and its
Makefile.in starts like a file that a person wrote:
# Makefile for GNU Compiler Collection
# Run 'configure' to generate Makefile from Makefile.in
Listing 2.3-17: the head of gcc/Makefile.in
(gcc/Makefile.in:1-2).
A runtime library that uses Automake starts with a line that names its source:
# Makefile.in generated by automake 1.15.1 from Makefile.am.
Listing 2.3-18: the head of libstdc++-v3/Makefile.in
(libstdc++-v3/Makefile.in:1).
The table sorts the directories by the way they get their Makefile.in:
| Where | How its Makefile.in is made |
|---|---|
| top level | AutoGen, from Makefile.def and Makefile.tpl |
gcc/, libgcc/, libcpp/, libiberty/, libdecnumber/, libobjc/, libcody/ | by hand |
libstdc++-v3/, libgomp/, libbacktrace/, libquadmath/, lto-plugin/, zlib/ | Automake 1.15.1, from Makefile.am |
The hand-written rows are the directories with no Makefile.am in GCC 15.2.0,
and the Automake rows each start with the line in Listing 2.3-18. In all three
cases, the directory's own configure turns Makefile.in into Makefile, and
only the way Makefile.in itself is made differs.
If you change a hand-written Makefile.in, you edit it. If you change an
Automake one, you edit Makefile.am and run automake. The install manual's
Prerequisites page gives these two rules, with a list of the
hand-written directories that is out of date in GCC 15.2.0. If you change the top
level, you edit Makefile.def or Makefile.tpl and run autogen.
Three things to carry away
The top-level build order is in Makefile.def, not in a Makefile. AutoGen
expands it into Makefile.in, and a hand edit of that file lasts only until the
next autogen run.
configure deletes the modules you do not build, and make configures the
rest. The @if module fences go, a soft maybe- edge to a missing module
becomes empty, and each subdirectory is configured by a configure-<module> rule.
Every target library waits for xgcc, and all but libgcc wait for libgcc.
CC_FOR_TARGET is xgcc -B$$r/gcc/, and libgcc copies itself into gcc/ so
that the later libraries can link.
Things that surprise people
A target library's configure gets --host=<target>. The command line is
at the top of <target>/libgcc/config.log
(libgcc/configure:1806-1813).
make all-gcc gives you a compiler without libgcc. Nothing in its graph
names a target module. Add make all-target-libgcc when you need it.
Editing Makefile.def in a build tree changes nothing. The regeneration rule
is commented out unless you configured with --enable-maintainer-mode.
newlib waits for libgcc, not the other way round. Only libgcc,
newlib and libgloss are exempt from the C-library edge, and only libgcc is
exempt from the libgcc edge.
Documentation coverage
The install manual's Prerequisites page says that AutoGen and Guile
are "Necessary to regenerate the top level Makefile.in file from Makefile.tpl and
Makefile.def" (gcc/doc/install.texi:584-593). The same page says which
directories do not use Automake (install.texi:549-557). The
Building a cross compiler section lists the order that make
follows, in four steps (install.texi:3247-3277). The internals manual's
Makefile Targets node (gcc/doc/makefile.texi:81-84)
says that the top level is "a complex Makefile that coordinates the various steps
of the build".
What is not documented:
- What
Makefile.defcontains, and that it holds the build order. The manuals name the file only as AutoGen input, and in one line for front-end check targets (gcc/doc/sourcebuild.texi:562-564). - The
@if/@endiffences and thesedpass inconfigurethat removes them. hardand soft edges, and themaybe-targets. Only the comment in Listing 2.3-13 explains them.- The default edges between target modules (
lang_env_dependencies), and thatnewlibwaits forlibgcc. - That
CC_FOR_TARGETisxgcc -Binto the build tree, and thatlibgcccopies its results intogcc/for the later libraries. make all-gccandmake all-target-libgcc. No manual in thegcc/doc/of GCC 15.2.0 names either target.- That
--enable-maintainer-modealso turns on the AutoGen rule. The option's entry names only Autoconf, Automake andgcc.pot(install.texi:1932-1939).
Two documented statements are out of date in GCC 15.2.0:
- The Automake list in
install.texi:554-557namesintl. That directory is inreleases/gcc-13.1.0and absent fromreleases/gcc-14.1.0. The list also omitslibgcc,libdecnumberandlibcody, which have hand-writtenMakefile.infiles too. - The internals manual's Top Level node says that the top-level
build system "is documented in a separate manual, included with GNU Binutils"
(
gcc/doc/sourcebuild.texi:157-160), and names no manual.
Next: Chapter 2.4, Generated sources in build/gcc/: options.cc, tm.h and
insn-*, the files that make writes into gcc/
and that no checkout contains, from insn-recog.cc to options.h, and the
generator that writes each.
2.4 Generated sources in build/gcc/: options.cc, tm.h and insn-*
GCC 15.2.0. To run the commands: a GCC build tree, configured and built.
Chapter 1.3 quoted case OPT_dumpspecs: from gcc/gcc.cc, and Chapter 1.4
quoted OPT_SPECIAL_input_file. Search a GCC checkout for the line that defines
either name, and you find only the places that use it. The same happens with
flag_rtti, which the C++ front end tests, with insn-recog.cc, which GCC 14
and earlier generate, and with the text that gcc -v prints after
Configured with:. All of them are in files that the build writes, and none of
them is in git.
The gcc subdirectory of a build tree, written build/gcc/ in this chapter,
holds a second set of sources. configure, shell and awk scripts, and programs
compiled for the build machine write it, and gcc/Makefile.in has one rule for
each file. When you cannot find a name in the checkout, find the rule, then read
the input of its generator.
This chapter assumes Chapter 1.2, for the build
machine, the Canadian cross and the uninstalled xgcc, and
Chapter 1.3, for the spec table, -dumpspecs and the
libgcc spec. It uses specs.h and the driver's option table from
Chapter 1.4, multilib.h from
Chapter 1.6 and gcc -v from
Chapter 1.14. From Part II, it uses
config.gcc as Chapter 2.1 describes it, the file
that selects the target headers, tm_defines and the machine description for
your triple. It also uses --enable-languages and the sub-configure runs of
Chapter 2.2, and the top-level makefile
of Chapter 2.3.
generated_files: built before the first host object
Most of the generated headers are in one variable of gcc/Makefile.in,
generated_files, and make writes every file in it before it compiles any host
object of the compiler. A broken generator for one of those files therefore
stops the build of gcc/ before the first host object compiles. Listing 2.4-1
is the list:
generated_files = config.h tm.h $(TM_P_H) $(TM_D_H) $(TM_H) multilib.h \
$(simple_generated_h) specs.h \
tree-check.h genrtl.h insn-modes.h insn-modes-inline.h \
tm-preds.h tm-constrs.h \
$(ALL_GTFILES_H) gtype-desc.cc gtype-desc.h version.h \
options.h target-hooks-def.h insn-opinit.h \
common/common-target-hooks-def.h pass-instances.def \
$(GIMPLE_MATCH_PD_SEQ_SRC) $(GENERIC_MATCH_PD_SEQ_SRC) \
gimple-match-auto.h generic-match-auto.h \
c-family/c-target-hooks-def.h d/d-target-hooks-def.h \
$(TM_RUST_H) rust/rust-target-hooks-def.h \
case-cfn-macros.h \
cfn-operators.pd omp-device-properties.h
Listing 2.4-1: generated_files (gcc/Makefile.in:3140-3152).
Every object of the compiler waits for that list, and the comment above the rule gives the reason:
# In order for parallel make to really start compiling the expensive
# objects from $(OBJS) as early as possible, build all their
# prerequisites strictly before all objects.
$(ALL_HOST_OBJS) : | $(generated_files)
Listing 2.4-2: generation before compilation (gcc/Makefile.in:4823-4826).
The | makes the list an order-only prerequisite, so no host object compiles
until every file in the list exists. A newer generated header does not by itself
force a rebuild through this rule, because the real header dependencies come
from the .Po files that the next lines include
(Makefile.in:4828-4832). The generated .cc files, such as
insn-attrtab.cc, are not in the list: make runs their generators when it
needs the objects.
Producers of build/gcc/ files: configure, scripts and build/gen*
A small number of producers write the files in build/gcc/: configure, the
script mkconfig.sh, shell commands and awk scripts in the makefile, and
programs that the build compiles and runs. The table gives each producer's
input, which is the file in the checkout to read when a generated name is
missing from it:
Files in build/gcc/ | Producer | Input |
|---|---|---|
auto-host.h, configargs.h | configure | config.in, the configure command line |
config.h, bconfig.h, tm.h, tm_p.h | mkconfig.sh | header lists from config.gcc |
specs.h, multilib.h | shell commands in Makefile.in | lang-specs.h files, MULTILIB_* variables |
optionlist, options.h, options.cc | awk scripts | every .opt file |
insn-*.h, insn-*.cc | build/gen* | the machine description |
insn-modes.h, insn-modes.cc | build/genmodes | machmode.def and the target's modes file |
gtype-desc.cc, gt-*.h | build/gengtype | GTY markers in the sources |
specs | xgcc -dumpspecs | the driver that the build just linked |
Chapter 1.4 showed specs.h (Makefile.in:2619-2625) and Chapter 1.6
showed multilib.h. The checkout's gcc/ directory has config.in,
the .opt files, the awk scripts and the generators' sources, but none of their
outputs.
build/gen* and GENERATOR_FILE: generators for the build machine
The gen* programs are C++ sources in gcc/ that the build compiles for the
build machine, because they must run on the machine that does the build. In
the Canadian cross of Chapter 1.2, they run on the build machine, and the cc1 that they help to make
runs on the host. A comment in gcc/Makefile.in states the rule:
# Compile the programs that generate insn-* from the machine description.
# They are compiled with $(COMPILER_FOR_BUILD), and associated libraries,
# since they need to run on this machine
# even if GCC is being compiled to run on some other machine.
Listing 2.4-3: why the generators use the build compiler
(gcc/Makefile.in:3296-3299).
COMPILER_FOR_BUILD is CXX_FOR_BUILD (Makefile.in:863).
The generic rule puts the objects under build/ (:3155-3159), so the
programs are build/gcc/build/gencodes, build/gcc/build/genrecog and so on.
The generators' flags add -DGENERATOR_FILE (Makefile.in:860),
and a generator includes bconfig.h, the build machine's configuration header
(gencodes.cc:23). The host's config.h stops a generator
that includes it by mistake: mkconfig.sh writes #error config.h is for the host, not build, machine. into it under GENERATOR_FILE
(mkconfig.sh:43-49).
s-* stamp files: move-if-change and ; @true
Most generator rules write to a temporary file, replace the real output only
when its text has changed, and record the run in an s-* stamp file. The stamp
idiom decides how much a regeneration recompiles, and which file to delete when
you want one generator to run again. A comment in gcc/Makefile.in works
through the problem with tree-check.h as its example, and ends with the form
that the makefile uses:
# The problem with this solution is that make thinks that tree-check.h is
# always unchanged. Make must be deceived into thinking that tree-check.h is
# rebuild by the "tree-check.h: s-check" rule. To do this, add a dummy command:
# tree-check.h: s-check; @true
# s-check : build/gencheck$(build_exeext)
# $(RUN_GEN) build/gencheck$(build_exeext) > tmp-check.h
# $(SHELL) $(srcdir)/../move-if-change tmp-check.h tree-check.h
# $(STAMP) s-check
#
# This is what is done in this makefile. Note that mkconfig.sh has a
# move-if-change built-in
Listing 2.4-4: the stamp idiom (gcc/Makefile.in:2060-2070). The
whole comment starts at :2036.
Read the rule from the bottom:
- The generator writes a temporary file,
tmp-check.h. move-if-changereplacestree-check.honly if the new text is different. If the text is the same, the old file keeps its old timestamp.$(STAMP) s-checkwrites the stamp.STAMPisecho timestamp >(Makefile.in:365). The stamp records that the generator ran.- The
; @truerecipe tells make that the rule fortree-check.hran, so make reads the timestamp oftree-check.hagain.
A change to the machine description therefore runs every generator that reads
it. Only the outputs with new text get a new timestamp, so only the objects that
include those outputs compile again. To make one generator run again, delete its
stamp, for example build/gcc/s-options, and run make.
mkconfig.sh does the same comparison with cmp and writes its own stamp,
cs-tm.h for tm.h (mkconfig.sh:115-125). The rule for
options.cc has no stamp of its own: it writes straight to its target
(Makefile.in:2634-2638), and the stamp s-options belongs to
its input, optionlist.
options.cc and options.h: awk over every .opt file
options.cc and options.h are the output of three awk scripts that read every
.opt file in the build. They define OPT_dumpspecs, flag_rtti and the other
option names that a grep of the checkout cannot find, so the source to read is
the .opt record behind each name.
The inputs are common.opt, c-family/c.opt, params.opt and
analyzer/analyzer.opt on every build (Makefile.in:632), the
lang.opt of each front end, and the target's files (:1287).
config.gcc adds config/<cpu>/<cpu>.opt when that file exists
(config.gcc:629-631). Three awk steps turn the files into C++:
opt-gather.awkreads all the files and writes one sorted list,optionlist, behind the stamps-options(Makefile.in:2627-2632).optc-gen.awkwritesoptions.cc, the option table that the driver andcc1search, fromoptionlist(Makefile.in:2634-2638).opth-gen.awkwritesoptions.h, with theOPT_codes and the option variables (Makefile.in:2652-2659).
One record from c-family/c.opt shows the input:
frtti
C++ ObjC++ Optimization Var(flag_rtti) Init(1)
Generate run time type descriptor information.
Listing 2.4-5: the record for -frtti
(gcc/c-family/c.opt:2296-2298).
A record is a name, a line of properties and a line of help text, and two parts
of it make names that the checkout never defines. The record name becomes the
enumerator OPT_frtti: opt_enum adds OPT_ in front and changes each
character that is not a letter or a digit to _
(opt-functions.awk:355-365). Var(flag_rtti) becomes a structure
field and a macro:
var_seen[name] = 1;
print "#ifdef GENERATOR_FILE"
print "extern " var_type(flags[i]) name ";"
print "#else"
print " " var_type(flags[i]) "x_" name ";"
print "#define " name " global_options.x_" name
print "#endif"
Listing 2.4-6: how Var() becomes a macro
(gcc/opth-gen.awk:88-94).
flag_rtti is therefore a macro for global_options.x_flag_rtti. When
c-cppbuiltin.cc tests it to define __GXX_RTTI
(c-cppbuiltin.cc:941-944), it reads a field of a structure that
options.h declares.
OPT_dumpspecs comes from a two-line record in common.opt, the name
dumpspecs and the property Driver (common.opt:964-965).
OPT_SPECIAL_input_file and the other four OPT_SPECIAL_ codes after the real
options come from print statements in the script itself
(opth-gen.awk:570-575). To find the variable behind an option,
grep the .opt files for its record, because a grep of the .cc files for a
declaration finds nothing.
Every front end's lang.opt, whatever --enable-languages says
configure adds the lang.opt of each front end it reads to the option table,
whatever --enable-languages says, but adds a front end's lang-specs.h only
when you build that language. A compiler built from a full checkout with
--enable-languages=c therefore has the C++, Fortran and Ada options in its
option table. This is why the driver in
Chapter 1.4 can accept an option for a
language that it cannot compile.
The install manual documents --enable-languages under
Configuration as the subset of compilers and runtime
libraries to build. In configure, the language list gates lang-specs.h
(configure.ac:7321-7327), but lang.opt goes in for every front
end whose config-lang.in it reads (:7364-7367). A front end that
is not in the list is skipped only when a directory that the front end requires
is missing (configure.ac:7344-7355).
tm.h and tm_p.h: mkconfig.sh writes #include lines
tm.h has almost no text of its own, because mkconfig.sh writes it as guarded
#define lines and a list of #include lines. Reading it is the quickest way to
see which target headers config.gcc chose for your triple, and in what order.
The rule cs-tm.h runs the script with two lists from configure: HEADERS,
the include list, and DEFINES, the tm_defines from config.gcc
(Makefile.in:2101-2107). In Listing 2.4-7, the for def loop writes
the defines and the IN_GCC block writes the includes:
# Provide defines for other macros set in config.gcc for this file.
for def in $DEFINES; do
echo "#ifndef $def" | sed 's/=.*//' >> ${output}T
echo "# define $def" | sed 's/=/ /' >> ${output}T
echo "#endif" >> ${output}T
done
...
if [ $# -ge 1 ]; then
echo '#ifdef IN_GCC' >> ${output}T
for file in "$@"; do
if test x"$file" = x"defaults.h"; then
postpone_defaults_h="yes"
else
echo "# include \"$file\"" >> ${output}T
fi
done
echo '#endif' >> ${output}T
fi
Listing 2.4-7: mkconfig.sh, abridged (gcc/mkconfig.sh:57-62
and :77-87).
configure makes the include list. It starts with options.h and
insn-constants.h, then adds each file in tm_file under config/
(configure.ac:2419-2437). Before that, it appends
defaults.h to tm_file (:2209), and mkconfig.sh holds that
one back and writes it after insn-flags.h and insn-modes.h
(mkconfig.sh:90-110). tm.h is therefore a guard,
TARGET_CPU_DEFAULT when the target sets one, the tm_defines, options.h and
insn-constants.h, the target headers in the order that config.gcc gave, and
defaults.h last. To see that list for your triple, print the file:
$ cat build/gcc/tm.h
The order of the #include lines matters, because a later header can #undef
and redefine a macro from an earlier one. gnu-user.h does that to
LINK_GCC_C_SEQUENCE_SPEC, for example (gnu-user.h:116-117).
tm_p.h is the same for prototypes. Its list is the target's -protos.h files
and the generated tm-preds.h (configure.ac:2210 and
:2439-2451). config.h, bconfig.h and tconfig.h come from the
same script, with the lists for the host, the build machine and the target
(Makefile.in:2086-2099).
-dumpspecs text from tm.h, auto-host.h and DRIVER_DEFINES
The spec text that -dumpspecs prints is fixed when gcc.o compiles, by target
macros from the headers that tm.h names and by configure results in
auto-host.h. A third route, DRIVER_DEFINES, reaches gcc.o through no file
at all. Because configure tested the linker that you had when you built GCC,
the linker options in the spec do not change if you install a different binutils
later.
gcc.cc includes multilib.h and then tm.h (gcc.cc:37-38).
It fills its spec slots from macros, with link_spec = LINK_SPEC,
lib_spec = LIB_SPEC and startfile_spec = STARTFILE_SPEC
(gcc.cc:1214-1219), and the target headers in tm.h define
those macros.
Some of that text also depends on what configure found when it tested your
tools. configure writes its findings to auto-host.h, from the template
config.in, which is in the repository (configure.ac:29), and
make updates the header through config.status
(Makefile.in:2183-2187). The --as-needed in the libgcc spec of
Chapter 1.3 shows the full path from a configure test to a spec:
configurestarts with--as-neededand--no-as-needed(configure.ac:6560-6564). For a linker that is not built in the same tree, it runs the linker with--helpand searches the output foras-needed. If the linker is GNU ld 2.28 or later and also listspush-stateandpop-state, the two options become--push-state --as-neededand--pop-state(:6574-6587).- It defines
HAVE_LD_AS_NEEDED,LD_AS_NEEDED_OPTIONandLD_NO_AS_NEEDED_OPTION(:6617-6624).config.inhas an#undefline for each of them, andconfig.statuswrites the values intoauto-host.h(config.in:1727-1729,:2380and:2398). - On GNU/Linux targets,
gnu-user.h, one of the headers intm.h, turns the configure result into a target decision. Listing 2.4-8 shows the four lines. init_gcc_specsputsLD_AS_NEEDED_OPTIONbetween the static and the shared libgcc when the target definesUSE_LD_AS_NEEDED(gcc.cc:1811-1829).
/* Use --as-needed -lgcc_s for eh support. */
#ifdef HAVE_LD_AS_NEEDED
#define USE_LD_AS_NEEDED 1
#endif
Listing 2.4-8: USE_LD_AS_NEEDED
(gcc/config/gnu-user.h:119-122).
Chapter 1.3 gave the libgcc spec as "roughly" --as-needed -lgcc_s --no-as-needed. The exact options in your -dumpspecs output are the ones that
configure chose when it ran your linker with --help.
DRIVER_DEFINES, the route with no file, gives gcc.o the install prefixes,
DEFAULT_TARGET_MACHINE, ENABLE_SHARED_LIBGCC and CONFIGURE_SPECS as -D
options on its compile command (Makefile.in:2599-2616). The
--with-specs text of Listing 1.3-15 reaches the driver this way, so no
generated file holds it. Like the --with-cpu default below, it changes the
command line, so -dumpspecs does not show it.
specs: the generated file that -dumpspecs writes
The build does not make the driver from the specs file in build/gcc/: it
makes specs from the driver, with xgcc -dumpspecs. A specs file can
override the table compiled into a driver, so it matters which specs file the
build-tree driver reads and what make install does with it. Listing 2.4-9 is
the rule that writes the file:
# Dump a specs file to make -B./ read these specs over installed ones.
$(SPECS): xgcc$(exeext)
$(GCC_FOR_TARGET) -dumpspecs > tmp-specs
mv tmp-specs $(SPECS)
Listing 2.4-9: specs (gcc/Makefile.in:2441-2444).
The GCC manual documents -dumpspecs under Developer Options, and
says that "This is used when GCC itself is being built". Listing 2.4-9 is that
use, and its GCC_FOR_TARGET is ./xgcc -B./ (Makefile.in:496).
The driver reads a file named specs from the first startfile prefix that has
one (gcc.cc:8496-8501), and -B./, which the GCC manual
documents under Directory Options, puts the build directory first.
The driver in the build tree therefore reads its own dump, and not a specs file
that an older installation left in the install directory. The comment in
Listing 2.4-9 gives this as the rule's purpose.
-dumpspecs itself never reads a specs file. The driver handles the option in
process_command, which set_up_specs calls (gcc.cc:8481)
before it looks for the file. The dump that wrote specs and a new dump from the
same driver therefore print the same compiled-in table, and this cmp should
report no difference:
$ cd build/gcc
$ ./xgcc -B./ -dumpspecs | cmp - specs
make install does not copy specs into the installation, and it deletes any
old copy there. A specs file that the ls from Chapter 1.3 finds next to an
installed libgcc.a was therefore put there by something other than
make install. The comment in the install-common rule gives the reasons:
# We no longer install the specs file because its presence makes the
# driver slower, and because people who need it can recreate it by
# using -dumpspecs. We remove any old version because it would
# otherwise override the specs built into the driver.
rm -f $(DESTDIR)$(libsubdir)/specs
Listing 2.4-10: install-common deletes specs
(gcc/Makefile.in:4141-4145).
configargs.h: the line that gcc -v prints
configargs.h holds the configure command line that gcc -v prints after
Configured with:, and the thread model that it can print after
Thread model:. The way configure writes the header explains the
(reconfigured) that the line can contain, and the header also carries the
--with-cpu and --with-arch defaults to the driver. configure writes it
itself, with a here-document:
cat > configargs.h <<EOF
/* Generated automatically. */
static const char configuration_arguments[] = "$gcc_config_arguments_str";
static const char thread_model[] = "$thread_file";
static const struct {
const char *name, *value;
} configure_default_options[] = $configure_default_options;
EOF
Listing 2.4-11: configargs.h (gcc/configure.ac:2242-2250).
configuration_arguments is the command line of the top-level configure,
which collects it in TOPLEVEL_CONFIGURE_ARGUMENTS. The list starts with $0,
the path you typed to run the script, and each argument that has a shell
metacharacter gets quotes (configure.ac:38 and
:44-63). The top-level makefile exports the variable to each
sub-configure (Makefile.tpl:242).
The driver prints the string after Configured with:
(gcc.cc:7710), and prints thread_model after
Thread model: unless the target defines THREAD_MODEL_SPEC
(:7712-7724). To compare the header with what the driver
prints, run:
$ grep configuration_arguments build/gcc/configargs.h
$ build/gcc/xgcc -v 2>&1 | grep '^Configured with'
The two lines carry the same string, because gcc.cc includes configargs.h
(gcc.cc:225) and prints the array that it declares. If
configargs.h already exists, configure keeps the old string and appends
: (reconfigured) and the new arguments
(configure.ac:2223-2232). The comparison on line 2227 only
stops configure from adding the same arguments twice in a row.
You do not have to run configure by hand for the string to grow. When
gcc/configure or gcc/config.gcc is newer than build/gcc/config.status, for
example after a git pull, make runs config.status --recheck, which runs
configure again (Makefile.in:2200-2206).
configure_default_options holds the --with-cpu, --with-arch and similar
values, which the install manual documents under
Configuration as the defaults for -mcpu=, -march=
and the like. config.gcc checks each one against the options the target
supports and writes the initializer (config.gcc:6114-6144).
The driver reads the array in do_option_spec, which puts each value into the
target's OPTION_DEFAULT_SPECS and applies the result as a self spec
(gcc.cc:5877-5920).
On AArch64, --with-cpu=X becomes -mcpu=X unless you give -march or -mcpu
(aarch64.h:1499-1507). Like --with-specs in
Chapter 1.3, the default changes the command line, so -dumpspecs does not show
it. The cc1 line of -### shows the added -mcpu=, because cc1_options
passes %{m*} (gcc.cc:1288).
insn-* files: generators that read the machine description
The largest group of files in build/gcc/ comes from the machine description,
and most of them follow one naming rule: build/genX writes insn-X. When an
insn- file is missing from the checkout, the rule names the generator to read.
md_file, the description that the generators read, is common.md and
config/<cpu>/<cpu>.md, unless config.gcc names another file
(Makefile.in:608 and configure.ac:1943-1944).
configure prints the choice as it runs: Using `.../config/aarch64/aarch64.md' as machine description file. (configure.ac:1964). Most outputs
get their names from one pair of static pattern rules:
$(simple_generated_c): insn-%.cc: s-%; @true
$(simple_generated_c:insn-%.cc=s-%): s-%: build/gen%$(build_exeext)
$(RUN_GEN) build/gen$*$(build_exeext) $(md_file) \
$(filter insn-conditions.md,$^) > tmp-$*.cc
$(SHELL) $(srcdir)/../move-if-change tmp-$*.cc insn-$*.cc
$(STAMP) s-$*
Listing 2.4-12: one generator, one output, one stamp
(gcc/Makefile.in:2748-2753). The comment above the rules is at
:2716-2721.
The headers follow the same pattern, so gencodes writes insn-codes.h,
genflags writes insn-flags.h and genconfig writes insn-config.h
(Makefile.in:2723-2746). The generators that write more than one
file have their own rules: genattrtab writes insn-attrtab.cc,
insn-dfatab.cc and insn-latencytab.cc (:2787-2796), and
genopinit writes insn-opinit.cc and insn-opinit.h (:2798-2805).
What each generator reads in the .md file, and how its output becomes an
instruction, is the subject of Chapter 5.6.
insn-recog.cc and insn-emit.cc do not exist in GCC 15.2
In GCC 15.2, genrecog and genemit split their output into numbered files, so
a build tree has no insn-recog.cc and no insn-emit.cc to search. The file
names changed in GCC 12, 14 and 15, and the table gives the names that each
release uses:
| Output | GCC 11 | GCC 12, 13 | GCC 14 | GCC 15 |
|---|---|---|---|---|
| recogniser | insn-recog.c | insn-recog.cc | insn-recog.cc | insn-recog-1.cc … insn-recog-10.cc, insn-recog.h |
| emitters | insn-emit.c | insn-emit.cc | insn-emit-1.cc … insn-emit-10.cc | insn-emit-1.cc … insn-emit-10.cc |
| options | options.c | options.cc | options.cc | options.cc |
The .c to .cc change in GCC 12 applied to generated names too, so a note that
names insn-recog.c is from GCC 11 or earlier. The sources for the table are
lines of gcc/Makefile.in at five tags:
releases/gcc-11.4.0: lines 2395-2397 and 2306.releases/gcc-12.1.0: lines 2415-2417 and 2332.releases/gcc-13.3.0: lines 2447-2449 and 2363.releases/gcc-14.1.0: line 242 and lines 2545-2547.releases/gcc-15.2.0: lines 235-246, 2755-2764 and 2766-2776.
The number of files is --with-insnemit-partitions, with a default of 10
(configure.ac:933-943). The numbers come from
one_to_9999, which starts at 1 (Makefile.in:217-225), so
the files are insn-emit-1.cc to insn-emit-10.cc, although the comment above
the genemit rule says tmp-emit-01.cc. match.pd is split the same way into
gimple-match-N.cc and generic-match-N.cc, under
--with-matchpd-partitions (Makefile.in:227-233).
genmodes and gengtype: generators that do not read the .md file
genmodes and gengtype write insn-modes.cc and gtype-desc.cc from inputs
other than the .md file. The mode files carry the insn- prefix but come from
a .def file that genmodes includes when it is compiled, so build/genmodes
is a different program for each target.
genmodes writes insn-modes.cc, insn-modes.h, insn-modes-inline.h and
min-insn-modes.cc (Makefile.in:2831-2855). It reads no input file
at run time: create_modes includes machmode.def at compile time
(genmodes.cc:833-835), and machmode.def includes the
target's EXTRA_MODES_FILE (machmode.def:261-264).
config.gcc sets that file to config/<cpu>/<cpu>-modes.def when it exists
(config.gcc:624-628).
gengtype reads the GTY markers in the files listed in GTFILES. It writes
gtype-desc.cc, gtype-desc.h, one gt-*.h per source file and a state file,
gtype.state (Makefile.in:3117 and
:3128-3138).
Three things to carry away
A GCC name that the checkout uses but never defines is usually in a file under
build/gcc/. Find the rule in gcc/Makefile.in, then read the generator's
input: an .opt record, a target header list or the .md file.
An s-* stamp records that a generator ran. move-if-change keeps the
output's timestamp when its text is the same, so a regeneration recompiles only
what changed.
The build fixed what gcc -v and gcc -dumpspecs print.
configargs.h holds the configure line, and tm.h and auto-host.h hold the
spec text and what configure found in your linker.
Things that surprise people
make install deletes specs. The build-tree specs file is
xgcc -dumpspecs output. An installed one came from somewhere else.
gcc -v can print (reconfigured). A second run of gcc/configure in the
same build directory keeps the old arguments and appends the new ones after
: (reconfigured). make can start that run without you.
-dumpspecs ignores a specs file. It prints the table compiled into the
driver, before the driver looks for the file.
Documentation coverage
The internals manual describes some of these files:
- Configuration Files (
gcc/doc/configfiles.texi:5) listsauto-host.h,configargs.h,config.h,bconfig.h,tconfig.handtm_p.h, and says thatmkconfig.shwrites the configuration headers. It does not listtm.h. It says that these headers "also contain the typedefs forrtx,rtvecandtree" (configfiles.texi:48-49), but in GCC 15.2.0mkconfig.shwrites no typedefs. - Target Macros (
gcc/doc/tm.texi:17-19) says that "tm.hshould be a link tomachine.h" and that "config.hincludestm.h". In GCC 15.2.0,tm.his a generated list of#includelines, andconfig.hholds the host headers only (configure.ac:2494-2511).gcc.ccincludestm.hitself. - Option file format (
gcc/doc/options.texi:19) documents the.optrecords and their properties. - RTL passes (
gcc/doc/passes.texi:890-892) namesinsn-emit.ccas the output ofgenemit. GCC 15.2 has no file with that name. RTL is the representation in whichcc1describes the target's instructions, and Chapter 5.1 introduces it. - Files (
gcc/doc/gty.texi:644) documentsgtype-desc.ccand thegt-*.hheaders. - Configuration (
gcc/doc/sourcebuild.texi:240-245) says that Autoheader makesconfig.infromconfigure.acandacconfig.h. GCC 15.2.0 has nogcc/acconfig.h. - Build (
gcc/doc/sourcebuild.texi:303-309) is a FIXME: "describe the build system, including what is built in what stages".
The install manual's Configuration page describes
--enable-generated-files-in-srcdir (gcc/doc/install.texi:1955-1967). It says
that Bison and flex output and the manuals are not in the repository. It does
not mention the generated files in build/gcc/.
What is not documented:
- That the
gcc/build directory holds files that are not in the repository at all. No manual tells a newcomer to look inbuild/gcc/foroptions.horinsn-codes.h. - The stamp idiom. Its only description is the comment in
gcc/Makefile.in. - That every front end's
lang.optgoes into the option table, whatever--enable-languagessays. - That the build-tree
specsfile is-dumpspecsoutput, and thatmake installdeletesspecs. The-dumpspecsentry says only that the option "is used when GCC itself is being built" (invoke.texi:21668-21670). - The numbered
insn-emit-N.ccandinsn-recog-N.ccfiles, and the configure options--with-insnemit-partitionsand--with-matchpd-partitions. - That a second run of
gcc/configure, including the one thatconfig.status --recheckstarts, appends to the string thatgcc -vprints.
Next: Chapter 2.5, make bootstrap: the three-stage native
build, why a native make compiles the
compiler three times, and what make compare checks between the last two.
2.5 make bootstrap: the three-stage native build
GCC 15.2.0. To run the commands: a GCC checkout, and an installed native compiler to build it with.
You configure GCC for the machine you are on and type make. Some hours later
one of two things happens. The build stops with Bootstrap comparison failure!
and a list of object files (Makefile.in:65455-65458). Or the
build succeeds, and the build directory holds stage1-gcc, prev-gcc and
gcc, but no stage2-gcc and no stage3-gcc.
Both outcomes come from one piece of machinery. A native make builds GCC three
times, each time with the compiler from the build before, and then compares the
object files of the last two builds byte for byte.
For a native compiler, a bootstrap is this build of GCC with itself, which checks that the compiler compiles itself the same way twice. Part III uses the same word for an unrelated job, breaking the circular dependency between GCC and the C library for a cross target, and Chapter 3.1 starts that meaning. Part III also has its own "stage 1", a cross compiler built before any C library exists, which is not the stage 1 of a native bootstrap.
This chapter assumes Chapter 1.2, for build, host
and target and the uninstalled xgcc. It also assumes
Chapter 2.3, for Makefile.def, Makefile.tpl,
the @if blocks that configure prunes, and the host and target modules that
the top-level Makefile builds. It uses cc1 from
Chapter 1.1, -B from
Chapter 1.5, and the IR and the .gnu.lto_
sections of Chapter 1.13. From
Chapter 2.2 it uses --enable-languages
and target_noncanonical.
The install manual documents the procedure in its
Building a native compiler section: build the tools and three
stages, compare stage 2 with stage 3, and build the runtime libraries with the
stage 3 compiler. The same section documents two controls. --disable-bootstrap
turns the stages off, so a native make builds GCC once. make bootstrap-lean
runs the same sequence but deletes the object files of stages 1 and 2 as soon as
they are no longer needed, to save disk space. The manual gives the steps, and
the top-level configure.ac, Makefile.def and Makefile.tpl hold the rules
that carry them out.
--enable-bootstrap: configure decides from the triples
Unless you pass --enable-bootstrap or --disable-bootstrap, the top-level
configure decides whether the build bootstraps. It says yes only when the tree
has a compiler and the configuration is native, with host and target both equal
to build. Every stage rule in the top-level Makefile depends on that answer.
Watch the yes:$build:$build:default case:
case "$have_compiler:$host:$target:$enable_bootstrap" in
*:*:*:no) ;;
# Default behavior. Enable bootstrap if we have a compiler
# and we are in a native configuration.
yes:$build:$build:default)
enable_bootstrap=yes ;;
*:*:*:default)
enable_bootstrap=no ;;
...
# Other configurations, but we have a compiler. Assume the user knows
# what he's doing.
yes:*:*:yes)
AC_MSG_WARN([trying to bootstrap a cross compiler])
;;
Listing 2.5-1: the bootstrap decision, abridged (configure.ac:1532-1551).
have_compiler is yes when the tree has a gcc/configure
(configure.ac:1526-1530). If you pass --enable-bootstrap on
a cross configuration, configure prints a warning and goes ahead.
The answer becomes one word, bootstrap or no-bootstrap
(configure.ac:3180-3189). Makefile.in wraps the stage
rules in @if gcc-bootstrap lines, and a sed script in configure deletes the
markers that match the configuration and keeps what they enclose
(configure.ac:3364-3384). The script then deletes every block
still marked (:3409-3413), so in a --disable-bootstrap
tree the bootstrap and compare targets do not exist
(Makefile.tpl:1785-1874).
Two more decisions follow from enable_bootstrap=yes. C++ joins
--enable-languages even if you left it out
(configure.ac:2248-2258), because GCC is written in C++. The
install manual's Prerequisites page lists a C++14 compiler as
"Necessary to bootstrap GCC" (install.texi:225-226). The
other decision makes --disable-libstdcxx a configure error
(configure.ac:3340-3346).
bootstrap_stage in Makefile.def: four stages, two comparisons
Each stage of a bootstrap is a bootstrap_stage record in Makefile.def, and
AutoGen turns every record into the make rules for that stage. Four numbered
records hold the native sequence. From stage 2 on, each record names the stage
that builds it, and the records for stages 3 and 4 also name a comparison with
the stage before:
// Toplevel bootstrap
bootstrap_stage = { id=1 ; };
bootstrap_stage = {
id=2 ; prev=1 ;
bootstrap_target=bootstrap2 ; };
bootstrap_stage = {
id=3 ; prev=2 ; lean=1 ;
compare_target=compare ;
bootstrap_target=bootstrap ;
cleanstrap_target=cleanstrap ; };
bootstrap_stage = {
id=4 ; prev=3 ; lean=2 ;
compare_target=compare3 ;
bootstrap_target=bootstrap4 ; };
Listing 2.5-2: the numbered stages (Makefile.def:738-751). Records
for the profiled bootstraps follow at :752-765.
The loop in Makefile.tpl that expands the records writes a family of rules,
which for stage 3 are stage3-start, stage3-end, stage3-bubble, compare
and distclean-stage3 (Makefile.tpl:1727-1876). prev names
the stage whose compiler builds this one. compare_target asks for a comparison
with that previous stage, so stage 3 gets compare and stage 4 gets compare3.
bootstrap_target names the make target that stops at this stage, and lean
names the stage that bootstrap-lean deletes when this one starts.
bootstrap=true: the modules that every stage rebuilds
A stage rebuilds only the modules that Makefile.def marks with
bootstrap=true, not the whole tree, and configure decides which of their
stage rules are live. Together the flag and configure decide which build
directories get stage names, and so which objects make compare sees.
On the host side, bootstrap=true is on gcc, on the libraries it links, such
as libcpp and libiberty, and on binutils when its sources sit in the tree. On
the target side it is on libgcc, libstdc++-v3 and a few others
(Makefile.def:49, :99, :115,
:169-170, :183,
install.texi:3061-3065).
For target libraries, configure starts from libgcc alone. It adds the
libraries of each language that stage 1 builds, then libgomp whenever it is
built, and three more under conditions. fixincludes has bootstrap=true but
is built once by default (configure.ac:2214,
:2545-2554, :3240,
:3242-3271, :3374-3377).
Plain make is make bootstrap: stage_final and stage3-bubble
With bootstrap enabled, plain make and make bootstrap do the same work: both
run the bubble rule stage3-bubble, which rebuilds every stage up to stage 3, in
order. The bubble rules also decide what a second make rebuilds after you edit
a source file. The default target starts like this:
all:
@if gcc-bootstrap
[ -f stage_final ] || echo stage3 > stage_final
@r=`${PWD_COMMAND}`; export r; \
s=`cd $(srcdir); ${PWD_COMMAND}`; export s; \
$(MAKE) $(RECURSE_FLAGS_TO_PASS) `cat stage_final`-bubble
@endif gcc-bootstrap
@: $(MAKE); $(unstage)
Listing 2.5-3: the default target (Makefile.tpl:860-867).
The default target writes stage3 to stage_final unless that file exists, and
runs stage3-bubble. make bootstrap writes the same file and runs the same
target (Makefile.in:65471-65480). make bootstrap4 writes
stage4 instead, and a later plain make reads it back. Makefile.in holds the
bubble rule for stage 3 in its generated form:
stage3-bubble:: stage2-bubble
@r=`${PWD_COMMAND}`; export r; \
s=`cd $(srcdir); ${PWD_COMMAND}`; export s; \
if test -f stage3-lean || test -f stage2-lean ; then \
echo Skipping rebuild of stage3; \
else \
$(MAKE) stage3-start; \
if $(LEAN); then \
rm -rf stage1-*; \
$(STAMP) stage1-lean; \
fi; \
$(MAKE) $(RECURSE_FLAGS_TO_PASS) all-stage3; \
fi
$(MAKE) $(RECURSE_FLAGS_TO_PASS) compare
Listing 2.5-4: stage 3, as generated (Makefile.in:65407-65420).
stage3-bubble depends on stage2-bubble, which depends on stage1-bubble.
Each one moves its stage into place and runs make in every bootstrapped
module, and only stage 3 then runs compare. A stage that already has a
Makefile is not configured again (Makefile.in:12166), so
if you edit a source file and run make again, the change goes through all three
stages. The internals manual calls this "bubbling"
(makefile.texi:95-106).
After the bubble, the default target runs $(unstage), which moves the final
stage into gcc, and then all-host all-target
(Makefile.tpl:867-873). Bootstrapped modules are left out of those
two lists (:897-908). What remains is built once, by the stage 3
compiler: target libraries such as libgfortran and libquadmath
(Makefile.def:187-188), and host tools such as gnattools
(:159).
stage2-start and prev-gcc: each stage is built under the name gcc
Every stage is built in a directory named gcc, and from stage 2 on, the stage
that compiles it sits in prev-gcc. Between builds a stage keeps its own name, such as
stage2-gcc, and the -start rule of each stage renames the directories before
the build. The renames explain why a finished build has no stage2-gcc and no
stage3-gcc. In stage2-start, watch the two mv commands in each block:
stage2-start::
@: $(MAKE); $(stage); \
echo stage2 > stage_current; \
echo stage2 > stage_last; \
$(SHELL) $(srcdir)/mkinstalldirs $(HOST_SUBDIR)
...
@if gcc
@cd $(HOST_SUBDIR); [ -d stage2-gcc ] || \
mkdir stage2-gcc; \
mv stage2-gcc gcc; \
mv stage1-gcc prev-gcc || test -f stage1-lean
@endif gcc
...
@[ -d stage2-$(TARGET_SUBDIR) ] || \
mkdir stage2-$(TARGET_SUBDIR); \
mv stage2-$(TARGET_SUBDIR) $(TARGET_SUBDIR); \
mv stage1-$(TARGET_SUBDIR) prev-$(TARGET_SUBDIR) || test -f stage1-lean
Listing 2.5-5: the directory swap, abridged to gcc and the target directory
(Makefile.in:64708-64866).
Every bootstrapped module gets the same pair of renames, and so does the target
subdirectory, which is named after target_noncanonical
(config/acx.m4:101). HOST_SUBDIR is . unless you build
inside the source directory (config/acx.m4:93-99).
stage2-end reverses the renames (Makefile.in:64899-64904). The
template explains why the names stay constant:
# Since the 'compare' process will fail (on debugging information) if any
# directory names are different, we need to link the gcc directory for
# the previous stage to a constant name ('prev-gcc'), and to make the name of
# the build directories constant as well. For the latter, we use naked names
# like 'gcc', because the scripts in that directory assume it. We use
# mv on platforms where symlinks to directories do not work or are not
# reliable.
Listing 2.5-6: why every stage is built under the same name
(Makefile.tpl:1713-1719).
Two one-line files record the state. stage_current names the stage that is in
gcc now, and stage_last names the stage that was started last
(Makefile.tpl:1681-1683). The macro $(stage) runs the -end
rule of the current stage, and $(unstage) runs the -start rule of the last
stage if no stage is current (:1695-1699). Ordinary targets
begin with $(unstage), install among them
(Makefile.tpl:1062-1063), so install finds the final
stage under the plain names.
The two macros produce the directory names of a finished build. compare runs
$(stage) first, so stage 3 is back in stage3-gcc while it compares. Then
make bootstrap runs $(unstage), which runs stage3-start, before it builds
the remaining libraries. When make returns, gcc holds stage 3, prev-gcc
holds stage 2, and only stage 1 keeps its own name.
If you run make stage, all three stages get their own names back, and
make stage2-start brings stage 2 back into gcc. The internals manual
documents both targets (makefile.texi:157-174).
POSTSTAGE1_HOST_EXPORTS: prev-gcc/xgcc compiles stages 2 and 3
From stage 2 on, the uninstalled driver of the previous stage, prev-gcc/xgcc,
takes the place of the host's compiler, so stage 2 is compiled by stage 1 and
stage 3 by stage 2. The same substitution decides where each stage finds its
cc1 and its C++ library. POSTSTAGE1_HOST_EXPORTS puts the driver in CC:
# Similar, for later GCC stages.
POSTSTAGE1_HOST_EXPORTS = \
$(HOST_EXPORTS) \
CC="$(STAGE_CC_WRAPPER) $$r/$(HOST_SUBDIR)/prev-gcc/xgcc$(exeext) \
-B$$r/$(HOST_SUBDIR)/prev-gcc/ -B$(build_tooldir)/bin/ \
$(XGCC_FLAGS_FOR_TARGET) $$TFLAGS"; export CC; \
CC_FOR_BUILD="$$CC"; export CC_FOR_BUILD; \
Listing 2.5-7: stage 2 and stage 3 are compiled by the previous stage's xgcc
(Makefile.tpl:273-279).
-B points xgcc at that stage's cc1 and its other programs. CXX gets the
same treatment with prev-gcc/xg++, plus -nostdinc++ and the headers and
libraries of the libstdc++ that the previous stage built in
prev-$(TARGET_SUBDIR) (Makefile.tpl:254-271). That is why
libstdc++-v3 is always bootstrapped: stage 2 is C++ code, and it compiles
against stage 1's library, not against the host's.
Each stage is also configured on its own, with these variables set
(Makefile.in:12160-12187). The internals manual says why:
"to minimize problems due to ABI incompatibilities between the native compiler
and GCC" (makefile.texi:91-93).
STAGE1_CFLAGS and BOOT_CFLAGS: the flags and languages of each stage
Stage 1 is compiled with -g and no optimisation, and stages 2 and 3 with
BOOT_CFLAGS, which is -g -O2. Each flag variable is named after the stage it
builds, not after the compiler that receives it, so STAGE2_CFLAGS are the
flags that the stage 1 compiler receives while it compiles stage 2. Stage 1 also
differs in its checking and in the languages it builds:
| Stage | Compiled by | STAGEN_CFLAGS by default | Languages |
|---|---|---|---|
| 1 | the host's $CC and $CXX | -g | C, C++ and LTO, plus Ada and D when enabled |
| 2 | stage 1, from prev-gcc | -g -O2 -fno-checking, plus -gtoggle from bootstrap-debug | all enabled languages |
| 3 | stage 2, from prev-gcc | -g -O2 -fchecking=1 | all enabled languages |
Stage 1 gets its flags from configure
(configure.ac:4153-4163). Stages 2 and 3 start from
BOOT_CFLAGS (Makefile.tpl:398-400,
:514-528). The install manual documents BOOT_CFLAGS under
Building a native compiler, with the override
make BOOT_CFLAGS='-O' bootstrap. No comment says why stage 1 is not optimised.
Its object code is never compared, and the bootstrap-debug fragment calls it
"the unoptimized stage1" (Listing 2.5-10).
Stage 1 is configured with internal checking, --enable-checking=yes,types for a
release (configure.ac:4165-4188). The install manual
documents --enable-stage1-checking, which replaces that default, under
Configuration. The -fchecking options switch verification
of the IR on or off stage by stage, and the GCC manual documents them under
Developer Options. The comment above the settings calls it IL
verification:
# When using the slow stage1 compiler disable IL verification and forcefully
# enable it when using the stage2 compiler instead. As we later compare
# stage2 and stage3 we are merely avoid doing redundant work, plus we apply
# checking when building all target libraries for release builds.
STAGE1_TFLAGS += -fno-checking
STAGE2_CFLAGS += -fno-checking
STAGE2_TFLAGS += -fno-checking
STAGE3_CFLAGS += -fchecking=1
STAGE3_TFLAGS += -fchecking=1
Listing 2.5-8: IR verification by stage (Makefile.tpl:550-558).
Only stage 1 has to cope with an older compiler. Its configure gets
--disable-coverage, and also --disable-build-format-warnings, because "older
GCCs don't understand newer %s" (Makefile.tpl:537-543). If
the host compiler is GCC, the top-level configure adds -std=c++14 to it, so
that a C++14 compiler is enough to start (configure.ac:1563-1567).
Before GCC 15 a C++11 compiler was enough, and before GCC 4.8 a C89 compiler
(install.texi:229-232).
Stage 1 also builds only the languages that stage 2 needs. C++ is always on that
list (configure.ac:2364-2366), and LTO is on it when LTO is enabled
(gcc/lto/config-lang.in:32-33). Ada and D join it when you enable
them, because "the Ada front end is written in Ada" and "the D front end is
written in D" (gcc/ada/gcc-interface/config-lang.in:30,
gcc/d/config-lang.in:27, install.texi:265-272,
:322-326).
What make compare compares
make compare compares each .o file of stage 3 with the same file from stage
2, and records a difference in .bad_compare unless the file is excluded. What
the loop skips decides what a successful bootstrap proves, and which files a
Bootstrap comparison failure! can name. Watch the find that picks the files,
the continue for a file that stage 2 lacks, and the case on
@compare_exclusions@:
echo Comparing stages 2 and 3; \
sed=`echo stage3 | sed 's,^stage,,;s,.,.,g'`; \
files=`find stage3-* -name "*$(objext)" -print | \
sed -n s,^stage$$sed-,,p`; \
for file in $${files} ${extra-compare}; do \
f1=$$r/stage2-$$file; f2=$$r/stage3-$$file; \
if test ! -f $$f1; then continue; fi; \
$(do-compare) > /dev/null 2>&1; \
if test $$? -eq 1; then \
case $$file in \
@compare_exclusions@) \
echo warning: $$file differs ;; \
*) \
echo $$file differs >> .bad_compare ;; \
esac; \
fi; \
done; \
if [ -f .bad_compare ]; then \
echo "Bootstrap comparison failure!"; \
cat .bad_compare; \
exit 1; \
Listing 2.5-9: the compare rule, as generated
(Makefile.in:65438-65458).
The loop applies five rules:
- Only files that end in
.ounder astage3-*directory count.objextis set to.owith the comment "We only want to compare .o files" (Makefile.tpl:1724-1725). Executables, archives and shared libraries are not compared, unless a build configuration (BUILD_CONFIG) adds one throughextra-compare, asbootstrap-ltodoes forlto1(config/bootstrap-lto.mk:19-20). - A file that stage 2 does not have is skipped without a message.
- Only exit status 1 from
do-comparecounts as a difference. Any other status passes. - A file that matches
compare_exclusionsgives a warning, not a failure. - Every other difference goes into
.bad_comparein the top build directory, and the rule fails.
The stage3-* pattern covers the bootstrapped modules, on the host side and
the target side.
Other target libraries are built once, by stage 3, after the comparison, so
nothing compares them.
The comparison pairs stages 2 and 3, not 1 and 2, because the host compiler
produced stage 1's objects, which differ from stage 2's for that reason alone.
Stage 2's objects come from the stage 1 compiler and stage 3's from the stage 2
compiler, and those two compilers are the same source, built two ways. The
internals manual states the test: the compiler "should produce the same object
files regardless of how it itself was compiled"
(makefile.texi:133-136). A third stage is the first point at
which a correct GCC must produce two identical sets of objects.
do-compare, compare-debug and compare_exclusions: allowed differences
Stages 2 and 3 can differ in a few expected ways, and do-compare,
compare-debug and compare_exclusions are the three places where the
comparison allows for them. do-compare is the command that compares one pair
of objects, compare-debug is the script that the default build configuration
puts in its place, and compare_exclusions lists the files whose differences
only warn.
The default do-compare: cmp past 16 bytes
configure sets do-compare to a cmp that ignores the first 16 bytes of each
file. It uses cmp --ignore-initial=16, cmp f1 f2 16 16 or tail -c +17,
whichever the build machine supports (config/acx.m4:468-490). The
source does not say why 16. When bootstrap-debug is selected, as it is by
default, its fragment replaces this command.
bootstrap-debug: stage 2 without -g, compared after strip
bootstrap-debug is the default BUILD_CONFIG, and it makes a bootstrap test
two things: stage 3 must match stage 2, and -g must not change the code. To
test the second, it builds stage 2 without debug information and compares
stripped copies of the objects.
configure selects BUILD_CONFIG=bootstrap-debug whenever it enables bootstrap
(configure.ac:3180-3184), then tests the host compiler. It
compiles int f (void) { return 0; } with and without -g, runs
contrib/compare-debug on the two objects, and empties BUILD_CONFIG if they
differ (configure.ac:3204-3216). --with-build-config overrides
both (:3193-3202), and the top-level Makefile includes
config/NAME.mk for each name (Makefile.tpl:834-839). The
install manual documents BUILD_CONFIG and --with-build-config, and lists the
fragments, under Building a native compiler. The default
fragment sets two variables:
# This BUILD_CONFIG option builds checks that toggling debug
# information generation doesn't affect the generated object code.
# It is very lightweight: in addition to not performing any additional
# compilation (unlike bootstrap-debug-lean), it actually speeds up
# stage2, for no debug information is generated when compiling with
# the unoptimized stage1.
# For more thorough testing, see bootstrap-debug-lean.mk
STAGE2_CFLAGS += -gtoggle
do-compare = $(SHELL) $(srcdir)/contrib/compare-debug $$f1 $$f2
Listing 2.5-10: the default BUILD_CONFIG
(config/bootstrap-debug.mk:1-12).
-gtoggle, another of the GCC manual's Developer Options, turns -g
off for stage 2. For the comparison, compare-debug copies both objects and runs
strip on the copies (contrib/compare-debug:60-74), and then
compares them:
if cmp "$1.$suf1" "$2.$suf2"; then
status=0
else
status=1
# Remove any .comment sections.
if (objcopy -v) 2>&1 | grep ' --remove-section' > /dev/null \
&& (objdump --help) 2>&1 | grep ' --\[*section-\]*headers' > /dev/null; then
remove_comment "$1.$suf1"
remove_comment "$2.$suf2"
if cmp "$1.$suf1" "$2.$suf2"; then
status=0
fi
fi
Listing 2.5-11: .comment sections do not count
(contrib/compare-debug:90-103).
If the files still differ, the script removes .eh_frame, the section where the
assembler writes each function's unwind table
(Chapter 4.3), and any .gnu.lto_ sections, and
tries once more. It does this when only one file has .eh_frame, or when LTO
sections are present. The comment explains the first case: "Assembler-generated
CFI will add an .eh_frame section for -g not present in -g0"
(contrib/compare-debug:105-179). Last, it compares any .gkd
dump files next to the objects (:186-212). Under
bootstrap-debug-big (config/bootstrap-debug-big.mk:6-7),
another developer option, -fdump-final-insns, writes those files
(invoke.texi:21352-21357).
Apart from what strip removes, compare-debug removes only .comment,
.eh_frame and LTO sections, and it has no rule for timestamps or __DATE__
strings. bootstrap-lto takes the other approach and removes a source of
variation at compile time. It compiles stages 2 and 3 with -frandom-seed=1
(config/bootstrap-lto.mk:3-4), the option that the GCC manual offers
"to produce reproducibly identical object files"
(invoke.texi:21284-21290). Its script, contrib/compare-lto,
holds the only timestamp rule: "PE-COFF executables are timestamped so skip
leading bytes for them" (contrib/compare-lto:105-120).
compare_exclusions and cc1-checksum.o
compare_exclusions is the case pattern in the comparison loop, so a file that
matches it gives a warning when it differs and does not fail the build.
configure builds the pattern line by line:
compare_exclusions="gcc/cc*-checksum\$(objext) | gcc/ada/*tools/*"
compare_exclusions="$compare_exclusions | gcc/m2/gm2-compiler-boot/M2Version*"
compare_exclusions="$compare_exclusions | gcc/m2/gm2-compiler-boot/SYSTEM*"
compare_exclusions="$compare_exclusions | gcc/m2/gm2version*"
compare_exclusions="$compare_exclusions | gcc/cobol/parse\$(objext)"
Listing 2.5-12: files that only warn (configure.ac:4215-4219).
AIX adds libgomp objects at :4220-4223.
The source explains only the first pattern. cc1 embeds a checksum of its object
files for precompiled-header validation (gcc/genchecksum.cc:1).
In the final stage the build copies the previous stage's checksum source instead,
and the comment says why: "re-use the checksum from the prev-final stage so it
passes the bootstrap comparison and allows comparing of the cc1 binary"
(gcc/c/Make-lang.in:71-83). cc1plus does the same
(gcc/cp/Make-lang.in:129-141).
Cross compilers do not bootstrap: stage 2 would be target code
A cross compiler does not bootstrap by default, because stage 3 would need the
build machine to run stage 2, and stage 2 is target code. From stage 2 on, CC
is prev-gcc/xgcc (Listing 2.5-7), and that driver produces code for the
target, so on a cross build stage 2's cc1 would be a target program. Running it
on the build machine works only when that machine can run target code.
The install manual's Configuration page gives that case, an
i686 host with an i486 target, and asks for an explicit --enable-bootstrap
(install.texi:1947-1953). For every other cross,
its Building a cross compiler section says: "it is not
generally possible to do a 3-stage bootstrap"
(install.texi:3247-3251). Listing 2.5-1 encodes that default.
A cross build therefore compiles GCC once, "single stage only", and builds the
runtime libraries with that compiler
(install.texi:3273-3276). Those libraries need the
target's C library, which needs a compiler first, the cycle that
Chapter 1.2 showed. Breaking that cycle is the
other meaning of bootstrap, which
Chapter 3.1 begins.
Checking a bootstrap: stage_current, make stage and .bad_compare
A bootstrap leaves its state in the build directory, where you can read it after
make returns. stage_final and stage_current name stages, the directory
names show which stage is where, and .bad_compare lists the objects that
differed. A full native bootstrap takes hours, but one check needs only an
installed compiler and a checkout, because it repeats the test by which
configure picks the BUILD_CONFIG of Listing 2.5-10.
Untested recipe. The results described below come from the rules that the listings quote. The commands were not run.
The check compiles the function that configure uses, with and without -g,
and runs compare-debug on the two objects:
$ echo 'int f (void) { return 0; }' > conftest.c
$ gcc -c conftest.c && mv conftest.o conftest.o.g0
$ gcc -c -g conftest.c && mv conftest.o conftest.o.g
$ sh ~/src/gcc/contrib/compare-debug conftest.o.g0 conftest.o.g; echo $?
Status 0 means that configure would select bootstrap-debug on this machine.
The full run builds GCC in a build directory outside the source tree:
$ mkdir build && cd build
$ ~/src/gcc/configure --prefix="$HOME/opt/gcc-15" --enable-languages=c,c++
$ grep -E '^(BUILD_CONFIG|STAGE1_CFLAGS|STAGE1_CHECKING|STAGE1_LANGUAGES) =' Makefile
$ make -j"$(nproc)"
$ cat stage_final stage_current
$ ls -d stage*-* prev-* gcc
$ make stage && ls -d stage*-gcc
The grep works as soon as configure returns, and shows the values
substituted into Makefile.tpl:534-536 and :835.
After make, stage_final and stage_current both say stage3. The ls
finds stage1-gcc, prev-gcc and gcc, and the same three names for each
other bootstrapped module. After make stage, it finds stage1-gcc,
stage2-gcc and stage3-gcc.
After a comparison failure the directories keep their stage names.
compare-debug -p keeps the stripped copies for inspection
(contrib/compare-debug:26-31):
$ cat .bad_compare
$ sh ~/src/gcc/contrib/compare-debug -p stage2-gcc/FILE.o stage3-gcc/FILE.o
Three things to carry away
A native make is make bootstrap. It builds three stages, each with the
previous one, and compares the .o files of stages 2 and 3.
The stage being built is always in gcc, and its compiler in prev-gcc.
The names stay constant because directory names end up in the objects being
compared.
A cross compiler does not bootstrap by default. Stage 2 would be target code, and the build machine would have to run it.
Things that surprise people
After a successful make there is no stage2-gcc and no stage3-gcc. They
are prev-gcc and gcc. Run make stage to rename them.
--enable-languages=c still builds C++ when it bootstraps. configure adds
C++, because GCC is written in it.
The default bootstrap compiles stage 2 without debug information.
bootstrap-debug adds -gtoggle, and the comparison strips both stages.
BUILD_CONFIG=bootstrap-lto-noplugin turns the comparison off. It sets
do-compare = /bin/true (config/bootstrap-lto-noplugin.mk:9).
Most target libraries are never compared. Only the bootstrapped ones, such as
libgcc and libstdc++, exist in a stage3-* directory.
Documentation coverage
The install manual covers the procedure in
Building a native compiler (gcc/doc/install.texi:3044): the
steps (:3054-3073), bootstrap-lean (:3075-3079), BOOT_CFLAGS
(:3081-3101), what a failed comparison means (:3118-3123), and the
BUILD_CONFIG names (:3133-3245). Configuration documents
--disable-bootstrap and --enable-bootstrap (:1941, :1947),
--enable-werror (:2253), --enable-stage1-checking (:2303),
--enable-stage1-languages (:2117), and the stage link options (:2516-2536).
The internals manual's Makefile Targets node
(gcc/doc/makefile.texi:5) documents bubbling, stageN-start, stage,
compare and distclean-stageN (:86-205). -gtoggle is in
Developer Options (gcc/doc/invoke.texi:21402).
What is not documented:
- That
STAGE1_CFLAGSdefaults to-gwith no-O, and why. - The
-fno-checkingand-fchecking=1flags that each stage receives. prev-gcc, and the reason that each stage is built under a constant name.- That after
make,gccholds stage 3 andprev-gccholds stage 2. - What
compareskips: files other than.o, files that stage 2 lacks,compare_exclusions, and every target library that is not bootstrapped. - The default 16-byte skip, and what
compare-debugremoves:.comment,.eh_frameand LTO sections. - Why a third stage is needed. The internals manual states the test
(
makefile.texi:133-136). The install manual only names the step.
Two statements in the internals manual are out of date. It says the first stage
builds "typically, C and maybe Ada" (makefile.texi:182-183). In GCC 15.2.0 it
always builds C and C++, and LTO by default. It also says each stage is "copied
to its subdirectory" (:96-98). The rules rename the directories with mv.
The install manual says that, with no --enable-checking, stage 1 gets yes
checking (install.texi:2307-2310). configure.ac gives yes,types for a
release, yes,types,extra for an experimental tree, and a longer list for an
LTO BUILD_CONFIG (configure.ac:4165-4188).
Next: Chapter 2.6, Where __LDBL_MANT_DIG__ comes from,
how that macro and the other floating-point macros get their values, and which
part of target selection fixes them.
2.6 Where __LDBL_MANT_DIG__ comes from
GCC 15.2.0. To run the commands: an installed compiler.
You configure an aarch64-rtems6 cross compiler with --with-long-double-128,
because a library you port wants a 128-bit long double. The build succeeds.
The library still refuses to build, because it tests __LONG_DOUBLE_128__ and
that macro is not defined. You look for whatever defines it, and a grep of GCC 15
for LONG_DOUBLE_TYPE_SIZE, the macro that GCC 14 used, finds no definition. The
configure flag you passed changed nothing that you can find.
Every __LDBL_* macro reports a machine mode that the target backend chose. A
machine mode is GCC's name for a size and format of data, such as DImode for
a 64-bit integer or DFmode for an IEEE double, and the internals manual
describes the modes under Machine Modes. Your triple picks the
backend. On a few GNU/Linux targets, configure can also set the default of a
-m option that the backend reads, and it has no other say in these macros.
cc1 defines them before it reads any input, so no header and no C library is
their source.
This chapter assumes Chapter 1.2, for the target
as a property fixed when the compiler is built, and
Chapter 2.1, for gcc/config.gcc as the file that
turns a triple into a backend. It also uses the - input file of
Chapter 1.4, GCC's own <float.h> from
Chapter 1.8, the configure line that gcc -v
echoes from Chapter 1.14, and auto-host.h
from Chapter 2.4.
Checking the predefined macros with -dM -E
gcc -dM -E on an empty input lists every macro that the compiler defined
before it read a line, and it works on any installed compiler, native or cross.
It is the first thing to run, because it shows what your compiler reports for
long double before you go looking for the source that decided it. The first
command prints the floating-point macros, the second the type sizes, and the
third the effect of a -m option:
$ gcc -dM -E - < /dev/null | grep -E 'LDBL|FLT128|FLOAT128|LONG_DOUBLE'
$ gcc -dM -E - < /dev/null | grep __SIZEOF
$ gcc -mlong-double-64 -dM -E - < /dev/null | grep __LDBL_MANT_DIG__
-E with the file name - reads standard input
(Chapter 1.4), and /dev/null makes that
input empty. On x86_64, the first command shows a __LDBL_MANT_DIG__ of 64, and
the third shows 53.
The third command needs a backend that has a -mlong-double-64 option, such as
x86 or PowerPC, and the GCC manual documents the option under
x86 Options and RS/6000 and PowerPC Options. AArch64, ARM
and RISC-V have no such option, for a reason that the section on
TARGET_C_MODE_FOR_FLOATING_TYPE gives.
-d takes a string of letters, and the GCC manual documents -dM and its
siblings under Preprocessor Options. The C-family front end reads
the letters in handle_OPT_d, where M sets flag_dump_macros:
/* Args to -d specify what to dump. Silently ignore
unrecognized options; they may be aimed at toplev.cc. */
static void
handle_OPT_d (const char *arg)
{
char c;
while ((c = *arg++) != '\0')
switch (c)
{
case 'M': /* Dump macros only. */
case 'N': /* Dump names. */
case 'D': /* Dump definitions. */
case 'U': /* Dump used macros. */
flag_dump_macros = c;
break;
Listing 2.6-1: the -d letters (gcc/c-family/c-opts.cc:2054-2069).
-dM also sets flag_no_output, so cc1 writes no preprocessed text
(c-opts.cc:1545-1548). At the end of the input,
preprocess_file walks every identifier and prints each macro as a #define
(c-ppoutput.cc:116-118). The list therefore follows every option
that reaches cc1. Add -O2, which defines __OPTIMIZE__
(cppbuiltin.cc:104-105), or a -m option to the command, and the
output changes with it.
The compiler proper sees -d too, and does nothing with M. Its own letter loop
lists D, I, M, N and U as "handled by the preprocessor" and skips them
(gcc/opts.cc:3667-3672).
c_cpp_builtins and gcc/cppbuiltin.cc: which file defines which macro
c_cpp_builtins is the C-family hook that defines the front-end and
target-specific macros, and its first act is to call into gcc/cppbuiltin.cc
for the macros that every preprocessing language shares. Its own file,
c-family/c-cppbuiltin.cc, differs from that one by a directory and two
characters, and the two greps of the -dM list land in different files. A
surprising value therefore sends you to one file or the other, and the table
that closes this section says which.
c_finish_options first calls cpp_init_builtins, which defines libcpp's own
set, such as __STDC__ (libcpp/init.cc:584-595), and then
c_cpp_builtins (c-opts.cc:1642-1643). The -D and -U
options on your command line come after both calls, in the loop that follows
(:1665-1674). The C-family entry point starts like this:
/* Hook that registers front end and target-specific built-ins. */
void
c_cpp_builtins (cpp_reader *pfile)
{
int i;
/* -undef turns off target-specific built-ins. */
if (flag_undef)
return;
define_language_independent_builtin_macros (pfile);
Listing 2.6-2: the entry point (gcc/c-family/c-cppbuiltin.cc:902-912).
With -undef, another of the Preprocessor Options,
c_cpp_builtins returns before it defines anything, so none of the __LDBL_*,
__SIZEOF_*__ or target macros exist. Otherwise
define_language_independent_builtin_macros runs first, and the basic type
sizes are among the macros it defines. Each line reads the size of a type node,
so __SIZEOF_LONG_DOUBLE__ follows long_double_type_node:
/* Define macros for size of basic C types. */
static void
define_builtin_macros_for_type_sizes (cpp_reader *pfile)
{
#define define_type_sizeof(NAME, TYPE) \
cpp_define_formatted (pfile, NAME"=" HOST_WIDE_INT_PRINT_DEC, \
tree_to_uhwi (TYPE_SIZE_UNIT (TYPE)))
define_type_sizeof ("__SIZEOF_INT__", integer_type_node);
define_type_sizeof ("__SIZEOF_LONG__", long_integer_type_node);
define_type_sizeof ("__SIZEOF_LONG_LONG__", long_long_integer_type_node);
define_type_sizeof ("__SIZEOF_SHORT__", short_integer_type_node);
define_type_sizeof ("__SIZEOF_FLOAT__", float_type_node);
define_type_sizeof ("__SIZEOF_DOUBLE__", double_type_node);
define_type_sizeof ("__SIZEOF_LONG_DOUBLE__", long_double_type_node);
define_type_sizeof ("__SIZEOF_SIZE_T__", size_type_node);
Listing 2.6-3: the __SIZEOF_*__ macros (gcc/cppbuiltin.cc:143-158).
gcc/cppbuiltin.cc looks like a file of version macros, because its first
function defines __GNUC__, but its own comment states a wider scope: "macros
builtins common to all language performing CPP preprocessing". That covers the
version, the optimisation and PIC flags, _LP64, the basic type sizes,
__CHAR_BIT__ and the byte order (cppbuiltin.cc:198-207). The
Fortran front end calls the same function for its own preprocessor
(gcc/fortran/cpp.cc:170). The floating-point machinery is in
c-family/c-cppbuiltin.cc.
The cpp manual documents what __GNUC__, __VERSION__, __OPTIMIZE__ and the
__SIZEOF_*__ macros mean, under Common Predefined Macros. The
table adds where each one is defined:
| Macros | Defined in |
|---|---|
__GNUC__, __VERSION__, __ATOMIC_* | define__GNUC__, cppbuiltin.cc:57-74 |
__OPTIMIZE__, __PIC__, __FAST_MATH__ | cppbuiltin.cc:77-126 |
__SIZEOF_LONG_DOUBLE__ and the other basic sizes | Listing 2.6-3 |
__FLT_*, __DBL_*, __LDBL_*, __FLT128_* | builtin_define_float_constants, in c-family/c-cppbuiltin.cc |
__LONG_DOUBLE_128__, __FLOAT128__, __aarch64__ | the backend's TARGET_CPU_CPP_BUILTINS and TARGET_OS_CPP_BUILTINS (c-cppbuiltin.cc:1652-1659) |
builtin_define_float_constants: one function, three prefixes
builtin_define_float_constants defines the float.h macros, __FLT_*,
__DBL_* and __LDBL_*, and c_cpp_builtins calls it once for each standard
floating type, each time with a different prefix. Nobody wrote down a
__LDBL_MANT_DIG__ for long double: the value is a field of the format behind
the type's machine mode. The three calls are consecutive:
builtin_define_float_constants ("FLT", "F", "%s", "F", float_type_node);
/* Cast the double precision constants. This is needed when single
precision constants are specified or when pragma FLOAT_CONST_DECIMAL64
is used. The correct result is computed by the compiler when using
macros that include a cast. We use a different cast for C++ to avoid
problems with -Wold-style-cast. */
builtin_define_float_constants ("DBL", "L",
(c_dialect_cxx ()
? "double(%s)"
: "((double)%s)"),
"", double_type_node);
builtin_define_float_constants ("LDBL", "L", "%s", "L",
long_double_type_node);
Listing 2.6-4: three types, one function (gcc/c-family/c-cppbuiltin.cc:1268-1280).
Grep for the right names: the function is builtin_define_float_constants, not
cpp_define_float_constants, which does not exist, and its hexadecimal helper is
builtin_define_with_hex_fp_value. Inside the function, each macro name is pasted
from the prefix, and the significand digits come from the format of the type's
mode:
fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
...
/* The number of radix digits, p, in the floating-point significand. */
sprintf (name, "__%s_MANT_DIG__", name_prefix);
builtin_define_with_int_value (name, fmt->p);
Listing 2.6-5: __LDBL_MANT_DIG__ is fmt->p, abridged (gcc/c-family/c-cppbuiltin.cc:142-166).
REAL_MODE_FORMAT maps a machine mode to a struct real_format, and p is that
format's "Size of the significand in digits of radix B"
(gcc/real.h:118-130). __LDBL_MAX_EXP__ comes from the same
table's emax (c-cppbuiltin.cc:196-198). Four of the formats in
gcc/real.cc give these values, and the mode of long_double_type_node decides
which one applies:
Format in gcc/real.cc | p, so __LDBL_MANT_DIG__ | emax, so __LDBL_MAX_EXP__ |
|---|---|---|
ieee_double_format | 53 | 1024 |
ieee_extended_intel_96_format, one of the x86 XFmode formats | 64 | 16384 |
ibm_extended_format | 106, written 53 + 53 | 1024 |
ieee_quad_format | 113 | 16384 |
The LDBL_MANT_DIG in your program is the same number under its standard name,
because GCC's own <float.h> defines LDBL_MANT_DIG as __LDBL_MANT_DIG__
(gcc/ginclude/float.h:38-41).
Chapter 1.8 explains why that <float.h> is the
one you get.
Five of the limits, from __LDBL_MAX__ to __LDBL_DENORM_MIN__, are decimal
renderings of hexadecimal constants (c-cppbuiltin.cc:260-297). A
comment calls builtin_define_with_hex_fp_value, the helper that renders them,
"very expensive" (:1819-1821), so the helper normally defines a
placeholder and computes the value when code first uses the macro. It skips that
shortcut when flag_dump_macros is set (:1880-1884), so under
-dM, cc1 computes every value at once.
TARGET_C_MODE_FOR_FLOATING_TYPE: the backend picks the mode
TARGET_C_MODE_FOR_FLOATING_TYPE is the target hook that gives long double
its machine mode, so it decides which format, and which __LDBL_* values, a
compiler reports. A target hook is a function in targetm, the table that
each backend fills in, so each target can give its own answer. The compiler
calls this one when it builds its common types:
long_double_type_node = make_node (REAL_TYPE);
machine_mode long_double_type_mode
= targetm.c.mode_for_floating_type (TI_LONG_DOUBLE_TYPE);
SET_TYPE_MODE (long_double_type_node, long_double_type_mode);
TYPE_PRECISION (long_double_type_node)
= GET_MODE_PRECISION (long_double_type_mode).to_constant ();
layout_type (long_double_type_node);
Listing 2.6-6: one hook call fixes long double (gcc/tree.cc:9732-9738).
targetm.c.mode_for_floating_type is the hook's entry in that table, and a
backend that does not define it gets the default:
/* Return machine mode for a floating type which is indicated
by the given enum tree_index. */
machine_mode
default_mode_for_floating_type (enum tree_index ti)
{
if (ti == TI_FLOAT_TYPE)
return SFmode;
gcc_assert (ti == TI_DOUBLE_TYPE || ti == TI_LONG_DOUBLE_TYPE);
return DFmode;
}
Listing 2.6-7: the default (gcc/targhooks.cc:302-312).
Without the hook, long double is double, so __LDBL_MANT_DIG__ equals
__DBL_MANT_DIG__, 53 for the IEEE DFmode that machmode.def declares
(gcc/machmode.def:231-232). A grep of
gcc/config/ in GCC 15.2.0 finds the hook in seventeen backends. ARM is not one of them, so arm-none-eabi-gcc has
a 64-bit long double. AArch64 is one, and its hook returns TFmode for
long double with no condition:
/* Implement TARGET_C_MODE_FOR_FLOATING_TYPE. Return TFmode for
TI_LONG_DOUBLE_TYPE which is for long double type, go with the default
one for the others. */
static machine_mode
aarch64_c_mode_for_floating_type (enum tree_index ti)
{
if (ti == TI_LONG_DOUBLE_TYPE)
return TFmode;
return default_mode_for_floating_type (ti);
}
...
#undef TARGET_C_MODE_FOR_FLOATING_TYPE
#define TARGET_C_MODE_FOR_FLOATING_TYPE aarch64_c_mode_for_floating_type
Listing 2.6-8: AArch64's answer (gcc/config/aarch64/aarch64.cc:29192-29202
and :31687-31688).
AArch64 declares TFmode as FLOAT_MODE (TF, 16, ieee_quad_format)
(aarch64-modes.def:260-261), so every GCC 15.2.0 AArch64 compiler
reports a __LDBL_MANT_DIG__ of 113 and a __LDBL_MAX_EXP__ of 16384. No -m
option and no configure flag reaches that if.
LONG_DOUBLE_TYPE_SIZE before GCC 15: a size in bits, not a mode
LONG_DOUBLE_TYPE_SIZE is how a backend set up long double up to GCC 14: it
gave a size in bits, not a mode. GCC 15.1 was the first release with the hook, so
advice that tells you to look for the macro predates GCC 15. AArch64 at GCC 14.3.0
set all three sizes in its header:
#define FLOAT_TYPE_SIZE 32
#define DOUBLE_TYPE_SIZE 64
#define LONG_DOUBLE_TYPE_SIZE 128
Listing 2.6-9: AArch64 at releases/gcc-14.3.0 (gcc/config/aarch64/aarch64.h:99-103).
At that tag, tree.cc copied the size into the type's precision
(gcc/tree.cc:9618-9620 at 14.3.0). Commit
55947b32, "Replace {FLOAT,{,LONG_}DOUBLE}_TYPE_SIZE with new hook
mode_for_floating_type", made the change in June 2024. Its message gives the
reason: PowerPC has three 128-bit floating modes, and a precision alone could not
say which one a type meant.
The commit also adds the three names to the poison list in system.h, so GCC's
own sources can no longer use them (gcc/system.h:950-997). In GCC
15.2.0, a grep of gcc/config/ and of the files at the top of gcc/ for
LONG_DOUBLE_TYPE_SIZE finds that poison list and a few comments, and no
definition.
cpu_type and out_file: from the triple to aarch64.cc
config.gcc turns the triple into a cpu_type, and configure turns
cpu_type into a default out_file, the backend source file that holds the
hook. That chain is how the AArch64 hook gets into your compiler. For AArch64,
ARM and RISC-V, it is all that decides the mode of long double, because no
option reaches their answer.
config.gcc sets cpu_type=aarch64 for every aarch64*-*-* triple
(config.gcc:347-348). When the target's entry sets no out_file,
configure makes it $cpu_type/$cpu_type.cc
(gcc/configure.ac:1946-1947). gcc/Makefile.in compiles that file
(Makefile.in:2686-2688) and links it with the compiler's other
objects (:1845). At its end, aarch64.cc builds the hook table from
every TARGET_* macro it defined, the one in Listing 2.6-8 included:
struct gcc_target targetm = TARGET_INITIALIZER;
Listing 2.6-10: the hook table (gcc/config/aarch64/aarch64.cc:32218).
RISC-V's hook returns TFmode with no condition, as AArch64's does
(riscv.cc:13097-13102).
Chapter 2.1 follows config.gcc further, into the
headers and makefile fragments it also selects.
--with-long-double-128: a default for -mlong-double-128
--with-long-double-128 sets the default of -mlong-double-128 and does nothing
else, and only four target families read it: PowerPC, SPARC, s390 and Alpha
GNU/Linux. Some backends read an option in their hook, and PowerPC is the
clearest case. Its hook tests a variable, the variable has a compile-time
default, and configure can set that default:
/* Implement TARGET_C_MODE_FOR_FLOATING_TYPE. Return TFmode for
TI_LONG_DOUBLE_TYPE which is for long double type, go with the default
one for the others. */
static machine_mode
rs6000_c_mode_for_floating_type (enum tree_index ti)
{
if (ti == TI_LONG_DOUBLE_TYPE)
return rs6000_long_double_type_size == 128 ? TFmode : DFmode;
return default_mode_for_floating_type (ti);
}
Listing 2.6-11: PowerPC's answer depends on a variable (gcc/config/rs6000/rs6000.cc:24377-24387).
rs6000_long_double_type_size is the variable behind -mlong-double-<n>
(rs6000.opt:430-433). When you do not pass that option,
OPTION_SET_P is false, and the backend fills the variable in from a
compile-time default:
/* Use long double size to select the appropriate long double. We use
TYPE_PRECISION to differentiate the 3 different long double types. We map
128 into the precision used for TFmode. */
int default_long_double_size = (RS6000_DEFAULT_LONG_DOUBLE_SIZE == 64
? 64
: 128);
/* Set long double size before the IEEE 128-bit tests. */
if (!OPTION_SET_P (rs6000_long_double_type_size))
{
if (main_target_opt != NULL
&& (main_target_opt->x_rs6000_long_double_type_size
!= default_long_double_size))
error ("target attribute or pragma changes %<long double%> size");
else
rs6000_long_double_type_size = default_long_double_size;
}
Listing 2.6-12: the default, used only without -mlong-double- (gcc/config/rs6000/rs6000.cc:4105-4121).
RS6000_DEFAULT_LONG_DOUBLE_SIZE is 64 unless a target header says otherwise
(rs6000.cc:3385-3390). The GNU/Linux headers set it to 128
when configure defined TARGET_DEFAULT_LONG_DOUBLE_128
(rs6000/linux64.h:535-538, and the same in
rs6000/linux.h:136-139). configure defines it here:
# Check if TFmode long double should be used by default or not.
# Some glibc targets used DFmode long double, but with glibc 2.4
# and later they can use TFmode.
case "$target" in
powerpc*-*-linux* | \
sparc*-*-linux* | \
s390*-*-linux* | \
alpha*-*-linux*)
AC_ARG_WITH(long-double-128,
Listing 2.6-13: four target families (gcc/configure.ac:7031-7039).
The install manual documents the flag under Configuration, for
"selected GNU/Linux architectures". Without the flag, the default comes from the
target C library, and is 128 bits for glibc 2.4 or later. For an older or absent
glibc it is 64 bits, unless the target's bits/wordsize.h defines
__LONG_DOUBLE_MATH_OPTIONAL. musl gets a fixed answer, 128 bits on s390 and 64
on PowerPC (configure.ac:7042-7060).
configure records a yes as TARGET_DEFAULT_LONG_DOUBLE_128
(configure.ac:7063-7066), in the auto-host.h header that
it writes (:29) and Chapter 2.4
covers. SPARC, s390 and Alpha read it as PowerPC does: each sets its
MASK_LONG_DOUBLE_128 when you did not choose
(sparc.cc:1977-1980, s390.cc:16464-16467,
alpha.cc:603-606).
A 128-bit PowerPC long double has a second choice to make, its format. The mode
table declares TFmode as IEEE quad, and the backend switches it to IBM
double-double unless -mabi=ieeelongdouble is in effect
(rs6000-modes.def:41-46, rs6000.cc:4561-4562).
On PowerPC GNU/Linux the default is IBM (rs6000.cc:98-104),
and --with-long-double-format=ieee or =ibm changes that default through
tm_defines (config.gcc:5743-5749).
One PowerPC compiler can therefore report a __LDBL_MANT_DIG__ of 53, 106 or
113, from two options and two configure defaults. The install manual documents
--with-long-double-format next to --with-long-double-128, and the GCC manual
documents -mabi=ieeelongdouble under RS/6000 and PowerPC Options.
--with-long-double-128 on aarch64-rtems6: accepted, then ignored
On aarch64-rtems6, configure accepts --with-long-double-128 with no
warning and then ignores it, because configure reads the value only for
PowerPC, SPARC, s390 and Alpha GNU/Linux. The flag therefore has no effect on
that compiler, and only the configure line that gcc -v echoes
(Chapter 1.14) shows that you passed it.
Autoconf lists the option among the ones the generated gcc/configure knows, for
every target (gcc/configure:1046), although AC_ARG_WITH sits
inside the case of Listing 2.6-13. configure therefore never gives its
"unrecognized options" warning for it (:1501-1506), and reads
the value only inside the generated case (:33509-33520).
--with-long-double-format has a case of its own, which stops configure with
an error on any target that is not 64-bit PowerPC GNU/Linux
(configure.ac:7097-7101). The two flags sit 34 lines apart in
configure.ac and fail in opposite ways.
For five common targets, the mode of long double and what can change it are as
follows:
| Target | long double mode | __LDBL_MANT_DIG__ | What can change it |
|---|---|---|---|
aarch64-* | TFmode, always | 113 | nothing |
riscv*-* | TFmode, always (riscv-modes.def:23) | 113 | nothing |
arm-* | DFmode, the default | 53 | nothing |
x86_64-* | XFmode, or DFmode or TFmode (i386.cc:26306-26317) | 64 | -mlong-double-64 gives 53, -mlong-double-128 gives 113 (i386.opt:223-233) |
powerpc64le-*-linux* | TFmode or DFmode (Listing 2.6-11) | 106 with glibc 2.4 or later | -mlong-double-64, -mabi=ieeelongdouble, and the two configure defaults |
__LONG_DOUBLE_128__ and __FLOAT128__ follow backend options
__LONG_DOUBLE_128__ and __FLOAT128__ report backend options, not the width of
a type, so a library that tests them gets the wrong answer on AArch64. They are
not float.h constants, and builtin_define_float_constants never defines them.
Each backend defines its own macros in TARGET_CPU_CPP_BUILTINS or
TARGET_OS_CPP_BUILTINS, which c_cpp_builtins expands
(c-cppbuiltin.cc:1652-1659).
In GCC 15.2.0, __LONG_DOUBLE_128__ has five definitions in gcc/config/:
| Backend | Definition | Condition |
|---|---|---|
| PowerPC | rs6000-c.cc:706-708 | TARGET_LONG_DOUBLE_128 |
| s390 | s390-c.cc:427-428 | TARGET_LONG_DOUBLE_128 |
| x86 | i386-c.cc:916-917 | TARGET_LONG_DOUBLE_128, set by -mlong-double-128 |
| Alpha | alpha.h:68-69 | TARGET_LONG_DOUBLE_128 |
| SPARC GNU/Linux | sparc/linux.h:25-26, and sparc/linux64.h:27-29 for 32-bit code | TARGET_LONG_DOUBLE_128 |
Every condition tests the backend's own 128-bit switch, not the width of the
type, so __LONG_DOUBLE_128__ means "this backend's -mlong-double-128 is on",
not "long double is 128 bits". AArch64 and RISC-V have no such switch and never
define the macro, although their long double is always 128 bits. To test the
format, test __LDBL_MANT_DIG__. __SIZEOF_LONG_DOUBLE__ gives the storage only,
and storage is not format: on x86_64, "XFmode has size and alignment 16" for its
64-bit significand (i386-modes.def:30-38).
__FLOAT128__ has one definition in all of gcc/config/, in the PowerPC
backend:
if ((flags & OPTION_MASK_FLOAT128_KEYWORD) != 0)
{
rs6000_define_or_undefine_macro (define_p, "__FLOAT128__");
Listing 2.6-14: the only __FLOAT128__ (gcc/config/rs6000/rs6000-c.cc:567-569).
The macro follows the __float128 keyword, which the GCC manual documents under
Additional Floating Types, and which -mfloat128 controls
(rs6000.opt:544-546). On GNU/Linux with VSX, the backend
turns the keyword on by default (rs6000.cc:4157-4162 and
:4183-4186). The x86 backend has __float128 too
(extend.texi:238-242) but never defines __FLOAT128__, and
defines __SIZEOF_FLOAT128__ instead, with no condition
(i386-c.cc:922). libquadmath appears in neither condition, so
cc1's options decide __FLOAT128__, and whether libquadmath was built cannot
change it.
The portable test for a quad type is __FLT128_MANT_DIG__, because
c_cpp_builtins runs builtin_define_float_constants for each _FloatN type
that exists (c-cppbuiltin.cc:1282-1301). tree.cc creates
_Float128 only if targetm.floatn_mode returns a mode
(tree.cc:9740-9752). The default hook returns TFmode when its
format is IEEE binary128 and the backend supports the mode
(targhooks.cc:584-597). On AArch64, that is the TFmode of
Listing 2.6-8.
__LIBGCC_* and -fbuilding-libgcc: macros for libgcc only
c_cpp_builtins defines the __LIBGCC_* macros only under -fbuilding-libgcc,
so an ordinary -dM dump shows none of them. They come from the block of
c_cpp_builtins that tests whether the backend supports each floating mode, and
libgcc is their one reader:
/* For libgcc-internal use only. */
if (flag_building_libgcc)
{
...
sprintf (macro_name, "__LIBGCC_%s_MANT_DIG__", name);
builtin_define_with_int_value (macro_name,
REAL_MODE_FORMAT (mode)->p);
if (!targetm.scalar_mode_supported_p (mode)
|| !targetm.libgcc_floating_mode_supported_p (mode))
continue;
Listing 2.6-15: macros for libgcc only, abridged (gcc/c-family/c-cppbuiltin.cc:1380-1398).
The loop visits every floating mode the compiler knows, and each one gets its
__LIBGCC_<mode>_MANT_DIG__. Only the modes that pass both hooks go on to get
__LIBGCC_HAS_<mode>_MODE__ (c-cppbuiltin.cc:1399-1402).
-fbuilding-libgcc is marked Undocumented (c.opt:1707-1708),
and libgcc's makefile passes it (libgcc/Makefile.in:248-251).
libgcc2.h tests __LIBGCC_HAS_TF_MODE__ and its siblings
(libgcc/libgcc2.h:40-68), and
Chapter 4.1 covers what libgcc is for.
Three things to carry away
__LDBL_MANT_DIG__ is the p of the format behind the mode that the backend
picked. TARGET_C_MODE_FOR_FLOATING_TYPE picks the mode, and
builtin_define_float_constants prints the format's fields.
configure picks the backend, and on a few targets the default of a -m
option. --with-long-double-128 is that default on PowerPC, SPARC, s390 and
Alpha GNU/Linux. On every other target, configure accepts it with no warning
and ignores it.
Test __LDBL_MANT_DIG__, not __LONG_DOUBLE_128__ or __FLOAT128__. Those
two report backend options, and AArch64 defines neither.
Things that surprise people
A PowerPC GNU/Linux compiler configured without target headers gets a 64-bit
long double. With no --with-glibc-version and no target features.h to
read, configure takes the glibc version as 0.0
(configure.ac:6019-6037), and the default of Listing 2.6-13
falls to 64 bits. Pass --with-long-double-128 when you build that compiler
before its C library.
-D__LDBL_MANT_DIG__=64 changes a macro, not a type. Your -D options run
after c_cpp_builtins (c-opts.cc:1665-1674), so they overwrite
the report. The type still comes from Listing 2.6-6.
Documentation coverage
The cpp manual lists the generic macros in
Common Predefined Macros (gcc/doc/cpp.texi:1930, with
__SIZEOF_LONG_DOUBLE__ at :2266). Target macros such as __aarch64__ belong
to System-specific Predefined Macros (cpp.texi:2497), which
sends you to cpp -dM for the list. -dM is in
Preprocessor Options (gcc/doc/cppopts.texi:519-532, included at
invoke.texi:19004). The configure flags are on the install manual's
Configuration page (gcc/doc/install.texi:2438 for
--with-long-double-128, :2446 for --with-long-double-format). The
-mlong-double-* options are under RS/6000 and PowerPC Options
(invoke.texi:33337) and x86 Options (:35723). The targets that
have __float128 and _Float128 are listed in
Additional Floating Types (gcc/doc/extend.texi:238-279). The
hook is in the internals manual's Storage Layout node
(gcc/doc/tm.texi:1047).
What is not documented:
- Any
__FLT_*,__DBL_*or__LDBL_*macro, or__LONG_DOUBLE_128__, or__FLOAT128__. No.texifile in GCC 15.2.0 names them. - That their values follow the backend's choice of mode, and that no configure flag changes them on most targets.
- Which four target families read
--with-long-double-128. The install manual says "selected GNU/Linux architectures" (install.texi:2439-2440), and does not say that other targets accept the flag and ignore it. - That
__LONG_DOUBLE_128__follows a-mswitch, so AArch64 and RISC-V never define it.
Three statements in the GCC 15.2.0 manuals do not match the source:
- The install manual names a
--with-long-double-64(install.texi:2455). Neithergcc/configure.acnorgcc/config.gccreads such an option. The spelling that works is--without-long-double-128. cppopts.texi:535-536says that-dMwithout-Emeans-fdump-rtl-mach. The compiler proper skips theMletter and turns on no RTL dump (opts.cc:3667-3672). RTL, the representation that describes the target's instructions, is explained in Chapter 5.1.extend.texi:264-267says that PowerPC GNU/Linux needs-mfloat128for__float128. The backend turns it on by default with VSX, asinvoke.texi:32224-32225says.
Next: Chapter 3.1, The libgcc–libc cycle: make all-gcc and the three cross
recipes, on why a cross compiler and its C
library each need the other to exist first, and the three recipes that break that
cycle.
3.1 The libgcc–libc cycle: make all-gcc and the three cross recipes
GCC 15.2.0, with glibc 2.42. To run the commands: a GCC checkout.
Every recipe that builds a cross toolchain from nothing has the same odd shape.
It configures GCC and then types make all-gcc where a native build types
make. In a hosted recipe it installs half of a C library, its headers and start
files, and then goes back to the GCC build tree to finish the job. If you follow such a recipe
for a Linux target but type make at that point, the build compiles the
compiler, starts on libgcc and stops there. libgcc wants the C library's
headers, and the C library does not exist yet.
libgcc needs the target's C library to finish, and the C library needs libgcc to
link. make all-gcc builds the compiler and stops before libgcc, and that stop
is the cut that every recipe makes. What a recipe builds in the gap depends on
the target, and one question about the target's C library picks the recipe.
This chapter assumes Chapter 1.2, which stated the
cycle in four steps, drew the directory map and named inhibit_libc, and
Chapter 1.7, which showed which start files the C
library supplies and which libgcc supplies. It also uses fixincludes from
Chapter 1.8, the -nodefaultlibs table of
Chapter 1.10, libgcc's config.host and
its makefile fragments from Chapter 2.1, the
top-level makefile and its maybe- targets from
Chapter 2.3, and the native bootstrap of
Chapter 2.5.
tsystem.h: where libgcc asks for <stdio.h>
libgcc reaches the C library's headers through one header from the compiler's
directory, gcc/tsystem.h, and that header is the first edge of the cycle.
Unless inhibit_libc is defined, it includes headers that only the C library
installs, so libgcc does not compile until the C library's headers are
installed. The header has two halves, and Listing 3.1-1 shows the one with those
includes.
Chapter 1.2 quoted the --without-headers entry of the install manual's
Configuration page. It says that a GNU/Linux target needs the C
library's headers "so GCC can build the exception handling for libgcc". The
source asks for them in more places than the exception handling. libgcc2.c,
the unwinder's unwind-dw2.c, crtstuff.c and emutls.c all include
tsystem.h, and libgcc's include path reaches into gcc/ to find it
(libgcc/libgcc2.c:27,
unwind-dw2.c:26, crtstuff.c:61,
emutls.c:27,
libgcc/Makefile.in:286-287).
#else /* ! inhibit_libc */
/* We disable this when inhibit_libc, so that gcc can still be built without
needing header files first. */
/* ??? This is not a good solution, since prototypes may be required in
some cases for correct code. */
/* GCC supplies this header. */
#include <stdarg.h>
/* All systems have this header. */
#include <stdio.h>
...
/* If these system headers do not exist, fixincludes must create them. */
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
...
#endif /* inhibit_libc */
Listing 3.1-1: the C library branch of tsystem.h, abridged
(gcc/tsystem.h:85-118).
Without inhibit_libc, every one of those files reads <stdio.h>, <stdlib.h>,
<unistd.h> and four more headers that only the C library installs. The other
branch declares malloc, free, memcpy and five more functions by hand, and
turns abort () into __builtin_trap ()
(gcc/tsystem.h:47-83). The comment at the top of
Listing 3.1-1 gives GCC's reason for the switch: "so that gcc can still be built
without needing header files first".
inhibit_libc reaches the compiler as -Dinhibit_libc
(gcc/Makefile.in:791-793). In outline, gcc/configure sets
it to true when two clauses both hold. The first is a cross build with no
sysroot, or --with-newlib. The second is --without-headers, or no stdio.h
among the target's headers (gcc/configure.ac:2569-2583). A
hosted recipe's first GCC build, with a sysroot and without --with-newlib,
therefore keeps it false, and a bare-metal first build, with no sysroot and no C
library headers, gets it true. Chapter 3.2 reads
the test and the flags that it needs.
linux-unwind.h and dl_iterate_phdr: the unwinder reads the C library
On Linux, libgcc's unwinder reads the C library through more than its headers.
linux-unwind.h uses the types that the C library declares, and
dl_iterate_phdr is a function that the C library implements. Both
dependencies sit in libgcc's exception-handling code, which is the half of
libgcc that the cycle runs through.
For aarch64*-*-linux*, libgcc's config.host selects
config/aarch64/linux-unwind.h as the unwinder's target header
(libgcc/config.host:438-441). Its signal-frame code sits
under a guard on inhibit_libc and reads two C library headers:
#ifndef inhibit_libc
#include <signal.h>
#include <sys/ucontext.h>
...
/* The kernel creates an rt_sigframe on the stack immediately prior
to delivering a signal.
This structure must have the same shape as the linux kernel
equivalent. */
struct rt_sigframe
{
siginfo_t info;
ucontext_t uc;
};
Listing 3.1-2: the signal-frame fallback of the AArch64 Linux unwinder, abridged
(libgcc/config/aarch64/linux-unwind.h:26-59).
The fallback lets the unwinder pass through the frame of a signal handler. It
reads the frame that the kernel wrote, through types from the C library's
headers. Under inhibit_libc the whole fallback disappears, because the
#ifndef closes on the last line of the file
(linux-unwind.h:163).
Chapter 4.3 covers the unwinder itself.
Every *-*-linux* target also gets t-eh-dw2-dip
(config.host:313-314), a makefile fragment that
config.host adds to libgcc's build through tmake_file. The fragment puts
unwind-dw2-fde-dip.c into libgcc
(libgcc/config/t-eh-dw2-dip:1-3). That file finds the unwind
tables of a running program, the frame description entries (FDEs) that the
assembler writes into .eh_frame for each function.
To find them, unwind-dw2-fde-dip.c asks the C library where each loaded
object's PT_GNU_EH_FRAME segment is, and Chapter 4.3 follows that lookup, which
tries other methods first. Its fallback asks through dl_iterate_phdr
(unwind-dw2-fde-dip.c:569), a C library function that
<link.h> declares. The file includes <link.h> and
uses that method only when inhibit_libc is not defined
(:49-88). Otherwise it falls back to the generic
unwind-dw2-fde.c (:576-580).
SHLIB_LC = -lc: libgcc_s.so links the C library
libgcc also links a shared library, libgcc_s.so, and its link line adds the
C library through SHLIB_LC = -lc, so libgcc cannot finish until the C library
can be linked. The headers were the compiling half of the dependency, and this
is the linking half. A target gets libgcc_s.so when shared libraries are
enabled and its config.host entry names the fragment t-slibgcc
(libgcc/Makefile.in:395-397), as the *-*-linux* entry
does (config.host:313-314). The link rule is in
libgcc/config/t-slibgcc:
SHLIB_LC = -lc
...
SHLIB_LINK = $(CC) $(LIBGCC2_CFLAGS) -shared -nodefaultlibs \
$(SHLIB_LDFLAGS) $(LDFLAGS) \
-o $(SHLIB_DIR)/$(SHLIB_SONAME).tmp @multilib_flags@ \
$(SHLIB_OBJS) $(SHLIB_LC) && \
Listing 3.1-3: how libgcc_s.so is linked, abridged
(libgcc/config/t-slibgcc:29-37).
$(CC) is the new compiler. -nodefaultlibs removes the default libraries, and
$(SHLIB_LC) then puts the C library back by hand. The GCC manual documents
under Link Options that -nodefaultlibs keeps the start files, and
the table in Chapter 1.10 shows it. A
-shared link on GNU/Linux therefore asks for crti.o and crtn.o, which the C
library installs (Listing 1.7-5). The shared half of libgcc needs three things
from the C library before it can link: crti.o, crtn.o, and a library that
answers -lc.
When shared libraries are enabled, libgcc puts the exception-handling objects
into libgcc_s.so and libgcc_eh.a, not into libgcc.a
(libgcc/Makefile.in:867-890).
Chapter 4.2 says which file holds what.
The split matters here because the C library links only one of those files,
libgcc.a.
libc.so-gnulib in glibc's Makeconfig: the C library links libgcc
glibc links libc.so with -lgcc through the variable libc.so-gnulib, so
the C library cannot link until a libgcc.a exists, and that edge closes the
cycle. The variable is in glibc's top-level Makeconfig, which belongs to glibc
and not to GCC, and its comment states what glibc expects from libgcc in glibc's
own words. Watch the comment's split between libgcc.a and the
exception-handling functions, and the last line:
# How to link against libgcc. Some libgcc functions, such as those
# for "long long" arithmetic or software floating point, can always be
# built without use of C library headers and do not have any global
# state so can safely be linked statically into any executable or
# shared library requiring them; these functions are in libgcc.a.
# Other functions, relating to exception handling, may require C
# library headers to build and it may not be safe to have more than
# one copy of them in a process; these functions are only in
# libgcc_s.so and libgcc_eh.a.
#
# To avoid circular dependencies when bootstrapping, it is desirable
# to avoid use of libgcc_s and libgcc_eh in building glibc. Where any
# glibc functionality (in particular, thread cancellation) requires
# exception handling, this is implemented through dlopen of libgcc_s
# to avoid unnecessary dependencies on libgcc_s by programs not using
# that functionality; executables built with glibc do not use
# exception handling other than through thread cancellation.
...
libc.so-gnulib := -lgcc
Listing 3.1-4: glibc's view of libgcc, abridged
(Makeconfig:672-688 and :732, at the tag
glibc-2.42).
The comment also gives the way out. libgcc.a holds the functions that "can
always be built without use of C library headers". The parts that need the C
library are the exception-handling ones, and glibc's build avoids them on
purpose. So the cycle does not run between two whole libraries. It runs between
half of libgcc and the C library, and each side needs this much from the other:
- glibc needs only
libgcc.a, and only the functions in it that use no C library header. - The rest of libgcc, the unwinder and
libgcc_s.so, builds once glibc's headers, its start files and alibc.soexist.
The list gives what each side needs, not the order that a recipe follows. A
hosted recipe installs the C library's headers before it builds libgcc, so its
libgcc.a is compiled with them. That libgcc.a still links glibc, because
glibc uses none of the parts that need the headers.
GCC's configure machinery states its side of the same problem. libgcc's
configure calls GCC_NO_EXECUTABLES
(libgcc/configure.ac:219). The comment on that macro gives
the reason: "Several of the support libraries that are often built with GCC
can't assume the tool-chain is already capable of linking a program". The quotation
continues: "the compiler often expects to be able to link with some
of such libraries" (config/no-executables.m4:8-11).
make all-gcc: the target that stops before libgcc
make all-gcc builds the compiler and the host modules that it needs, and no
target module. Both sides of the cycle need that compiler first, because libgcc
and the C library are built for the target with it. The top-level makefile's
rules show both directions: nothing that all-gcc needs is a target module, and
every target module waits for all-gcc.
Plain make runs the all rule, which builds all-host all-target
(Makefile.tpl:860-877): every host module, then every target
module. Of the two modules that matter here, libgcc is a target module
(Makefile.def:183-185), and gcc, the directory that builds
xgcc and cc1, is a host module.
all-gcc builds the gcc host module and what it depends on. Every one of
those dependencies is a host or build module, such as binutils, libiberty,
libcpp or GMP, and no target module is on the list
(Makefile.def:367-398).
The target modules' dependencies point the other way. The configure step of
each target module waits for all-gcc (Makefile.tpl:1927-1930), because
the xgcc that all-gcc produces is the compiler for every target library.
That compiler is CC_FOR_TARGET (Makefile.tpl:591), set to
gcc/xgcc -B$$r/$(HOST_SUBDIR)/gcc/ at
configure.ac:4059. Each target module except libgcc also
waits for libgcc (Makefile.tpl:2108-2111).
Two greps over the top-level Makefile.in check both directions. You can run
them in a GCC source tree with nothing configured, because the file is generated
and checked in. Each edge points at a maybe- target, which stays empty when
configure leaves its module out (Chapter 2.3):
$ grep -E '^configure-target-(libgcc|libstdc\+\+-v3): maybe-all' Makefile.in
configure-target-libstdc++-v3: maybe-all-gcc
configure-target-libgcc: maybe-all-gcc
configure-target-libstdc++-v3: maybe-all-target-libgcc
configure-target-libstdc++-v3: maybe-all-target-newlib maybe-all-target-libgloss
$ grep -E '^(all|configure)-gcc:.*target' Makefile.in
$
Output 3.1-1: grep over the top-level Makefile.in, GCC 15.2.0 on an
unconfigured releases/gcc-15.2.0 tree.
The first command shows the order: the compiler, then libgcc, then the other libraries. Its last line shows that libstdc++ also waits for newlib and libgloss, which Chapter 3.6 uses. The second command prints nothing, because no rule makes the compiler wait for a target library.
If you type a plain make for a hosted target that has no C library yet, it
continues from all-gcc into libgcc and fails there, so every recipe names its
make targets. The later targets split the build the same way.
all-target-libgcc builds libgcc alone (Makefile.in:50400),
and install-gcc and install-target-libgcc install each half
(:12862, :50809).
A cross build uses these rules unchanged, because it does not bootstrap by
default. configure turns bootstrapping on by default only when the host and
the target are both the build machine (configure.ac:1532-1541).
The install manual documents that default for a native build in its
--disable-bootstrap entry, under Configuration.
stmp-fixinc: what make all-gcc still reads from the target
make all-gcc compiles nothing for the target, but its stmp-fixinc rule
still reads the target's header directory, because it runs fixincludes over it.
That read can stop the build before libgcc, so a hosted recipe has to prepare
the directory before its first GCC build. In a cross compiler, all-gcc reaches
fixincludes through four make targets:
all.cross, thealltarget ofgcc/Makefile.inin a cross compiler (gcc/configure.ac:2550)libgcc-support, whichall.crossincludes (gcc/Makefile.in:2218-2220)stmp-int-hdrs, whichlibgcc-supportneeds (:2459-2460)stmp-fixinc, whichstmp-int-hdrsneeds (:3475)
stmp-fixinc runs fixincludes, the subject of
Chapter 1.8, over the target's header
directory. First it checks that the directory exists:
if ! $(inhibit_libc) && test ! -d ${BUILD_SYSTEM_HEADER_DIR}; then \
echo "The directory (BUILD_SYSTEM_HEADER_DIR) that should contain system headers does not exist:" >&2 ; \
...
tooldir_sysinc=`echo "${gcc_tooldir}/sys-include" | sed -e :a -e "s,[^/]*/\.\.\/,," -e ta`; \
if test "x${BUILD_SYSTEM_HEADER_DIR}" = "x$${tooldir_sysinc}"; \
then sleep 1; else exit 1; fi; \
fi; \
Listing 3.1-5: the header check in stmp-fixinc, abridged
(gcc/Makefile.in:3616-3627).
Which directory the check tests depends on the sysroot that you configure:
- With a sysroot, it is the sysroot's
/usr/include(gcc/configure.ac:174, with the default/usr/includefromgcc/config.gcc:253). - With
--with-build-sysroot, it is the same path under the build sysroot (gcc/configure.ac:2539-2545). - Without a sysroot, it is
$tooldir/sys-include(gcc/configure.ac:188).
The install manual documents --with-sysroot under
Configuration, as the root of "(a subset of) the root
filesystem of the target operating system". The same page documents
--with-build-sysroot, a second sysroot that replaces the first while the
target libraries build.
The check stops make all-gcc when inhibit_libc is false and the directory is
missing. The only exception is a missing $tooldir/sys-include, which costs one
second of sleep and no error. In this rule, $(inhibit_libc) is the make
variable behind -Dinhibit_libc, and its value, the word true or false,
runs as a shell command (Chapter 3.2).
The comment above the rule does not match the code. It promises an abort
"unless building a crosscompiler"
(gcc/Makefile.in:3600-3601), but the code also aborts
for a cross compiler with a sysroot.
The check tests only that the directory exists. If you configure a hosted
recipe with a sysroot, inhibit_libc stays false, and the recipe's kernel
headers make the directory exist. They go into the sysroot's /usr/include
before the first GCC build in any case, because glibc's headers include them.
Phases of a hosted bootstrap around make all-gcc
The edges in tsystem.h, t-slibgcc, glibc's Makeconfig and stmp-fixinc
fix the order of a hosted bootstrap, for example for aarch64-linux-gnu. Each
phase can start only when the phases that it waits for are done. The table gives
the reason for each wait, so a failed step can be traced to the phase that it
needed.
Untested recipe. The order comes from the sources that the table cites. The sequence was not run end to end.
In Part III, stage 1 is the first GCC build, the one that starts with
make all-gcc, and stage 2 is the second, complete GCC build, in a new build
directory. Neither is the stage1 of a native bootstrap in
Chapter 2.5.
Chapter 1.2 drew this order as binutils → libc headers → minimal GCC → full libc → full GCC. The table splits its "libc headers" step in two. The Linux
kernel headers come before stage 1, because all-gcc needs the directory.
glibc's own headers and start files come after it, because they are built for
the target. Its "full GCC" step splits too: libgcc comes before the full C
library, and the rest of GCC after it.
| Phase | Waits for | Why |
|---|---|---|
| binutils for the target | nothing | GCC's configure needs the target assembler and linker, as the install manual's Building a cross compiler section says (install.texi:3281-3285) |
| Linux kernel headers, into the sysroot | nothing | glibc's headers include them (local_lim.h:38), and all-gcc needs the directory (Listing 3.1-5) |
Stage 1: make all-gcc | binutils, the sysroot's /usr/include | all-gcc depends on host and build modules only (Makefile.def:367-398) |
C library headers, crti.o, crtn.o and a placeholder libc.so | the stage-1 compiler | they are built for the target, and the placeholder only has to answer -lc for the libgcc_s.so link |
libgcc, with libgcc_s.so, in the stage-1 tree (make all-target-libgcc) | C library headers, crti.o, crtn.o, a libc.so | Listings 3.1-1 and 3.1-3 |
| The full C library | libgcc.a | libc.so links with -lgcc (Listing 3.1-4) |
| Stage 2: the full GCC, with libstdc++ and the other target libraries | the full C library | they wait for libgcc (Makefile.tpl:2108-2111), and Chapter 3.3 explains what they need from the C library |
The placeholder libc.so breaks the cycle on the link side. libgcc links
libgcc_s.so against it, and the full C library in the next row replaces it.
Step 4 of Chapter 3.3 makes it, and that
chapter gives the commands for each phase.
A bare-metal target removes rows from the table, because there is no kernel and
no sysroot. The arm*-*-eabi* entry in libgcc's config.host names no
t-slibgcc, so there is no libgcc_s.so to link against a C library
(config.host:578-584). inhibit_libc is true for a
bare-metal stage 1, so tsystem.h asks for no C library header.
GCC's own makefile expects libgcc to build first on such a target. In a
combined tree, newlib's configure step waits for libgcc
(Makefile.in:69375).
Chapter 3.4 gives the bare-metal sequence.
Prebuilt sysroot, hosted or bare metal: the C library decides
A prebuilt sysroot, a hosted bootstrap and a bare-metal bootstrap are the three cross recipes, and one question picks among them. Does a C library for the target already exist, with its headers, its start files and a library that you can link? The answer picks one of Chapters 3.3 to 3.5, which are alternative routes through the cycle, not a sequence. Chapter 3.6 is a variant of the bare-metal route.
-
Yes. Chapter 3.5 covers this case, and there is no cycle to break. One
configurewith--with-sysrootand onemakebuild everything. This is the case that the install manual documents, and a native rebuild on a machine that already has its C library is this case too. -
No, for a Linux target. You need the hosted bootstrap of Chapter 3.3, with each phase of the hosted table as a step.
-
No, for a bare-metal target. The target has no operating system, so you need the bare-metal bootstrap of Chapter 3.4. If newlib's source can sit next to GCC's, Chapter 3.6 builds the same toolchain with one
make.
The install manual's Building a cross compiler section is the
documented path, and it covers only the first case and the in-tree variant. It
says that make builds the compiler and then the "runtime libraries using the
compiler from the previous step" (install.texi:3276). It then
says: "If you are not building a C library in the same source tree as GCC, you
should also provide the target libraries and headers before configuring GCC"
(:3313-3315). The page never names the cycle or
make all-gcc.
aarch64-linux-gnu against arm-none-eabi: hosted and bare metal
The hosted triple aarch64-linux-gnu and the bare-metal triple arm-none-eabi
differ in the rows that the cycle touches, and Chapters 3.3 and 3.4 follow
them. The bare-metal column needs less from outside GCC: no kernel to supply
headers, no shared libgcc to link against the C library, and start files that
libgcc mostly supplies itself.
Hosted, aarch64-linux-gnu | Bare metal, arm-none-eabi | |
|---|---|---|
| C library | glibc, or musl for a *-musl triple (config.gcc:913-926) | newlib, or none |
| Linux kernel headers | needed before the C library (local_lim.h:38) | none |
| Where the C library goes | a sysroot (Chapter 1.2) | the tooldir, $prefix/<target>/, which the driver searches (gcc.cc:5536-5538) |
| Start files from the C library | crt1.o, crti.o, crtn.o (Listings 1.7-4 and 1.7-5) | crt0.o (unknown-elf.h:32-45) |
| Start files from libgcc | crtbegin*.o, crtend*.o | crti.o, crtn.o, crtbegin.o, crtend.o (config.host:584) |
libgcc_s.so, linked with -lc | yes (config.host:313-314) | no (config.host:578-584) |
| GCC builds | two (Chapter 3.3) | two (Chapter 3.4), or one in a combined tree (Chapter 3.6) |
On arm-none-eabi, libgcc builds crti.o and crtn.o itself, so the C library
supplies only crt0.o. The configure flags that make stage 1 possible also
differ between the two columns, and Chapter 3.2
explains them.
Three things to carry away
Only half of libgcc is in the cycle. glibc links libc.so with -lgcc
alone, and the functions that it takes from libgcc.a need no C library header.
The Linux unwinder and libgcc_s.so do not build without the C library.
make all-gcc builds the compiler and stops before libgcc. No dependency of
all-gcc names a target module, and every target module waits for all-gcc.
One question picks the recipe. If the target's C library exists, build once against it. If it does not, the target's operating system decides between the hosted and the bare-metal recipe.
Things that surprise people
"Stage 1" in a cross recipe is not stage1 in a bootstrap. The install
manual says that a three-stage bootstrap of a cross compiler "is not generally
possible" (install.texi:3249-3251), and a cross build
does not bootstrap by default (configure.ac:1532-1541). The
stage1- directories of Chapter 2.5 never
appear in a Part III build.
make all-gcc can fail on an empty sysroot. When inhibit_libc is false,
stmp-fixinc stops if the sysroot has no /usr/include (Listing 3.1-5).
glibc avoids libgcc_s.so on purpose. Its makefile says so, "to avoid
circular dependencies when bootstrapping" (Listing 3.1-4).
Documentation coverage
The install manual documents the case with no cycle in it.
Building a cross compiler (gcc/doc/install.texi:3247-3322)
describes one make that builds the compiler and then the runtime libraries. It
tells you to provide the target headers and libraries before you configure, and
it names STARTFILE_SPEC as the place to look up a target's start files
(:3321-3322). Configuration documents --with-sysroot
(:2709-2731), --without-headers (:2763-2766) and --with-newlib
(:2776-2780), one at a time.
What is not documented:
- The cycle itself. The
--without-headersentry says that a GNU/Linux target needs headers to build libgcc's exception handling. No page says thatlibgcc_s.solinks against the C library, or that the C library links libgcc. make all-gcc. No manual names the top-level target that every cross recipe uses to split the build at libgcc, orall-target-libgccafter it. The internals manual's Makefile Targets node says that the top-level makefile uses "the new compiler to build target libraries" (gcc/doc/makefile.texi:81-84). Its list of top-level targets (:108) names only bootstrap targets.tsystem.h, the header through which libgcc includes the C library's headers.- That
make all-gccruns fixincludes, and stops when the sysroot's header directory is missing. - Which recipe a given target needs. The manual has one procedure, for a target whose C library already exists.
Next: Chapter 3.2, "inhibit_libc: the switch that
makes stage 1 possible", reads the configure test that picks the half of
tsystem.h that libgcc compiles, and shows why --without-headers alone does
not set it.
3.2 inhibit_libc: the switch that makes stage 1 possible
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
You configure a stage-1 cross compiler for aarch64-linux-gnu with a sysroot and
--without-headers. make all-gcc finishes. Then libgcc stops on its first
file:
fatal error: stdio.h: No such file or directory
The install manual's Configuration page says that
--without-headers "Tells GCC not use any target headers from a libc"
(install.texi:2763-2766). The flag did its job. It is
one half of a condition, and the sysroot switched off the other half.
--without-headers alone does not set inhibit_libc. inhibit_libc is a
variable in gcc/configure. It decides whether libgcc is compiled with the target
C library's headers. Two clauses decide it, and --without-headers answers only
the second.
This chapter assumes Chapter 1.2, for the tooldir
and the sysroot, and Chapter 3.1, for the
cycle that stage 1 breaks and for make all-gcc.
The condition in gcc/configure.ac
The whole switch is one shell if, with the two comments that introduce it:
# If this is a cross-compiler that does not
# have its own set of headers then define
# inhibit_libc
# If this is using newlib, without having the headers available now,
# then define inhibit_libc in LIBGCC2_CFLAGS.
# This prevents libgcc2 from containing any code which requires libc
# support.
: ${inhibit_libc=false}
if { { test x$host != x$target && test "x$with_sysroot" = x ; } ||
test x$with_newlib = xyes ; } &&
{ test "x$with_headers" = xno || test ! -f "$target_header_dir/stdio.h"; } ; then
inhibit_libc=true
fi
AC_SUBST(inhibit_libc)
Listing 3.2-1: the condition (gcc/configure.ac:2569-2583).
Read it as two groups joined by &&. Each group is an || of two tests:
| Clause | True when | The flag that makes it true |
|---|---|---|
| first | a cross build with no --with-sysroot, or --with-newlib | --with-newlib |
| second | --without-headers, or no stdio.h in $target_header_dir | --without-headers |
inhibit_libc is true only when both clauses are true. The two comments describe
two cases: a cross compiler with no headers, and a newlib build whose headers do
not exist yet. The code merges the two cases into one test, so no single flag
controls the result.
The flags reach this test as plain shell variables. Autoconf turns
--without-headers into with_headers=no (configure:1267-1281),
and the top level passes your options down to gcc/configure
(configure.ac:3596-3608).
The first line, : ${inhibit_libc=false}, assigns false only if the variable
has no value yet. gcc/configure.ac runs the target's config.gcc entry long
before this point (gcc/configure.ac:1931). One entry uses
that: mcore-*-elf sets inhibit_libc=true itself
(gcc/config.gcc:2471-2475). After that line, the if can only set
true. Nothing in gcc/configure.ac sets the variable back to false.
Before GCC 5, the second clause did not look at the disk. At
releases/gcc-4.9.0it readtest "x$with_headers" = x || test "x$with_headers" = xno(gcc/configure.ac:1886-1891), so every build that did not pass--with-headerssatisfied it.releases/gcc-5.1.0has the current form (gcc/configure.ac:1994-1999). The ChangeLog entry of 2014-09-22 records the change: "When considering $with_headers, just check it it's explicitly "no". If not, also check if $target_header_dir/stdio.h is present." (gcc/ChangeLog-2014:17598-17606).
--with-sysroot turns the first clause off
The first clause tests "x$with_sysroot" = x, that is, an empty value. Any
--with-sysroot makes the value non-empty, with a directory or without one. The
install manual documents both forms under Configuration: the
directory is the root in which the compiler looks for target headers, libraries
and run-time object files. So on a cross build with a sysroot, only
--with-newlib can make the first clause true.
That is the case from the start of this chapter. These are the three flags of the hosted stage-1 configure line that matter here (Chapter 3.3 gives the rest):
--target=aarch64-linux-gnu --with-sysroot=/opt/cross/sysroot --without-headers
--without-headers makes the second clause true. --with-sysroot makes the first
clause false, and this is not a newlib build. So inhibit_libc stays false.
The build still gets through make all-gcc, and Chapter 3.1 explains why the
recipe stops there. But all-gcc reads the value once. A cross build's all
target depends on libgcc-support (gcc/Makefile.in:2219-2220),
which depends on the fixincludes stamp
(:2459-2460, :3475). The fixincludes rule
stops the build when the system header directory is missing and inhibit_libc is
false:
if ! $(inhibit_libc) && test ! -d ${BUILD_SYSTEM_HEADER_DIR}; then \
echo "The directory (BUILD_SYSTEM_HEADER_DIR) that should contain system headers does not exist:" >&2 ; \
echo " ${BUILD_SYSTEM_HEADER_DIR}" >&2 ; \
...
if test "x${BUILD_SYSTEM_HEADER_DIR}" = "x$${tooldir_sysinc}"; \
then sleep 1; else exit 1; fi; \
Listing 3.2-2: the one test in all-gcc that reads inhibit_libc, abridged
(gcc/Makefile.in:3616-3626).
Here $(inhibit_libc) runs as a shell command. Its value is the word true or
false, so the test becomes ! true or ! false. The comment above the rule
admits that this is a proxy: "FIXME: abort unless building --without-headers
would be more accurate and less ugly" (gcc/Makefile.in:3600-3601).
The sleep 1 branch lets a build continue when the missing directory is the
tooldir's sys-include, which is the header directory of a cross compiler with
no sysroot (gcc/configure.ac:2544, :185-189). With a
sysroot, the directory is the sysroot's usr/include
(:174), and it must exist. In the hosted recipe it does,
because the kernel headers go into it before stage 1 (Chapter 3.3).
libgcc is where the build fails. Its sources include gcc/tsystem.h, and with
inhibit_libc false that header includes <stdio.h> (Listing 3.2-6). A sysroot
that holds only kernel headers has no stdio.h.
To get inhibit_libc with a sysroot, add --with-newlib. It is the only part of
the first clause that a sysroot cannot cancel. The install manual documents it
under Configuration as the flag that names newlib as the target
C library. But it is not private to this condition. The top level reads it to
decide whether to build newlib (configure.ac:292-296).
libstdc++'s configure reads it too.
On a cross build it then configures for newlib, with a hard-coded list of features
(libstdc++-v3/configure.ac:335-343). A C-only stage 1 builds no
libstdc++. A later stage that builds libstdc++ for glibc must not get the flag.
In a combined tree with newlib, you do not pass --with-newlib at all. The top
level adds it to the gcc/configure arguments itself when newlib is one of the
target directories (configure.ac:2997-3003).
Chapter 3.6 covers that build.
$target_header_dir: where configure looks for stdio.h
The second clause tests one file in one directory. gcc/configure.ac computes the
directory a few lines earlier:
if test "x$with_build_sysroot" != "x"; then
target_header_dir="${with_build_sysroot}${native_system_header_dir}"
elif test "x$with_sysroot" = x; then
target_header_dir="${test_exec_prefix}/${target_noncanonical}/sys-include"
elif test "x$with_sysroot" = xyes; then
target_header_dir="${test_exec_prefix}/${target_noncanonical}/sys-root${native_system_header_dir}"
else
target_header_dir="${with_sysroot}${native_system_header_dir}"
fi
else
target_header_dir=${native_system_header_dir}
fi
Listing 3.2-3: the probe directory (gcc/configure.ac:2556-2567).
The else at the bottom is for a native build with no sysroot
(:2539-2540). test_exec_prefix is --exec-prefix, else
--prefix, else /usr/local (:149-158).
native_system_header_dir is /usr/include unless the target's config.gcc
entry or --with-native-system-header-dir changes it
(gcc/config.gcc:253, gcc/configure.ac:2054-2056). So:
| Configuration | configure looks for |
|---|---|
--with-build-sysroot=B | B/usr/include/stdio.h |
cross, no --with-sysroot | $exec_prefix/<target>/sys-include/stdio.h |
--with-sysroot with no directory | $exec_prefix/<target>/sys-root/usr/include/stdio.h |
--with-sysroot=S | S/usr/include/stdio.h |
| native, no sysroot | /usr/include/stdio.h |
Three things in this table cost people time.
--with-build-sysroot wins. When you give both, the probe looks in the build
sysroot, not in the one the installed compiler will use. The install manual
documents the option under Configuration, as the system root
for the compiler that builds the target libraries.
With no sysroot, the probe looks in sys-include, not in include. The
tooldir has both directories (Chapter 1.2), and the compiler searches both
(gcc/Makefile.in:3408-3409). The probe looks only in
sys-include. A C library whose headers are installed in <target>/include does
not exist as far as the probe can tell.
The probe runs once, when gcc/configure runs. Headers that you install later
do not change the answer until gcc/ is configured again. So each stage of a
bootstrap needs its own run of gcc/configure.
The stdio.h probe adds to your flags, never cancels them
The second clause is an ||. Either test is enough. Two consequences follow, and
both are easy to read the wrong way round.
--without-headers wins over the disk. With the flag, the second clause is
true whether stdio.h exists or not. The disk check cannot cancel it.
A missing stdio.h sets the second clause without the flag. You do not need
--without-headers when the probe directory is empty.
Now apply both clauses to a bare-metal stage 1, such as arm-none-eabi with no
sysroot. The build is a cross with no --with-sysroot, so the first clause is
already true. If sys-include has no stdio.h, the second clause is true too. So
inhibit_libc is true with neither flag. The conventional
--without-headers --with-newlib pair still earns its place. Each flag pins one
clause, so the result no longer depends on what is on the disk, or on a
--with-sysroot added later. Chapter 3.4
uses the pair.
The same rule can work against a bare-metal compiler's final stage. Take a final
stage with no sysroot, configured with --with-newlib and no other header flag.
The first clause is true. If the C library's headers are in <target>/include
and not in <target>/sys-include, the probe finds no stdio.h, and the second
clause is true too. So inhibit_libc is still true in the compiler you install.
The next section shows the flag that puts the headers where the probe looks.
--with-headers=DIR puts headers where the probe looks
--with-headers=DIR is the positive form of --without-headers. The top-level
configure handles it, not gcc/configure:
# Handle --with-headers=XXX. If the value is not "yes", the contents of
# the named directory are copied to $(tooldir)/sys-include.
if test x"${with_headers}" != x && test x"${with_headers}" != xno ; then
if test x${is_cross_compiler} = xno ; then
echo 1>&2 '***' --with-headers is only supported when cross compiling
exit 1
fi
if test x"${with_headers}" != xyes ; then
x=${gcc_cv_tool_prefix}
copy_dirs="${copy_dirs} ${with_headers} $x/${target_noncanonical}/sys-include"
fi
fi
Listing 3.2-4: --with-headers (configure.ac:2931-2942).
gcc_cv_tool_prefix is the same --exec-prefix, else --prefix, else the default
(config/acx.m4:258-267). So the copy lands in the directory that
Listing 3.2-3 probes when there is no sysroot. The copy itself runs inside the
top-level configure, with tar (configure.ac:3005-3033).
gcc/configure runs later, from the top-level Makefile
(configure.ac:3319-3321). So the probe finds stdio.h if
DIR has it.
Three details:
--with-headerswith no directory copies nothing. It also leaves the second clause to the disk, because the clause tests only forno.- A native build stops with an error. The option is for cross compilers only.
- The install manual's Configuration page marks the option
"Deprecated in favor of
--with-sysroot", and says the directory form "is required" whenprefix/target/sys-includedoes not already exist (gcc/doc/install.texi:2751-2761). The probe explains that sentence.
What -Dinhibit_libc removes from libgcc
gcc/configure decides, and libgcc obeys. gcc/Makefile.in turns the configure
variable into a preprocessor flag:
# "true" if the target C library headers are unavailable; "false"
# otherwise.
inhibit_libc = @inhibit_libc@
ifeq ($(inhibit_libc),true)
INHIBIT_LIBC_CFLAGS = -Dinhibit_libc
endif
Listing 3.2-5: from variable to flag (gcc/Makefile.in:789-794).
The comment states what the variable means: target C library headers. The rule
for libgcc.mvars writes INHIBIT_LIBC_CFLAGS into that file
(gcc/Makefile.in:2462-2466). libgcc's Makefile includes the file
(libgcc/Makefile.in:184) and puts the flag into the options for
libgcc2.a and for crtbegin.o and crtend.o
(:248-251, :302-306). libgcc never runs
the probe again. It uses the answer that gcc/ wrote.
Four targets do not ask. Their libgcc fragments set the flag themselves: BPF,
nvptx and AMD GCN assign INHIBIT_LIBC_CFLAGS = -Dinhibit_libc
(t-bpf:22-23, t-nvptx:15-18, t-amdgcn:22-23),
and AVR adds -Dinhibit_libc to its own flags (t-avr:129). libgcc's
Makefile includes the fragments after libgcc.mvars
(libgcc/Makefile.in:379-380), so their value wins.
gcc/tsystem.h: headers out, declarations in
Most of libgcc reaches the C library through one header, gcc/tsystem.h. The
unwinder and the emulated TLS code include it, for example
(libgcc/unwind-dw2-fde.c:28, libgcc/emutls.c:27):
#ifdef inhibit_libc
#ifndef malloc
extern void *malloc (size_t);
#endif
...
#ifndef abort
#define abort() __builtin_trap ()
#endif
...
#else /* ! inhibit_libc */
/* We disable this when inhibit_libc, so that gcc can still be built without
needing header files first. */
/* ??? This is not a good solution, since prototypes may be required in
some cases for correct code. */
...
/* All systems have this header. */
#include <stdio.h>
Listing 3.2-6: tsystem.h, abridged (gcc/tsystem.h:47-95).
With inhibit_libc, the header declares malloc, calloc, realloc, free,
atexit, strlen, memcpy and memset itself, and turns abort () into a trap
instruction. Without it, the header includes <stdio.h>, <sys/types.h>,
<errno.h>, <string.h>, <stdlib.h>, <unistd.h> and <time.h>
(gcc/tsystem.h:85-118).
inhibit_libc removes the C library's headers from libgcc, not its calls. The
unwinder still calls malloc (libgcc/unwind-dw2-fde.c:171). The
declaration now comes from tsystem.h, and the definition must still come from a
C library when something links.
The code that inhibit_libc compiles out
Code that needs more than those declarations sits behind #ifndef inhibit_libc.
At the pin, these are the parts that a libgcc built with -Dinhibit_libc does
not have:
| Source | Without the C library's headers | What you lose |
|---|---|---|
libgcc/libgcc2.c:2975-2995 | __eprintf is not built | old objects that call __eprintf |
libgcc/unwind-dw2-fde-dip.c:49-84 | no dl_iterate_phdr search for unwind tables | the unwinder uses only frames registered at startup (:576-580) |
libgcc/config/*/linux-unwind.h, for example i386 | no signal-frame decoding | unwinding through a signal handler |
libgcc/generic-morestack.c:37-43 | the file compiles to nothing | -fsplit-stack |
libgcc/libgcov-driver.c:41-46, libgcov-merge.c:28-33 | gcov's runtime becomes empty stubs | .gcda output from --coverage |
libgcc/config/i386/heap-trampoline.c:3-4 (also AArch64) | the file compiles to nothing | -ftrampoline-impl=heap (common.opt:3121-3123) |
The split-stack file states the trade-off in its own words:
/* If inhibit_libc is defined, we cannot compile this file. The
effect is that people will not be able to use -fsplit-stack. That
is much better than failing the build particularly since people
will want to define inhibit_libc while building a compiler which
can build glibc. */
#ifndef inhibit_libc
Listing 3.2-7: the policy in one comment (libgcc/generic-morestack.c:37-43).
The gcov row needs one more sentence. By default the compiler adds a constructor
that calls __gcov_init and a destructor that calls __gcov_exit to each
--coverage object (gcc/coverage.cc:1195-1201, built at
:1069-1119). With
inhibit_libc, __gcov_init is an empty function, and __gcov_exit is not
defined at all, because its definition is inside the block that needs the C
library (libgcov-driver.c:66-68, :744-746). So the
source predicts an undefined __gcov_exit when such a program links. One gcov
entry point survives: __gcov_info_to_gcda, "intended for freestanding
environments which do not support the C library file I/O"
(libgcov-driver.c:787-792). It pairs with
-fprofile-info-section, which the GCC manual documents under
Instrumentation Options. That option replaces the constructor and
the destructor with a pointer to the profile data in a named section, for
freestanding environments.
One file goes the other way on purpose. crtstuff.c builds the same crtbegin.o
for a glibc target with or without inhibit_libc:
#if defined(OBJECT_FORMAT_ELF) \
&& !defined(OBJECT_FORMAT_FLAT) \
&& defined(HAVE_LD_EH_FRAME_HDR) \
&& !defined(CRTSTUFFT_O) \
&& defined(inhibit_libc) \
&& (defined(__GLIBC__) || defined(__gnu_linux__) || defined(__GNU__))
/* On systems using glibc, an inhibit_libc build of libgcc is only
part of a bootstrap process. Build the same crt*.o as would be
built with headers present, so that it is not necessary to build
glibc more than once for the bootstrap to converge. */
# define USE_PT_GNU_EH_FRAME
#endif
Listing 3.2-8: the glibc exception (libgcc/crtstuff.c:121-132).
The other USE_PT_GNU_EH_FRAME blocks above it require !defined(inhibit_libc)
(crtstuff.c:88-119). This one requires the opposite, so a
stage-1 crtbegin.o for Linux matches the final one.
What inhibit_libc does not decide: libgcc_s.so
The shared libgcc is a separate decision. libgcc builds it when shared libraries
are enabled and the target knows how to link one
(libgcc/Makefile.in:392-397). The link rule ends in -lc
(libgcc/config/t-slibgcc:29-37), and inhibit_libc does not change
that. A stage 1 that builds libgcc with no C library therefore turns shared
libraries off as well. Chapter 4.2 covers
libgcc_s.so.
Reading the answer from gcc/Makefile and libgcc.mvars
The observable for this chapter is weak, and it is fair to say so. inhibit_libc
is a configure variable, not a compiler option. No driver option prints it. You
read it from the build tree:
$ grep '^inhibit_libc' build/gcc/Makefile
$ grep '^INHIBIT_LIBC_CFLAGS' build/gcc/libgcc.mvars
The first command works as soon as gcc/ is configured. Listing 3.2-5 shows that
the line reads inhibit_libc = true or inhibit_libc = false. The second works
after make all-gcc, which builds libgcc.mvars through libgcc-support. Its
value is -Dinhibit_libc or nothing. These commands were not run for this
chapter, because no GCC build tree was available. The values above come from the
rules in Listings 3.2-1 and 3.2-5.
To predict the value before you build, find the probe file from the table in this chapter and test for it:
$ ls /opt/cross/sysroot/usr/include/stdio.h
Diagnosing inhibit_libc from the error message
| Symptom | Step | Cause |
|---|---|---|
fatal error: stdio.h: No such file or directory in a libgcc source | make all-target-libgcc | inhibit_libc is false, so tsystem.h includes <stdio.h>. Check both clauses. |
The directory (BUILD_SYSTEM_HEADER_DIR) that should contain system headers does not exist: | make all-gcc | inhibit_libc is false, and the sysroot has no usr/include (Listing 3.2-2). |
undefined __gcov_exit when a --coverage program links | your link | libgcov was built with inhibit_libc. |
a -fsplit-stack program does not link | your link | generic-morestack.c compiled to nothing (Listing 3.2-7). |
The first message comes from the preprocessor, which reports a missing include as
the file name and the system's error text
(libcpp/files.cc:1869-1874, libcpp/errors.cc:358-359).
The last two rows are predictions from the source, not reproduced failures.
A stage-2 compiler that builds but gives a libstdc++ with features missing is a different problem. Its cause is libstdc++'s configure, not this switch, and Chapter 3.3 covers it.
Three things to carry away
inhibit_libc is two clauses, and each flag answers one. --with-newlib, or a
cross build with no sysroot, makes the first true. --without-headers, or a
missing stdio.h, makes the second true.
--with-sysroot turns the first clause off. A hosted stage 1 with a sysroot
keeps inhibit_libc false despite --without-headers, unless you add
--with-newlib.
It removes headers from libgcc, not calls. libgcc still needs malloc and
memcpy at link time, and it loses -fsplit-stack, gcov output and signal-frame
unwinding.
Things that surprise people
The probe looks in <target>/sys-include, not <target>/include. A bare-metal
compiler with no sysroot, configured with --with-newlib, keeps inhibit_libc
true in its final stage unless stdio.h is in sys-include.
A misspelled --without-header is accepted in silence. Neither the top-level
configure.ac nor gcc/configure.ac declares --with-headers or
--with-newlib, so configure --help does not list them. Unknown options
produce no warning, because the top level turns option checking off
(configure.ac:36) and passes --disable-option-checking to every
subdirectory (:3644-3646).
The misspelled flag sets a variable that neither script reads.
--with-headers=DIR writes into your install prefix at configure time. The
copy happens in the top-level configure, before any make.
On BPF, nvptx, AMD GCN and AVR, libgcc always uses -Dinhibit_libc. The
target's libgcc fragment sets it, whatever configure decided.
Documentation coverage
The install manual's Configuration page documents each flag on its
own: --with-sysroot (gcc/doc/install.texi:2709), --with-build-sysroot
(:2733), --with-headers (:2751), --without-headers (:2763) and
--with-newlib (:2776). Its Building page tells you to provide the
target headers with --with-sysroot or --with-headers before you configure
(install.texi:3313-3322). The Instrumentation Options node documents
-fprofile-info-section for freestanding targets (gcc/doc/invoke.texi:17800).
What is not documented:
inhibit_libcitself. The name does not appear ingcc/doc/.- That
--without-headersand--with-newlibanswer the two halves of one condition. This is the fact that would prevent the failure at the start of this chapter. - That
--with-sysrootturns the first half off. - That configure probes for
stdio.h, and which directory it probes. The--with-headersentry namesprefix/target/sys-include. The code uses the exec prefix, which is the same directory unless you give--exec-prefix. - That the documented effect of
--with-newlib, omitting__eprintffromlibgcc.a(install.texi:2776-2780), happens only throughinhibit_libc. So it happens only when the second half is also true. - That libgcc built this way still calls
mallocand the other functions thattsystem.hdeclares. - That such a libgcc has no split-stack support, stub gcov functions and no signal-frame unwinding.
Next: the seven steps of a hosted cross bootstrap, and why its stage 1 stops at
make all-gcc even though inhibit_libc is false.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
3.3 Hosted cross bootstrap: where glibc fits between GCC's make targets
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
You want an aarch64-linux-gnu toolchain, and nobody can hand you a sysroot.
Every guide gives you the same shell transcript: binutils, kernel headers, a GCC,
half of glibc, more GCC, all of glibc, then GCC again. When a step fails, the
transcript cannot tell you which earlier step it depended on. When its author
wrote it for an older glibc, a step can quietly do nothing at all.
GCC's build cannot wait for glibc, because glibc is not one of its modules. You are the dependency edge, and the recipe is a list of the places where you stand. Most steps exist because a named file in GCC's build reads something from the sysroot at that moment. This chapter names the file for each one.
This chapter assumes Chapter 3.1, for the
cycle and for where make all-gcc stops, and
Chapter 3.2, for the inhibit_libc condition. It
also uses the -print-file-name rule from
Chapter 1.5, the start files from
Chapter 1.7 and the assembled <limits.h> from
Chapter 1.8.
The C library has no edge in the Makefile: maybe-all-target-newlib
The top-level Makefile orders the target libraries by declared dependencies. A
comment in Makefile.def states the default: "By default target modules depend
on libgcc and newlib/libgloss" (Makefile.def:647-649). In the
generated Makefile.in, that dependency is a rule such as
configure-target-libstdc++-v3: maybe-all-target-newlib maybe-all-target-libgloss
(Makefile.in:69398). The rule names newlib and libgloss,
the C-library modules that GCC's tree can build itself. Here is the target it
waits on:
.PHONY: all-target-newlib maybe-all-target-newlib
maybe-all-target-newlib:
@if gcc-bootstrap
all-target-newlib: stage_current
@endif gcc-bootstrap
@if target-newlib
TARGET-target-newlib=all
maybe-all-target-newlib: all-target-newlib
all-target-newlib: configure-target-newlib
Listing 3.3-1: the C-library target (Makefile.in:49502-49510).
configure keeps the lines inside @if target-newlib only when newlib is a
configured target module, and a final sed expression removes every @if block
that remains (configure.ac:3400-3413). In a hosted build there is no
newlib in the tree, so maybe-all-target-newlib keeps no prerequisites. The edge
from "the C library" to every library that links against it is empty, and make
would run from libgcc straight into those libraries.
Chapter 3.6 shows the case where the edge is real.
So the recipe drives GCC's build with named targets, all-gcc
(Makefile.in:12440) and all-target-libgcc
(:50400), and puts glibc in the gaps between them.
The recipe: seven steps for aarch64-linux-gnu and glibc 2.42
Nobody ran this recipe end to end at GCC 15.2.0. Each reason for a step comes from the 15.2.0 sources. The glibc commands come from glibc 2.42's own files. The sequence as a whole is the conventional one, and it is not tested.
The glibc commands are glibc's interface, not GCC's. The chapter shows them
because the GCC steps around them depend on what they produce. For each one, it
says why GCC needs it. glibc's own INSTALL file is the authority for everything
else about them.
The commands use these variables, with the four source trees side by side and one build directory for each build:
TARGET=aarch64-linux-gnu
PREFIX=/opt/cross
SYSROOT=$PREFIX/$TARGET/sysroot
PATH=$PREFIX/bin:$PATH
Step 1: binutils, with the same --prefix and --with-sysroot
../binutils/configure --target=$TARGET --prefix=$PREFIX --with-sysroot=$SYSROOT
make && make install
This step needs nothing from the target. It gives GCC an assembler and a linker.
The install manual documents this step under
Building a cross compiler: GCC expects the cross tools in
prefix/target/bin, and binutils configured with the same --target and
--prefix installs them there (install.texi:3281-3311). binutils has its own
--with-sysroot, which is a different mechanism with the same name. It is outside
this book.
Step 2: kernel headers, so that $SYSROOT/usr/include exists
make -C linux ARCH=arm64 INSTALL_HDR_PATH=$SYSROOT/usr headers_install
glibc documents this command for its own reasons. glibc reads the kernel
interface from these headers (glibc INSTALL:620-635).
GCC needs them for a smaller reason. Its stage-1 build runs fixincludes, and
fixincludes stops when the system header directory is missing:
if ! $(inhibit_libc) && test ! -d ${BUILD_SYSTEM_HEADER_DIR}; then \
echo "The directory (BUILD_SYSTEM_HEADER_DIR) that should contain system headers does not exist:" >&2 ; \
echo " ${BUILD_SYSTEM_HEADER_DIR}" >&2 ; \
case ${build_os} in \
darwin*) \
echo "(on Darwin this usually means you need to pass the --with-sysroot= flag to point to a valid MacOS SDK)" >&2; \
;; \
esac; \
tooldir_sysinc=`echo "${gcc_tooldir}/sys-include" | sed -e :a -e "s,[^/]*/\.\.\/,," -e ta`; \
if test "x${BUILD_SYSTEM_HEADER_DIR}" = "x$${tooldir_sysinc}"; \
then sleep 1; else exit 1; fi; \
fi; \
Listing 3.3-2: the check in the stmp-fixinc rule
(gcc/Makefile.in:3616-3627).
In this recipe inhibit_libc is false, because --with-sysroot makes the first
half of its condition false (Chapter 3.2). With a
sysroot, BUILD_SYSTEM_HEADER_DIR is the sysroot's /usr/include
(gcc/configure.ac:174 and :2544). If step 2
has not run, make all-gcc stops in stmp-fixinc with the message above. The
sleep 1 branch is for the other layout, a cross compiler with no sysroot, whose
headers go in tooldir/sys-include.
The test asks only that the directory exists. The kernel headers make it exist, and GCC needs nothing from glibc yet.
Step 3: stage-1 GCC, with make all-gcc and --with-glibc-version
mkdir build-gcc1 && cd build-gcc1
../gcc-15.2.0/configure --target=$TARGET --prefix=$PREFIX \
--with-sysroot=$SYSROOT --enable-languages=c \
--with-glibc-version=2.42
make all-gcc && make install-gcc
This step needs binutils and the header directory. It gives an installed
$TARGET-gcc that compiles but cannot link a program yet. glibc's configure
accepts a compiler like that on purpose. It replaces Autoconf's executable test,
with the comment "These modifications are to allow for an empty cross compiler
tree" (glibc aclocal.m4:96-98).
The target is all-gcc because inhibit_libc is false. If make built libgcc
now, libgcc would compile the parts that include libc headers, and those headers
do not exist yet. make all-gcc never gets that far, because libgcc's configure step
comes after all-gcc and not the other way around
(Makefile.in:67908).
Chapter 3.1 shows the difference between
the two targets.
Many transcripts also pass --without-headers at this step. With a sysroot it
cannot make inhibit_libc true (Chapter 3.2). The only other reader of
with_headers in gcc/configure.ac is a test for s390
(gcc/configure.ac:7892). For this target the flag does nothing.
The recipe also needs no --disable-multilib, because aarch64 GNU/Linux builds
one variant, lp64, unless --with-multilib-list asks for more
(gcc/config.gcc:1249-1253).
What stage 1 reads from a sysroot with no C library: target_header_dir
This is the part that the transcripts leave out. Stage 1 reads the sysroot's
/usr/include twice. configure reads it as target_header_dir, which
--with-sysroot sets to that directory
(gcc/configure.ac:2563). make reads it as
BUILD_SYSTEM_HEADER_DIR, as in Listing 3.3-2. At step 3 the directory holds only
the kernel headers. Three probes find less than they will find after step 6:
stdio.h, forinhibit_libc. With a sysroot, this probe does not change the result (Chapter 3.2).features.h, for the glibc version (Listing 3.3-3).limits.h, forLIMITS_H_TEST, whenmakeassembles GCC's own<limits.h>(Chapter 1.8, Listing 1.8-9).
Here is the glibc version probe. It runs when --with-glibc-version is absent:
glibc_version_major=0
glibc_version_minor=0
[if test -f $target_header_dir/features.h \
&& glibc_version_major_define=`$EGREP '^[ ]*#[ ]*define[ ]+__GLIBC__[ ]+[0-9]' $target_header_dir/features.h` \
&& glibc_version_minor_define=`$EGREP '^[ ]*#[ ]*define[ ]+__GLIBC_MINOR__[ ]+[0-9]' $target_header_dir/features.h`; then
glibc_version_major=`echo "$glibc_version_major_define" | sed -e 's/.*__GLIBC__[ ]*//'`
glibc_version_minor=`echo "$glibc_version_minor_define" | sed -e 's/.*__GLIBC_MINOR__[ ]*//'`
fi]])
Listing 3.3-3: reading the glibc version from features.h
(gcc/configure.ac:6030-6037).
With no features.h, the version stays 0.0. It goes into auto-host.h as
TARGET_GLIBC_MAJOR and TARGET_GLIBC_MINOR
(gcc/configure.ac:6039-6042). Every later
GCC_GLIBC_VERSION_GTE_IFELSE test compares against it
(gcc/acinclude.m4:548-556). Among other things, those tests
decide:
- whether the target C library provides the stack protector
(
gcc/configure.ac:6958-6961), - whether to use
@gnu_unique_object(:6056), - on PowerPC, SPARC, s390 and Alpha, whether
long doubleis 128 bits wide (:7051).
The last one changes the ABI that stage 1 compiles glibc with. Chapter 2.6 owns that case.
The install manual documents --with-glibc-version on its
Configuration page, and it names this situation
(install.texi:2620-2625). The option "may be needed when bootstrapping a cross
toolchain without the header files available for building the initial bootstrap
compiler". Give it the version of the glibc that you are about to build.
Step 4: glibc headers, crti.o, crtn.o and a placeholder libc.so
mkdir build-glibc && cd build-glibc
../glibc-2.42/configure --prefix=/usr --host=$TARGET \
--build=$(../glibc-2.42/scripts/config.guess) \
--with-headers=$SYSROOT/usr/include CC=$TARGET-gcc
make install-headers DESTDIR=$SYSROOT
make csu/subdir_lib
mkdir -p $SYSROOT/usr/lib64
cp csu/crt1.o csu/crti.o csu/crtn.o $SYSROOT/usr/lib64
$TARGET-gcc -nostdlib -nostartfiles -shared -x c /dev/null \
-o $SYSROOT/usr/lib64/libc.so
touch $SYSROOT/usr/include/gnu/stubs.h
This step needs the stage-1 compiler and the kernel headers. The lines after
configure put four things in the sysroot that step 5 reads. Step 5 builds
libgcc in full, including the shared library, and GCC's sources decide what that
build needs.
The first is the libc headers, because inhibit_libc is false. Chapter 3.2 lists
what libgcc compiles in that case.
The second is crti.o and crtn.o. The driver links libgcc_s.so.1 with
-shared, and it keeps the start files. On GNU/Linux the start-file specs put
crti.o and crtn.o in every such link
(gcc/config/gnu-user.h:43-44). For a shared link the same spec
adds no crt1.o, because its first clause is %{shared:; ...}
(gnu-user.h:51-58). The recipe copies crt1.o now only
because the same glibc target builds it (glibc csu/Makefile:174-175).
The third is a libc.so, because the link line for libgcc_s.so.1 ends in
-lc:
SHLIB_LC = -lc
...
SHLIB_LINK = $(CC) $(LIBGCC2_CFLAGS) -shared -nodefaultlibs \
$(SHLIB_LDFLAGS) $(LDFLAGS) \
-o $(SHLIB_DIR)/$(SHLIB_SONAME).tmp @multilib_flags@ \
$(SHLIB_OBJS) $(SHLIB_LC) && \
Listing 3.3-4: how libgcc links its shared library, abridged
(libgcc/config/t-slibgcc:29-37).
-nodefaultlibs removes the default libraries, and SHLIB_LC then adds -lc
back by name. Every GNU/Linux target uses this fragment
(libgcc/config.host:313-314). The real libc.so does not
exist until step 6, so the recipe links an empty shared object under that name.
It satisfies the link and nothing more.
The fourth is gnu/stubs.h. glibc's features.h includes it
(glibc include/features.h:548), and glibc generates it only at
the end of a full make install (glibc Makefile:452-458). An
empty file is enough until then.
The files go into usr/lib64 because step 6 installs the real ones there.
glibc's aarch64 port installs its libraries into lib64
(glibc sysdeps/unix/sysv/linux/aarch64/configure.ac:6). GCC's
aarch64 GNU/Linux port names ../lib64 as the OS directory for lp64
(gcc/config/aarch64/t-aarch64-linux:25), and the driver adds
it to /usr/lib (Chapter 1.6). Step 6 then overwrites
the placeholders. To check that the driver finds them, run
$TARGET-gcc -print-file-name=crti.o. If it echoes the name back, the driver did
not find the file (Chapter 1.5).
DESTDIR works for install-headers too. glibc documents it for make install
(glibc INSTALL:429-435). Its makefiles copy it into
install_root, and every installation directory starts with install_root
(glibc config.make.in:8 and
Makeconfig:180).
Older transcripts also pass install-bootstrap-headers=yes here. No file in the
glibc 2.42 release contains that name. make accepts the
assignment, and nothing reads it.
Step 5: make all-target-libgcc, not make
cd build-gcc1
make all-target-libgcc && make install-target-libgcc
This step needs everything that step 4 put in the sysroot. It gives libgcc.a,
libgcc_s.so.1 and the crtbegin and crtend objects
(libgcc/config.host:315). glibc's build in step 6 needs
only libgcc.a. It links its own libraries and programs with -lgcc alone
(glibc Makeconfig:719 and :732). The
comment above those lines gives the reason: "To avoid circular dependencies when
bootstrapping, it is desirable to avoid use of libgcc_s and libgcc_eh in building
glibc" (glibc Makeconfig:682-683).
A plain make would not stop after libgcc. Because the C-library edge of
Listing 3.3-1 is empty, make would go on to configure the other target
libraries. libgomp is one of them, because the top-level configure turns it
on by default for *-linux* targets
(configure.ac:529-546). libgomp's configure must link
programs. Autoconf's compiler check links one
(libgomp/configure.ac:114), and a later check links a call
to pthread_create (:198-214). With a placeholder
libc.so, the first link fails, and configure stops with "C compiler cannot
create executables". Chapter 3.5 explains what
that message points at.
Step 6: the full glibc
cd build-glibc
make && make install DESTDIR=$SYSROOT
This step needs libgcc.a from step 5. It gives the complete C library: the real
libc.so, the shared libraries, the start files and a generated gnu/stubs.h.
They replace every placeholder from step 4. Nothing new happens on GCC's side.
The sysroot is now complete, and GCC's configure last read it at step 3.
Step 7: a fresh build directory, with --enable-languages=c,c++
mkdir build-gcc2 && cd build-gcc2
../gcc-15.2.0/configure --target=$TARGET --prefix=$PREFIX \
--with-sysroot=$SYSROOT --enable-languages=c,c++
make && make install
This step needs the complete sysroot. It gives the compiler that you ship. It is
a new build directory, and not another make in build-gcc1, because the
stage-1 tree recorded what the sysroot held at step 3. Four things in it are
wrong for the finished toolchain.
The first is the glibc version. A new configure reads features.h again
(Listing 3.3-3) and finds the real version. You no longer need
--with-glibc-version.
The second is <limits.h>. At step 3 the sysroot had no limits.h, so LIMITS_H_TEST
failed and the build assembled GCC's <limits.h> without the #include_next
that reaches glibc's (Chapter 1.8). The stamp
that builds it depends only on GCC's own files
(gcc/Makefile.in:3475), so no later make in build-gcc1
rebuilds it. A program that includes <limits.h> through that compiler gets none
of what glibc's limits.h adds, such as the POSIX limits
(glibc include/limits.h:193-196). fixincludes also ran on
the kernel headers only.
The third is libgcc_s.so.1. Step 5 linked it against the placeholder
libc.so. The new build links it against the real one.
The fourth is libstdc++. On a cross build, libstdc++'s configure decides its features by
linking test programs against the target C library. For GNU/Linux targets it
runs these checks, among others:
GCC_CHECK_TLS
AC_CHECK_FUNCS(__cxa_thread_atexit_impl)
AC_CHECK_FUNCS(aligned_alloc posix_memalign memalign _aligned_malloc)
AC_CHECK_FUNCS(timespec_get)
AC_CHECK_FUNCS(sockatmark)
AC_CHECK_FUNCS(uselocale)
Listing 3.3-5: libstdc++'s link tests for *-linux*
(libstdc++-v3/crossconfig.m4:184-189, in the branch that
starts at :177).
Each AC_CHECK_FUNCS defines a HAVE_ macro only when the test program links
(Autoconf manual, Generic Function Checks). When the test does
not find a function, its macro stays undefined, and libstdc++ builds without the
code that needs it. For example, the check for __cxa_thread_atexit_impl decides whether
thread_local destructors call glibc's function or libstdc++'s own fallback
(libstdc++-v3/libsupc++/atexit_thread.cc:60-72). If no program
links at all, configure stops instead, with "Link tests are not allowed after
GCC_NO_EXECUTABLES" (config/no-executables.m4:44-47).
libstdc++ applies that macro to every cross build except a Darwin one
(libstdc++-v3/configure.ac:36-56). A C library that links but
lacks functions gives you a smaller libstdc++, not an error. Configure
libstdc++ only after the complete glibc is in the sysroot.
Five steps instead of seven: build-many-glibcs.py
glibc's source tree contains a script that builds cross compilers and then
glibc for many configurations, scripts/build-many-glibcs.py
(glibc build-many-glibcs.py:21-29). Its order is binutils, kernel
headers, a first GCC, glibc, and a final GCC
(glibc build-many-glibcs.py:1410-1429). There is no minimal-libc
pass. Its first GCC explains why:
tool_build = 'gcc-first'
# Building a static-only, C-only compiler that is
# sufficient to build glibc. Various libraries and
# features that may require libc headers must be disabled.
# When configuring with a sysroot, --with-newlib is
# required to define inhibit_libc (to stop some parts of
# libgcc including libc headers); --without-headers is not
# sufficient.
cfg_opts += ['--enable-languages=c', '--disable-shared',
'--disable-threads',
'--disable-libatomic',
'--disable-decimal-float',
'--disable-gcov',
'--disable-libffi',
'--disable-libgomp',
'--disable-libitm',
'--disable-libmpx',
'--disable-libquadmath',
'--disable-libsanitizer',
'--without-headers', '--with-newlib',
'--with-glibc-version=%s' % self.ctx.glibc_version
]
Listing 3.3-6: the first GCC in glibc's own script
(glibc scripts/build-many-glibcs.py:1518-1539).
Two flags remove the reasons for steps 4 and 5. --with-newlib, together with
--without-headers, makes inhibit_libc true even with a sysroot, as the comment
says. libgcc then compiles without libc headers. Chapter 3.2 has the condition. --disable-shared removes
libgcc_s.so.1, and with it the -lc link of Listing 3.3-4. The --disable-lib*
flags remove the libraries that would need a C library, so the script builds this
GCC with a plain make (glibc build-many-glibcs.py:1450). glibc
then builds in full against libgcc.a alone, which is all it asks for. The
final GCC is a new configure with --enable-languages=c,c++ and
--enable-shared (:1541-1552).
The script passes --with-glibc-version to the first GCC for the reason that
step 3 gives. It does not pass --with-newlib to the final GCC, and you must not
either: with --with-newlib, libstdc++'s cross configure takes its newlib
branch (libstdc++-v3/configure.ac:340-341).
The seven-step recipe shows what each part of libgcc needs from the C library. glibc keeps the five-step one in its own tree, and it uses fewer glibc-internal targets. Nobody ran either one for this book at GCC 15.2.0.
--with-build-sysroot: when the sysroot is not where it will live
The recipe builds into $SYSROOT, which is also the path given to
--with-sysroot. If you build in a staging directory and move the result later,
the build must read one path and the installed compiler must search another.
--with-build-sysroot gives the first one. The install manual documents it under
Cross-Compiler-Specific Options as the system root "while
building target libraries" (install.texi:2733-2745).
It does more than the manual says. In gcc/configure.ac it also replaces the
sysroot in the two header paths that stage 1 probes:
if test "x$with_build_sysroot" != x; then
BUILD_SYSTEM_HEADER_DIR=$with_build_sysroot'$${sysroot_headers_suffix}$(NATIVE_SYSTEM_HEADER_DIR)'
...
if test "x$with_build_sysroot" != "x"; then
target_header_dir="${with_build_sysroot}${native_system_header_dir}"
Listing 3.3-7: --with-build-sysroot moves the header probes, abridged
(gcc/configure.ac:2541-2542 and
:2556-2557).
So fixincludes, LIMITS_H_TEST, and the stdio.h and features.h probes all
look in the build sysroot. The target libraries get --sysroot=DIR on their
compiler command line. The top-level configure stores it as
SYSROOT_CFLAGS_FOR_TARGET (configure.ac:2868-2875), and the
Makefile adds it to the CC that configures every target library
(Makefile.tpl:637 and :308). Every
testsuite compile gets it too, as TEST_ALWAYS_FLAGS
(gcc/Makefile.in:4520-4522).
Chapter 3.7 covers the testsuite. The
installed driver keeps the --with-sysroot path, which configure takes from
--with-sysroot alone (gcc/configure.ac:168-171).
Checking the result: -print-file-name, -dumpspecs and -H
The first check works on any finished toolchain:
$ aarch64-linux-gnu-gcc -print-sysroot
$ aarch64-linux-gnu-gcc -print-file-name=crt1.o
$ aarch64-linux-gnu-gcc -print-file-name=crtbegin.o
$ echo 'int main(void){return 0;}' | aarch64-linux-gnu-gcc -x c - -o /tmp/t && echo OK
-print-sysroot must print $SYSROOT. The two -print-file-name lines must
print a path, not the name you typed (Chapter 1.5). An echoed crt1.o points at
glibc and the sysroot. An echoed crtbegin.o points at GCC's own installation.
The link puts the start files, libgcc and the C library on one command line.
The next three checks find a final compiler that configure set up against an
incomplete sysroot. The link test does not find that:
$ aarch64-linux-gnu-gcc -dumpspecs | grep -A1 '^\*link_ssp:'
$ echo '#include <limits.h>' | aarch64-linux-gnu-gcc -H -E -x c - 2>&1 >/dev/null
$ grep -E 'TARGET_GLIBC_(MAJOR|MINOR)' build-gcc2/gcc/auto-host.h
-dumpspecs prints every spec (gcc/gcc.cc:4216-4225), and
link_ssp is one of them (:1724). Its value comes from
LINK_SSP_SPEC (gcc/gcc.cc:994-1002). It is an empty %{...:}
when configure found stack protector support in the C library, and it adds
-lssp_nonshared -lssp when it did not. A final compiler that found glibc 2.42
must show the first form. The -H line shows the include tree that
Chapter 1.8 describes: GCC's limits.h, then syslimits.h, then the sysroot's
limits.h. A limits.h from step 3 stops at the first. The auto-host.h line
works only in a build tree. It must show the version that you installed, not
0.
Three things to carry away
glibc is not a module of GCC's build, so make cannot wait for it. The
recipe stops GCC's build at all-gcc and at all-target-libgcc, and puts glibc
in the gaps.
Steps 4 and 5 exist only for a shared libgcc that includes libc headers.
--with-newlib, --without-headers and --disable-shared remove both reasons,
and glibc's own script needs only five steps.
The first GCC reads a sysroot that has no C library in it. Its glibc version, its <limits.h> and its fixed headers stay wrong until a new build
directory reads the finished sysroot.
Things that surprise people
The kernel headers are a GCC prerequisite, not only glibc's. Without
$SYSROOT/usr/include, stage 1 stops in fixincludes, before any glibc command
runs.
install-bootstrap-headers=yes does nothing with glibc 2.42. No file in the
release reads it.
Another make in the stage-1 tree leaves <limits.h> as it was. The stamp
does not depend on the sysroot, so make sees nothing to rebuild.
Documentation coverage
The install manual documents the configure flags one at a time. The
cross-specific ones are under Cross-Compiler-Specific Options
(gcc/doc/install.texi:2701): --with-sysroot at :2709,
--with-build-sysroot at :2733, --without-headers at :2763 and
--with-newlib at :2776. --with-glibc-version is on the
Configuration page (:2620). Its entry is the only place
where the manual mentions bootstrapping a cross toolchain (:2624-2625).
Building a cross compiler (:3247) assumes that the C library
exists: "you should also provide the target libraries and headers before
configuring GCC" (:3313-3315). -print-file-name, -print-sysroot and
-dumpspecs are in Developer Options
(gcc/doc/invoke.texi:21571, :21635 and :21668).
What is not documented:
- The order of the steps. No GCC manual describes building GCC around a C library that does not exist yet.
- That stage-1 fixincludes stops when
inhibit_libcis false and the sysroot has no/usr/include. - That the shared libgcc link needs
crti.o,crtn.oand alibc.so. - That
configurereadsfeatures.handstdio.hfrom the sysroot, andmakereadslimits.h, and that the build tree keeps what they found. - That
makecannot order a C library that is outside GCC's tree. - That
--with-build-sysrootalso moves the header probes and fixincludes for GCC itself. The manual describes it for target libraries only. - That libstdc++'s cross
configuredrops a feature, without an error, when the C library links but lacks the function.
Next: the bare-metal recipe, where there is no kernel and no sysroot, and two GCC phases replace three.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
3.4 Bare metal: two GCC configures around newlib, and no sysroot
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
The bare-metal recipe you found has four steps. Its first GCC has
--disable-multilib, and its last step is make all in the build directory of
that first GCC. Everything builds, and the toolchain links a test program. Then a
colleague adds --coverage to a build, and the sources say that the link will
fail on an undefined __gcov_exit. Another colleague passes
-mthumb -march=armv7e-m+fp -mfloat-abi=hard and gets the one libc.a that
newlib built, for the default variant.
A bare-metal toolchain is two configure runs of GCC with newlib installed
between them, and no sysroot anywhere. The first GCC only has to compile
newlib. newlib asks that first compiler which variants to build. Everything the
first configure decided stays decided in its build tree, and every target file
lands in the tooldir, $prefix/<target>/, which the driver already searches.
This chapter assumes Chapter 3.1 for the
cycle and for why stage 1 stops at make all-gcc, and
Chapter 3.2 for the inhibit_libc condition. It
also assumes Chapter 1.5 for the tooldir prefix and
Chapter 1.6 for the multilib fallback.
The recipe for arm-none-eabi
Nobody ran this recipe end to end at
releases/gcc-15.2.0. Each flag, and each claim about what a step needs, is checked against the sources this chapter cites. The order of the steps is the conventional one. newlib claims cite newlib 4.5.0.
$ # 1. binutils
$ $SRC/binutils/configure --target=arm-none-eabi --prefix=/opt/cross
$ make && make install
$ export PATH=/opt/cross/bin:$PATH
$ # 2. stage 1: a compiler, and no target libraries
$ $SRC/gcc-15.2.0/configure --target=arm-none-eabi --prefix=/opt/cross \
--enable-languages=c --without-headers --with-multilib-list=rmprofile
$ make all-gcc && make install-gcc
$ # 3. newlib, from the top of its own source tree
$ $SRC/newlib-4.5.0/configure --target=arm-none-eabi --prefix=/opt/cross
$ make && make install
$ # 4. stage 2: a new build directory and a new configure
$ $SRC/gcc-15.2.0/configure --target=arm-none-eabi --prefix=/opt/cross \
--enable-languages=c,c++ --with-newlib --with-multilib-list=rmprofile
$ make && make install
There are two GCC phases, not three, because there is no C library to build in
two passes. The hosted recipe in
Chapter 3.3 needs kernel headers and a
minimal libc before its second GCC. Here, newlib is complete after one build.
The install manual documents each GCC flag in this recipe on its
Configuration page: --prefix (install.texi:910),
--enable-languages (:2094), --with-multilib-list (:1325),
--without-headers (:2763) and --with-newlib (:2776). The sections below
say why each one is at its step.
Step 1: binutils, and the target name that names directories
GCC needs a cross assembler and linker before stage 1. The install manual's
Building a cross compiler section documents where they go:
$prefix/<target>/bin (install.texi:3281-3310). The driver searches that
directory through the tooldir prefix (gcc.cc:5534-5536).
binutils takes no --with-sysroot here, and its own flags are binutils'
business.
Spell --target the same way in all four steps. The string you type becomes a
directory name on both sides. GCC's top level sets
tooldir='${exec_prefix}'/${target_noncanonical}
(configure.ac:3121-3122), and
Chapter 2.2 shows that
target_noncanonical is the target as typed. newlib's top level gives each of
its libraries that same string as --host (newlib 4.5.0
Makefile.tpl:48 and :1349), and newlib
installs into $(exec_prefix)/$(host_alias) (Listing 3.4-2). So
--target=arm-eabi for GCC and --target=arm-none-eabi for newlib give two
tooldirs, and the driver searches only one of them.
The export PATH line is for step 3. newlib's configure looks for the target
compiler as <target>-gcc on PATH (newlib 4.5.0
configure.ac:3433). The macro behind that line prefixes
the program name with the target as typed
(config/acx.m4:116-117), and newlib carries the same macro.
Step 2: stage 1 with --without-headers and make all-gcc
Stage 1 exists to compile newlib, and newlib never links anything while it
configures. Its configure macro calls AC_NO_EXECUTABLES (newlib 4.5.0
newlib/acinclude.m4:121), and libgloss does the same
(libgloss/configure.ac:38). So the stage-1 compiler and binutils
are enough. Stage 1 needs no libgcc, no crt0.o and no linker script.
Chapter 3.1 explains why make all-gcc
stops before libgcc.
--without-headers makes inhibit_libc true without looking at the disk.
Chapter 3.2 gives the condition. On this layout, a
cross build with no sysroot already satisfies its first clause, so
--with-newlib adds nothing in stage 1. gcc/configure reads with_newlib in
exactly one place, that condition (gcc/configure.ac:2579).
Many recipes pass it in stage 1 anyway. It is harmless there, and it earns its
place in step 4.
Stage 1 must use the same multilib setting as stage 2. That is not about stage 1
itself, which builds no libraries. It is about newlib, which asks the stage-1
compiler for its variant list in step 3. A stage-1 --disable-multilib gives the
driver one variant: s-mlib then runs genmultilib with every list empty
(gcc/Makefile.in:2479-2499). The section on
--with-multilib-list=rmprofile below says which list to choose.
Step 3: newlib, built by the stage-1 compiler
newlib's own README states the order: "NOTE THAT YOU MUST HAVE ALREADY BUILT AND
INSTALLED GCC and BINUTILS." (newlib 4.5.0 newlib/README:40).
Configure newlib from the top of its source tree. That top level is built from
the same Makefile.tpl as GCC's, and it turns --target into each library's
--host (Makefile.tpl:1349).
newlib builds one copy of libc.a per line that the compiler prints for
--print-multi-lib:
multidirs=
for i in `${CC-gcc} --print-multi-lib 2>/dev/null`; do
dir=`echo $i | sed -e 's/;.*$//'`
Listing 3.4-1: newlib's variant list comes from the compiler (newlib 4.5.0
config-ml.in:217-219).
CC is the stage-1 arm-none-eabi-gcc. This is the whole reason the stage-1
multilib setting matters. A one-variant stage 1 gives a one-variant newlib. The
stage-2 driver then asks for a Thumb hard-float libc.a, finds no such
directory, and falls back to the default one. That is the second pass of
for_each_path, and Chapter 1.6 shows why it does not
fail. In a combined tree the top level hands newlib the same list from xgcc.
That is Chapter 3.6's subject.
config-ml.in can only remove lines from that list. The install manual lists
per-target switches under --disable-multilib, such as fpu for arm-*-*
(install.texi:1304-1308). For Arm, config-ml.in drops every directory whose
name contains fpu when it sees --disable-fpu (newlib 4.5.0
config-ml.in:234-245). Nothing in gcc/configure.ac,
gcc/config.gcc or the top-level configure.ac reads that switch, so the
driver still selects the variants that newlib skipped.
newlib installs into the tooldir:
tooldir = $(exec_prefix)/$(host_alias)
toollibdir = $(tooldir)/lib$(MULTISUBDIR)
Listing 3.4-2: newlib's install directories (newlib 4.5.0
newlib/Makefile.am:67-68).
libc.a, libm.a and crt0.o go to toollibdir, one directory per variant
(:75-76 and :86). The headers go to
$(tooldir)/include (:264-268). That is
/opt/cross/arm-none-eabi/include, not sys-include. The difference matters in
step 4.
Step 4: stage 2 is a new configure, not make all
The stage-1 build tree keeps every decision its configure made. configure
substitutes inhibit_libc into gcc/Makefile
(gcc/configure.ac:2583), and the makefile turns true into
-Dinhibit_libc for libgcc (gcc/Makefile.in:789-794). Because
stage 1 had --without-headers, that value is true whatever is on disk. The
multilib list is fixed in multilib.h by the s-mlib rule
(gcc/Makefile.in:2479-2499). The install manual documents that
--enable-languages builds only the listed compilers and their runtime
libraries (install.texi:2094-2096). So make all in the stage-1 tree builds a
C-only toolchain whose libgcc can never have its libc-dependent parts. Configure
again, in a new directory, with the same --prefix and --target.
The stage-2 build compiles libgcc and libstdc++ with the xgcc it has just
built, not with the installed driver. The top level tells that xgcc where the
installed newlib is:
if test "${build}" = "${host}" && test -d ${srcdir}/gcc; then
# Search for pre-installed headers if nothing else fits.
FLAGS_FOR_TARGET=$FLAGS_FOR_TARGET' -B$(build_tooldir)/bin/ -B$(build_tooldir)/lib/ -isystem $(build_tooldir)/include -isystem $(build_tooldir)/sys-include'
fi
Listing 3.4-3: the installed tooldir, handed to the build-tree compiler
(configure.ac:3829-3832).
build_tooldir is GCC's tooldir, $exec_prefix/<target>
(configure.ac:3121-3122). That is the directory newlib
installed into in Listing 3.4-2. FLAGS_FOR_TARGET becomes part of
the CC that every target library is configured with
(Makefile.tpl:637 and :308). That is why
newlib must be installed at the same prefix before step 4 runs.
--with-newlib in stage 2 is for libstdc++
The top level passes every --with-* option on to the target libraries'
configure scripts. It holds back only the GMP, MPFR, MPC and isl options, and
libintl and libiconv (configure.ac:3548 and
:3557, in the loop at :3472-3617). So libstdc++'s
configure sees --with-newlib, and that is where the option does its real work.
libstdc++ cannot link test programs on a cross target. Its configure explains
why, in a comment that names the file you lack: "cannot open crt0.o"
(libstdc++-v3/configure.ac:309-322). So it hard-codes what it
knows about the C library:
# Construct crosses by hand, eliminating bits that need ld...
# GLIBCXX_CHECK_MATH_SUPPORT
# First, test for "known" system libraries. We may be using newlib even
# on a hosted environment.
if test "x${with_newlib}" = "xyes"; then
os_include_dir="os/newlib"
Listing 3.4-4: the newlib branch of libstdc++'s cross configuration
(libstdc++-v3/configure.ac:335-341).
Without --with-newlib, and with headers allowed, configure takes the other
branch and calls GLIBCXX_CROSSCONFIG
(:420-421). That macro chooses by target name, and
nothing in it matches arm-none-eabi:
*)
AC_MSG_ERROR([No support for this host/target combination.])
Listing 3.4-5: the default case of GLIBCXX_CROSSCONFIG
(libstdc++-v3/crossconfig.m4:302-303).
So a stage 2 with C++ and no --with-newlib stops in libstdc++'s configure.
inhibit_libc is still true after stage 2
A fresh configure does not make libgcc complete. The second clause of the
condition probes for stdio.h in $target_header_dir. With no sysroot, that is
${test_exec_prefix}/${target_noncanonical}/sys-include
(gcc/configure.ac:2558-2559). newlib installed its headers in
include, next to it. So the probe fails, and stage 2's libgcc is built with
-Dinhibit_libc like stage 1's. Chapter 3.2 lists
what that removes, starting with the --coverage failure in this chapter's
first paragraph.
If you need those parts, give stage 2 --with-headers=DIR. The install manual
documents the option under Configuration, as deprecated in favour
of --with-sysroot, and says that fixincludes runs on the copied files
(install.texi:2751-2762). The source shows when the copy happens. The top-level
configure copies DIR into $prefix/<target>/sys-include
(configure.ac:2931-2942) during its own run
(:3005-3033). gcc/configure runs later, from make, and then
finds stdio.h. For this recipe, DIR is /opt/cross/arm-none-eabi/include.
The tooldir, instead of a sysroot
No step passes --with-sysroot, so the driver has none. -print-sysroot then
prints nothing (gcc.cc:8876-8886), as the GCC manual
documents under Developer Options (invoke.texi:21635-21640).
The tooldir does the sysroot's job:
| What | Installed by | Directory | How the driver finds it |
|---|---|---|---|
arm-none-eabi-as, -ld | binutils | $prefix/<target>/bin | tooldir bin prefix, gcc.cc:5534-5536 |
stdio.h and the other libc headers | newlib | $prefix/<target>/include | TOOL_INCLUDE_DIR, gcc/Makefile.in:2613 |
nothing, unless --with-headers=DIR | top-level configure | $prefix/<target>/sys-include | CROSS_INCLUDE_DIR, before include |
libc.a, libm.a, crt0.o | newlib | $prefix/<target>/lib/<variant> | tooldir lib prefix, gcc.cc:5537-5539 |
libnosys.a, nosys.specs, nano.specs | libgloss | $prefix/<target>/lib/<variant> | the same prefix |
libgcc.a, crti.o, crtbegin.o, crtend.o, crtn.o | libgcc | $prefix/lib/gcc/<target>/15.2.0/<variant> | GCC's own prefix, Chapter 1.5 |
On a cross build with no sysroot, cppdefault.cc drops /usr/include and
/usr/local/include from the header search and keeps sys-include
(gcc/cppdefault.cc:30-35). sys-include then comes just
before the tooldir's include (:90-97).
sys-include is CROSS_SYSTEM_HEADER_DIR, $(gcc_tooldir)/sys-include, when no
sysroot is given (gcc/configure.ac:185-189).
Chapter 1.8 covers the rest of the list.
This is the layout's one trap. The compiler finds newlib's headers in include.
The inhibit_libc probe looks for them in sys-include. Both directories are
in the table, and only one of them has the files.
The arm-none-eabi link line: __aeabi_*, crt0.o and --start-group
The most common bare-metal link failure is an undefined __aeabi_idiv after
-nostdlib. Chapter 1.10 owns it: the
compiler emits calls into libgcc whatever you link, so -nostdlib needs -lgcc
back by hand. On this target, the names come from the Arm back end:
/* For SImode division the ABI provides div-without-mod routines,
which are faster. */
set_optab_libfunc (sdiv_optab, SImode, "__aeabi_idiv");
set_optab_libfunc (udiv_optab, SImode, "__aeabi_uidiv");
Listing 3.4-6: where __aeabi_idiv gets its name
(gcc/config/arm/arm.cc:2663-2666).
arm_init_libfuncs returns early unless the target uses the BPABI
(arm.cc:2573-2576). arm-none-eabi does: bpabi.h makes
AAPCS the default ABI and defines TARGET_BPABI as TARGET_AAPCS_BASED
(bpabi.h:27-30).
STARTFILE_SPEC in arm/unknown-elf.h: three providers
Without -nostdlib, the startfiles come from arm/unknown-elf.h, which
config.gcc puts in the arm*-*-eabi* header list:
/* Now we define the strings used to build the spec file. */
#define UNKNOWN_ELF_STARTFILE_SPEC " crti%O%s crtbegin%O%s crt0%O%s"
#undef STARTFILE_SPEC
#define STARTFILE_SPEC \
"%{Ofast|ffast-math|funsafe-math-optimizations:%{!shared:crtfastmath.o%s}} " \
UNKNOWN_ELF_STARTFILE_SPEC
#define UNKNOWN_ELF_ENDFILE_SPEC "crtend%O%s crtn%O%s"
#undef ENDFILE_SPEC
#define ENDFILE_SPEC UNKNOWN_ELF_ENDFILE_SPEC
Listing 3.4-7: the bare-metal Arm startfiles
(gcc/config/arm/unknown-elf.h:31-42).
libgcc supplies crti.o, crtbegin.o, crtend.o and crtn.o on this target
(libgcc/config.host:578-584), and t-crtfm in the same entry
supplies crtfastmath.o. crt0.o is the C library's. By default newlib builds
it (newlib/Makefile.am:86). With
--disable-newlib-supplied-syscalls, newlib has no crt0.o for Arm (newlib
4.5.0 newlib/configure.host:466-470), and libgloss installs one
instead (libgloss/arm/Makefile.inc:1-3). Either way, the file
lands in the tooldir and %s finds it.
The port also adds no linker script. Its LINK_SPEC has no -T
(bpabi.h:81-87), so the script is yours or a board package's.
The GCC manual says as much under Link Options: on bare-board targets
-T "may be required when linking to avoid references to undefined symbols"
(invoke.texi:19437-19441).
LINK_GCC_C_SEQUENCE_SPEC: libgcc and libc in one group
Chapter 1.10 showed the generic library sequence, %G %L %G. This port replaces
it, and the comment says why:
/* The libgcc udivmod functions may throw exceptions. If newlib is
configured to support long longs in I/O, then printf will depend on
udivmoddi4, which will depend on the exception unwind routines,
which will depend on abort, which is defined in libc. */
#undef LINK_GCC_C_SEQUENCE_SPEC
#define LINK_GCC_C_SEQUENCE_SPEC "--start-group %G %{!nolibc:%L} --end-group"
Listing 3.4-8: libgcc and newlib depend on each other
(gcc/config/arm/unknown-elf.h:91-96).
The cycle of Chapter 3.1 is back, at link
time. printf in newlib needs a libgcc helper, the helper needs the unwinder,
and the unwinder needs abort from newlib. A linker group lets the linker go
around that loop.
Syscalls: what newlib leaves to libgloss and libnosys
newlib's libc.a does its I/O through a small set of functions that it does not
always define. _write_r, for example, calls _write (newlib 4.5.0
newlib/libc/reent/writer.c:49). Someone has to supply _write,
_sbrk, _exit and their relatives.
By default, newlib supplies them itself on Arm. It compiles its syscalls for a
debug monitor: the comment in configure.host says that ARM_RDI_MONITOR
"selects the Angel monitor" (newlib/configure.host:653-666). The
README documents --disable-newlib-supplied-syscalls as the switch that turns
this off (newlib/README:396-398). Then libc.a leaves
the names undefined, and a library from libgloss must define them. libgloss
describes itself in its README:
Libgloss is a library for all the details that usually get glossed over. This library refers to things like startup code, and usually I/O support for GCC and the C library.
newlib 4.5.0
libgloss/README:1-3
libgloss is a separate module because its pieces depend on the board or the
debug monitor, not only on the CPU. The Arm directory alone builds startup files
and libraries for RedBoot, the RDP monitor and Linux
(libgloss/arm/Makefile.inc:10-30). When you have no board
package, libnosys gives every name a stub that fails:
int
_write (int file,
char *ptr,
int len)
{
errno = ENOSYS;
return -1;
}
stub_warning(_write)
Listing 3.4-9: a libnosys stub (newlib 4.5.0
libgloss/libnosys/write.c:13-22).
stub_warning puts a string in a .gnu.warning. section named after the
symbol (libgloss/libnosys/warning.h:19-22), and the
string says that _write "is not implemented and will always fail"
(:38-42). The GNU linker prints it when the link uses the stub.
The link succeeds, and every call to _write fails at run time with ENOSYS.
-specs=nosys.specs: how libgloss reaches the link line
libgloss plugs libnosys into the driver with a specs file. It uses the
%rename idiom of Chapter 1.3:
%rename link_gcc_c_sequence nosys_link_gcc_c_sequence
*nosys_libgloss:
-lnosys
*nosys_libc:
%{!specs=nano.specs:-lc} %{specs=nano.specs:-lc_nano}
*link_gcc_c_sequence:
%(nosys_link_gcc_c_sequence) --start-group %G %(nosys_libc) %(nosys_libgloss) --end-group
Listing 3.4-10: nosys.specs (newlib 4.5.0
libgloss/libnosys/nosys.specs:1-10).
The new link_gcc_c_sequence keeps the port's group from Listing 3.4-8 and adds
a second group with -lnosys in it.
You write -specs=nosys.specs with no directory, and the driver finds it. The
driver looks up each -specs= file along the startfile prefixes, with the
multilib subdirectory first (gcc.cc:8633-8640). libgloss installs
nosys.specs in $(tooldir)/lib$(MULTISUBDIR)
(libgloss/libnosys/Makefile.inc:1 and
libgloss/Makefile.am:15-17), and that is the tooldir prefix of
the table above. The GCC manual documents -specs= under
Overall Options (invoke.texi:2257-2265), but not where the
driver looks for the file.
nano.specs works the same way. libgloss copies it from elf-nano.specs for
Arm (libgloss/arm/Makefile.inc:81-82). It renames link,
link_gcc_c_sequence and cpp_unique_options, swaps -lc for -lc_nano with
%:replace-outfile, and adds an include/newlib-nano header directory
(libgloss/arm/elf-nano.specs:1-21). newlib's own install creates
neither of those. It installs libc.a and libm.a
(newlib/Makefile.am:75-76), and its makefile never names
libc_nano.a. A toolchain that ships nano.specs working has a second newlib
build installed under those names by whoever packaged it.
--with-multilib-list=rmprofile, and the variants newlib gets
Without --with-multilib-list, arm*-*-eabi* builds the variants in
arm/t-arm-elf (config.gcc:1504):
# Build a very basic set of libraries that should cater for most cases.
# Single-precision floating-point is NOT supported; we don't build a
# suitable library for that. Use the rm-profile config in that case.
...
# Build a total of 4 library variants (base options plus the following):
MULTILIB_REQUIRED += mthumb
MULTILIB_REQUIRED += marm/mfpu=auto/march=armv5te+fp/mfloat-abi=hard
MULTILIB_REQUIRED += mthumb/mfpu=auto/march=armv7+fp/mfloat-abi=hard
Listing 3.4-11: the default variant set, abridged
(gcc/config/arm/t-arm-elf:19-22 and
:83-86).
The -march=armv7e-m+fp of this chapter's first paragraph falls in that gap.
t-arm-elf puts armv7e-m in its all_sp_only group
(t-arm-elf:61), and it maps only armv7e-m+fp.dp onto a
library (:122-123). The fragment's own comment sends you to
the R and M profile set.
--with-multilib-list=rmprofile selects arm/t-multilib
(config.gcc:4489-4497), which includes
arm/t-rmprofile (t-multilib:87). config.gcc refuses it
together with any of --with-arch, --with-cpu, --with-fpu, --with-float or
--with-mode (:4515-4524). The install manual
documents the aprofile and rmprofile values on its
Configuration page (install.texi:1357-1365).
Pass the same list to steps 2 and 4. Step 2's list is the one newlib reads
(Listing 3.4-1). Step 4's list is the one the driver selects from at every
link. If they differ, the driver searches variant directories that newlib never
filled, and Chapter 1.6's fallback hands the link the
default libc.a without a diagnostic from GCC.
Checking the result with -print-file-name and -print-multi-lib
These commands need only the finished toolchain:
$ arm-none-eabi-gcc -print-sysroot
$ arm-none-eabi-gcc -print-search-dirs
$ arm-none-eabi-gcc -print-file-name=libc.a
$ arm-none-eabi-gcc -print-file-name=crt0.o
$ arm-none-eabi-gcc -print-file-name=nosys.specs
$ arm-none-eabi-gcc -print-multi-lib
$ arm-none-eabi-gcc -mthumb -march=armv7e-m+fp -mfloat-abi=hard \
-print-multi-directory
$ arm-none-eabi-gcc -mthumb -march=armv7e-m+fp -mfloat-abi=hard \
-print-file-name=libc.a
$ grep '^inhibit_libc' build-stage2/gcc/Makefile
What the source predicts:
-print-sysrootprints nothing, because no step configured a sysroot.-print-search-dirslists the tooldir'slib/underlibraries. Expect it in an unnormalised form,.../lib/gcc/arm-none-eabi/15.2.0/../../../../arm-none-eabi/lib/. The driver builds the tooldir from its own versioned directory with../steps (gcc.cc:5522-5531andgcc/Makefile.in:2607).-print-file-name=libc.aprints a path that resolves to/opt/cross/arm-none-eabi/lib/libc.a. An answer that echoeslibc.aback means newlib is not where the driver looks. Chapter 1.5 explains the echo rule.-print-file-namesearches the startfile prefixes with the multilib subdirectory first (gcc.cc:8068-8072). So the two variant commands must agree: thelibc.apath must contain the directory that-print-multi-directoryprinted. A path without it is the fallback at work.- The last line prints
inhibit_libc = trueunless stage 2 had--with-headers=DIR. Chapter 3.2 gives this observable.
The __aeabi_idiv observable is
Chapter 1.10's Listing 1.10-5, and it
runs on this toolchain as written.
Three things to carry away
Stage 2 is a second configure, not a second make. The stage-1 build tree
keeps C only, its multilib list and inhibit_libc as they were configured.
newlib builds the variants that the stage-1 compiler reports. Give stage 1 the multilib list you want at the end.
There is no sysroot, and the tooldir replaces it. newlib's include and lib
in $prefix/<target>/ are on the driver's search lists already, but the
inhibit_libc probe looks in sys-include.
Things that surprise people
-print-sysroot prints nothing on a working bare-metal toolchain. That is the
normal state for this layout, not a broken install.
--with-newlib changes nothing in stage 1. On a cross build without a sysroot
it only repeats a clause that is already true. In stage 2 it keeps libstdc++'s
configure away from "No support for this host/target combination."
The target name is a directory name. arm-eabi and arm-none-eabi describe
the same machine and name two different tooldirs.
nano.specs names a sysroot path, and this layout has no sysroot. It adds
-isystem =/include/newlib-nano
(libgloss/arm/elf-nano.specs:5-6). cc1 replaces a leading
= only when it has a sysroot (gcc/incpath.cc:354-363). A
compiler configured without one starts with none
(c-family/c-opts.cc:52-53 and :91-92),
and the driver passes -isysroot only when a sysroot is set
(gcc.cc:6592-6601). So the path stays =/include/newlib-nano,
relative to the current directory, and gcc -v reports it as a nonexistent
directory (incpath.cc:83-85).
Documentation coverage
The install manual documents every configure flag in the recipe on its
Configuration page: --prefix (gcc/doc/install.texi:910),
--disable-multilib (:1298), --with-multilib-list with the Arm values
(:1325, :1357-1365), --enable-languages (:2094), --with-headers
(:2751-2762), --without-headers (:2763-2766) and --with-newlib
(:2776-2780). Its Building a cross compiler section
(install.texi:3247-3322) documents where binutils go and names crt0.o and
STARTFILE_SPEC. The host/target notes for arm-*-eabi
(install.texi:4102-4108) cover only an Ada build problem. The GCC manual
documents -specs= under Overall Options
(gcc/doc/invoke.texi:2257-2265), -nostdlib and -T under
Link Options (:19227, :19437-19441), and -print-file-name,
-print-multi-lib, -print-search-dirs and -print-sysroot under
Developer Options (:21571, :21584, :21622, :21635).
newlib documents its own configure options in newlib/README, which ships in
newlib's source tree, not on the web.
What is not documented:
- That a bare-metal toolchain needs two GCC configures, and that
make allin the stage-1 tree keeps stage 1'sinhibit_libc, languages and multilibs. - That the
inhibit_libcprobe looks in$prefix/<target>/sys-include, while newlib installs its headers in$prefix/<target>/include. The--with-headersentry hints at it: the option is "required" ifsys-include"doesn't pre-exist" (install.texi:2756-2759). - What
--with-newlibdoes at the pin. The manual names one effect, omitting__eprintffromlibgcc.a(install.texi:2776-2780).__eprintfis omitted byinhibit_libc, not by--with-newlibdirectly (libgcc/libgcc2.c:2979-2980). The effect that matters for C++ is libstdc++'s newlib branch, which the manual does not mention. - That
-specs=files are looked up along the startfile prefixes, multilib directories first, which is how-specs=nosys.specsworks without a path. - That newlib takes its variant list from the compiler that builds it.
- The
arm*-*-eabi*default variant set. The manual says that omitting--with-multilib-liston Arm means "only the default run-time library will be enabled" (install.texi:1363-1365). Forarm*-*-eabi*,t-arm-elfbuilds four variants (Listing 3.4-11).
Next: when someone hands you a sysroot, one configure and one make is the
documented path. The next chapter reads what goes wrong when that sysroot lacks
a file GCC needs.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
3.5 When someone hands you a sysroot: what --with-sysroot must contain
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
A vendor gives you a sysroot for aarch64-linux-gnu. You configure GCC with
--with-sysroot pointing at it, and configure finishes without a complaint.
make builds the compiler and libgcc. Then the configure script of the next
target library stops. It says C compiler cannot create executables, or, if you
disabled that library, libstdc++ says
Link tests are not allowed after GCC_NO_EXECUTABLES. Neither message names a
file. The second names an Autoconf macro, and it interrupts a check that has
nothing to do with your sysroot.
A prebuilt sysroot is read at four points in the build. At the last one, a
missing file can fail in silence and come back later as a different error.
That last point is the first link test of each target library. This chapter
follows the four in build
order and says which part of the sysroot each one needs: the libc headers, the
kernel headers that they include, the startfiles, and a libc to link against.
This chapter assumes Chapter 1.5, for how the
driver adds the sysroot to its search lists and why -print-file-name echoes a
name it cannot find. It assumes Chapter 1.7, for the
startfiles that a link asks for. It also assumes
Chapter 3.1, whose decision procedure sent
you here, and Chapter 3.2, for the inhibit_libc
condition.
--with-sysroot and one make: the documented path
The install manual documents this case under Building a cross
compiler. If you do not build a C library in the same tree, you
"provide the target libraries and headers before configuring GCC". You name them
with --with-sysroot, or with the older --with-headers and --with-libs
(install.texi:3313-3322). The manual documents
--with-sysroot itself under Configuration. The built compiler
acts as if --sysroot=DIR were one of its default options, and GCC does not
copy DIR into the install tree (install.texi:2709-2731).
The recipe is one configure and one make. Nobody ran it at the pin for this
book. The flags are checked against the sources, and the sequence is the one the
manual gives:
$ $GCC_SRC/configure --target=aarch64-linux-gnu --prefix=/opt/cross \
--with-sysroot=/opt/cross/aarch64-linux-gnu/sysroot \
--enable-languages=c,c++
$ make
$ make install
The cross assembler and linker must be installed first, in
$prefix/<target>/bin, as the same manual section says
(install.texi:3281-3285).
There is no make all-gcc step, because nothing has to be built between the
compiler and its libraries. The C library already exists. The price is that the
sysroot must be complete before you run configure. This configuration passes
--with-sysroot and no --without-headers, so inhibit_libc stays false
(Chapter 3.2). libgcc builds in full, and every
target library links test programs against the sysroot.
That is the whole difference from the bootstrap recipes:
| Build mode | inhibit_libc | Target headers needed | crt*.o and libc needed | Why |
|---|---|---|---|---|
Stage 1 of a bootstrap: --without-headers with its partner flag | true | no | later, from the C library you build next | libgcc leaves out the code that uses libc |
Against a prebuilt sysroot: --with-sysroot, no --without-headers | false | before configure | before make reaches libgcc | libgcc builds in full, and target libraries run link tests |
Chapter 3.2 gives the partner flag. The rest of this chapter is the second row, one reader at a time.
features.h: what gcc/configure reads before anything is built
gcc/configure runs before any compiler for the target exists. It cannot
compile or link a test program for the target, so it reads files. They come from
one directory, target_header_dir. With --with-sysroot=DIR, that is DIR
followed by the native header directory (gcc/configure.ac:2562-2563),
which is /usr/include unless you configure another one
(install.texi:2729-2731). A --with-build-sysroot takes the
place of DIR (gcc/configure.ac:2556-2557).
Chapter 3.2 covers the stdio.h test in that
directory. The other read is the glibc version:
glibc_version_major=0
glibc_version_minor=0
[if test -f $target_header_dir/features.h \
&& glibc_version_major_define=`$EGREP '^[ ]*#[ ]*define[ ]+__GLIBC__[ ]+[0-9]' $target_header_dir/features.h` \
&& glibc_version_minor_define=`$EGREP '^[ ]*#[ ]*define[ ]+__GLIBC_MINOR__[ ]+[0-9]' $target_header_dir/features.h`; then
glibc_version_major=`echo "$glibc_version_major_define" | sed -e 's/.*__GLIBC__[ ]*//'`
glibc_version_minor=`echo "$glibc_version_minor_define" | sed -e 's/.*__GLIBC_MINOR__[ ]*//'`
fi]])
Listing 3.5-1: the target glibc version, read from features.h
(gcc/configure.ac:6030-6037).
Two egrep calls, and no compiler. If features.h is missing, or does not
define __GLIBC__ and __GLIBC_MINOR__, the version stays 0.0. Configure
prints checking for target glibc version... 0.0
(:6020, :6038) and continues. A target with
no glibc gets the same 0.0, so nothing marks the value as a failure.
The version then sets defaults that are compiled into the driver and into cc1.
Each test goes through GCC_GLIBC_VERSION_GTE_IFELSE, a plain comparison of the
two numbers (gcc/acinclude.m4:548-556):
| glibc at least | What it sets | Where |
|---|---|---|
| 2.4 | TARGET_LIBC_PROVIDES_SSP on GNU/Linux. Without it, the driver's default LINK_SSP_SPEC adds -lssp_nonshared -lssp to every -fstack-protector link | configure.ac:6958-6961, gcc.cc:994-1002 |
| 2.4 | 128-bit long double by default on PowerPC, SPARC, s390 and Alpha GNU/Linux | configure.ac:7034-7038, :7051-7056 |
| 2.11 | the gnu_unique_object symbol type, if the assembler supports it | configure.ac:6044-6056 |
| 2.23 | TARGET_LIBC_PROVIDES_HWCAP_IN_TCB on PowerPC GNU/Linux | configure.ac:7105-7112 |
| 2.31 | TARGET_LIBC_GNUSTACK on MIPS GNU/Linux | configure.ac:7118-7127 |
The PowerPC port also reads the two numbers directly, as
TARGET_GLIBC_MAJOR and TARGET_GLIBC_MINOR, in its headers
(rs6000/linux64.h:176).
So a sysroot without features.h fails nothing, and builds a different
compiler. Take PowerPC GNU/Linux. With version 0.0, configure defines
TARGET_DEFAULT_LONG_DOUBLE_128 only if bits/wordsize.h defines
__LONG_DOUBLE_MATH_OPTIONAL (configure.ac:7051-7066).
Without that macro, the port's headers do not raise the default
(rs6000/linux64.h:536-537), and long double falls back to 64
bits, the same as double (rs6000.cc:3385-3390). That
is an ABI change, and no later step reports it.
The install manual documents --with-glibc-version=M.N under
Configuration, for a bootstrap that has no headers yet
(install.texi:2620-2630). It sets the version without
reading features.h. For a prebuilt sysroot, the better fix is the missing
features.h.
stmp-fixinc: the one check that names the directory
make builds the compiler first. Part of that step is fixincludes, which copies
the target's system headers into the include-fixed/ snapshot that
Chapter 1.8 describes. It reads
BUILD_SYSTEM_HEADER_DIR. For a cross compiler with a sysroot, that is the
sysroot's header directory, or the build sysroot's if you gave
--with-build-sysroot (gcc/configure.ac:2541-2544, :174).
The rule first checks that the directory exists:
fix_dir=include-fixed$${multi_dir}; \
if ! $(inhibit_libc) && test ! -d ${BUILD_SYSTEM_HEADER_DIR}; then \
echo "The directory (BUILD_SYSTEM_HEADER_DIR) that should contain system headers does not exist:" >&2 ; \
echo " ${BUILD_SYSTEM_HEADER_DIR}" >&2 ; \
case ${build_os} in \
darwin*) \
echo "(on Darwin this usually means you need to pass the --with-sysroot= flag to point to a valid MacOS SDK)" >&2; \
;; \
esac; \
tooldir_sysinc=`echo "${gcc_tooldir}/sys-include" | sed -e :a -e "s,[^/]*/\.\.\/,," -e ta`; \
if test "x${BUILD_SYSTEM_HEADER_DIR}" = "x$${tooldir_sysinc}"; \
then sleep 1; else exit 1; fi; \
Listing 3.5-2: the header-directory check in stmp-fixinc
(gcc/Makefile.in:3615-3626).
This is the only check in this chapter that prints the directory it looked
for. It fires when inhibit_libc is false and the directory does not exist,
which in this recipe means a wrong --with-sysroot value. It does not look inside the
directory. A usr/include that exists and has no stdio.h passes.
The listing has one exception. If the missing directory is the tool directory's
sys-include, the rule waits one second and continues. That is the directory
that --with-headers fills, and the last section returns to it.
libgcc: tsystem.h, crti.o, crtn.o and -lc
libgcc is the first target library, and every other one waits for it. The
top-level makefile template gives each target module a rule
configure-target-<module>: maybe-all-target-libgcc, unless the module is marked
no_gcc (Makefile.tpl:2108-2111). libgcc is the only module
with that mark (Makefile.def:654). So libgcc is the first
thing that compiles and links against your sysroot.
The libc headers, and the kernel headers behind them
With inhibit_libc false, libgcc compiles the code that uses the C library.
Its common header, gcc/tsystem.h, then includes <stdio.h>, <sys/types.h>,
<errno.h>, <string.h>, <stdlib.h> and <unistd.h>
(gcc/tsystem.h:85-110). The AArch64 unwinder includes <signal.h>
and <sys/ucontext.h> under the same #ifndef inhibit_libc
(libgcc/config/aarch64/linux-unwind.h:26-29). A sysroot without
the libc headers stops at the first libgcc file that includes one, with an
ordinary missing-header error.
For a hosted Linux target, "the libc headers" includes the kernel's headers too.
This crosses into the C library, but only to show what GCC expects to find in
the same usr/include. glibc's bits/local_lim.h includes <linux/limits.h>
(glibc 2.42 sysdeps/unix/sysv/linux/bits/local_lim.h:38).
GCC's own tree does the same where it needs kernel types: libsanitizer includes
a list of <linux/...> headers directly
(sanitizer_platform_limits_posix.cpp:69-87).
libgcc_s.so: crti.o, crtn.o and -lc, but no crt1.o
On GNU/Linux, libgcc also links a shared library, libgcc_s.so, through the
t-slibgcc fragment (libgcc/config.host:313-314):
SHLIB_LINK = $(CC) $(LIBGCC2_CFLAGS) -shared -nodefaultlibs \
$(SHLIB_LDFLAGS) $(LDFLAGS) \
-o $(SHLIB_DIR)/$(SHLIB_SONAME).tmp @multilib_flags@ \
$(SHLIB_OBJS) $(SHLIB_LC) && \
Listing 3.5-3: the first lines of the libgcc_s.so link
(libgcc/config/t-slibgcc:34-37). SHLIB_LC is -lc
(:29).
-nodefaultlibs removes the default libraries and keeps the startfiles
(Chapter 1.10). For a -shared link,
the GNU/Linux startfile spec selects no crt1.o variant, but it still adds
crti.o and crtn.o (Chapter 1.7). Then -lc needs
a libc to link against. The crtbeginS.o and crtendS.o in the same link are
libgcc's own, and libgcc copies them into the compiler's build directory before
this link for that reason (libgcc/Makefile.in:1106-1118).
So libgcc needs the libc headers, crti.o, crtn.o and a libc. It does not
need crt1.o.
libgcc's configure script needs even less. It calls GCC_NO_EXECUTABLES
(libgcc/configure.ac:219-220), the macro of the next section.
Its own link commands pass -nostartfiles -nodefaultlibs
(:500, :514). It configures against a sysroot
where nothing links.
GCC_NO_EXECUTABLES: the link test that fails without a word
Many target libraries do not assume that the new compiler can link a program.
They call GCC_NO_EXECUTABLES before AC_PROG_CC. The macro replaces
Autoconf's executable-suffix check with one link of its own, and puts a guard in
front of every later link test:
m4_define([_AC_COMPILER_EXEEXT],
[AC_LANG_CONFTEST([AC_LANG_PROGRAM(
[#include <stdio.h>],
[printf ("hello world\n");])])
# FIXME: Cleanup?
AS_IF([AC_TRY_EVAL(ac_link)], [gcc_no_link=no], [gcc_no_link=yes])
if test x$gcc_no_link = xyes; then
# Setting cross_compile will disable run tests; it will
# also disable AC_CHECK_FILE but that's generally
# correct if we can't link.
cross_compiling=yes
EXEEXT=
else
]m4_defn([_AC_COMPILER_EXEEXT])dnl
fi
)
m4_define([AC_LINK_IFELSE],
if test x$gcc_no_link = xyes; then
AC_MSG_ERROR([Link tests are not allowed after [[$0]].])
fi
m4_defn([AC_LINK_IFELSE]))
Listing 3.5-4: the replacement link test, and the guard on every later link
test (config/no-executables.m4:27-48).
The test program includes <stdio.h> and calls printf. To link it, the driver
needs everything that a normal link needs: the libc headers, the crt1.o
variant that the startfile spec selects, crti.o, crtn.o, a libc, and the
libgcc from the step before. Which crt1.o variant depends on how you
configured GCC. With --enable-default-pie, PIE_SPEC matches every link that
has no -no-pie (gcc/gcc.cc:1005-1006), so the spec asks for
Scrt1.o. Without it, the spec asks for crt1.o
(Chapter 1.7).
If the link fails, the macro prints nothing. It sets gcc_no_link=yes, sets
cross_compiling=yes so that no run test is tried, and configure continues.
From then on, each AC_LINK_IFELSE in the script starts with the guard at the
bottom of Listing 3.5-4. The first link test that runs stops configure with
Link tests are not allowed after GCC_NO_EXECUTABLES.
That first test is unrelated to the cause. libstdc++ calls the macro for every
cross build except Darwin to Darwin (libstdc++-v3/configure.ac:35-58).
In its generated script, for a GNU/Linux target, the first link test that runs
is libtool's probe for whether the linker sets DT_RUNPATH
(libstdc++-v3/configure:11567-11580). That probe is inside the
check that prints checking dynamic linker characteristics...
(:11141-11142). The guarded tests before it belong to SCO, Darwin,
AIX and IRIX (:7878-7895, :8470-8484,
:10246-10253, :10620-10629). So the
terminal shows a libtool check that failed. The real failure happened earlier,
at the top of the same script, with no message.
The other message: C compiler cannot create executables
Not every target library uses the macro. libgcc, libstdc++, libgfortran,
libquadmath, libssp, libobjc and zlib do. libgomp, libatomic, libitm,
libsanitizer and libbacktrace call plain AC_PROG_CC
(libgomp/configure.ac:112-115,
libatomic/configure.ac:134). For those, Autoconf's own check
runs, and a failed link stops configure at once. The script prints
checking whether the C compiler works... no, then
C compiler cannot create executables
(libgomp/configure:3882-3883, :3953-3954).
| Message | Printed by | What it means |
|---|---|---|
Link tests are not allowed after GCC_NO_EXECUTABLES. | a library that calls GCC_NO_EXECUTABLES | its link test failed earlier, with no message |
C compiler cannot create executables | a library that calls plain AC_PROG_CC | its link test failed now |
The build order decides which message you see first. Every target library waits
for libgcc. libstdc++'s configure also waits for libgomp's
(Makefile.def:675), and the top level builds libgomp by
default on GNU/Linux targets (configure.ac:529-546). So in a
default GNU/Linux build, libgomp reports C compiler cannot create executables
before libstdc++ runs at all. With make -j, libatomic can report the same
message at the same time. The two messages have the same cause.
Finding the failed link in config.log
The terminal does not show the failed link. The library's config.log does.
The generated test writes the link command, and everything the linker printed,
to file descriptor 5, which is config.log
(libstdc++-v3/configure:4261-4264). Each target library has its
own build directory, <objdir>/<target>/<library>/, where <target> is the
target name as you typed it (config/acx.m4:101). Each
multilib variant configures again in <objdir>/<target>/<multidir>/<library>/
(config-ml.in:670-701), with its own config.log.
Open the log of the library that stopped. The failed link is near the top, among the C compiler checks: a link command, the linker's own messages, and a non-zero exit status. Those linker messages are the diagnosis.
cannot compute sizeof (int): what that message means in GCC 15.2
You may have read that this failure shows itself as
cannot compute sizeof (int), and that the message means "configure compiled
but failed to link, so check crt1.o". In GCC 15.2, a missing startfile cannot
produce it.
AC_CHECK_SIZEOF(int) appears in two places at the pin. In gcc/configure.ac,
it measures the compiler that builds GCC, not the target
(gcc/configure.ac:523-527). In GCC_HEADER_STDINT, which
libatomic, libbacktrace, libgfortran, libitm and libsanitizer use, it runs only
when the macro found no header that defines the fixed-width integer types
(config/stdint.m4:140-144).
Neither can fail because a target link failed. The first one measures the build
machine's compiler. In a target library, a failed link either stopped configure
already, or GCC_NO_EXECUTABLES set cross_compiling=yes. With
cross_compiling=yes, Autoconf computes a size by compiling test programs, not
by linking or running them (libatomic/configure:1895-1914). And
the error branch has its own condition:
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (int))" "ac_cv_sizeof_int" "$ac_includes_default"; then :
else
if test "$ac_cv_type_int" = yes; then
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (int)
See \`config.log' for more details" "$LINENO" 5; }
else
ac_cv_sizeof_int=0
fi
Listing 3.5-5: the size check, as Autoconf 2.69 generates it for libatomic
(libatomic/configure:12344-12354).
The script stops only if ac_cv_type_int is yes. None of the generated
scripts that contain this check sets that variable: gcc/configure, and the
scripts of libatomic, libbacktrace, libgfortran, libitm and libsanitizer. A
failed measurement records 0, and configure continues. In
GCC_HEADER_STDINT, a later check then stops with
no 8-bit type, please report a bug (config/stdint.m4:146-150).
That message points at the libc headers, not at the startfiles. To get there,
the library found no integer-type header, and its size checks failed to compile
a program whose default includes start with <stdio.h>
(libatomic/configure:596-597).
If a build log shows cannot compute sizeof (int), find the config.log that
printed it before you act on it.
--with-headers and --with-libs: copying instead of pointing
Before --with-sysroot, you gave a cross build its target files with
--with-headers=DIR and --with-libs="DIR...". The install manual documents
both under Configuration as deprecated in favour of
--with-sysroot, and says that both copy their directories into the install
tree (install.texi:2751-2761,
:2768-2774). The top-level configure does the copying:
# Handle --with-headers=XXX. If the value is not "yes", the contents of
# the named directory are copied to $(tooldir)/sys-include.
if test x"${with_headers}" != x && test x"${with_headers}" != xno ; then
if test x${is_cross_compiler} = xno ; then
echo 1>&2 '***' --with-headers is only supported when cross compiling
exit 1
fi
if test x"${with_headers}" != xyes ; then
x=${gcc_cv_tool_prefix}
copy_dirs="${copy_dirs} ${with_headers} $x/${target_noncanonical}/sys-include"
fi
fi
Listing 3.5-6: --with-headers (configure.ac:2931-2942).
--with-libs follows at :2944-2960 and copies into
<target>/lib.
Three details are in the source and not in the manual.
The copy happens when you run configure. A loop after the option handling
copies each directory with tar, into <exec_prefix>/<target>/sys-include or
<exec_prefix>/<target>/lib, before make starts
(configure.ac:3005-3033). <exec_prefix> falls back to the
prefix when you give no exec prefix (config/acx.m4:260-268).
So configure writes into your install tree.
A second configure does not copy again. The loop writes the source
directory name into a COPIED file in the destination, and skips the copy when
the name matches (configure.ac:3009-3010). If you change the
headers in DIR and run configure again with the same DIR, the build keeps
the old copy. Symbolic links are copied as tar copies them. "It is the
responsibility of the user to correctly adjust all symlinks"
(:3027-3029).
gcc/configure reads the copy. With no --with-sysroot,
target_header_dir is <exec_prefix>/<target>/sys-include
(gcc/configure.ac:2558-2559). So Listing 3.5-1 reads the copied
features.h. The same directory is the fixincludes input
(:185-189), which is why Listing 3.5-2 accepts it even when
it is missing.
Both options together also change one default. Unless you pass --with-newlib,
they set --without-newlib (configure.ac:283-290). On a
native build, either option stops configure with
--with-headers is only supported when cross compiling (Listing 3.5-6), or the
same text for --with-libs.
Checking a sysroot before it fails: -print-sysroot and -print-file-name
None of the commands below were run for this book. They use only the files and options cited above.
Before configure: the files
There is no target compiler yet, so check the files. Use the directories that
your target's driver searches. Chapter 1.5 shows
how the driver forms them. Chapter 1.6 shows why a
64-bit or multiarch target can use lib64 or lib/<multiarch> in place of
lib.
$ S=/opt/cross/aarch64-linux-gnu/sysroot
$ ls $S/usr/include/features.h $S/usr/include/stdio.h
$ ls $S/usr/include/linux/limits.h
$ ls $S/usr/lib/crt1.o $S/usr/lib/Scrt1.o $S/usr/lib/crti.o $S/usr/lib/crtn.o
$ ls $S/usr/lib/libc.so
During the build: the compiler the target libraries use
The top level runs the target libraries' configure scripts with
gcc/xgcc -B<objdir>/gcc/ (configure.ac:4059). When libgcc
finishes, it copies its archives and startfiles into <objdir>/gcc/
(libgcc/Makefile.in:116-122). So after libgcc is built,
you can run the link that every GCC_NO_EXECUTABLES test will try:
$ cd $OBJDIR
$ make all-gcc all-target-libgcc
$ ./gcc/xgcc -B$PWD/gcc/ -print-sysroot
$ ./gcc/xgcc -B$PWD/gcc/ -print-file-name=crt1.o
$ ./gcc/xgcc -B$PWD/gcc/ -print-file-name=Scrt1.o
$ printf '#include <stdio.h>\nint main (void) { printf ("hello world\\n"); return 0; }\n' > t.c
$ ./gcc/xgcc -B$PWD/gcc/ t.c -o t
If you configured with --with-build-sysroot, add --sysroot= with the same
directory. The top level adds it to every target compile
(Makefile.tpl:634-637). A name that -print-file-name echoes
back unchanged was not found (Chapter 1.5).
After make install: the installed driver
$ aarch64-linux-gnu-gcc -print-sysroot
$ aarch64-linux-gnu-gcc -print-file-name=crt1.o
$ aarch64-linux-gnu-gcc -print-file-name=libc.so
$ aarch64-linux-gnu-g++ -print-file-name=libstdc++.so
The GCC manual documents both options under Developer
Options. -print-sysroot prints nothing when the compiler has no
sysroot (invoke.texi:21634-21640). The last line checks
GCC's side, not the sysroot: libstdc++.so is installed under GCC's prefix
(Chapter 1.12).
Making the failure on purpose
This recipe was not run for this book. The expected result comes from the
sources in this chapter. Copy a working sysroot, remove the crt1.o variants
from the directory where your sysroot keeps them, and build against the copy:
$ cp -a /opt/cross/aarch64-linux-gnu/sysroot /tmp/broken-sysroot
$ rm /tmp/broken-sysroot/usr/lib/crt1.o /tmp/broken-sysroot/usr/lib/Scrt1.o
$ mkdir /tmp/build && cd /tmp/build
$ $GCC_SRC/configure --target=aarch64-linux-gnu --prefix=/tmp/inst \
--with-sysroot=/tmp/broken-sysroot --enable-languages=c,c++
$ make
gcc/configure and fixincludes pass, because the headers are there. libgcc
builds, because nothing in it needs crt1.o. Then libgomp, or libatomic
beside it, stops with C compiler cannot create executables. Add
--disable-libgomp --disable-libatomic, and the failure can come instead from a
library that calls GCC_NO_EXECUTABLES, such as libstdc++, with the other
message. The failed link is in the config.log of the library that stopped,
under /tmp/build/aarch64-linux-gnu/.
Three things to carry away
A prebuilt sysroot is read four times: by gcc/configure, by fixincludes,
by libgcc, and by the first link test of every later target library.
GCC_NO_EXECUTABLES hides a failed link. The error comes later, from a
check that has nothing to do with the cause, and the cause is in that library's
config.log.
A missing features.h stops nothing and changes the compiler, because the
target glibc version falls to 0.0.
Things that surprise people
libgcc builds without crt1.o. Its configure script links nothing that
needs a startfile, and libgcc_s.so is a -shared link. The first failure
comes from the next library.
cannot compute sizeof (int) is not the missing-crt1.o message in GCC
15.2. Its error branch needs ac_cv_type_int=yes, and no GCC script sets it.
--with-headers copies when you run configure, and only once. A COPIED
stamp stops later runs from refreshing the copy.
Documentation coverage
The install manual documents the procedure under Building a cross
compiler (gcc/doc/install.texi:3247, the sysroot paragraph at
:3313-3322). It documents the options under Configuration:
--with-glibc-version (:2620), --with-sysroot (:2709),
--with-build-sysroot (:2733), --with-headers (:2751),
--without-headers (:2763) and --with-libs (:2768). The GCC manual
documents --sysroot under Directory Options
(gcc/doc/invoke.texi:19559), and -print-file-name and -print-sysroot under
Developer Options (:21571, :21635).
What is not documented:
- Which files the build reads from the sysroot, and at which step. The manual's
cross section names
crt0.oandcrtn.oas examples and sends you toSTARTFILE_SPEC. Chapter 1.7 reads that spec for GNU/Linux. - That libgcc needs
crti.o,crtn.oandlibc, and does not needcrt1.o. GCC_NO_EXECUTABLES, its silent fallback, and the two messages that a failed link produces. None of the messages in this chapter appears in the manuals.- Where a target library's
config.logis. - That the target glibc version comes from two
egrepcalls onfeatures.h, that a missing file gives0.0with no error, and which defaults depend on it. The manual says only that the version "can be detected from the C library's header files" (install.texi:2622-2623). - That the fixincludes check accepts a missing tool-directory
sys-include. - That
--with-headersand--with-libscopy when you runconfigure, and do not copy again while theCOPIEDstamp matches.
Next: newlib built in the same tree as GCC, where the top level breaks the wait
for a C library with one no_c=true.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
3.6 newlib in the middle of a GCC build: the one no_c=true
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
You link newlib/ and libgloss/ into a GCC source tree. You run the top-level
configure with a target and a prefix, and nothing else. The top-level
Makefile then orders one make to build the compiler, libgcc, the C library
and libstdc++, with newlib built once for every multilib the compiler has. You
never typed --with-newlib.
Then a colleague runs newlib/configure by hand in the same tree, to rebuild
only the C library. That configure looks for an installed compiler. It builds
newlib with a different compiler, or it stops because it finds none.
The top-level build declares newlib a target module like libstdc++, and then
exempts it, with one no_c=true, from the C-library dependency that every other
target module gets. The rest of this chapter is what the top level hands
newlib once that edge is gone: a compiler, flags, --with-newlib, and the
multilib list.
This chapter crosses an interface on purpose. The book covers the C library only
where GCC meets it, but a combined tree is GCC's top level running newlib's
configure, and the handshake has code on both sides. newlib sources are cited
at the newlib-4.5.0 tag, and the link text says so.
This chapter assumes Chapter 2.3, for
Makefile.def, Autogen and target modules, Chapter 3.2,
for inhibit_libc, and Chapter 1.6, for
-print-multi-lib and the driver's two-pass multilib search.
Chapter 3.4 builds the same toolchain in
separate phases. This chapter builds it in one.
The combined tree: newlib/ and libgloss/ beside gcc/
$ tar xf gcc-15.2.0.tar.xz
$ tar xf newlib-4.5.0.20241231.tar.gz
$ ln -s ../newlib-4.5.0.20241231/newlib gcc-15.2.0/newlib
$ ln -s ../newlib-4.5.0.20241231/libgloss gcc-15.2.0/libgloss
$ mkdir build && cd build
$ ../gcc-15.2.0/configure --target=arm-none-eabi --prefix=/opt/arm \
--enable-languages=c,c++
$ make
$ make install
Nobody ran this recipe at the pin. Each mechanism below is read from the sources at the tags named. The sequence is the conventional one, not a tested one.
binutils can go into the same tree, or be installed into the same prefix first.
The install manual documents both. Under Downloading the source
it says to link the binutils components into the GCC source directory
(install.texi:698-704). Under Building it says where the
assembler and linker go if you do not (install.texi:3281-3286). The list of
components is the top level's own module list: bfd waits for libsframe
(Makefile.def:489) and ld waits for libctf
(:505), so those directories go in too.
What makes the top level see newlib: three tests in configure.ac
The top-level configure keeps target-newlib in its list of target
directories only if three tests pass.
The source directory must have a newlib/configure. The loop that applies this
test describes itself well:
Quietly strip out all directories which aren't configurable in this tree.
The target must not exclude it. A long case adds target-newlib to
noconfigdirs for operating systems that have their own C library, including
every *-*-linux* triple (configure.ac:1017-1090). When
newlib goes, libgloss goes with it, "since libgloss depends upon some newlib
header files" (:1398-1403).
The build must be a cross. A native build puts newlib in skipdirs
(configure.ac:277-281), and only an explicit --with-newlib
takes it out again (:292-296). Chapter 3.2 covers that flag's
other effect.
Why GCC's top level, and not newlib's
The newlib release ships its own copy of the same top-level files. Its
Makefile.def declares newlib with the same no_c=true line
(newlib-4.5.0 Makefile.def:542). But the copy is not GCC 15's.
It has no libcody module. GCC 15's all-gcc has a hard dependency on all-libcody
(Makefile.def:393). So you link newlib into GCC's tree, and GCC's
top level runs the build.
Why not newlib/configure directly
newlib's configure finds its compiler the Autoconf way, through AC_PROG_CC
(newlib-4.5.0 newlib/acinclude.m4:123). Nothing in it knows that
gcc/xgcc exists in your build directory. Everything the next four sections
describe comes from the top level, and a hand-run configure gets none of it.
newlib's own README states the standalone contract plainly:
NOTE THAT YOU MUST HAVE ALREADY BUILT AND INSTALLED GCC and BINUTILS.
What the top level adds by itself: --with-newlib, twice
Once newlib is in the target list, the top level tells two different audiences.
# If using newlib, add --with-newlib to the extra_host_args so that gcc/configure
# can detect this case.
if test x${with_newlib} != xno && echo " ${target_configdirs} " | grep " target-newlib " > /dev/null 2>&1 ; then
with_newlib=yes
extra_host_args="$extra_host_args --with-newlib"
fi
Listing 3.6-1: --with-newlib for gcc/configure (configure.ac:2997-3003).
extra_host_args goes into the arguments of every host module, gcc/ included
(configure.ac:3681). A second block, about 700 lines later, adds
--with-newlib to target_configargs, which every target library receives
(configure.ac:3719-3723).
In gcc/configure: inhibit_libc turns on by itself
--with-newlib satisfies the first clause of the inhibit_libc condition. The
second clause looks for stdio.h in $target_header_dir, which is
$exec_prefix/<target>/sys-include when there is no sysroot
(gcc/configure.ac:2556-2559). newlib never installs there. It puts
its headers in $(tooldir)/include
(newlib-4.5.0 newlib/Makefile.am:263-268). So on a fresh
prefix, inhibit_libc is true, and you needed neither --with-newlib nor
--without-headers. The comment above the condition names this case:
If this is using newlib, without having the headers available now, then define inhibit_libc in LIBGCC2_CFLAGS.
Chapter 3.2 quotes the condition in full and lists what it removes from libgcc.
The fact that matters here comes from the ordering in the next section: libgcc
configures before newlib, and the same make does not build libgcc again. The
libgcc a combined tree installs is the inhibit_libc libgcc.
In the target libraries: libstdc++ stops probing
libstdc++ reads --with-newlib. In a cross build, it then skips its link probes
and defines a fixed list of features it knows newlib has
(libstdc++-v3/configure.ac:340). The comment above that branch
says why the probes cannot run in this build:
Here's why GLIBCXX_CHECK_MATH_SUPPORT, and other autoconf macros that involve linking, can't be used: "cannot open sim-crt0.o" "cannot open crt0.o"
How libstdc++ configures is Part IV's subject. For this chapter, the point is
that --with-newlib reaches every target library without you.
no_c=true in lang_env_dependencies: why newlib does not wait for itself
Every target library needs a C library before it can configure. The top level writes that need into the dependency graph once, for all target modules, and then lists the exceptions:
// Target modules. These can also have dependencies on the language
// environment (e.g. on libstdc++). By default target modules depend
// on libgcc and newlib/libgloss.
lang_env_dependencies = { module=libitm; cxx=true; };
lang_env_dependencies = { module=libffi; cxx=true; };
lang_env_dependencies = { module=newlib; no_c=true; };
lang_env_dependencies = { module=libgloss; no_c=true; };
lang_env_dependencies = { module=libgcc; no_gcc=true; no_c=true; };
Listing 3.6-2: the exemptions (Makefile.def:647-654).
The template turns "by default" into one line per target module, and no_c
switches that line off:
[+ FOR target_modules +][+ IF (not (lang-dep "no_c")) +]
configure-target-[+module+]: maybe-all-target-newlib maybe-all-target-libgloss[+
ENDIF +][+ IF (lang-dep "cxx") +]
configure-target-[+module+]: maybe-all-target-libstdc++-v3[+
ENDIF +]
[+ ENDFOR target_modules +]
Listing 3.6-3: the C-library edge, and its switch (Makefile.tpl:2113-2118).
In the generated Makefile.in, libstdc++ gets
configure-target-libstdc++-v3: maybe-all-target-newlib maybe-all-target-libgloss
(Makefile.in:69398). newlib and libgloss get no such line.
Without the exemption, configure-target-newlib would wait for
all-target-newlib, and all-target-newlib already waits for
configure-target-newlib (Makefile.in:49510). newlib
would wait for a C library that is newlib.
The maybe- prefix is what makes the default cheap. maybe-all-target-newlib
is an empty target, and it depends on the real all-target-newlib only inside
an @if target-newlib block (Makefile.in:49503-49509).
configure deletes that block when newlib is not in the tree
(configure.ac:3400-3413). So every target module can carry
the edge, and in a tree without newlib it costs nothing.
The edges newlib does have
Makefile.def names only two explicit edges for newlib, to all-binutils and
all-ld. It is easy to read those as its only dependencies. The generated
Makefile.in has two more:
configure-target-newlib waits for | Because | Source |
|---|---|---|
maybe-all-binutils, maybe-all-ld | explicit in Makefile.def | Makefile.def:705-706 |
maybe-all-gcc | every target module waits for the compiler | Makefile.tpl:1927-1930 |
maybe-all-target-libgcc | newlib has no_c but not no_gcc | Makefile.tpl:2108-2111, Makefile.in:69375 |
not all-target-newlib | no_c=true | Makefile.def:652 |
The gcc and libgcc edges sit in @if gcc-no-bootstrap blocks. A cross
compiler does not bootstrap by default (configure.ac:1532-1541), so
those blocks stay in its Makefile. libgloss waits for all-target-newlib
(Makefile.def:703), and every target library without
no_c waits for both. The order of one cross make is therefore binutils, then gcc
(Makefile.def:373-375), then libgcc, newlib, libgloss, and
the rest.
To see the edges in your own build directory, read the generated Makefile after
the top-level configure:
$ grep -n '^configure-target-newlib:' Makefile
$ grep -n '^configure-target-libstdc++-v3:' Makefile
Chapter 2.3 explains why grep and not make -n:
GNU make runs $(MAKE) lines even under -n.
What newlib is handed: CC_FOR_TARGET and FLAGS_FOR_TARGET
CC_FOR_TARGET is xgcc -B into the build tree
The top level picks the target compiler with a macro, GCC_TARGET_TOOL. When
gcc/ is in the tree and the build machine is the host, the macro reports "just
compiled" and sets the variable to the in-tree program
(config/acx.m4:550-585). For the C compiler, that program
is gcc/xgcc -B$$r/$(HOST_SUBDIR)/gcc/
(configure.ac:4059). $$r is the build directory. The
configure rule sets r before it runs anything
(Makefile.in:49463).
newlib's configure receives that compiler as CC, with more flags after it:
CC="$(CC_FOR_TARGET) $(XGCC_FLAGS_FOR_TARGET) $$TFLAGS"; export CC; \
CFLAGS="$(CFLAGS_FOR_TARGET)"; export CFLAGS; \
Listing 3.6-4: CC for every target library
(Makefile.tpl:308-309).
XGCC_FLAGS_FOR_TARGET is FLAGS_FOR_TARGET plus the build sysroot and debug
prefix maps (Makefile.tpl:637). The sub-make gets the same
CC again through EXTRA_TARGET_FLAGS (Makefile.tpl:787).
FLAGS_FOR_TARGET: the build tree dressed as an install
When --with-newlib is in target_configargs, the top level fills
FLAGS_FOR_TARGET for every target library. If gcc/ is in the tree, it starts
with -nostdinc (configure.ac:3750-3752). Then, for a cross:
# If we're building newlib, use its generic headers last, but search
# for any libc-related directories first (so make it the last -B
# switch).
FLAGS_FOR_TARGET=$FLAGS_FOR_TARGET' -B$$r/$(TARGET_SUBDIR)/newlib/ -isystem $$r/$(TARGET_SUBDIR)/newlib/targ-include -isystem $$s/newlib/libc/include'
# If we're building libgloss, find the startup file, simulator library
# and linker script.
case " $target_configdirs " in
*" libgloss "*)
# Look for startup file, simulator library and maybe linker script.
FLAGS_FOR_TARGET=$FLAGS_FOR_TARGET' -B$$r/$(TARGET_SUBDIR)/libgloss/'"$libgloss_dir"
# Look for libnosys.a in case the target needs it.
FLAGS_FOR_TARGET=$FLAGS_FOR_TARGET' -L$$r/$(TARGET_SUBDIR)/libgloss/libnosys'
# Most targets have the linker script in the source directory.
FLAGS_FOR_TARGET=$FLAGS_FOR_TARGET' -L$$s/libgloss/'"$libgloss_dir"
;;
esac
Listing 3.6-5: what every target library compiles with in a newlib tree
(configure.ac:3780-3796).
Read it as two halves.
Headers. -nostdinc drops every standard include directory, GCC's own
included (Chapter 1.10). That also drops
the tooldir include/ under your prefix, where an older newlib may already be
installed (Chapter 1.8). GCC's own headers come
back through the -B in CC_FOR_TARGET. Each -B directory joins
include_prefixes (gcc/gcc.cc:4615-4616), and the %I
directive in cpp_unique_options (gcc.cc:1248-1249) turns
each one that exists into -isystem DIR/include and
-isystem DIR/include-fixed (gcc.cc:6604-6632). It is
Chapter 1.10's -nostdinc -isystem pair, done with -B. The two -isystem
options in Listing 3.6-5 add newlib's configured headers from its build
directory, targ-include/, and its generic headers from the source tree, which
the comment wants searched last.
newlib checks for this half. If CC already names a libc/include directory, it
adds no -I of its own:
# These get added in the top-level configure.in, except in the case where
# newlib is being built natively.
LIBC_INCLUDE_GREP=`echo ${CC} | grep \/libc\/include`
if test -z "${LIBC_INCLUDE_GREP}"; then
CC_FOR_NEWLIB="${CC} -I$PWD/targ-include -I${abs_newlib_basedir}/libc/include"
else
CC_FOR_NEWLIB="${CC}"
fi
Listing 3.6-6: newlib's side of the handshake
(newlib-4.5.0 newlib/configure.ac:334-341).
Libraries. -B$$r/$(TARGET_SUBDIR)/newlib/ makes every library built after
newlib find crt0.o, libc.a and libm.a in newlib's build directory, as if
they were installed. libgloss adds its startup files, libnosys.a, and the
linker scripts in its source directory. What libgloss is, and what libnosys
does, is Chapter 3.4's subject.
A -B directory alone is not enough for a multilib toolchain, because the
driver searches each prefix with the multilib directory appended first. newlib
copies its outputs into a multilib-shaped subdirectory of its build directory
for that reason (newlib-4.5.0 newlib/Makefile.am:78-84), and
its configure.ac explains the copy:
The search directories specified by -B are a bit special, see for_each_path() in gcc.c of the GCC sources. First a search is performed on all search paths with the multilib directory appended (if desired), then a second search is performed on demand with the base directory only.
That is the two-pass search of Chapter 1.6, seen from the library's side.
CFLAGS_FOR_TARGET and --enable-target-optspace
A cross build compiles its target libraries with -g -O2 unless you set
CFLAGS_FOR_TARGET (configure.ac:2895-2897).
The install manual documents --enable-target-optspace under
Configuration: target libraries are optimized for code space
(install.texi:1898-1901). The mechanism is a makefile fragment.
configure selects config/mt-ospace (configure.ac:3098-3117),
the top-level Makefile includes it (Makefile.tpl:650), and
the fragment appends to the flags of every target library:
CFLAGS_FOR_TARGET += -g -Os
CXXFLAGS_FOR_TARGET += -g -Os
Listing 3.6-7: config/mt-ospace (config/mt-ospace:2-3).
The result is -g -O2 -g -Os. The GCC manual documents that the last -O
option wins, under Optimize Options (invoke.texi:12918-12919).
The same flag also reaches newlib's own configure, which adds a second -Os
(newlib-4.5.0 newlib/configure.host:82-85).
That is the general rule for newlib options in a combined tree. The top level
passes most of your --enable-* and --with-* options to every target
library's configure (configure.ac:3473-3611,
:3683), and adds --disable-option-checking
(:3646). So an option such as --enable-newlib-nano-malloc
goes on the GCC top-level command line, and each library that does not know it
ignores it.
The multilib matrix: --print-multi-lib, multilib.out and config-ml.in
Chapter 1.6 left a promise: prune multilibs in GCC and you prune them in newlib. Two pieces of code keep it, one in each project's build.
The top level records the list in multilib.out
Before it configures newlib, the top level asks the new compiler for its variants and compares the answer with the last one:
echo "Checking multilib configuration for newlib..."; \
$(SHELL) $(srcdir)/mkinstalldirs $(TARGET_SUBDIR)/newlib; \
$(CC_FOR_TARGET) --print-multi-lib > $(TARGET_SUBDIR)/newlib/multilib.tmp 2> /dev/null; \
if test -r $(TARGET_SUBDIR)/newlib/multilib.out; then \
if cmp -s $(TARGET_SUBDIR)/newlib/multilib.tmp $(TARGET_SUBDIR)/newlib/multilib.out; then \
rm -f $(TARGET_SUBDIR)/newlib/multilib.tmp; \
else \
rm -f $(TARGET_SUBDIR)/newlib/Makefile; \
mv $(TARGET_SUBDIR)/newlib/multilib.tmp $(TARGET_SUBDIR)/newlib/multilib.out; \
fi; \
else \
mv $(TARGET_SUBDIR)/newlib/multilib.tmp $(TARGET_SUBDIR)/newlib/multilib.out; \
fi; \
test ! -f $(TARGET_SUBDIR)/newlib/Makefile || exit 0; \
Listing 3.6-8: the start of configure-target-newlib
(Makefile.in:49465-49478).
This code does not hand the list to newlib. It decides whether newlib needs a new
configure. If the list changed, the rule deletes newlib's Makefile, and the
test on the last line lets the configure run again. Every target module gets the
same check, from check_multilibs=true in the template
(Makefile.tpl:1174-1188, :1488-1493).
config-ml.in builds one newlib per line
newlib's configure.ac calls AM_ENABLE_MULTILIB(, ..)
(newlib-4.5.0 newlib/configure.ac:316), which runs the shared
top-level script config-ml.in. In a combined tree that is GCC's copy. Its own
header draws the result, with newlib as the example:
# The build tree is layed out as
#
# ./
# newlib
# m68020/
# newlib
# m68881/
# newlib
Listing 3.6-9: one build directory per variant (config-ml.in:54-61).
The directory list comes from ${CC-gcc} --print-multi-lib, with the . line
dropped (config-ml.in:217-229). CC here is the xgcc from
Listing 3.6-4. For each directory, the script finds that directory's line again
and turns its options into compiler flags:
for i in `${CC-gcc} --print-multi-lib 2>/dev/null`; do
dir=`echo $i | sed -e 's/;.*$//'`
if [ "${dir}" = "${ml_dir}" ]; then
flags=`echo $i | sed -e 's/^[^;]*;//' -e 's/@/ -/g'`
break
fi
done
ml_config_env='CC="${CC_}$flags" CXX="${CXX_}$flags" F77="${F77_}$flags" GFORTRAN="${GFORTRAN_}$flags" GOC="${GOC_}$flags" GDC="${GDC_}$flags"'
Listing 3.6-10: a -print-multi-lib line becomes CC
(config-ml.in:755-762).
thumb;@mthumb becomes -mthumb, appended to CC. Before that, the script
rewrites every -B, -I or -L argument, and every bare path, that points into
the target build directory, so that it points into the variant's directory
instead (config-ml.in:776-788). So Listing 3.6-5's
-B$$r/arm-none-eabi/newlib/ becomes -B$$r/arm-none-eabi/thumb/newlib/ for the
thumb variant, and each variant links against its own newlib.
make install then puts each variant's libraries in
$(tooldir)/lib$(MULTISUBDIR)
(newlib-4.5.0 newlib/Makefile.am:67-68). That is the tooldir
prefix of Chapter 1.5 with the multilib
directory of Chapter 1.6 appended, so the installed driver finds each variant
where it looks first.
newlib builds exactly the variants that xgcc -print-multi-lib prints, with
exactly the options it prints. The install manual documents
--disable-multilib under Configuration
(install.texi:1298-1302). The top level passes it to gcc/configure and to
every library, so the compiler and newlib agree on one variant.
The switches that prune newlib and not the compiler
The same page lists finer-grained switches for some targets, such as
--disable-fpu and --disable-interwork for arm-*-*
(install.texi:1304-1322). Those switches are read in exactly one place.
config-ml.in turns each --disable-NAME into enable_NAME=no
(config-ml.in:131-134) and then drops matching directories from
the library's list (config-ml.in:234-489). Nothing in
gcc/configure.ac, gcc/config.gcc or the top level reads them. So the
compiler still lists the variant, and newlib does not build it.
On arm-none-eabi, the default multilib set comes from t-arm-elf
(gcc/config.gcc:1497-1504), and it names its two hard-float
variants with a final fpu directory
(gcc/config/arm/t-arm-elf:71-86). Configure with --disable-fpu,
and -print-multi-lib still prints both fpu lines while newlib builds neither.
An option set that selects one of them finds no libc.a in its directory, and
the driver's second pass takes the default variant's libc.a instead
(Chapter 1.6). That is the "surprise link error on an
exotic -m option" that Chapter 3.4 sends here: the compiler and the library
disagree about which variants exist.
Watching it work: -print-multi-lib against the newlib log
These commands need a finished combined build. Nobody ran them at the pin, so no output is shown.
$ gcc/xgcc -Bgcc/ -print-multi-lib
$ cat arm-none-eabi/newlib/multilib.out
$ grep -e 'Configuring in arm-none-eabi/' \
-e 'Running configure in multilib subdirs' build.log
The first two must match line for line, because Listing 3.6-8 wrote the second
from the same command. build.log is your saved make output. The top level
prints "Configuring in" before each target configure
(Makefile.in:49481), and config-ml.in prints the
directory list before it configures the variants
(config-ml.in:664-668). In a serial build, the list that follows
"Configuring in arm-none-eabi/newlib" is newlib's. Every line of
-print-multi-lib except . appears in it, unless one of the switches in the
previous section pruned it.
The nano variant: --enable-newlib-nano-formatted-io and nano.specs
newlib has a small-footprint configuration, called nano. Using it takes two halves that live in different places, and a combined tree supplies only one of them.
The build half is a newlib configure run with
--enable-newlib-nano-malloc and --enable-newlib-nano-formatted-io
(newlib-4.5.0 newlib/configure.ac:232-280). newlib's README
explains what each one changes (newlib-4.5.0 README:336-342).
The link half is a specs file. libgloss installs nano.specs for ARM
(newlib-4.5.0 libgloss/arm/Makefile.inc:7-8), copied
from elf-nano.specs on ELF targets (:81-82):
*cpp_unique_options:
-isystem =/include/newlib-nano %(nano_cpp_unique_options)
*nano_libc:
-lc_nano
Listing 3.6-11: nano.specs, abridged
(newlib-4.5.0 libgloss/arm/elf-nano.specs:5-9).
It expects a libc_nano.a and an include/newlib-nano directory. Nothing in
newlib-4.5.0's build files creates either name. So they must come from a second
newlib build, configured with the nano options and renamed by whoever assembles
the toolchain. A combined tree cannot be that second build. It configures newlib
once, in $(TARGET_SUBDIR)/newlib, so one make produces one newlib. How
%rename and -specs= rewrite the spec table is
Chapter 1.3's subject.
If you do put --enable-newlib-nano-formatted-io on GCC's top-level command
line, the whole newlib in the tree becomes the nano-I/O one, and GCC notices in
one place. The testsuite's newlib_nano_io effective target searches the
"Configured with:" line of gcc -v for that option
(gcc/testsuite/lib/target-supports.exp:10217-10220,
:279-291). The internals manual lists the keyword under
Effective-Target Keywords (sourcebuild.texi:2911-2913).
Chapter 3.7 runs that testsuite.
Three things to carry away
One no_c=true breaks the deadlock. Every target module waits for newlib and
libgloss by default, and the two of them are exempt.
The top level hands newlib everything. The in-tree xgcc, the -B and
-isystem flags that make build directories look installed, and --with-newlib,
which you never typed.
newlib's multilibs are xgcc -print-multi-lib, line for line. Prune the
compiler and you prune newlib. Prune only newlib and the driver links the wrong
variant.
Things that surprise people
newlib's headers never pass through fixincludes. The stmp-fixinc rule runs
inside all-gcc (gcc/Makefile.in:3602-3639, reached from
all.cross through libgcc-support and stmp-int-hdrs,
:2219-2220, :2459,
:3475), before newlib can configure. It scans
$(gcc_tooldir)/sys-include on a cross without a sysroot
(gcc/configure.ac:188, :2537-2545).
newlib installs into the tooldir's include/, not sys-include/.
newlib waits for libgcc. It has no_c but not no_gcc, so libgcc is
configured and built first, before any newlib header exists in the build tree.
A combined tree needs no --with-newlib. The top level passes it to
gcc/configure and to every target library as soon as newlib/configure is in
the tree. Passing it yourself changes nothing on a cross.
Documentation coverage
GCC's manuals document the combined tree for binutils, not for newlib. The
install manual's Downloading the source page says how to link
binutils components into the GCC source directory (install.texi:698-704). For
newlib, the only such instruction is in the nvptx notes on the
Host/target specific installation notes page: "add a symbolic
link to nvptx-newlib's newlib directory to the directory containing the GCC
sources" (install.texi:4684-4687). Building mentions "a C library
in the same source tree as GCC" once, to say what you must supply when you do
not have one (install.texi:3313-3322). Configuration
documents --with-newlib only as omitting __eprintf from libgcc.a
(install.texi:2776-2780), and documents --disable-multilib, the per-target
multilib switches and --enable-target-optspace (:1298-1322, :1898-1901).
-print-multi-lib is in Developer Options
(invoke.texi:21583-21589).
The internals manual sends the reader elsewhere. Its
Top Level Source Directory node says the top-level build
system, "including how recursion into subdirectories works and how building
runtime libraries for multilibs is handled, is documented in a separate manual,
included with GNU Binutils" (sourcebuild.texi:157-160). This chapter reads the
source instead. newlib's own documentation and its README describe
newlib's options and a standalone build after GCC is installed.
What is not documented:
- That newlib is exempt from the default C-library dependency through
no_c=true, and that it still waits forgccand libgcc. - That the top level passes
--with-newlibtogcc/configureand to every target library whennewlib/is in the tree, and thatinhibit_libcis then true on a fresh prefix with no other flag. - That a combined tree installs the
inhibit_libclibgcc. FLAGS_FOR_TARGET: the-nostdinc,-Band-isystemflags that let target libraries use newlib's build directory as if it were installed.- That
config-ml.inbuilds one newlib per-print-multi-libline, and that the top level reconfigures newlib when that list changes. - That the per-target multilib switches act on the libraries only, so the compiler can select a variant that newlib never built.
- That
--enable-target-optspaceappends to the default-O2rather than replacing it. - That newlib's headers are not processed by fixincludes.
Next: the toolchain exists. Chapter 3.7 asks whether it works, and runs GCC's own testsuite against it on a simulator or a board.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
3.7 Testing the toolchain you built: where --target_board runs each test
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
Your arm-eabi toolchain builds, and make check runs for hours. Then
gcc.sum reports thousands of failed execution tests. The compiler is not at
fault. DejaGnu ran each ARM executable on your x86 build machine, and it said so in
one warning near the top of the log.
GCC's testsuite does not decide where a test program runs. A DejaGnu board file
decides, and --target_board names the board. A cross run with no board name
uses the board unix, which is the build machine.
This chapter assumes Chapter 1.6, for
-print-multi-directory and the multilib search, and
Chapter 3.4 and
Chapter 3.6, for the bare-metal toolchain and the
combined tree that the examples test. How to write a test is
Chapter 6.1's subject. This chapter runs all of them
against a toolchain you built.
The chapter crosses into DejaGnu, a separate GNU project, because the code that
picks a board, starts a simulator and reads the exit status is DejaGnu's. GCC's
testsuite supplies the configuration and reads the answers. DejaGnu citations are
to the dejagnu-1.6.3 tag, the newest release. GCC 15.2 requires DejaGnu 1.5.3 or
later (install.texi:574).
Nothing in this chapter was run. A test run needs a build tree, DejaGnu and, for a
cross target, a simulator or a board. The commands follow from the cited source and
the install manual. Without a build you can still read a board file from DejaGnu's
baseboards directory and a .sum file from another run, and that is enough to
follow the chapter.
make check writes site.exp, then runs runtest
The install manual documents the user-facing part on its Testing
page: make -k check in the object directory, per-language targets such as
make check-gcc, and RUNTESTFLAGS to pass options to DejaGnu. Under that, the
top-level check target runs check-host and check-target
(Makefile.tpl:993-1015), so the target libraries' testsuites run
too. In gcc/, each check-<tool> target ends in
$(RUNTEST) --tool <tool> $(RUNTESTFLAGS), run in testsuite/<tool>
(gcc/Makefile.in:4610-4625). check-gcc takes the parallel path
to the same command (:4688-4713,
gcc/c/Make-lang.in:174-180).
One file carries configure's decisions to DejaGnu. Every check target depends on
site.exp, which gcc/Makefile.in writes:
@echo "set host_triplet $(host)" >> ./site.tmp
@echo "set build_triplet $(build)" >> ./site.tmp
@echo "set target_triplet $(target)" >> ./site.tmp
@echo "set target_alias $(target_noncanonical)" >> ./site.tmp
Listing 3.7-1: the triplets in site.exp (gcc/Makefile.in:4508-4511).
DejaGnu loads this site.exp before its global configuration files
(runtest.exp:680-710). target_alias is target_noncanonical,
the target name as you typed it (Chapter 2.2).
A board file uses it later to name the simulator.
Three more lines matter for a cross build:
TEST_ALWAYS_FLAGSis--sysroot=DIRwhen you configured with--with-build-sysroot=DIR(gcc/Makefile.in:4520-4522,gcc/configure.ac:140-147).gcc_target_compileputs it first on every compile (gcc/testsuite/lib/gcc.exp:137-142).- When the build tree has a target
newlibdirectory and the host is not the target,site.expadds-Iand-Boptions for it (gcc/Makefile.in:4536-4553). The comment above the block says the compiler needs the-B"so it can find newlib's crt0.o". - In a combined tree,
-Lto the in-treelddirectory lets the linker find its scripts (:4554-4557).
The compiler under test is the one in the build tree. When nothing sets
GCC_UNDER_TEST, gcc_init asks DejaGnu's find_gcc
(gcc.exp:101-107). It returns xgcc -B<dir>/ for the xgcc it
finds, and <target_alias>-gcc only when there is none
(lib/libgloss.exp:631-648). libgcc helps by copying itself back
into gcc/, and its comment gives the reason:
all: all-multi
# Now that we have built all the objects, we need to copy
# them back to the GCC directory. Too many things (other
# in-tree libraries, and DejaGNU) know about the layout
# of the build tree, for now.
$(MAKE) install-leaf DESTDIR=$(gcc_objdir) \
slibdir= libsubdir= MULTIOSDIR=$(MULTIDIR)
Listing 3.7-2: libgcc returns to the compiler's directory (libgcc/Makefile.in:116-122).
install-leaf puts libgcc.a in $(libsubdir)$(MULTISUBDIR), and libsubdir
is empty here, so each variant lands in gcc/<multilib directory>/
(libgcc/Makefile.in:315, :1188-1193).
The multilib section below depends on that layout.
No --target_board means unix
DejaGnu runs every test once for each board in target_list. When nothing has set
the list, it supplies one:
if {![info exists target_list]} {
# Make sure there is at least one target machine. It's probably a Unix box,
# but that's just a guess.
set target_list { "unix" }
} else {
verbose "target list is $target_list"
}
Listing 3.7-3: the default board (runtest.exp:1772-1778, DejaGnu 1.6.3).
unix is not an ordinary board name. is_remote treats it as the build machine,
in a check whose comment calls unix "a magic string that should really go away
someday" (lib/framework.exp:195-201). On a local board,
unix_load runs the program as $prog $parg
(config/unix.exp:64-69). On a cross toolchain that program is an
ARM executable, and the execution tests fail by the thousand.
DejaGnu does notice. After it loads a board, it checks for a cross target on a local board:
if { ![isnative] && ![isremote target] } {
global env build_triplet target_triplet
if { (![info exists env(DEJAGNU)]) && ($build_triplet ne $target_triplet) } {
warning "Assuming target board is the local machine (which is probably wrong).\nYou may need to set your DEJAGNU environment variable."
}
}
Listing 3.7-4: the only warning (runtest.exp:953-958, DejaGnu 1.6.3).
The warning disappears when DEJAGNU is set, whatever the file it names contains.
The install manual calls another message harmless, "Couldn't find
the global config file" (install.texi:3439-3443). On a cross run, read it as a hint: unless
~/.dejagnurc sets target_list, no file chose a board for you
(runtest.exp:1021-1044).
You name a board in one of two ways. The install manual documents
RUNTESTFLAGS=--target_board=arm-sim on the make line. GCC's
simulator testing page, outside the source tree, uses that board for an
arm-eabi combined tree (read on 2026-10-19, last modified 2026-07-21). The other
way is the global configuration file that DEJAGNU names
(runtest.exp:1029-1041), which can set target_list for each
triplet. The command line wins. DejaGnu parses --target_board again after that
file, with the comment "Set it again, father knows best"
(runtest.exp:1206-1209).
load_board_description: from a board name to arm-sim.exp
--target_board=arm-sim/-mthumb names a board and a variant. DejaGnu splits the
name at each / (runtest.exp:1796-1807). The first part selects the
file. The rest is the variant list, which a later section follows.
load_board_description looks for arm-sim.exp in this order
(runtest.exp:1509-1521):
<dir>/<host>/for each directory inboards_dir,$libdir/baseboards/<host>/,- each directory in
boards_dir, $libdir/baseboards/, the boards that DejaGnu installs.
<host> is the host board's name, by default the build machine's host name
(runtest.exp:915-931),
and boards_dir defaults to a boards directory next to the file that DEJAGNU
names (runtest.exp:1038-1040). So your own board files go
there, and they shadow DejaGnu's. A name that matches no file stops the run with
"couldn't load description file". Only unix falls back to the generic
configuration (runtest.exp:931-938).
This is the board that the simulator page uses:
# Load the generic configuration for this board. This will define a basic
# set of routines used to communicate with the board.
load_generic_config "sim"
# No multilib flags needed by default.
process_multilib_options ""
...
# basic-sim.exp is a basic description for the standard Cygnus simulator.
load_base_board_description "basic-sim"
# The name of the directory in the build tree where the simulator lives.
setup_sim arm
# The compiler used to build for this board. This has *nothing* to do
# with what compiler is tested if we're testing gcc.
set_board_info compiler "[find_gcc]"
# The basic set of flags needed to build "hello world" for this
# board. This board uses libgloss and newlib.
set_board_info cflags "[libgloss_include_flags] [newlib_include_flags]"
set_board_info ldflags "[libgloss_link_flags] [newlib_link_flags] $additional_options"
# This board doesn't use a linker script.
set_board_info ldscript ""
# The simulator doesn't return exit statuses and we need to indicate this.
set_board_info needs_status_wrapper 1
# Used by a few gcc.c-torture testcases to delimit how large the stack can
# be.
set_board_info gcc,stack_size 16384
Listing 3.7-5: the ARM simulator board, abridged (baseboards/arm-sim.exp:19-61, DejaGnu 1.6.3).
Each line hands a decision to a later stage:
load_generic_config "sim"loadsconfig/sim.exp, which sets the board'sprotocoltosim(config/sim.exp:142). The next section follows that word.process_multilib_options ""turns the variant list into compiler flags.setup_sim armnames the simulator.find_simtakes theSIMvariable if it is set, thensim/arm/runin the build tree, then<target_alias>-runfromPATH(baseboards/basic-sim.exp:24-47). Thetarget_aliasof Listing 3.7-1 makes thatarm-eabi-run. A combined tree that containssim/, as the simulator page builds, has the in-tree one.cflagsandldflagsadd libgloss and newlib from the build tree. The multilib section shows how they choose the variant's directory.needs_status_wrappersays that the simulator loses the exit status.
The compiler line carries a comment that is easy to skip. That compiler "has
nothing to do with what compiler is tested if we're testing gcc".
gcc_target_compile passes compiler=$GCC_UNDER_TEST
(gcc.exp:160-161), and DejaGnu's default_target_compile
uses an explicit compiler= option before it looks at the board's key
(lib/target.exp:444-447 and :559-568).
A board file can derive from another, but set_board_info keeps the first value
it sees for a key (lib/targetdb.exp:59-64). So a derived
board sets its own keys before it loads the base board.
remote_load: how a dg-do run test reaches the simulator
A dg-do run test compiles to an executable. DejaGnu's dg-test then calls
${tool}_load on it (lib/dg.exp:797-802). GCC wraps that procedure to
handle dg-shouldfail and target environment variables
(gcc-dg.exp:465-486), and DejaGnu's own version calls
remote_load target (lib/standard.exp:22-36).
remote_load passes the request to call_remote, which looks for a procedure
named after the board's protocol:
foreach try "$high_prot [board_info $dest file_transfer] [board_info $dest connect] telnet standard" {
verbose "looking for ${try}_${proc}" 4
if { $try ne "" } {
if { [info procs "${try}_${proc}"] ne "" } {
verbose "call_remote calling ${try}_${proc}" 3
return [eval ${try}_${proc} \"$dest\" $args]
}
}
}
Listing 3.7-6: the protocol picks the load procedure (lib/remote.exp:659-667, DejaGnu 1.6.3).
high_prot holds the board name and its protocol value
(lib/remote.exp:624-631). For arm-sim that is sim, so
sim_load runs the board's sim program, with sim,options, on the test
executable (config/sim.exp:25-56), and turns the status into
pass or fail (config/sim.exp:62-122). For unix it is unix
(config/unix.exp:161). A board with no load procedure of its
own ends at standard_load, which copies the program to the remote board and runs
it there (lib/remote.exp:1077-1120).
So one protocol value decides where your test runs, and the file that holds it
does not come from GCC.
needs_status_wrapper: exit codes through testglue.c
A simulator that loses the exit status would turn every abort () into a pass.
The board declares this with needs_status_wrapper, and GCC's testsuite responds
in two places. gcc_init builds a wrapper object once, as gcc-testglue.o
(gcc.exp:116, wrapper.exp:24-53). Then each
compile links it:
if {[target_info needs_status_wrapper] != "" && \
[target_info needs_status_wrapper] != "0" && \
[info exists gluefile] } {
lappend options "libs=${gluefile}"
lappend options "ldflags=$wrap_flags"
if { $type == "executable" } {
set options [concat "{additional_flags=-dumpbase \"\"}" $options]
}
}
Listing 3.7-7: linking the status wrapper (gcc/testsuite/lib/gcc.exp:164-172).
The object comes from DejaGnu's testglue.c, and wrap_flags is
-Wl,-wrap,exit -Wl,-wrap,_exit -Wl,-wrap,main -Wl,-wrap,abort
(lib/libgloss.exp:939-968). The linker sends each of those
calls to the wrapper, which writes *** EXIT code N to file descriptor 1 before it
exits (testglue.c:7-9, :94-97).
sim_load reads the code from that line (config/sim.exp:110-113).
When the board needs a wrapper and the line is missing, check_for_board_status
treats the program as crashed, whatever status the simulator returned
(lib/remote.exp:1226-1251).
The wrapper changes the test program, so tests can opt out. The unwrapped
effective target is false on such a board
(target-supports.exp:1666-1674).
Board keys GCC reads: gcc,timeout, gcc,stack_size and others
A board file is a list of set_board_info keys. DejaGnu reads most of them. GCC's
own testsuite reads these:
| Key | What GCC's testsuite does with it | Source |
|---|---|---|
multilib_flags | adds the variant's flags to each compile | gcc.exp:150-158 |
needs_status_wrapper | links the wrapper, and makes unwrapped false | Listing 3.7-7 |
gcc,timeout | sets the time limit when neither the test nor its .exp file set one | timeout.exp:43-55 |
gcc,stack_size | makes stack_size true, with the key's value as the limit | target-supports.exp:654-682 |
gcc,no_trampolines | makes trampolines false | target-supports.exp:637-650 |
gcc,signal_suppress | makes signal false | target-supports.exp:686-691 |
is_simulator, slow_simulator | make simulator true and hw false | target-supports.exp:10474-10515 |
The names in the middle column are effective targets, which tests require with
dg-require-effective-target (Chapter 6.1). So one board key can turn a family of
tests into UNSUPPORTED results without a change to GCC.
Not every effective target comes from the board. newlib_nano_io searches the
Configured with: line of gcc -v for --enable-newlib-nano-formatted-io
(target-supports.exp:10217-10220, :278-291).
That flag is newlib's, so it reaches GCC's line only when you passed it to a
combined tree's top-level configure (Chapter 3.6).
A nano newlib built on its own, as in Chapter 3.4, counts only if GCC's own
configure line carries the flag too.
DejaGnu also marks a board as remote unless its name is the build machine's host
name (runtest.exp:1527-1537). On a remote target, GCC's load
wrapper reports tests that set target environment variables as unsupported
(gcc-dg.exp:479-483).
Read a board file before you trust its results. DejaGnu 1.6.3 also ships a
qemu.exp board, and its load procedure tests the result of local_exec with
array size:
proc qemu_load { dest prog args } {
global qemu
global timeout
set ret [local_exec "$qemu $prog" "" "" $timeout]
if { [array size ret] == 0 } {
return "pass"
} else {
return "fail"
}
}
Listing 3.7-8: qemu_load (baseboards/qemu.exp:199-209, DejaGnu 1.6.3).
local_exec returns a list (lib/remote.exp:281-285), not an
array. Tcl's array size returns 0 for a variable that is not an array
(Tcl array manual). So this procedure returns pass for every
program it runs.
For a hosted toolchain such as Chapter 3.3's aarch64-linux-gnu, a board of your
own can load the sim configuration and name a user-mode emulator as its sim
program, such as the qemu-aarch64 that qemu.exp picks for aarch64*-gnu*
(baseboards/qemu.exp:86-89). sim_load then reads the
emulator's real exit status. How the emulator finds the target's dynamic loader is
run-time setup, outside this book.
--target_board=arm-sim/-mthumb: variants become multilib_flags
The install manual documents the variant syntax on the Testing
page: slashes separate options, and braces expand into several runs, as in
arm-sim\{-mhard-float,-msoft-float\}\{-O1,-O2,-O3,\}. DejaGnu expands the braces
itself, before the main loop (runtest.exp:1685-1714). Each
expanded name is a board with options after slashes. It prints as a
Running target line,
and the results after that line belong to that variant
(runtest.exp:1796-1807).
The options do not reach the compiler by themselves. The board must call
process_multilib_options, as arm-sim.exp and unix.exp do, and that procedure
decides what each word means:
foreach x $board_variant_list {
regsub -all "^\[ \t\]*" $x "" x
regsub -all "\[ \t\]*$" $x "" x
if { $x eq "" } {
continue
}
switch -glob -- $x {
...
"little*endian" -
"el" -
"EL" {
append multilib_flags " -EL"
}
"big*endian" -
"eb" -
"EB" {
append multilib_flags " -EB"
}
"soft*float" {
append multilib_flags " -msoft-float"
}
"-*" {
append multilib_flags " $x"
}
default {
append multilib_flags " -m$x"
}
}
}
set_board_info multilib_flags $multilib_flags
Listing 3.7-9: variant words become multilib_flags, abridged (lib/libgloss.exp:824-894, DejaGnu 1.6.3). The omitted cases turn words such as elf and dwarf2 into other board keys.
A word that starts with - passes through. Any other word gets -m in front. So
arm-sim/thumb means -mthumb, soft-float means -msoft-float, and el means
-EL. The procedure also does nothing when the board already has
multilib_flags (:831-833).
default_target_compile then puts multilib_flags in front of the other flags
(lib/target.exp:696-704), so a test's own dg-options come
after the variant's. GCC relies on that order. Its comment in
gcc_target_compile says that a flag is "appended here to multilib_flags as it can
be overridden by the latter if it was added earlier"
(gcc.exp:150-158).
get_multilibs: the variant asks the driver for its directory
The libraries must come from the variant's multilib, and the board finds them by
asking the compiler under test. newlib_link_flags, which arm-sim.exp calls for
its ldflags, takes a directory from get_multilibs and adds -B and -L for
its newlib subdirectory (lib/libgloss.exp:108-139).
get_multilibs finds the target's directory in the build tree, which is named
after target_alias, and appends what the driver prints:
set gccpath [eval exec $compiler --print-multi-directory $mopts]
set gccpath [lindex $gccpath 0]
if { $gccpath ne "" } {
verbose "GCC path is $gccpath"
if { [llength $args] == 0 } {
set board_info($target_board,multitop) $multitop/$gccpath
}
return $multitop/$gccpath
}
Listing 3.7-10: the driver chooses the variant's directory (lib/libgloss.exp:513-521, DejaGnu 1.6.3).
$mopts is the board's multilib_flags (:444-452). So for
arm-sim/-mthumb the board runs <objdir>/gcc/xgcc --print-multi-directory -mthumb, and newlib comes from <objdir>/arm-eabi/<that directory>/newlib.
libgcc needs no help. It put each variant under gcc/<multilib directory>/, and
the driver searches a -B prefix with that directory appended
(gcc/gcc.cc:4613-4614, and pass four in Chapter 1.6).
This is where a variant run can test less than you think. When the variant's flags
select the default multilib, -print-multi-directory prints .
(Chapter 1.6). The board then links the default newlib,
and the driver's search finds the default libgcc. The test objects get the
variant's code generation, and the libraries do not. Check before a long run:
$ cd <objdir>
$ ./gcc/xgcc -B./gcc/ -print-multi-lib
$ ./gcc/xgcc -B./gcc/ -mthumb -print-multi-directory
If the second command prints ., the -mthumb run links the default libraries.
check-gcc//: one directory per variant
The install manual documents a parallel form for the gcc subdirectory. The rule
passes the text after // as --target_board, and gives each variant its own
testsuite directory, with each / turned into a dot
(gcc/Makefile.in:4587-4600):
$ cd <objdir>/gcc
$ make -j2 check-gcc//arm-sim/{-marm,-mthumb}
The -mthumb results land in testsuite.arm-sim.-mthumb/gcc/gcc.sum.
Reading gcc.sum: Running target lines and the # of counts
Each tool writes a .sum and a .log file in its testsuite directory, so the C
results are in <objdir>/gcc/testsuite/gcc/gcc.sum. Under make -j that file is
merged from parallel parts (gcc/Makefile.in:4657-4686). The
install manual documents the two files and the status codes. The layout is
DejaGnu's, and four kinds of line carry it:
- The header names the configuration:
Target is <triplet>for a cross run,Native configuration is <triplet>for a native one (runtest.exp:1392-1405). With no triplet fromsite.expor--target, DejaGnu uses the build machine's (runtest.exp:880-888). Schedule of variations:lists every board and variant before any test runs (runtest.exp:1789-1793).Running target <board/variant>starts each variant's results (runtest.exp:1805).- Each result is one line,
<STATUS>: <test name>(lib/framework.exp:863-869). Each variant ends with a block of# ofcounts (lib/framework.exp:486-527).
To see the skeleton of a run without its thousands of results:
$ grep -E '^(Target is|Native configuration is|Running target|# of )' \
<objdir>/gcc/testsuite/gcc/gcc.sum
The test name does not contain the variant. The same name appears once under each
Running target line, and only its position tells the variants apart.
The manual lists seven status codes. DejaGnu counts four more: KFAIL, KPASS,
UNRESOLVED and UNTESTED (lib/framework.exp:1060-1071).
A cross builder meets UNRESOLVED first. A missing crt0.o, or a link error from
the board's ldflags, gives each run test a FAIL for "test for excess errors"
(lib/dg.exp:781-792) and an UNRESOLVED because "compilation failed
to produce executable" (lib/dg.exp:797-800).
contrib/compare_tests: comparing two runs
You compare a run with a baseline: the same toolchain before your change, or the
results posted for a similar target. compare_tests PREVIOUS CURRENT takes two
.sum files, or two directories whose common .sum files it compares
(contrib/compare_tests:8-33). It rewrites both inputs first:
sed 's/^XFAIL/FAIL/; s/^ERROR/FAIL/; s/^XPASS/PASS/' < "$1" | awk '/^[ ]*=== [^ ]* tests ===$/ {tool = $2} /^Running target / {target = $3} { if (tool != "") { sub(/:[ ]/, "&"tool": " ); }; if (target != "unix") { sub(/:[ ]/, "&"target": " ); }; print $0; }' | cut -c1-2000 >$tmp1
Listing 3.7-11: normalising a .sum file (contrib/compare_tests:111).
Read it from left to right:
sedfoldsXFAILintoFAIL,ERRORintoFAILandXPASSintoPASS. From here on, a test either passed or failed.awkremembers the tool from the=== gcc tests ===line and the board from eachRunning targetline, and inserts both after the status. Eachsubinserts after the first colon, so a line readsFAIL: arm-sim/-mthumb: gcc: <test name>. The board is left out when it isunix.- Later steps keep only the lines that start with
PASSorFAIL(:127-203).
Step 2 keeps variants apart, so runs on different boards share no test names. A
baseline from arm-sim against a run from arm-sim/-mthumb gives only
disappeared tests and new ones. Step 3 leaves out UNSUPPORTED and UNRESOLVED.
A test that passed before and is UNRESOLVED now appears only under "Old tests that
passed, that have disappeared".
Two sections make the script exit with 1: "Tests that now fail, but worked before"
(:127-138) and "New tests that FAIL"
(:153-164). Improvements and disappearances count only with
-strict. Because step 1 folded the expectations away, an XFAIL that turns into a
FAIL is not reported.
contrib/test_summary and contrib/test_installed
The install manual documents contrib/test_summary for mailing results to the
gcc-testresults list. The script itself sends nothing. It prints a shell script:
pipe it to more to look, or to sh to act (contrib/test_summary:25-29).
The report keeps only the XPASS, FAIL, UNRESOLVED, WARNING, ERROR and
# of lines of every .sum file below the current directory (:72,
:132), with the configure flags (:94). Piped to
sh, it also renames each .sum and .log file to .sent
(:151-155), unless you pass -t.
contrib/test_installed tests an installed compiler. In an empty directory it
writes its own site.exp and runs runtest for each language
(contrib/test_installed:36-43, :107-130). Its defaults
suit a native compiler. --prefix=DIR tests DIR/bin/gcc (:113),
so name a cross driver with --with-gcc=. The triplet and target_alias reach
site.exp only with --target= (:122-125). Without them DejaGnu
assumes a native run, and find_sim cannot name arm-eabi-run. The first
argument that the script does not recognise, and the rest after it, go to
runtest (:31-34):
$ mkdir /tmp/installed-test && cd /tmp/installed-test
$ <srcdir>/contrib/test_installed --target=arm-eabi \
--with-gcc=/opt/cross/bin/arm-eabi-gcc --without-g++ \
--without-gfortran --without-objc --target_board=arm-sim
Three things to carry away
A board file decides where a test runs. A cross run with no --target_board
runs every program on the build machine.
Variant options reach the libraries through -print-multi-directory. A
variant that selects the default multilib links the default libraries.
compare_tests compares only PASS and FAIL lines, and keys them by board.
Compare runs on the same board name, and read the UNRESOLVED results yourself.
Things that surprise people
--target_board=unix/O2 passes -mO2. process_multilib_options puts -m
in front of every variant word without a leading -. Write unix/-O2.
"Native configuration is" at the top of a cross .sum means DejaGnu never got
the target triplet. Check the site.exp that the run used.
test_summary | sh renames your results. The .sum and .log files become
.sent files. Run it without | sh to read the summary.
Documentation coverage
The install manual's Testing page (gcc/doc/install.texi:3393-3619)
documents make -k check, RUNTESTFLAGS, the --target_board variant syntax
(:3490-3535), the check-gcc// form (:3537-3557), the status codes
(:3560-3588) and test_summary (:3591-3606). For a cross compiler it points
to the simulator page (:3445-3446), outside the source tree. The
internals manual documents gcc,timeout as a board key under
Directives (gcc/doc/sourcebuild.texi:1105-1119), and the
effective targets simulator, signal, trampolines, unwrapped and
stack_size under Effective-Target Keywords
(sourcebuild.texi:2935-2973, :3156-3160). DejaGnu's manual documents
board files and lists board keys.
What is not documented:
- That a cross run with no
--target_boardruns every program on the build machine, and that a setDEJAGNUhides the warning. - What GCC's testsuite does with each board key. DejaGnu's manual lists
gcc,stack_size,gcc,no_trampolines,is_simulatorandneeds_status_wrappermostly without a description, and the internals manual describes the effective targets without the keys behind them. - That
newlib_nano_ioreads GCC'sConfigured with:line, not newlib's own configuration. - That
process_multilib_optionsadds-mto variant words, that a variant reaches newlib through-print-multi-directory, and that a variant on the default multilib links the default libraries. - How the status wrapper works, and that a missing
*** EXIT codeline counts as a crash. UNRESOLVEDand the other status codes beyond the manual's seven.compare_tests, its folding of XFAIL and XPASS, and its restriction to PASS and FAIL lines.contrib/test_installedis not mentioned either.
Next: what libgcc is for, and why the compiler emits calls into it when you link no C library at all.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
4.1 What libgcc is actually for
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
Your firmware for a Cortex-M0 divides two long long values in one function. You
link it with -nostdlib and your own startup code, and the linker reports an
undefined reference to __aeabi_ldivmod. You add -lgcc and the link works.
Chapter 1.10 gave that fix and its reason
in one sentence: the compiler emitted the call when it compiled your code. It did
not show what is at the other end of the call, or why a compiler needs a library
at all.
libgcc is not a library that you call. It is the second half of GCC's code generator. When the target has no instruction for an operation, the compiler emits a call to a helper with a fixed name, and libgcc holds the body under that name. The compiler and libgcc agree on each name and on the machine mode of each argument. No header file and no other library takes part in that agreement.
This chapter assumes Chapter 1.10, for Listing 1.10-5 and the -lgcc that you
put back by hand, Chapter 1.7, for the -lgcc slots on
the link line, and Chapter 1.6, because each multilib
has its own libgcc.a.
Both halves from the outside: -S, -print-libgcc-file-name and nm
Start from Listing 1.10-5 and make the operands 64 bits wide:
$ printf 'long long div64 (long long a, long long b) { return a / b; }\n' > div64.c
$ arm-none-eabi-gcc -O2 -mcpu=cortex-m0 -S -o - div64.c | grep aeabi
$ lib=$(arm-none-eabi-gcc -mcpu=cortex-m0 -print-libgcc-file-name)
$ arm-none-eabi-nm -A "$lib" | grep -w -e __aeabi_ldivmod \
-e __gnu_ldivmod_helper -e __divdi3 -e __udivmoddi4
The first command shows the call that the compiler wrote into the assembly, to
__aeabi_ldivmod. The second asks the driver which libgcc.a it links for this
multilib. The GCC manual documents -print-libgcc-file-name under
Developer Options, as the same as -print-file-name=libgcc.a. The
nm -A line puts the archive member in front of each symbol. A T line is a
definition, and a U line is a call out of that member. The output is a small
call graph inside libgcc.
Without a cross compiler, run the same experiment on x86-64 with __int128:
$ printf '__int128 div128 (__int128 a, __int128 b) { return a / b; }\n' > div128.c
$ gcc -O2 -S -o - div128.c | grep divti3
$ nm -A "$(gcc -print-libgcc-file-name)" | grep -w __divti3
This chapter shows no output for these commands. Each name that it predicts comes from the source cited in the sections below.
The name is the contract: gen_libfunc and optabs.def
The compiler never reads libgcc. It knows each helper only by its name, and it makes that name with one rule:
/* Initialize the libfunc fields of an entire group of entries in some
optab. Each entry is set equal to a string consisting of a leading
pair of underscores followed by a generic operation name followed by
a mode name (downshifted to lowercase) followed by a single character
representing the number of operands for the given operation (which is
usually one of the characters '2', '3', or '4').
Listing 4.1-1: the naming rule, above gen_libfunc
(gcc/optabs-libfuncs.cc:137-142).
The row for signed division in optabs.def supplies the operation name and the
operand count, "div" and '3' (gcc/optabs.def:139). On a
32-bit target a long long is two words (gcc/defaults.h:508-510),
which is the 8-byte mode DImode (gcc/machmode.def:212). So a signed
long long division is __ + div + di + 3, which is __divdi3. The
internals manual lists the helpers by these mode names, and it says that they
"take arguments and return values of a specific machine mode, not a specific C
type" (gcc/doc/libgcc.texi:28-29).
The same row serves floating point. Its generator calls the float generator for a
float mode and the integer generator for an integer mode
(optabs-libfuncs.cc:315-324). So one row names __divdi3,
__divsf3 and __divdf3, and the soft-float routines are the same kind of
helper as the integer ones.
The integer generator does not name a helper for every integer mode:
int maxsize = 2 * BITS_PER_WORD;
int minsize = BITS_PER_WORD;
...
if (GET_MODE_BITSIZE (int_mode) < minsize
|| GET_MODE_BITSIZE (int_mode) > maxsize)
return;
gen_libfunc (optable, opname, suffix, int_mode);
Listing 4.1-2: integer helpers exist for one word and two words, abridged
(gcc/optabs-libfuncs.cc:187-205).
On a 32-bit target the range is 32 to 64 bits, which gives __divsi3 and
__divdi3. On a 64-bit target it is 64 to 128 bits, which gives __divdi3 and
__divti3. For the trapping optabs the floor drops to the size of int
(:198-201), so __addvsi3 exists on a 64-bit target too.
Which of these names the compiler uses for one statement, and when it uses an instruction instead, is decided by the optab lookup during expansion. Chapter 5.5 owns that decision. This chapter follows the name to the library side.
One file, one archive member per helper: libgcc2.c and -DL_divdi3
Most integer helpers are in one file, libgcc/libgcc2.c, and the build compiles
it once for each helper, with a different macro each time:
# Build lib2funcs. For the static library also include LIB2FUNCS_ST.
lib2funcs-o = $(patsubst %,%$(objext),$(lib2funcs) $(LIB2FUNCS_ST))
$(lib2funcs-o): %$(objext): $(srcdir)/libgcc2.c
$(gcc_compile) -DL$* -c $< $(vis_hide)
libgcc-objects += $(lib2funcs-o)
Listing 4.1-3: one compile of libgcc2.c per helper
(libgcc/Makefile.in:509-513).
lib2funcs is a list of stems such as _muldi3, _negdi2 and _lshrdi3
(Makefile.in:451-460). For the stem _divdi3, $* is
_divdi3, and the command defines L_divdi3. Each helper in libgcc2.c is in
its own #ifdef:
#ifdef L_divdi3
DWtype
__divdi3 (DWtype u, DWtype v)
{
...
w = __udivmoddi4 (uu.ll, vv.ll, (UDWtype *) 0);
if (c)
w = -w;
return w;
}
#endif
Listing 4.1-4: __divdi3, abridged (libgcc/libgcc2.c:1209-1231).
The omitted lines make both operands positive and remember the sign.
So the member _divdi3.o holds only __divdi3, and a link takes that member
only when something calls __divdi3.
__divdi3 calls __udivmoddi4, but not the one in the member
_udivmoddi4.o. When the build compiles one of the division helpers, libgcc2.c
also defines L_udivmoddi4 (libgcc2.c:663-667), and it
compiles that copy of __udivmoddi4 as static inline with always_inline
(:989-993). Each division member carries its own copy. The
separate _udivmoddi4.o is for callers outside libgcc2.c, such as the Arm
routine later in this chapter.
The division helpers also have a list of their own, with this comment: "These
might cause a divide overflow trap and so are compiled with unwinder info"
(Makefile.in:476-480). By default they get -fexceptions -fnon-call-exceptions (:544-554). The Arm fragment removes the
second flag, because on Arm "specifying -fnon-call-exceptions will needlessly pull
in the unwinder in simple programs which use 64-bit division"
(libgcc/config/arm/t-bpabi:17-20). A helper is target code, like
your own code, and its compile flags decide what else it brings into your link.
Chapter 4.3 explains the unwinder.
__divdi3 is a macro: libgcc2.h and the 128-bit helpers
The name __divdi3 in Listing 4.1-4 is not always the symbol name. libgcc2.h
makes it from the word size:
#elif LIBGCC2_UNITS_PER_WORD == 4
#define W_TYPE_SIZE (4 * __CHAR_BIT__)
#define Wtype SItype
...
#define DWtype DItype
#define UDWtype UDItype
...
#define __NW(a,b) __ ## a ## si ## b
#define __NDW(a,b) __ ## a ## di ## b
...
#define __divdi3 __NDW(div,3)
Listing 4.1-5: names made from the word size, abridged
(libgcc/libgcc2.h:219-233 and :286-288).
DWtype is the double-word integer type, and __NDW pastes the double-word mode
into the name. With a 4-byte word, __divdi3 stays __divdi3. With an 8-byte
word, the branch above this one makes DWtype a TItype and pastes ti
(libgcc2.h:203-217). The same function then compiles as __divti3.
libgcc2.c takes the word size from the target's MIN_UNITS_PER_WORD
(libgcc2.c:38-52).
The 128-bit helpers of a 64-bit target are the 64-bit helpers of a 32-bit
target, compiled with a wider word. This matches Listing 4.1-2: the compiler
names helpers for one word and two words, and libgcc2.h builds those two.
The conversions between integer and float modes, such as __floatdidf, work the
same way (Makefile.in:461-474, libgcc2.h:299-314).
With an 8-byte word, __floatdidf compiles as __floattidf.
The float modes come from the compiler that builds libgcc. The build passes
-fbuilding-libgcc (Makefile.in:248-251), an option that
c.opt marks Undocumented (gcc/c-family/c.opt:1707-1708). With
it, the compiler predefines macros such as __LIBGCC_HAS_DF_MODE__
(c-cppbuiltin.cc:1380-1400), and libgcc2.h reads them
(libgcc2.h:40-68).
Chapter 2.6 explains how target selection
fixes predefined macros. libgcc does not probe the target. It asks its compiler.
The
_BitInthelpers are new in GCC 14._mulbitint3and_divmodbitint4are on the lists atreleases/gcc-14.1.0(libgcc/Makefile.in:455and:476), and neither is inlibgcc/Makefile.inatreleases/gcc-13.3.0.
__aeabi_*: arm_init_libfuncs and DECLARE_LIBRARY_RENAMES
The Arm EABI does not use GCC's names. Its run-time ABI document gives its own, and GCC follows that document in both halves.
The compiler side is a target hook. The internals manual documents
TARGET_INIT_LIBFUNCS in Implicit Calls to Library Routines: it
"should declare additional library routines or rename existing ones"
(gcc/doc/tm.texi:5866-5874). init_optabs calls it after
it sets the default names (optabs-libfuncs.cc:905). Arm's hook
cites its source:
/* There are no special library functions unless we are using the
ARM BPABI. */
if (!TARGET_BPABI)
return;
/* The functions below are described in Section 4 of the "Run-Time
ABI for the ARM architecture", Version 1.0. */
...
set_optab_libfunc (sdiv_optab, DImode, "__aeabi_ldivmod");
set_optab_libfunc (udiv_optab, DImode, "__aeabi_uldivmod");
/* For SImode division the ABI provides div-without-mod routines,
which are faster. */
set_optab_libfunc (sdiv_optab, SImode, "__aeabi_idiv");
set_optab_libfunc (udiv_optab, SImode, "__aeabi_uidiv");
Listing 4.1-6: arm_init_libfuncs, abridged
(gcc/config/arm/arm.cc:2573-2666).
arm-none-eabi includes arm/bpabi.h (gcc/config.gcc:1503),
and there TARGET_BPABI is true for every AAPCS-based configuration
(gcc/config/arm/bpabi.h:30). So the division in div64.c
becomes __aeabi_ldivmod, not __divdi3. A divmod routine can serve a plain
division because, as the comment above the sdiv_optab lines says, "The quotient
is returned in the usual location" (arm.cc:2651-2654).
The library side must then define every __aeabi_ name. It does so in three
ways.
An alias for a C helper. config.host adds arm/bpabi-lib.h to libgcc's
target headers for Arm EABI (libgcc/config.host:580). That header
gives some libgcc2.c helpers a second name:
/* Make __aeabi_AEABI_NAME an alias for __GCC_NAME. */
#define RENAME_LIBRARY(GCC_NAME, AEABI_NAME) \
typeof (__##GCC_NAME) __aeabi_##AEABI_NAME \
__attribute__((alias ("__" #GCC_NAME)));
/* Give some libgcc functions an additional __aeabi name. */
#ifdef L_muldi3
#define DECLARE_LIBRARY_RENAMES RENAME_LIBRARY (muldi3, lmul)
#endif
Listing 4.1-7: the libgcc half of a rename
(libgcc/config/arm/bpabi-lib.h:26-34).
libgcc2.c expands DECLARE_LIBRARY_RENAMES near its top
(libgcc2.c:57-59), so _muldi3.o defines __muldi3 and
__aeabi_lmul at one address. The internals manual documents the macro in the
same node (tm.texi:5857-5862).
An alias in assembly. The 32-bit division is hand-written in
libgcc/config/arm/lib1funcs.S, and the alias is one directive:
#ifdef L_divsi3
#if defined(__prefer_thumb__)
FUNC_START divsi3
FUNC_ALIAS aeabi_idiv divsi3
Listing 4.1-8: __aeabi_idiv is __divsi3
(libgcc/config/arm/lib1funcs.S:1227-1232).
On a core with a divide instruction, the same routine is one sdiv
(lib1funcs.S:1282-1289).
A rename before compilation. On a Thumb-1 multilib, the soft-float routines
come from the C soft-fp code. Arm's sfp-machine.h defines __adddf3 as
__aeabi_dadd, and the other names in the same way, before that code compiles
(libgcc/config/arm/sfp-machine.h:70-110). In that build the
routine has only the Arm name.
Some __aeabi_ helpers have no GCC twin. __aeabi_ldivmod returns the quotient
and the remainder together, so it is its own assembly routine. lib1funcs.S
includes bpabi.S for the 32-bit instruction sets and bpabi-v6m.S for Thumb-1
(lib1funcs.S:2255-2264). The bpabi.S version calls
__udivmoddi4 (bpabi.S:184-194). The bpabi-v6m.S version calls
__gnu_ldivmod_helper (bpabi-v6m.S:126-135), a C function that
calls __divdi3 (libgcc/config/arm/bpabi.c:31-41). Both
versions first test for a zero divisor and branch to __aeabi_ldiv0
(bpabi.S:104). That is the call graph of the first section. When
the driver picks a Thumb-1 multilib for -mcpu=cortex-m0, one long long
division takes at least _aeabi_ldivmod.o, bpabi.o and _divdi3.o into the
link, plus the member that defines __aeabi_ldiv0.
Both halves follow a document outside GCC, Arm's run-time ABI. The comment in Listing 4.1-6 is the only place where GCC names it.
How a target picks its helpers: config.host and LIB1ASMFUNCS
libgcc has its own config.gcc. libgcc/config.host maps the target triple to a
list of makefile fragments, tmake_file. Its header says that it "bears an
obvious resemblance to gcc/config.gcc" (libgcc/config.host:26-30).
libgcc is built for the target, so this file switches on ${host}, and that
host is GCC's target. The entry for arm-none-eabi:
arm*-*-eabi* | arm*-*-symbianelf* | arm*-*-rtems*)
tmake_file="${tmake_file} arm/t-arm arm/t-elf t-fixedpoint-gnu-prefix"
tm_file="$tm_file arm/bpabi-lib.h"
case ${host} in
arm*-*-eabi* | arm*-*-rtems*)
tmake_file="${tmake_file} arm/t-bpabi arm/t-sync t-crtfm"
extra_parts="crtbegin.o crtend.o crti.o crtn.o"
;;
...
esac
tmake_file="$tmake_file t-softfp-sfdf t-softfp-excl arm/t-softfp t-softfp"
extra_parts="$extra_parts crtfastmath.o"
unwind_header=config/arm/unwind-arm.h
;;
Listing 4.1-9: the helper set for Arm EABI, abridged
(libgcc/config.host:578-595).
Each fragment sets a few variables. LIB1ASMFUNCS lists helpers written in
assembly, in the one file that LIB1ASMSRC names
(libgcc/config/arm/t-arm:1-3). LIB2ADD adds whole files, such as
bpabi.c (t-bpabi:5-6). LIB2FUNCS_EXCLUDE removes helpers. The
softfp_* variables choose the soft-float routines
(t-softfp:19-61). The generic makefile then removes from the C list
everything that a fragment supplies another way:
# Remove any objects from lib2funcs and LIB2_DIVMOD_FUNCS that are
# defined as optimized assembly code in LIB1ASMFUNCS or as C code
# in LIB2FUNCS_EXCLUDE.
lib2funcs := $(filter-out $(LIB2FUNCS_EXCLUDE) $(LIB1ASMFUNCS),$(lib2funcs))
LIB2_DIVMOD_FUNCS := $(filter-out $(LIB2FUNCS_EXCLUDE) $(LIB1ASMFUNCS), \
$(LIB2_DIVMOD_FUNCS))
Listing 4.1-10: assembly replaces C (libgcc/Makefile.in:482-487).
arm/t-elf puts _divsi3, _udivsi3, the 64-bit shifts and _clzsi2 into
LIB1ASMFUNCS (t-elf:21-29). So on Arm those helpers come from
lib1funcs.S, and libgcc2.c is not compiled for them.
GCC keeps no fixed list of required helpers. Every target gets the generic
libgcc2.c list, less what its fragments replace or exclude. Soft-float,
fixed-point and decimal float helpers come only from fragments that the target
names. The requirement is per target: libgcc must define every name that the
compiler can emit for that configuration. For Arm, the compiler half of that
list is in arm.cc, and the library half is in t-bpabi, t-elf and
bpabi-lib.h.
The soft-float code has an owner outside GCC. Its README says: "The files in this
directory are part of the GNU C Library, not part of GCC"
(libgcc/soft-fp/README:1-4). Each file is one routine, such as
__adddf3 (soft-fp/adddf3.c:32-49).
Helpers from builtins and options: __popcountsi2, __addvsi3, __muldc3
Arithmetic operators are not the only source of helper calls. Some builtins and some options produce them as well:
| You write | Helper | Compiler side | libgcc side |
|---|---|---|---|
__builtin_popcount (x) | __popcountsi2 and relatives | builtins.cc:8203-8207, optabs.def:188 | libgcc2.c:819-821 |
a + b with -ftrapv | __addvsi3 and relatives | optabs-tree.cc:256-262, optabs-libfuncs.cc:280-294 | libgcc2.c:74-84 |
a * b on _Complex double | __muldc3 | tree.cc:10225-10266, tree-complex.cc:1178-1188 | libgcc2.c:2694-2698 |
__builtin_powi (x, n) | __powidf2 | optabs.def:204 | libgcc2.c:2557-2588 |
The -ftrapv row is a helper that changes what your program does. The GCC manual
documents -ftrapv under Code Gen Options: it "generates traps
for signed overflow on addition, subtraction, multiplication operations". For a
signed type, -ftrapv makes the compiler choose addv_optab and its relatives,
whose library names have a v after the operation. The helper calls abort when
the addition overflows:
#ifdef L_addvsi3
Wtype
__addvSI3 (Wtype a, Wtype b)
{
Wtype w;
if (__builtin_add_overflow (a, b, &w))
abort ();
return w;
}
Listing 4.1-11: __addvsi3 (libgcc/libgcc2.c:74-84).
So the "trap" from the manual can be a call into libgcc, and from there a call
into the C library. The internals manual says the same about the whole trapping
family: "These functions call the libc function abort upon signed arithmetic
overflow" (libgcc.texi:145-149).
The complex row needs no option. C uses the C99 rules for complex
multiplication by default (gcc/c-family/c-opts.cc:230-232).
Under those rules, at -O0 or when optimising for size, a complex
multiplication of two variables is a call to __muldc3
(tree-complex.cc:1178-1188).
Where libgcc needs the C library: tsystem.h and inhibit_libc
Part III depends on one claim: GCC needs a C library to finish building itself. Chapter 3.1 states the cycle. This section shows where the claim is true in libgcc's source.
libgcc2.c includes tsystem.h as its second line of code
(libgcc2.c:26-27). The file is in gcc/, and libgcc finds
it through -I$(srcdir)/../gcc (Makefile.in:285-287). It begins
with a switch:
#ifdef inhibit_libc
...
#else /* ! inhibit_libc */
/* We disable this when inhibit_libc, so that gcc can still be built without
needing header files first. */
...
/* All systems have this header. */
#include <stdio.h>
...
/* If these system headers do not exist, fixincludes must create them. */
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
...
#endif /* inhibit_libc */
Listing 4.1-12: the C library headers in every helper, abridged
(gcc/tsystem.h:47-118).
Every helper compiled from libgcc2.c reads the target's <stdio.h>,
<stdlib.h> and <unistd.h>, including __divdi3, which calls nothing in the
C library. The arithmetic does not need the headers. One #include at the top
of a shared file does. Without the target's C library headers, the compile of
_divdi3.o fails, unless the build defines inhibit_libc. In that case
tsystem.h declares by hand the few functions that libgcc uses, and it turns
abort () into __builtin_trap () (tsystem.h:47-84).
LIBGCC2_CFLAGS carries the switch as $(INHIBIT_LIBC_CFLAGS)
(Makefile.in:248-251), which gcc/Makefile.in sets to
-Dinhibit_libc (gcc/Makefile.in:791-794). The condition that
sets it, and how the value travels from gcc/ to libgcc, belong to
Chapter 3.2. Beyond the headers, a few pieces of
libgcc use the C library itself, and each has its own guard:
| Piece | What it uses from the C library | With inhibit_libc | Source |
|---|---|---|---|
__addvsi3 and the trapping family | abort | __builtin_trap | Listing 4.1-11 |
__eprintf, in libgcc.a only | fprintf, fflush, abort | not compiled | libgcc2.c:2975-2995 |
unwinder lookup through PT_GNU_EH_FRAME | <link.h>, dl_iterate_phdr | registered frames only | unwind-dw2-fde-dip.c:49-89, :569, :576-580 |
-fsplit-stack support | <signal.h>, <sys/mman.h> and more | file compiles to nothing | generic-morestack.c:37-52 |
The last row carries a comment that states the whole trade:
/* If inhibit_libc is defined, we cannot compile this file. The
effect is that people will not be able to use -fsplit-stack. That
is much better than failing the build particularly since people
will want to define inhibit_libc while building a compiler which
can build glibc. */
Listing 4.1-13: why a stage-1 libgcc is smaller
(libgcc/generic-morestack.c:37-43).
One more call into the C library depends on the target, not on inhibit_libc.
On Arm, division by zero ends in __aeabi_idiv0. On bare metal that is a weak
function that only returns (lib1funcs.S:1459-1468). For
arm*-linux-gnueabi*, t-linux-eabi swaps in a version that calls raise with
SIGFPE (libgcc/config/arm/t-linux-eabi:1-2,
lib1funcs.S:1477-1499). So libgcc can need libc at link time as
well as at build time. Chapter 1.7 shows how the -lgcc that follows -lc on
the link line resolves those calls.
What libgcc leaves to others: memcpy and __atomic_load_16
Not every call that the compiler invents goes to libgcc. The internals manual
says: "GCC will also generate calls to C library routines, such as memcpy and
memset, in some cases" (libgcc.texi:20-23). The GCC manual
documents the full rule in Standards: "GCC requires the
freestanding environment provide memcpy, memmove, memset and memcmp"
(gcc/doc/standards.texi:190-198). So -nostdlib -lgcc is not
all that you owe on bare metal. Those four functions are also on the list.
Atomic operations are the same shape of problem with a third library. When the
target has no instruction for an atomic load of some size, the builtin falls
through to a normal call (builtins.cc:8732-8741 and
:9068-9070). The callee has a name such as __atomic_load_16
(gcc/sync-builtins.def:309-310). libgcc does not define it.
libatomic does (libatomic/libatomic.map:63). The generic
driver never adds -latomic: neither gcc/gcc.cc nor gcc/configure.ac
mentions libatomic at the pin. A few target specs add it, such as RTEMS
(gcc/config/rtems.h:52). Elsewhere, a program that needs an
atomic call links only when you add -latomic yourself.
Why proprietary code can link it: COPYING.RUNTIME
libgcc's files are under the GPL version 3 with an extra permission, the GCC
Runtime Library Exception in the top-level COPYING.RUNTIME
(libgcc2.c:17-19). The exception states its purpose: "When
you use GCC to compile a program, GCC may combine portions of certain GCC header
files and runtime libraries with the compiled program"
(COPYING.RUNTIME:16-20). It lets you convey the result "under
terms of your choice", if "all Target Code was generated by Eligible Compilation
Processes" (:61-66). A compilation by GCC, alone or with
GPL-compatible software, is eligible. A compilation in which non-GPL-compatible
software optimises GCC's intermediate representation is not
(:53-57). The exception exists because of this chapter's
claim: the compiler puts libgcc into programs whose authors never asked for it.
The calls that this chapter followed from the outside start inside cc1, where
expansion looks for an instruction and falls back to the name.
Chapter 5.5 shows that lookup on an integer division like
the one in div64.c.
Three things to carry away
libgcc is the second half of the code generator. When the target has no instruction, the compiler emits a call by name, and libgcc holds the body under that name.
A helper's name is operation, mode and operand count, unless the target renames
it. __divdi3 is division in DImode with three operands. Arm renames it in both
halves, in arm_init_libfuncs and in bpabi-lib.h.
libgcc needs the C library headers to build, even for helpers that never call
the C library. tsystem.h includes <stdio.h> unless inhibit_libc is set,
and that is where the bootstrap cycle bites.
Things that surprise people
On a 64-bit target, the __divdi3 in libgcc2.c is __divti3 in the
library. libgcc2.h makes the name from the word size.
-ftrapv can end in the C library's abort. The trapping helpers call
abort. Only an inhibit_libc build replaces it with __builtin_trap.
On a Thumb-1 multilib, nm finds __aeabi_dadd but no __adddf3.
sfp-machine.h renames the soft-fp routine before it compiles.
On Arm GNU/Linux, a division by zero inside libgcc calls raise. The
bare-metal __aeabi_idiv0 only returns.
Documentation coverage
The internals manual has a chapter on libgcc,
The GCC low-level runtime library (gcc/doc/libgcc.texi:6). It
lists the helpers by mode name in
Routines for integer arithmetic (:48) and
Routines for floating point emulation (:266), with sections for
decimal float (:561), fixed point (:883) and miscellaneous routines (:2341).
Its section on exception handling routines (:2305) is a list of names
under the text "document me!" (:2308). The target side is in
Implicit Calls to Library Routines (gcc/doc/tm.texi:5849), with
DECLARE_LIBRARY_RENAMES (:5857), TARGET_INIT_LIBFUNCS (:5866) and
TARGET_LIBFUNC_GNU_PREFIX (:5876).
The GCC manual explains why -nostdlib usually needs -lgcc under
Link Options (gcc/doc/invoke.texi:19245-19259). It documents
-print-libgcc-file-name under Developer Options (:21611), -ftrapv
under Code Gen Options (:19680), and the four functions that a
freestanding environment must supply under Standards
(gcc/doc/standards.texi:190-198).
What is not documented:
- The rule that builds a helper name from the operation, the mode and the operand count, and that integer helpers exist only for one word and two words.
- That
libgcc2.cis compiled once per helper with-DL_name, and that its__divdi3becomes__divti3on a 64-bit target. - That each division helper carries a private inline copy of
__udivmoddi4. - The libgcc fragment variables that select the helpers:
LIB1ASMFUNCS,LIB1ASMSRC,LIB2ADDandLIB2FUNCS_EXCLUDE. The internals manual's Target Makefile Fragments node documentsLIB2FUNCS_EXTRAinstead (gcc/doc/fragments.texi:46-49), and neitherlibgcc/Makefile.innorgcc/Makefile.inreads that variable at the pin. - That every
libgcc2.chelper includes the target's C library headers throughtsystem.h, unlessinhibit_libcis set. - That the trap from
-ftrapvis a libgcc call that callsabort. The internals manual says the helpers callabort, but the GCC manual's text for-ftrapvdoes not say that a library is involved. - The three ways that Arm's libgcc provides the
__aeabi_names. -fbuilding-libgcc, whichc.optmarksUndocumented.- The Runtime Library Exception. It is in
COPYING.RUNTIME, not in the manuals.
Two places in the manuals mislead. The -nostdlib text sends the reader to an
internals node, "Interfacing to GCC Output" (gcc/doc/invoke.texi:19249), and
no file in gcc/doc at the pin defines that node. The prototypes in the libgcc
chapter use an illustrative mapping in which long long is TImode
(libgcc.texi:30-38). On a 32-bit target a long long is
DImode, so read the mode in the helper's name, not the C type in the prototype.
Next: the static archive, the exception archive and the shared library that libgcc is built into, and how the driver chooses between them.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
4.2 Which libgcc you link: libgcc.a, libgcc_eh.a and libgcc_s.so
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
Link one object file twice on a GNU/Linux machine, once with gcc and once with
g++, and compare the -### output. The C link asks for -lgcc and then for
-lgcc_s inside an --as-needed bracket. The C++ link asks for -lgcc_s first
and -lgcc after it. You gave no libgcc option to either driver. Now give
-shared-libgcc to arm-none-eabi-gcc. The driver accepts it, and the link line
does not change.
libgcc is built as up to three files, and configure and the language driver
decide which of them your link gets. libgcc.a holds code that
each linked object may copy. libgcc_eh.a and libgcc_s.so.1 hold the code that
must exist once per process. The libgcc spec chooses between them. Its default
depends on the target, on the linker that configure found, and on which driver you
ran.
This chapter assumes Chapter 1.3, for the libgcc spec and
its startup rewrite (Listing 1.3-5), and Chapter 1.7,
for where %G sits on the link line. Chapter 4.1
says why the compiler calls into libgcc at all. This chapter is about which file
each call resolves against.
The partition: libgcc-objects, LIB2ADDEH and one copy per process
libgcc/Makefile.in builds three lists of objects: libgcc-objects for
libgcc.a, libgcc-eh-objects for libgcc_eh.a and libgcc-s-objects for
libgcc_s.so.1. With a shared libgcc, most helpers go into two of the lists,
because the makefile compiles each one twice from the same source:
# Build lib2funcs. For the static library also include LIB2FUNCS_ST.
lib2funcs-o = $(patsubst %,%$(objext),$(lib2funcs) $(LIB2FUNCS_ST))
$(lib2funcs-o): %$(objext): $(srcdir)/libgcc2.c
$(gcc_compile) -DL$* -c $< $(vis_hide)
libgcc-objects += $(lib2funcs-o)
ifeq ($(enable_shared),yes)
lib2funcs-s-o = $(patsubst %,%_s$(objext),$(lib2funcs))
$(lib2funcs-s-o): %_s$(objext): $(srcdir)/libgcc2.c
$(gcc_s_compile) -DL$* -c $<
libgcc-s-objects += $(lib2funcs-s-o)
endif
Listing 4.2-1: one helper, two objects (libgcc/Makefile.in:509-520).
The two compiles differ in two flags. The _s object gets -DSHARED
(Makefile.in:321). The archive object gets $(vis_hide),
which configure sets to -fvisibility=hidden -DHIDE_EXPORTS when the compiler
supports hidden visibility (libgcc/configure.ac:549-554).
libgcc2.h and unwind-generic.h restore default visibility only when
HIDE_EXPORTS is absent (libgcc2.h:28-30,
unwind-generic.h:37-39).
So the archive copy of each helper in Listing 4.2-1 is a hidden symbol. An
executable or a shared library that takes the helper from the archive gets a
private copy, and no other object can bind to it. For an arithmetic helper that is harmless. The archive also has members
that the shared library does not have. LIB2FUNCS_ST and LIB2ADD_ST are the
lists for the static library only (Makefile.in:266-278), and
Chapter 4.1 says which helpers they hold.
The exception-handling sources follow a different rule:
# Build LIB2ADDEH, LIB2ADDEHSTATIC, and LIB2ADDEHSHARED. If we don't have
# libgcc_eh.a, only LIB2ADDEH matters. If we do, only LIB2ADDEHSTATIC and
# LIB2ADDEHSHARED matter. (Usually all three are identical.)
c_flags := -fexceptions
ifeq ($(enable_shared),yes)
libgcc-eh-objects += $(addsuffix $(objext),$(basename $(notdir $(LIB2ADDEHSTATIC))))
libgcc-s-objects += $(addsuffix _s$(objext),$(basename $(notdir $(LIB2ADDEHSHARED))))
iter-items := $(sort $(LIB2ADDEHSTATIC) $(LIB2ADDEHSHARED))
-include $(iterator)
else
# Not shared. LIB2ADDEH are added to libgcc.a.
libgcc-objects += $(addsuffix $(objext),$(basename $(notdir $(LIB2ADDEH))))
iter-items := $(LIB2ADDEH)
-include $(iterator)
endif
Listing 4.2-2: where the unwinder goes (libgcc/Makefile.in:867-889).
LIB2ADDEH defaults to the DWARF and SJLJ unwinders and unwind-c.c
(Makefile.in:346-350), and targets replace it. Arm EABI, for
example, puts its own unwinder there (libgcc/config/arm/t-bpabi:10-12).
With a shared libgcc, these objects never enter libgcc.a. They go to
libgcc_eh.a for static links and to libgcc_s.so.1 for dynamic ones. Without a
shared libgcc, they go into libgcc.a, and there is only one file.
The reason is state. The unwinder keeps the frame tables that objects register in
static variables: registered_frames when the target has the atomic fast path
(libgcc/unwind-dw2-fde.c:50-51), and the unseen_objects and
seen_objects lists when it does not (:77-78). A hidden copy in each
shared library is a separate set of those variables. The makefile states the
rule itself, for a file that has nothing to do with exceptions:
# While emutls.c has nothing to do with EH, it is in LIB2ADDEH*
# instead of LIB2ADD because that's the way to be sure on some targets
# (e.g. *-*-darwin*) only one copy of it is linked.
LIB2ADDEH += $(srcdir)/emutls.c
LIB2ADDEHSTATIC += $(srcdir)/emutls.c
LIB2ADDEHSHARED += $(srcdir)/emutls.c
Listing 4.2-3: the EH lists mean "one copy" (libgcc/Makefile.in:443-448).
That gives three files on a target with a shared libgcc:
| File | Contains | Its symbols are |
|---|---|---|
libgcc.a | the helpers, plus the static-only members | hidden, for most members |
libgcc_eh.a | the LIB2ADDEH set: unwinder, unwind-c.c, emutls.c | hidden |
libgcc_s.so.1 | the helpers, plus the LIB2ADDEH set | exported by a version script |
The objects in libgcc_eh.a get $(vis_hide) too
(libgcc/shared-object.mk:13-17). A shared library linked
with -lgcc_eh therefore has its own private unwinder.
What libgcc_s.so.1 exports, and what it links against
libgcc_s.so.1 does not export everything it contains. A version script
decides. libgcc/mkmap-symver.awk writes that script at build time from two
inputs: the nm output of the _s objects, and the map files the target lists,
starting with libgcc-std.ver (Makefile.in:982-997). The script
exports a symbol only if an object defines it and a map file lists it
(mkmap-symver.awk:119). Everything else falls under local: *
(:139). The map file has version nodes
from GCC_3.0, which holds the integer helpers and the unwinder entry points, to
GCC_14.0.0 (libgcc/libgcc-std.ver.in:19 and
:1949-1962). The soname is libgcc_s.so.1
(libgcc/config/t-slibgcc:21-24).
Two details of that link matter. The shared library is linked from its
_s objects and from libgcc.a (Makefile.in:1003-1015).
So a helper that only the archive has can still go into libgcc_s.so.1, as a
hidden copy that it does not export. And the link line ends with $(SHLIB_LC),
which t-slibgcc sets to -lc (t-slibgcc:29 and
:34-37). So on a target that keeps that setting,
libgcc_s.so.1 cannot be linked before a C library exists. Chapter 3.1 owns that
consequence for a bootstrap.
init_gcc_specs: the two forms of the libgcc spec
Chapter 1.3 showed the driver walk the libgcc spec at startup and replace each
-lgcc it finds (Listing 1.3-5). The call passes three names: -lgcc_s as the
shared name, -lgcc as the static name and -lgcc_eh as the EH name
(gcc/gcc.cc:1931-1947). Other text in the target's spec is
copied unchanged (:1967-1972). The function that builds the
replacement is where the choice is made:
static void
init_gcc_specs (struct obstack *obstack, const char *shared_name,
const char *static_name, const char *eh_name)
{
char *buf;
#if USE_LD_AS_NEEDED
buf = concat ("%{static|static-libgcc|static-pie:", static_name, " ", eh_name, "}"
"%{!static:%{!static-libgcc:%{!static-pie:"
"%{!shared-libgcc:",
static_name, " " LD_AS_NEEDED_OPTION " ",
shared_name, " " LD_NO_AS_NEEDED_OPTION
"}"
"%{shared-libgcc:",
shared_name, "%{!shared: ", static_name, "}"
"}}"
#else
buf = concat ("%{static|static-libgcc:", static_name, " ", eh_name, "}"
"%{!static:%{!static-libgcc:"
"%{!shared:"
"%{!shared-libgcc:", static_name, " ", eh_name, "}"
"%{shared-libgcc:", shared_name, " ", static_name, "}"
"}"
#ifdef LINK_EH_SPEC
"%{shared:"
"%{shared-libgcc:", shared_name, "}"
"%{!shared-libgcc:", static_name, "}"
"}"
#else
"%{shared:", shared_name, "}"
#endif
#endif
"}}", NULL);
obstack_grow (obstack, buf, strlen (buf));
free (buf);
}
Listing 4.2-4: the two forms (gcc/gcc.cc:1815-1851).
Both forms agree on the explicit cases. -static and -static-libgcc give
-lgcc -lgcc_eh: the archive and the static unwinder. -shared-libgcc gives
-lgcc_s -lgcc for an executable and -lgcc_s alone for a shared library. The
forms differ when you give none of these options.
The as-needed form gives -lgcc --as-needed -lgcc_s --no-as-needed, for
executables and shared libraries alike. Chapter 1.3 worked out that expansion.
The partition explains why it works. The linker reads libgcc.a first and takes
from it every helper the link needs. The references left for libgcc_s.so are
the ones the archive cannot resolve. On a shared-libgcc target, those are the
references into the LIB2ADDEH set. Configure describes LD_AS_NEEDED_OPTION as
"the linker option to ignore unused dependencies"
(gcc/configure.ac:6620-6623). So for a program that never
calls into the unwinder, the linker records no dependency on libgcc_s.so.1. A
program that does call into it gets the one shared copy, not a private one.
The older form gives -lgcc -lgcc_eh for an executable, so the executable
gets a static unwinder. For -shared, it gives -lgcc if the target defines
LINK_EH_SPEC and -lgcc_s if it does not. With -lgcc alone, the shared
library carries no unwinder, because on a shared-libgcc target the unwinder is
not in libgcc.a. A reference
to _Unwind_Resume stays undefined in the file the linker writes.
Neither form looks at your objects. A comment above the rewrite lists heuristics that GCC could use, and does not:
/* ??? If neither -shared-libgcc nor --static-libgcc was
seen, then we should be making an educated guess. Some proposed
heuristics for ELF include:
(1) If "-Wl,--export-dynamic", then it's a fair bet that the
program will be doing dynamic loading, which will likely
need the shared libgcc.
...
Doing any of this probably requires invoking an external program to
do the actual object file scanning. */
Listing 4.2-5: the guess GCC does not make, abridged (gcc/gcc.cc:1894-1920).
The default comes from flags and configuration, never from the objects you link. The as-needed form comes close to "shared if the link needs the unwinder". It gets there by giving that decision to the linker.
USE_LD_AS_NEEDED and LINK_EH_SPEC: which form a target gets
USE_LD_AS_NEEDED defaults to 0 (gcc.cc:1811-1813), so a
target header must turn it on. For GNU/Linux, gnu-user.h does that when
configure found a linker that accepts --as-needed. The same header defines
LINK_EH_SPEC when the linker accepts --eh-frame-hdr:
#if defined(HAVE_LD_EH_FRAME_HDR)
#define LINK_EH_SPEC "%{!static|static-pie:--eh-frame-hdr} "
#endif
...
/* Use --as-needed -lgcc_s for eh support. */
#ifdef HAVE_LD_AS_NEEDED
#define USE_LD_AS_NEEDED 1
#endif
Listing 4.2-6: the GNU/Linux settings, abridged
(gcc/config/gnu-user.h:108-110 and
:119-122).
Both HAVE_ macros come from tests of the linker that GCC's configure found:
--eh-frame-hdr at gcc/configure.ac:6098-6127, and
--as-needed at :6560-6624. The second test also picks
--push-state --as-needed and --pop-state for GNU ld 2.28 or later, as
Chapter 1.3 noted. Other targets set USE_LD_AS_NEEDED in their own headers, for
example Solaris (sol2.h:410-413) and Alpha GNU/Linux
(alpha/linux.h:116-119). A target whose headers never set it
gets the older form, whatever its linker supports.
LINK_EH_SPEC has two jobs. First, the driver prepends it to the link spec
(gcc.cc:1995-1998). The linker then gets --eh-frame-hdr for
every link except a plain -static one. That option makes the linker write a
PT_GNU_EH_FRAME header. The unwinder uses the header with dl_iterate_phdr to
find an object's frame tables "to avoid register/deregister calls"
(libgcc/unwind-dw2-fde-dip.c:25-27).
Chapter 4.3 covers that lookup. The second job is in
Listing 4.2-4. In the older form, LINK_EH_SPEC is what lets gcc -shared
default to -lgcc. A shared library with no unwinder of its own can still be
unwound through. It does not have to register its tables with an unwinder,
because the unwinder finds them through the header.
The GCC manual documents this second job under Link Options.
It says that GCC links shared libraries with the static libgcc by default if the
GNU linker supports --eh-frame-hdr. Otherwise GCC uses the shared one. That is
the older form. On a GNU/Linux target where configure also found
--as-needed, the as-needed form applies instead, and the manual does not
describe it.
t-slibgcc and --enable-shared: whether there is a choice at all
None of Listing 4.2-4 is compiled unless ENABLE_SHARED_LIBGCC is defined and
REAL_LIBGCC_SPEC is not (gcc.cc:1809 and
:1893). The macro comes from the command that compiles the
driver:
$(if $(SHLIB),$(if $(filter yes,@enable_shared@),-DENABLE_SHARED_LIBGCC)) \
Listing 4.2-7: ENABLE_SHARED_LIBGCC in DRIVER_DEFINES
(gcc/Makefile.in:2611).
SHLIB is set by gcc/config/t-slibgcc, a fragment whose only line of make
is SHLIB = true (gcc/config/t-slibgcc:1-2). So there are
two conditions:
- The target's entry in
gcc/config.gccaddst-slibgcctotmake_file. The generic GNU/Linux entry does (config.gcc:888-895). Bare-metal entries such asarm*-*-eabi*do not (config.gcc:1497-1530). enable_sharedisyes. That is the default, and--disable-sharedturns it off.
libgcc makes the same decision on its own side. Its configure parses
--enable-shared with the same code as gcc/configure.ac
(libgcc/configure.ac:52-69 and
gcc/configure.ac:1051-1068). Its makefile then falls back to
static only if no fragment defined SHLIB_LINK
(libgcc/Makefile.in:392-397). The generic GNU/Linux entry of
libgcc/config.host adds the fragment that defines it, t-slibgcc
(config.host:313-315). The arm*-*-eabi* entry does not
(config.host:578-595).
The install manual documents --enable-shared under
Configuration, including the form that takes a list of
packages and the package name libgcc, also spelled gcc. The code shows what
the list form does to libgcc. Both configure scripts start from
enable_shared=no and set yes only if the list names gcc or libgcc. So
--enable-shared=libstdc++ builds a static-only libgcc, and the driver has no
libgcc_s to choose.
On a target without a shared libgcc, the libgcc spec keeps the target's
LIBGCC_SPEC, which defaults to -lgcc (gcc.cc:878-889).
The driver accepts -static-libgcc and -shared-libgcc on every target, and its
comment says that gcc.cc "understands the first two"
(gcc.cc:4664-4677). But in gcc.cc, only the text that
init_gcc_specs builds tests them. A target without a shared libgcc does not
build that text, so the two options do nothing unless a target header tests them.
The arm-none-eabi headers do not. The manual states the result under Link
Options: "these options have no effect".
Two target families skip the rewrite. They define REAL_LIBGCC_SPEC, which the
driver uses unmodified. Cygwin's spec gives -lgcc_s -lgcc to every link without
-static or -static-libgcc (config/i386/cygwin.h:63-76). Darwin chooses by
flags such as -fexceptions and by the deployment target
(config/darwin.h:559-568), under a long comment about the
system unwinder (:528-558).
Who adds -shared-libgcc: g++spec.cc and the other language drivers
The second input to the choice is the driver you run. Each language's
lang_specific_driver can add options before the specs expand, and g++ adds
one:
if (shared_libgcc && !static_link)
generate_option (OPT_shared_libgcc, NULL, 1, CL_DRIVER,
&new_decoded_options[j++]);
Listing 4.2-8: g++ adds -shared-libgcc (gcc/cp/g++spec.cc:444-446).
shared_libgcc starts at 1 (g++spec.cc:137-138). -static-libgcc
clears it (:231-232). -static sets static_link
(:227-228). A driver built without ENABLE_SHARED_LIBGCC forces
it to 0 (:297-301). The GCC manual documents the result under
Link Options: the G++ driver adds -shared-libgcc because C++ programs typically
use exceptions. The manual does not mention the other drivers:
| Driver | Adds | Source |
|---|---|---|
gcc | -shared-libgcc only if an input ends in .m or .mi, and not with -static or -static-libgcc | c/gccspec.cc:32-92 |
g++, gccgo, gdc, gm2, gccrs | -shared-libgcc, unless -static or -static-libgcc | go/gospec.cc:425-427, d/d-spec.cc:506-510, m2/gm2spec.cc:917-918, rust/rustspec.cc:174-176 |
gfortran | -shared-libgcc when it links libgfortran, unless -static or -static-libgcc | fortran/gfortranspec.cc:409-421 |
gnatlink | -shared-libgcc for a shared GNAT runtime, otherwise a default from gcc/ada/link.c, -static-libgcc in its GNU/Linux arm | ada/gnatlink.adb:1155-1160, :1980-2005, ada/link.c:130-134 |
So for the same object file, on a GNU/Linux target with the as-needed form, %G
expands like this. Read each row off Listing 4.2-4:
| Command | The driver adds | %G expands to |
|---|---|---|
gcc foo.o | nothing | -lgcc --as-needed -lgcc_s --no-as-needed |
gcc -shared foo.o | nothing | -lgcc --as-needed -lgcc_s --no-as-needed |
g++ foo.o | -shared-libgcc | -lgcc_s -lgcc |
g++ -shared foo.o | -shared-libgcc | -lgcc_s |
g++ -static-libgcc foo.o | nothing | -lgcc -lgcc_eh |
With GNU ld 2.28 or later, read --push-state --as-needed and --pop-state for
the two bracket options. The C link names libgcc_s inside the bracket and the
C++ link names it outside, so only the C link lets the linker drop it.
Where they install: slibdir, and libgcc_s.so as a linker script
libgcc.a and libgcc_eh.a install into inst_libdir, the directory of
crtbegin.o (Listing 1.7-6, and libgcc/Makefile.in:1177-1193).
libgcc_s.so.1 installs into slibdir, plus the multilib OS directory
(Makefile.in:316). The install manual documents
--with-slibdir under Configuration, with libdir as
its default. Configure's own default has one more case:
AC_ARG_WITH(slibdir,
[ --with-slibdir=DIR shared libraries in DIR [LIBDIR]],
slibdir="$with_slibdir",
[if test "${version_specific_libs}" = yes; then
slibdir='$(libsubdir)'
elif test -n "$with_cross_host" && test x"$with_cross_host" != x"no"; then
case ${with_toolexeclibdir} in
no)
slibdir='$(exec_prefix)/$(host_noncanonical)/lib'
;;
*)
slibdir=${with_toolexeclibdir}
;;
esac
else
slibdir='$(libdir)'
fi])
Listing 4.2-9: where libgcc_s.so.1 goes (libgcc/configure.ac:114-130).
A native compiler puts it in $libdir. A cross compiler puts it in
$exec_prefix/<target>/lib, the same pattern that
Chapter 1.12 traced for libstdc++, where
host in a target library means GCC's target. The static and shared halves of
libgcc therefore install into different directories.
The link-time name libgcc_s.so is not always a symlink. t-slibgcc makes it
one (t-slibgcc:30-32). A second fragment replaces the
symlink with a linker script:
# Instead of creating $(SHLIB_SOLINK) symlink create a GNU ld
# linker script which sources in both $(SHLIB_SONAME) and libgcc.a.
# This is needed on targets where libgcc.a contains routines that aren't in
# $(SHLIB_SONAME) and are needed for shared libraries.
SHLIB_MAKE_SOLINK = \
(echo "/* GNU ld script"; \
echo " Use the shared library, but some functions are only in"; \
echo " the static library. */"; \
echo "GROUP ( $(SHLIB_SONAME) -lgcc )" \
) > $(SHLIB_DIR)/$(SHLIB_SOLINK)
Listing 4.2-10: libgcc_s.so as a GROUP script
(libgcc/config/t-slibgcc-libgcc:19-29).
Most GNU/Linux targets use it: AArch64, Arm and RISC-V in their own entries
(config.host:438-447, :555-561
and :1352-1355), and x86 in a later block
(:1593-1597). On AArch64, the reason is visible in t-lse,
and a comment in the VxWorks block names it: the fragment "is needed on at least
aarch64 (for lse)" (:1650-1651). It adds the out-of-line atomic helpers, such as
__aarch64_cas4_acq, to libgcc-objects and to no other list
(aarch64/t-lse:21-31), and each helper is a hidden symbol
(aarch64/lse.S:175-183). Now look at the g++ -shared row of the
table above: %G is -lgcc_s alone. Without the script, a C++ shared library
that calls those helpers would have no libgcc.a on its link line. The script
puts it back.
Watching the choice: -dumpspecs, -### and nm
These commands were not run for this chapter. What they should print is read off the listings above, so check them on your own toolchain.
Start with the libgcc spec as the driver holds it after the rewrite:
$ gcc -dumpspecs | sed -n '/^\*libgcc:/,/^$/p'
On a target without a shared libgcc, this prints the target's LIBGCC_SPEC,
usually -lgcc. On a shared-libgcc target, it prints one of the two forms of
Listing 4.2-4. Next, let the drivers and the flags pick, for any object file
foo.o:
$ gcc -### foo.o 2>&1 | tr ' ' '\n' | grep -E 'lgcc|needed|state'
$ g++ -### foo.o 2>&1 | tr ' ' '\n' | grep -E 'lgcc|needed|state'
$ g++ -### -shared foo.o 2>&1 | tr ' ' '\n' | grep -E 'lgcc|needed|state'
$ gcc -### -static-libgcc foo.o 2>&1 | tr ' ' '\n' | grep -E 'lgcc|needed|state'
Expect each expansion of the table twice, because a GNU/Linux link has %G on
both sides of the C library, as Chapter 1.7 explains.
Then check that the partition is real. On a shared-libgcc target, the unwinder's
entry point is in libgcc_eh.a and libgcc_s.so.1, and not in libgcc.a:
$ nm -A "$(gcc -print-file-name=libgcc.a)" | grep -w _Unwind_RaiseException
$ nm -A "$(gcc -print-file-name=libgcc_eh.a)" | grep -w _Unwind_RaiseException
$ nm -D "$(gcc -print-file-name=libgcc_s.so.1)" | grep -w _Unwind_RaiseException
Listing 4.2-2 predicts no output from the first command on such a target, and a
definition from the other two. On arm-none-eabi, the first command finds the
symbol, because there the unwinder is in libgcc.a
(arm/libunwind.S:356), and the other two files do not exist.
Last, ask what the link-time name is:
$ file -L "$(gcc -print-file-name=libgcc_s.so)"
As GCC installs it, this is a text file on a target that uses
t-slibgcc-libgcc, and an ELF shared object on any other target with a shared
libgcc. If -print-file-name echoes the
bare name, the file is not on the driver's search list
(Chapter 1.5).
Three things to carry away
libgcc.a holds what each object may copy, and the EH set holds what must
exist once. With a shared libgcc, the unwinder and emutls.c move out of
libgcc.a into libgcc_eh.a and libgcc_s.so.1.
The default comes from init_gcc_specs, not from your objects. The as-needed
form lets the linker drop libgcc_s when nothing needs the unwinder. The older
form links a static unwinder into executables.
The driver you run is an input. g++ and most other language drivers add
-shared-libgcc, and gcc does not. A target without t-slibgcc has no choice
to make.
Things that surprise people
--enable-shared=libstdc++ gives you a static-only libgcc. The list form
turns shared libraries off for every package it does not name, and libgcc is a
package.
g++ -shared names libgcc_s and never libgcc.a. On most GNU/Linux
targets, the libgcc_s.so linker script adds -lgcc back. Replace that
script with a symlink, and static-only helpers such as __aarch64_cas4_acq have
nowhere to come from.
gcc foo.m adds -shared-libgcc, and gcc foo.c does not. The C driver's
only libgcc rule is for Objective-C inputs.
-shared-libgcc on arm-none-eabi-gcc is accepted and does nothing. No
spec for that target tests it.
Documentation coverage
The GCC manual documents -shared-libgcc and -static-libgcc under
Link Options (gcc/doc/invoke.texi:19340-19371): why
exceptions across shared libraries need the shared libgcc, the g++ default, and
the --eh-frame-hdr default for shared libraries. The install manual documents
--enable-shared and its package list, and --with-slibdir, under
Configuration (gcc/doc/install.texi:1127-1145 and
:942-944). The internals manual documents LIBGCC_SPEC, REAL_LIBGCC_SPEC,
USE_LD_AS_NEEDED and LINK_EH_SPEC in the Driver node
(gcc/doc/tm.texi:255-291), and the helpers in
The GCC low-level runtime library
(gcc/doc/libgcc.texi:6-18).
What is not documented:
libgcc_eh.a. No manual names it.- The partition: which sources go to
libgcc.a, which tolibgcc_eh.aandlibgcc_s.so.1, and that a shared libgcc takes the unwinder out oflibgcc.a. - That
libgcc.aandlibgcc_eh.aare compiled with hidden visibility, so each linked object gets a private copy. - The as-needed form, and so the default that
gcc -sharedhas on a current GNU/Linux toolchain. Link Options describes only the older form. The internals manual definesUSE_LD_AS_NEEDEDbut does not say which targets set it. - That
gfortran,gccgo,gdc,gm2andgccrsadd-shared-libgccasg++does, thatgnatlinkhas its own rule, and thatgccadds it for Objective-C inputs. - That
libgcc_s.sois a linker script on some targets, and why. - That a cross compiler installs
libgcc_s.so.1under$exec_prefix/<target>/lib, not underlibdir.
Next: the unwinder that libgcc_eh.a and libgcc_s.so.1 carry, and how a C++
throw uses its tables to find a handler.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
4.3 The unwinder: how _Unwind_RaiseException finds a catch
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
You port a C++ program to an aarch64-none-elf board. A C file, filter.c,
calls back into C++, and the callback throws. The catch around the call into
filter.c never runs, and the program stops in std::terminate. On x86-64
GNU/Linux the same code catches the exception. Compile filter.c with
-fexceptions and the board catches it too. The C file has no try and no
throw, and you did not change it.
A throw is two walks up the stack. libgcc does both walks, from one table per
frame that the compiler wrote. A frame with no table ends the walk, as if the
stack ended there. The x86-64 compiler writes a table for every C function by
default. The aarch64-none-elf compiler does not.
This chapter assumes Chapter 1.7, which named the
stack unwinder as part of libgcc, and Chapter 4.1,
which showed why the compiler emits calls into libgcc.
Chapter 4.2 explains the libgcc_eh.a
and libgcc_s.so artifacts that hold the unwinder.
Three parties to a throw: __cxa_throw, _Unwind_* and the personality routine
The C++ front end compiles throw into two library calls:
__cxa_allocate_exception for the object, then __cxa_throw
(gcc/cp/except.cc:568, :669). Both are in libsupc++,
the language-support part of libstdc++. __cxa_throw fills in an exception
header and gives it to libgcc:
#ifdef __USING_SJLJ_EXCEPTIONS__
_Unwind_SjLj_RaiseException (&header->exc.unwindHeader);
#else
_Unwind_RaiseException (&header->exc.unwindHeader);
#endif
// Some sort of unwinding error. Note that terminate is a handler.
__cxa_begin_catch (&header->exc.unwindHeader);
std::terminate ();
Listing 4.3-1: the end of __cxa_throw
(libstdc++-v3/libsupc++/eh_throw.cc:90-98).
_Unwind_RaiseException returns only when it fails. A successful throw
continues in a landing pad in some other frame. Every failure ends in
std::terminate.
Three parties do the work, in two libraries:
| Party | What it knows | Where it is |
|---|---|---|
__cxa_throw, __cxa_begin_catch | the C++ exception object | libsupc++, in libstdc++ |
_Unwind_RaiseException, _Unwind_Resume | how to find a caller's frame from a table | libgcc |
| the personality routine | which catch clauses and cleanups a frame has | the language's runtime |
GCC did not invent this split. The Itanium C++ ABI exception-handling
specification defines it: "the method of locating and restoring
previous stack frames is language independent", and "the validity of a given
handler" is language dependent. libgcc's driver "is derived from the C++ ABI for
IA-64" (libgcc/unwind.inc:25-28). That document and the
Arm EHABI are the real specifications. The GCC manuals do not
restate them.
What the unwinder reads: .eh_frame, the CIE and the LSDA
For each function, the compiler emits .cfi_startproc, .cfi_endproc and CFI
directives between them. The assembler turns them into a frame description entry
(FDE) in .eh_frame. An FDE tells the unwinder, for any PC in the function, where
the caller's frame is and where the caller's registers were saved. This chapter
does not decode those rules.
Each FDE belongs to a common information entry (CIE). The CIE's augmentation
string can contain P and L. P names a personality routine. L says that
each FDE points to a language-specific data area (LSDA)
(libgcc/unwind-dw2.c:472-496, :1044-1050). The
compiler writes these as .cfi_personality and .cfi_lsda, only for functions
that need them (gcc/dwarf2out.cc:977-1039). The LSDA goes
into .gcc_except_table (gcc/except.cc:2983-2990). It is a
table of call sites. Each entry gives a range of code addresses, the landing pad
for an exception that passes through that range, and the catch types.
Now the failure in the opening. For each frame, the unwinder looks up the FDE that covers the return address:
fde = _Unwind_Find_FDE (context->ra + _Unwind_IsSignalFrame (context) - 1,
&context->bases);
if (fde == NULL)
{
#ifdef MD_FALLBACK_FRAME_STATE_FOR
/* Couldn't find frame unwind info for this function. Try a
target-specific fallback mechanism. This will necessarily
not provide a personality routine or LSDA. */
return MD_FALLBACK_FRAME_STATE_FOR (context, fs);
#else
return _URC_END_OF_STACK;
#endif
}
Listing 4.3-2: a frame with no FDE, in uw_frame_state_for
(libgcc/unwind-dw2.c:1008-1020).
The fallback does not rescue an ordinary function. On x86-64 GNU/Linux it
recognises the signal-return trampoline and returns _URC_END_OF_STACK for
anything else (libgcc/config/i386/linux-unwind.h:41-67).
A frame without an FDE looks to the unwinder like the end of the stack. The
search stops, _Unwind_RaiseException returns, and Listing 4.3-1 calls
std::terminate.
The libstdc++ manual documents this result in the "With C" part of its Exceptions page. It does not say when the compiler writes the tables.
When the compiler writes .eh_frame: -fexceptions, -funwind-tables, -fasynchronous-unwind-tables
The GCC manual documents the three options under Code Gen Options.
-fexceptions generates the code and data that propagate exceptions.
-funwind-tables generates only the static data. -fasynchronous-unwind-tables
makes the table exact at every instruction, not only at calls. The manual also
says that -fexceptions is on by default for C++ and off for C. The front end
does that in one line, opts->x_flag_exceptions = c_dialect_cxx ();
(gcc/c-family/c-opts.cc:225).
One function decides whether a translation unit gets .eh_frame:
bool
dwarf2out_do_eh_frame (void)
{
return
(flag_unwind_tables || flag_exceptions)
&& targetm_common.except_unwind_info (&global_options) == UI_DWARF2;
}
Listing 4.3-3: the .eh_frame decision
(gcc/dwarf2cfi.cc:3703-3709).
-fasynchronous-unwind-tables works through flag_unwind_tables, because
toplev.cc sets that flag whenever the asynchronous one is on. The same lines
turn the asynchronous flag on for -fnon-call-exceptions
(gcc/toplev.cc:1376-1379).
So a C function gets an FDE only if the target sets one of those flags. The manual does not say which targets do. The source does:
- x86. The option starts at a "not set" value of 2
(
gcc/common/config/i386/i386-common.cc:2075). For 64-bit code, the option-override hook turns 2 into both flags (gcc/config/i386/i386-options.cc:1913-1915). For 32-bit code, it depends on the frame-pointer default (:1924-1925). - AArch64 and RISC-V. Both flags are on when
TARGET_DEFAULT_ASYNC_UNWIND_TABLESis 1 (aarch64-common.cc:63-66,riscv-common.cc:2530-2533).gcc/config.gccdefines it for AArch64 FreeBSD, GNU/Linux and Hurd (:1231,:1243,:1272) and for RISC-V GNU/Linux (:2530). The bare-metal-elftargets do not get it. - 32-bit Arm EABI. There are no tables unless you give
-fexceptionsor-funwind-tables(gcc/common/config/arm/arm-common.cc:49-77).
-g does not help. With debug information and no unwind tables, GCC emits
.cfi_sections .debug_frame (gcc/dwarf2out.cc:29852-29855), so
the CFI goes to .debug_frame. A debugger reads that section. The unwinder does
not: crtbegin.o registers the section named by __LIBGCC_EH_FRAME_SECTION_NAME__
(gcc/c-family/c-cppbuiltin.cc:1515-1517), which is .eh_frame
by default (gcc/defaults.h:365-366).
You can watch the decision on any installed compiler. Use C, and no -g:
$ gcc -S -o - frame.c | grep '\.cfi_'
$ gcc -S -fno-asynchronous-unwind-tables -o - frame.c | grep '\.cfi_'
$ gcc -c frame.c && readelf --debug-dump=frames frame.o
$ gcc -S -fexceptions -o - cleanup.c | grep -E '\.cfi_(personality|lsda)'
On x86-64 the source predicts .cfi_startproc lines from the first command and
none from the second. The third shows the CIE and FDEs that the assembler built.
For the fourth, give cleanup.c a variable with the cleanup attribute and a
call in its scope. The source predicts a .cfi_personality that names
__gcc_personality_v0. These commands were not run for this book.
Finding the table at run time: _Unwind_Find_FDE and __register_frame_info
The unwinder must also find .eh_frame in memory. libgcc has two ways.
With glibc and a linker that builds .eh_frame_hdr
(libgcc/unwind-dw2-fde-dip.c:49-52), libgcc asks the C library
where each loaded object's PT_GNU_EH_FRAME segment is. It tries registered
objects first, then glibc's _dl_find_object if it exists, then
dl_iterate_phdr (:535-574). That is the interface with binutils
and the C library, and the book stops there. libgcc/config.host selects this
file for *-*-linux* through t-eh-dw2-dip (config.host:314,
t-eh-dw2-dip).
Elsewhere, crtbegin.o registers the program's .eh_frame at startup. A
-static link on GNU/Linux takes this path too. The spec passes
--eh-frame-hdr only without -static (gcc/config/gnu-user.h:109),
and the static start file, crtbeginT.o, is built with CRTSTUFFT_O
(libgcc/Makefile.in:1054), which
excludes it from every USE_PT_GNU_EH_FRAME block
(crtstuff.c:88-132). So it registers the frames itself.
crtstuff.c defines USE_EH_FRAME_REGISTRY when it cannot use
PT_GNU_EH_FRAME (crtstuff.c:139-141). crtbegin.o puts a
label at the start of .eh_frame (:260-267), crtend.o
puts a zero terminator at the end (:653-669), and a constructor
gives the label to libgcc:
static void __attribute__((used))
frame_dummy (void)
{
#ifdef USE_EH_FRAME_REGISTRY
static struct object object;
...
if (__register_frame_info)
__register_frame_info (__EH_FRAME_BEGIN__, &object);
...
#endif /* USE_EH_FRAME_REGISTRY */
Listing 4.3-4: frame_dummy, abridged (libgcc/crtstuff.c:473-488).
The omitted branch passes two base addresses to __register_frame_info_bases.
Two details matter on a board. The references to __register_frame_info are
weak (crtstuff.c:180-189), so crtbegin.o does not pull the
unwinder into a C program. And the receiving function names its caller:
"Called from crtbegin.o to register the unwind info for an object"
(unwind-dw2-fde.c:123-154). An aarch64-none-elf libgcc has
no t-eh-dw2-dip (config.host:405-414), so registration is
its only path. -nostartfiles drops crtbegin.o
(Chapter 1.10). Unless your startup code
then calls __register_frame_info itself, every throw ends in
std::terminate.
Two walks up the stack: phase 1 and phase 2 in unwind.inc
_Unwind_RaiseException is in libgcc/unwind.inc, which unwind-dw2.c
includes (unwind-dw2.c:1483). Its first loop is the search phase:
/* Phase 1: Search. Unwind the stack, calling the personality routine
with the _UA_SEARCH_PHASE flag set. Do not modify the stack yet. */
while (1)
{
_Unwind_FrameState fs;
/* Set up fs to describe the FDE for the caller of cur_context. The
first time through the loop, that means __cxa_throw. */
code = uw_frame_state_for (&cur_context, &fs);
if (code == _URC_END_OF_STACK)
/* Hit end of stack with no handler found. */
return _URC_END_OF_STACK;
if (code != _URC_NO_REASON)
/* Some error encountered. Usually the unwinder doesn't
diagnose these and merely crashes. */
return _URC_FATAL_PHASE1_ERROR;
/* Unwind successful. Run the personality routine, if any. */
if (fs.personality)
{
code = (*fs.personality) (1, _UA_SEARCH_PHASE, exc->exception_class,
exc, &cur_context);
if (code == _URC_HANDLER_FOUND)
break;
else if (code != _URC_CONTINUE_UNWIND)
return _URC_FATAL_PHASE1_ERROR;
}
/* Update cur_context to describe the same frame as fs. */
uw_update_context (&cur_context, &fs);
}
Listing 4.3-5: phase 1 (libgcc/unwind.inc:96-128).
Each turn finds the caller's FDE through Listing 4.3-2, calls the CIE's
personality routine with _UA_SEARCH_PHASE, and moves cur_context one frame
up. cur_context is a copy, so no register changes and no destructor runs. A
frame with no personality routine, such as a C function with tables but without
-fexceptions, is walked through without a call.
When a personality routine answers _URC_HANDLER_FOUND, _Unwind_RaiseException
records that frame's canonical frame address in private_2, starts again from
the throw point, and runs _Unwind_RaiseException_Phase2
(unwind.inc:130-140). Phase 2 walks the same frames with
_UA_CLEANUP_PHASE, and adds _UA_HANDLER_FRAME at the frame that phase 1
found (:52-65). When a personality routine returns
_URC_INSTALL_CONTEXT, the loop stops (:66-67), and
uw_install_context loads that frame's registers and jumps to its landing pad.
The Itanium ABI states the reason for two walks: if the search phase reports
failure, the framework calls terminate() rather than start phase 2. libgcc
follows it. Phase 1 returns _URC_END_OF_STACK before phase 2 has touched a
frame. An exception that nothing catches runs no destructor. std::terminate
runs with the throwing frame still on the stack, so a debugger stopped in it shows
__cxa_throw and the function that threw.
The personality routine: __gxx_personality_v0
The unwinder knows nothing about C++ types. The compiler names the routine that
does, as __<lang>_personality plus a suffix for the unwinding model: _v0 for
tables, _sj0 for setjmp/longjmp and _seh0 for Windows SEH
(gcc/expr.cc:14122-14149). The C++ front end passes gxx
(gcc/cp/cp-lang.cc:156-165). C keeps the default hook
(gcc/langhooks-def.h:147), which passes gcc
(gcc/tree.cc:12379-12386). The suffix is deliberate: "Using a
different personality function name causes link failures when trying to mix code
using different exception handling models"
(eh_personality.cc:336-345).
The routine reads the frame's LSDA and looks up the PC in its call-site table. Then it answers according to the phase:
do_something:
if (found_type == found_nothing)
CONTINUE_UNWINDING;
if (actions & _UA_SEARCH_PHASE)
{
if (found_type == found_cleanup)
CONTINUE_UNWINDING;
// For domestic exceptions, we cache data from phase 1 for phase 2.
if (!foreign_exception)
{
save_caught_exception(ue_header, context, thrown_ptr,
handler_switch_value, language_specific_data,
landing_pad, action_record);
}
return _URC_HANDLER_FOUND;
}
Listing 4.3-6: the phase test in __gxx_personality_v0
(libstdc++-v3/libsupc++/eh_personality.cc:649-665).
In phase 1 a frame with only cleanups (destructors) answers "continue". Only a
matching catch finds a handler. In phase 2 the routine loads the
exception pointer and the clause's selector into two registers, sets the PC to
the landing pad, and returns _URC_INSTALL_CONTEXT (:726-737).
A frame with no LSDA is passed through (:449-451). A frame
whose PC is not in its call-site table gets std::terminate, "for a destructor
inside a cleanup, or a library routine the compiler was not expecting to throw"
(:522-526). The compiler makes that case on purpose: a
must-not-throw region gets no call-site entry
(gcc/except.cc:176).
Cleanups end in _Unwind_Resume
A landing pad for a cleanup runs the destructors and must then give the exception
back to the unwinder. The compiler adds that call when it lowers the end of the
cleanup region: "When we don't have a destination region, this exception escapes
up the call chain. We resolve this by generating a call to the _Unwind_Resume
library function" (gcc/tree-eh.cc:3485-3522). The built-in is
named _Unwind_Resume, or _Unwind_SjLj_Resume for setjmp/longjmp
unwinding (gcc/tree.cc:10166-10171). The callee is in
unwind.inc:
/* Choose between continuing to process _Unwind_RaiseException
or _Unwind_ForcedUnwind. */
if (exc->private_1 == 0)
code = _Unwind_RaiseException_Phase2 (exc, &cur_context, &frames);
else
code = _Unwind_ForcedUnwind_Phase2 (exc, &cur_context, &frames);
Listing 4.3-7: the core of _Unwind_Resume
(libgcc/unwind.inc:239-244). Its comment says it is "not to
implement rethrowing" (:226-227).
It does not search again. Phase 1 already found the handler, so _Unwind_Resume
continues phase 2 from the cleanup's frame toward the frame in private_2. So
on a target with .eh_frame, a C++ object file with a destructor on an
exception path refers to _Unwind_Resume even if it never throws.
Why the unwinder is in libgcc: __gcc_personality_v0 and libgcc_eh.a
Only the personality routine knows C++. Everything in Listings 4.3-2, 4.3-5 and 4.3-7 is language independent, so it can live below every language runtime, and C can use it too. libgcc has its own small personality routine for C:
/* Currently we only support cleanups for C. */
if ((actions & _UA_CLEANUP_PHASE) == 0)
CONTINUE_UNWINDING;
Listing 4.3-8: __gcc_personality_v0 ignores phase 1
(libgcc/unwind-c.c:148-150).
C has no catch, so in phase 1 every C frame says "continue". In phase 2 the
routine runs the landing pads that the cleanup variable attribute creates. The
GCC manual documents that attribute under Common Variable Attributes:
with -fexceptions, the cleanup function runs during unwinding, and the
attribute cannot catch the exception. A PC that is not in a C function's table
means "no cleanup", not std::terminate. A GCC comment marks that difference
from C++ (unwind-c.c:218-221).
The build puts all of this in one group of sources:
# Additional sources to handle exceptions; overridden by targets as needed.
LIB2ADDEH = $(srcdir)/unwind-dw2.c $(srcdir)/unwind-dw2-fde.c \
$(srcdir)/unwind-sjlj.c $(srcdir)/unwind-c.c
LIB2ADDEHSTATIC = $(LIB2ADDEH)
LIB2ADDEHSHARED = $(LIB2ADDEH)
Listing 4.3-9: the unwinder sources (libgcc/Makefile.in:346-350).
They are compiled with -fexceptions (Makefile.in:871). With a
shared libgcc they go into libgcc_eh.a and libgcc_s.so
(:873-879). Without one, they go into libgcc.a
(:882-887), and a target with no shared-library link command has
no shared libgcc (:392-397). Chapter 4.2 explains how the driver
picks between them.
The Arm EHABI: .ARM.exidx, .cantunwind and __aeabi_unwind_cpp_pr0
32-bit Arm EABI targets do not use .eh_frame for exceptions. bpabi.h sets
ARM_UNWIND_INFO to 1 (gcc/config/arm/bpabi.h:32-34). The
target hook then returns UI_TARGET, or UI_NONE when neither -fexceptions
nor -funwind-tables is on (arm-common.cc:58-67).
UI_TARGET is not UI_DWARF2, so Listing 4.3-3 is false. The compiler emits
.fnstart and .fnend around each function instead. It adds .cantunwind for
a function that cannot throw, unless -funwind-tables is on or the function has
an LSDA (gcc/config/arm/arm.cc:30464-30483). The assembler builds
the index table .ARM.exidx from these directives:
$ arm-none-eabi-gcc -S -o - frame.c | grep -E '\.(fnstart|fnend|cantunwind)'
$ arm-none-eabi-gcc -S -fexceptions -o - frame.c | grep -E '\.(fnstart|fnend|cantunwind)'
The source predicts no lines from the first command, because the hook returns
UI_NONE. These commands were not run for this book.
The model differs from the Itanium one in three places.
The index is found through two linker symbols. libgcc declares
__gnu_Unwind_Find_exidx weak and calls it if the link defines it
(libgcc/unwind-arm-common.inc:69-70, :272-275).
Otherwise it searches from __exidx_start to __exidx_end
(:302-307). The file declares both as extern
(:128-130), so something in the link, such as the linker script,
must define them. An entry marked EXIDX_CANTUNWIND ends the search with
_URC_END_OF_STACK (:339-363).
The personality routine unwinds its own frame. The unwinder loop calls the
personality routine with _US_VIRTUAL_UNWIND_FRAME until the routine stops
answering "continue" (unwind-arm-common.inc:585-633). There is no
uw_update_context step. The personality routine unwinds the frame itself, so in
libstdc++ "continue" means "unwind this frame, then continue":
#define CONTINUE_UNWINDING \
do \
{ \
if (__gnu_unwind_frame(ue_header, context) != _URC_OK) \
return _URC_FAILURE; \
return _URC_CONTINUE_UNWIND; \
} \
while (0)
Listing 4.3-10: CONTINUE_UNWINDING for the EHABI
(libstdc++-v3/libsupc++/eh_personality.cc:193-200). The
generic version is one return (:317).
The EHABI also defines three personality routines that a table entry can select
by index. libgcc provides them as __aeabi_unwind_cpp_pr0, pr1 and pr2
(libgcc/config/arm/unwind-arm.c:497-523), and the index lookup is at
unwind-arm-common.inc:384-418. They reach the C++ runtime only
through weak references such as __cxa_type_match (:63-67).
A C++ function that needs a full LSDA names __gxx_personality_v0 instead.
A C++ cleanup ends in __cxa_end_cleanup. With the EHABI unwinder, the
compiler declares a __cxa_end_cleanup built-in
(gcc/tree.cc:10155-10163) and calls it, with no argument,
at the end of a C++ cleanup (gcc/tree-eh.cc:3489-3495). The EHABI
requires it: "A cleanup must return control to the unwinding code by tail
calling __cxa_end_cleanup". libsupc++'s version does its housekeeping and then
calls _Unwind_Resume (eh_arm.cc:215-223), which on Arm is an
assembly wrapper around __gnu_Unwind_Resume
(libgcc/config/arm/libunwind.S:314-360).
libgcc/config/arm/t-bpabi replaces LIB2ADDEH with these Arm files and
unwind-c.c (t-bpabi:10-12). arm*-*-eabi* uses that fragment
(libgcc/config.host:578-595).
Exceptions with no operating system: what -fexceptions costs
On a target with no operating system, a C++ program that throws carries five parts:
- Tables.
.eh_frame, or.ARM.exidxand its entries, for each function on a throw path, and.gcc_except_tablefor each function with a cleanup or acatch. The GCC manual warns, under-fexceptions, that this "can produce significant data size overhead". - The unwinder. The
LIB2ADDEHobjects, fromlibgcc.aon a target with no shared libgcc. - libsupc++.
__cxa_throw, the personality routine, type matching andstd::terminate. - An allocator.
__cxa_allocate_exceptioncallsmallocfirst, and uses an emergency pool only ifmallocfails (libstdc++-v3/libsupc++/eh_alloc.cc:393-403). The pool itself comes frommallocat startup, unless libstdc++ was configured with a static pool (eh_alloc.cc:45-47). The libstdc++ manual documents the pool and its two configure options on its Configure page. - A terminate handler. Its default depends on how libstdc++ was built:
/* We default to the talkative, informative handler in a normal hosted
library. This pulls in the demangler, the dyn-string utilities, and
elements of the I/O library. For a low-memory environment, you can return
to the earlier "silent death" handler by configuring GCC with
--disable-libstdcxx-verbose and rebuilding the library.
In a freestanding environment, we default to this latter approach. */
#if _GLIBCXX_HOSTED && _GLIBCXX_VERBOSE && __cpp_exceptions
# define _GLIBCXX_DEFAULT_TERM_HANDLER __gnu_cxx::__verbose_terminate_handler
#else
# include <cstdlib>
# define _GLIBCXX_DEFAULT_TERM_HANDLER std::abort
#endif
Listing 4.3-11: the default terminate handler
(libstdc++-v3/libsupc++/eh_term_handler.h:27-39).
_GLIBCXX_HOSTED describes how libstdc++ was configured, not your board. Every
throw reads the handler (eh_throw.cc:70), so the first
throw links the default handler, and in a hosted libstdc++ that brings the
demangler.
So -fno-exceptions is standard practice in embedded C++. It removes items 1 to
5 from your own code. cc1plus rejects throw and catch with "exception
handling disabled, use -fexceptions to enable" (gcc/cp/except.cc:395).
Listing 4.3-3 is false for a C++ file too. The libstdc++ manual documents what
the flag does to the library's headers, under "Doing without" on its
Exceptions page.
-fno-exceptions changes your code, not the libstdc++ you link. The library
reports errors through functions such as __throw_bad_alloc
(libstdc++-v3/src/c++11/functexcept.cc:52-54), and whether
those throw or call abort was decided when libstdc++ itself was compiled:
#ifndef _GLIBCXX_THROW_OR_ABORT
# if __cpp_exceptions
# define _GLIBCXX_THROW_OR_ABORT(_EXC) (throw (_EXC))
# else
# define _GLIBCXX_THROW_OR_ABORT(_EXC) (__builtin_abort(), (void)(_EXC))
# endif
#endif
Listing 4.3-12: _GLIBCXX_THROW_OR_ABORT
(libstdc++-v3/include/bits/c++config:260-266).
A libstdc++ compiled with the C++ default of -fexceptions still throws from
inside the library. Your frames, compiled with -fno-exceptions, have no LSDA,
and on Arm they may have no table at all. Nothing catches the exception, and
Listing 4.3-1 calls std::terminate.
That is the whole path of a throw with no handler. std::terminate calls the
handler and then std::abort, and it calls std::abort if the handler throws
(eh_terminate.cc:43-59). The handler is the verbose one or
std::abort itself (Listing 4.3-11). abort belongs to the C library or to your
board support code, and what it does on your board is outside GCC. A handler
that you install with std::set_terminate is the only part of this path that
your code controls.
Three things to carry away
A throw walks the stack twice. Phase 1 searches without changing anything,
and phase 2 runs cleanups and jumps to the handler. No handler means
std::terminate before any destructor runs.
A frame without unwind tables is the end of the stack. Whether a C function has tables depends on the target's defaults, not on the language.
The unwinder is libgcc's and language independent, and the personality routine
is the language's. That split lets C code take part in C++ unwinding, and it is
why the unwinder ships in libgcc_eh.a and libgcc_s.so, not in libstdc++.
Things that surprise people
On a bare-metal DWARF target, crtbegin.o is what makes exceptions work. With
-nostartfiles, register .eh_frame yourself or every throw terminates.
On arm-none-eabi, 64-bit division can bring the unwinder into a C program.
libgcc compiles its division functions with -fexceptions
(libgcc/config/arm/t-bpabi:17-20). A GCC comment states the
result: "printf will depend on udivmoddi4, which will depend on the exception
unwind routines" (gcc/config/arm/unknown-elf.h:91-96).
Documentation coverage
The GCC manual documents -fexceptions (gcc/doc/invoke.texi:19714),
-fnon-call-exceptions (:19728), -funwind-tables (:19748) and
-fasynchronous-unwind-tables (:19755) under Code Gen Options,
and the cleanup attribute (gcc/doc/extend.texi:7217) under
Common Variable Attributes. The libstdc++ manual's
Exceptions page (libstdc++-v3/doc/xml/manual/using_exceptions.xml)
covers the emergency pool, -fno-exceptions and C code, and its
Configure page (configure.xml:462-478) covers the pool options.
The internals manual lists the unwinder's entry points under
Exception handling routines (gcc/doc/libgcc.texi:2305-2339),
and the target macros under Exception Handling
(gcc/doc/tm.texi:3500) and Exception Region Output
(tm.texi:10018), with TARGET_EXCEPT_UNWIND_INFO at :10067 and
TARGET_ARM_EABI_UNWINDER at :10176. The real specifications are the
Itanium C++ ABI and the Arm EHABI.
What is not documented:
- What the unwinder's entry points do. The internals manual lists their names under the text "document me!".
- Which targets turn on
-fasynchronous-unwind-tablesby default, and so which targets give C functions tables. - That CFI from
-galone goes to.debug_frameand does not help an exception. - That a frame without an FDE ends the search. The libstdc++ manual states the result for C, not the mechanism.
- The two ways libgcc finds
.eh_frame, and that bare-metal targets depend oncrtbegin.oto register it. - The personality routine names, and that C has its own, which runs cleanups only.
- That
-fno-exceptionsdoes not change the prebuilt libstdc++.
Next: why a program built against one libstdc++ runs against a newer one, and
what __cxx11 is doing in your link errors.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
4.4 How libstdc++.so.6 stays compatible: version nodes and __cxx11
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
You build a program on a new distribution and copy it to an older machine. It
stops before main runs. The dynamic loader prints
version `%s' not found (required by %s), with a name such as
GLIBCXX_3.4.34 in the first %s (elf/dl-version.c:143-144,
glibc 2.42). On another day you link your code against a vendor's prebuilt
library, and the link fails with an undefined reference to a function that takes
std::__cxx11::basic_string<char, ...>. The vendor's header declares that exact
function.
The two failures come from the same library and from two different mechanisms. The first is symbol versioning, which the loader checks at run time. The second is the dual ABI, which changes mangled names, so the linker sees it.
libstdc++ keeps one soname because no release changes what an older release
exported. New symbols go under a new version name, and the C++11 std::string
went in beside the old one, under a different mangled name.
This chapter assumes Chapter 1.11, for how g++
puts -lstdc++ on the link line, and Chapter 1.12,
for which libstdc++.so that -l finds.
This is the book's one planned excursion into run time. Part I kept link-time
search and run-time search apart, and Chapter 1.12 ended on that point. But
whether a newer libstdc++.so.6 can replace an older one is a run-time
question: the program meets the library a second time when the loader maps it.
So this chapter follows the library past the linker, as far as the loader's
version check. The loader's search order, DT_RUNPATH and LD_LIBRARY_PATH
stay out of scope.
libtool_VERSION=6:34:0: where the .so.6 comes from
The library's file names come from one configure assignment:
# For libtool versioning info, format is CURRENT:REVISION:AGE
libtool_VERSION=6:34:0
Listing 4.4-1: the version triple (libstdc++-v3/acinclude.m4:4235-4236).
The link rule passes it to libtool as -version-info $(libtool_VERSION)
(src/Makefile.am:163-164). On GNU/Linux, libtool turns the
triple into a file-name suffix like this:
linux)
func_arith $current - $age
major=.$func_arith_result
versuffix="$major.$age.$revision"
;;
Listing 4.4-2: libtool's Linux rule (ltmain.sh:6546-6550).
With CURRENT 6, REVISION 34 and AGE 0, the major number is 6 and the suffix is
.6.0.34. The same platform entry in libtool.m4 installs three names, the
real file libstdc++.so.6.0.34 and two symbolic links, libstdc++.so.6 and
libstdc++.so. It sets the soname to the name that ends at the major number,
libstdc++.so.6 (libtool.m4:2526-2531). At install time,
libtool creates the two links with ln -s (ltmain.sh:2294-2303).
The three names have three readers:
| Name | Read by |
|---|---|
libstdc++.so | the link editor, when it resolves -lstdc++ (Chapter 1.12) |
libstdc++.so.6 | the dynamic loader, because the program records it |
libstdc++.so.6.0.34 | nobody by name: it is the file the links point at |
The middle row is the bridge from link time to run time. The ld manual
documents it under -soname, in Options: when an executable is
linked with a shared object that has a DT_SONAME, the dynamic linker later
loads the object that DT_SONAME names, not the file the linker was given
(ld/ld.texi:699-705, binutils 2.45). The linker copies the
library's DT_SONAME into the program's DT_NEEDED entry, and uses the file
name only when there is no soname (bfd/elflink.c:4745-4754,
binutils 2.45).
So the soname is a promise. Every program linked since the soname last changed
asks the loader for libstdc++.so.6, and whatever file has that name must serve
all of them. The libstdc++ manual's ABI Policy and Guidelines page
lists the history. The last change was GCC 3.4.0, where libstdc++.so.6.0.0
is marked "Incompatible with previous"
(doc/xml/manual/abi.xml:247). Since then, only the last
number has moved. The REVISION field of the triple went from 0 to 34, and it
appears only in the real file's name.
gnu.ver: one version node per release
A soname that never changes cannot tell an old library from a new one. Symbol
versions can. configure selects a GNU ld version script,
config/abi/pre/gnu.ver, when the linker is GNU ld
(acinclude.m4:4115-4126 and
:4243-4244). The libstdc++ manual documents the
--enable-symvers option and its styles on its Configure
page. The install manual does not list it.
The script defines a chain of version nodes. The base node, GLIBCXX_3.4, is
the interface of GCC 3.4.0, and the manual's version-name table maps each later
release to its node (abi.xml:313-365). The base node ends
with a catch-all that hides every symbol the script does not name. Each later
node names the one before it:
# DO NOT DELETE THIS LINE. Port-specific symbols, if any, will be here.
local:
*;
};
GLIBCXX_3.4.1 {
_ZNSt12__basic_fileIcE4fileEv;
} GLIBCXX_3.4;
Listing 4.4-3: the end of the base node, and the first node after it
(libstdc++-v3/config/abi/pre/gnu.ver:1109-1121).
The chain runs to GLIBCXX_3.4.34, which the file labels "GCC 15.1.0" and which
is still the newest node at 15.2.0:
# GCC 15.1.0
GLIBCXX_3.4.34 {
# std::__format::__with_encoding_conversion
_ZNSt8__format26__with_encoding_conversionERKSt6locale;
# std::__format::__locale_encoding_to_utf8
_ZNSt8__format25__locale_encoding_to_utf8ERKSt6localeSt17basic_string_viewIcSt11char_traitsIcEEPv;
# __sso_string constructor and destructor
_ZNSt12__sso_string[CD][12]Ev;
# void std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_construct<bool>(char const*, size_t)
# and wide char version
_ZNSt7__cxx1112basic_stringI[cw]St11char_traitsI[cw]ESaI[cw]EE12_M_constructILb[01]EEEvPK[cw][jmy];
} GLIBCXX_3.4.33;
Listing 4.4-4: the newest node (gnu.ver:2536-2547).
A second chain starts at CXXABI_1.3, with the comment "Symbols in the
support library (libsupc++) have their own tag"
(gnu.ver:2549-2550). That chain holds the language support
that the compiler calls directly, such as __cxa_allocate_exception. One node,
CXXABI_1.3.16, exists only on RISC-V (gnu.ver:2881-2888).
The script uses two kinds of pattern. Inside an extern "C++" block, a pattern
matches the demangled name. Outside one, it matches the mangled name
(gnu.ver:25-26 and :212-215). The ld
manual documents both forms under VERSION
(ld/ld.texi:6882-6892).
libstdc++-symbols.ver: the script is preprocessed
gnu.ver is not passed to the linker as it is. The build copies it, splices in
the target's extra symbol files at the "DO NOT DELETE" line of Listing 4.4-3,
and then runs the result through the C preprocessor:
$(EGREP) -v '^[ ]*#(#| |$$)' $@.tmp | \
$(CC) -E -P -include $(CONFIG_HEADER) - > $@ || (rm -f $@ ; exit 1)
Listing 4.4-5: the last step that builds libstdc++-symbols.ver
(libstdc++-v3/src/Makefile.am:330-331). The whole rule is
:313-332.
The grep drops lines that start with ##, # , or a lone #, which are the
script's comments. A line such as #ifdef __riscv has no space after the #,
so it survives, and the preprocessor evaluates it against the target's
config.h. That is how one version script serves every target. The extra files
come from configure.host, for example arm-eabi-extra.ver for Arm GNU/Linux
(configure.host:369). The link then adds
-Wl,--version-script=libstdc++-symbols.ver
(src/Makefile.am:336-338).
What the loader checks: version names in DT_VERNEED
When the linker resolves a program's reference against a versioned definition,
the program records the version node it needs, per library. The ld manual
explains the purpose under VERSION: the loader can make "a quick
check" that each library supplies every version node the program needs, so
that it does not discover a missing symbol halfway through a run
(ld/ld.texi:6813-6832).
glibc's loader does that check in _dl_check_map_versions. It walks the
program's DT_VERNEED entries and, for each version name, searches the
library's DT_VERDEF list (elf/dl-version.c:152-240). A name
that is not there ends the load:
/* XXX We cannot translate the message. */
_dl_exception_create_format
(&exception, DSO_FILENAME (map->l_name),
"version `%s' not found (required by %s)", string, name);
Listing 4.4-6: the error from the opening (elf/dl-version.c:141-144,
glibc 2.42).
The check is by version name, not by symbol. A program that calls one function
from GLIBCXX_3.4.34 needs the whole node, and a library from GCC 14 does not
define it. The other direction passes, because a library built for the same
target defines every node of the chain up to its own. That asymmetry is the
whole guarantee.
The ABI Policy page documents it as forward compatibility, and says that the
reverse is not true (abi.xml:108-121).
You can see each side with tools that only read files:
$ objdump -T "$(g++ -print-file-name=libstdc++.so.6)" | grep -o 'GLIBCXX_[0-9.]*' | sort -u -V
$ objdump -p ./prog | sed -n '/^Version References/,$p'
$ LD_DEBUG=versions ./prog
The first command lists the nodes the library defines. The second prints the
program's Version References section, one required from block per library
(bfd/elf.c:1690-1695, binutils 2.45). The third makes glibc's
loader report each version it checks, through the versions debug category
(elf/rtld.c:2401-2402, glibc 2.42). These commands were
not run for this book.
make check-abi: the test that keeps the promise
Version nodes only help if nobody edits an old one. The ABI Policy page lists
the changes a release may make (add exported data, functions or instantiations)
and the ones it may not (delete a symbol, or change its size, layout or
mangling) (abi.xml:744-800). The source enforces that policy
with a test, not with review alone.
A directory per target under config/abi/post/, such as x86_64-linux-gnu,
holds a baseline_symbols.txt. It has one line per exported symbol, with the
symbol's type and version:
FUNC:_ZNSs6appendERKSs@@GLIBCXX_3.4
FUNC:_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE6appendERKS4_@@GLIBCXX_3.4.21
Listing 4.4-7: two lines from the x86-64 GNU/Linux baseline
(config/abi/post/x86_64-linux-gnu/baseline_symbols.txt:1670
and :3264).
make check-abi runs abi.exp (testsuite/Makefile.am:164-167).
That script extracts the same list from the new libstdc++.so with
scripts/extract_symvers, which reads the dynamic symbols with
readelf --symbols (scripts/extract_symvers.in:48-66).
Then it runs a small program, abi_check, on the two lists
(testsuite/libstdc++-abi/abi.exp:57-71). A target with no
baseline file skips the test (abi.exp:48-54). The comparison
in testsuite_abi.cc fails the run on three kinds of change. A baseline symbol
that is missing counts as incompatible (testsuite_abi.cc:477-483).
A symbol in both lists must keep its type and its size
(:320-344). And an added symbol must carry the newest version
name:
// Check that added symbols are added in the latest pre-release version.
bool latestp = (test.version_name == "GLIBCXX_3.4.34"
|| test.version_name == "CXXABI_1.3.16"
Listing 4.4-8: the rule for new symbols (libstdc++-v3/testsuite/util/testsuite_abi.cc:260-262).
That last rule protects against the script itself. The base node exports most
of std through demangled globs, and the ld manual warns that "it's slightly
crazy to use wildcards in a global spec except on the last version node",
because a glob can add symbols to an old version
(ld/ld.texi:6793-6797). A symbol that slipped into
GLIBCXX_3.4 would pass the loader's name check on an old library that does
not have it. So the globs leave gaps on purpose:
std::basic_[p-r]*;
# std::basic_streambuf
# std::basic_string
# std::basic_stringbuf
# std::basic_stringstream;
std::basic_[t-z]*;
Listing 4.4-9: no std::basic_s glob in the base node
(gnu.ver:56-61).
No pattern in that list matches a name that starts with std::basic_s. The old
std::string members are instead listed one mangled pattern at a time, starting
at gnu.ver:217-222. A new member function that the globs did
catch would still fail check-abi, because Listing 4.4-8 requires the newest
node.
The dual ABI: _GLIBCXX_USE_CXX11_ABI and inline namespace __cxx11
C++11 forbids a copy-on-write std::string and requires a std::list to keep
track of its size. Both changes alter what the object stores, and the ABI
Policy page lists a change of layout as prohibited
(abi.xml:744-800). The libstdc++ manual documents the outcome
on its Dual ABI page. GCC 5.1 added new implementations, kept
the old ones in the same library, and gave the new ones different names for
linkage, by putting them in an inline namespace
(using.xml:1354-1370).
The namespace is in <bits/c++config>:
#define _GLIBCXX_USE_DUAL_ABI
#if ! _GLIBCXX_USE_DUAL_ABI
// Ignore any pre-defined value of _GLIBCXX_USE_CXX11_ABI
# undef _GLIBCXX_USE_CXX11_ABI
#endif
#ifndef _GLIBCXX_USE_CXX11_ABI
#define _GLIBCXX_USE_CXX11_ABI
#endif
#if _GLIBCXX_USE_CXX11_ABI
namespace std
{
inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { }
}
namespace __gnu_cxx
{
inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { }
}
# define _GLIBCXX_NAMESPACE_CXX11 __cxx11::
# define _GLIBCXX_BEGIN_NAMESPACE_CXX11 namespace __cxx11 {
# define _GLIBCXX_END_NAMESPACE_CXX11 }
# define _GLIBCXX_DEFAULT_ABI_TAG _GLIBCXX_ABI_TAG_CXX11
Listing 4.4-10: the switch and the namespace (libstdc++-v3/include/bits/c++config:357-380).
Three details in that listing matter.
The two #define lines have no value in the source. The build fills them in
when it generates the installed c++config.h. A sed command appends a 1 or a
0 to each (include/Makefile.am:1407-1408), from stamp files
that configure conditionals select (include/Makefile.am:1325-1339).
--with-default-libstdcxx-abi chooses the second value, and its default is
new (acinclude.m4:4899-4924). --disable-libstdcxx-dual-abi
sets the first one to 0 (acinclude.m4:4878-4889). The
libstdc++ manual documents both options on its Configure page
(configure.xml:395-417).
The #ifndef lets each translation unit choose. A
-D_GLIBCXX_USE_CXX11_ABI=0 on the command line is defined before the header
runs, so the configured default does not replace it. The Macros
page documents the macro. The #undef above it is the exception: in a library
built without the dual ABI, the header discards your value.
The inline namespace hides itself from lookup, not from the linker. The string class is declared inside it:
_GLIBCXX_BEGIN_NAMESPACE_CXX11
template<typename _CharT, typename _Traits = char_traits<_CharT>,
typename _Alloc = allocator<_CharT> >
class basic_string;
_GLIBCXX_END_NAMESPACE_CXX11
Listing 4.4-11: the declaration (libstdc++-v3/include/bits/stringfwd.h:70-76).
Source code that names std::string finds the class through the inline
namespace and never spells __cxx11. The mangled name spells it. With the macro
at 0, the same macros expand to nothing, and <bits/basic_string.h> includes
the old copy-on-write class from cow_string.h instead
(basic_string.h:64-71).
How __cxx11 reaches a mangled name: Ss and B5cxx11
The namespace changes mangled names by two routes. The first route applies to any name that contains the type. The second applies to functions that only return it.
The lost Ss abbreviation
The Itanium C++ ABI gives std::string a two-letter abbreviation, Ss. GCC's
mangler applies it only when the class is declared directly in ::std:
if (!DECL_NAMESPACE_STD_P (CP_DECL_CONTEXT (decl)))
return false;
Listing 4.4-12: the test in is_std_substitution
(gcc/cp/mangle.cc:504-505).
DECL_NAMESPACE_STD_P is true only for std_node itself
(gcc/cp/cp-tree.h:3742-3743). The context of the new class is
std::__cxx11, so the test fails, and the "Ss" branch at
mangle.cc:643-663 never runs. The mangler writes the full nested
name instead. The version script shows both forms for one constructor parameter,
a const std::string&. The old form is RKSs, and the new form begins
RKNSt7__cxx1112basic_string (gnu.ver:1742 and
:1744).
So a function void use(const std::string&) gets one name under each value of
the macro. Under the old ABI it is _Z3useRKSs. Under the new ABI it is
_Z3useRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE. Mix the two in
one link and the reference cannot meet the definition.
abi_tag and [abi:cxx11]
The first route misses one case. The mangled name of an ordinary function does
not include its return type, so std::string make() would mangle the same under
both ABIs, and an old-ABI caller would link against a new-ABI definition with no
error. The abi_tag attribute on the namespace closes that gap. The GCC manual
documents the attribute under C++ Attributes, including the
inline-namespace form and the automatic tagging of a function whose return type
carries a tag (gcc/doc/extend.texi:30298-30333).
The front end does the tagging when it mangles the function.
write_mangled_name starts with a call to check_abi_tags
(mangle.cc:794-799):
/* Check that DECL has all the ABI tags that are used in parts of its type
that are not reflected in its mangled name. */
void
check_abi_tags (tree decl)
{
if (VAR_P (decl))
check_abi_tags (decl, TREE_TYPE (decl));
else if (TREE_CODE (decl) == FUNCTION_DECL
&& !DECL_CONV_FN_P (decl)
&& !mangle_return_type_p (decl))
check_abi_tags (decl, TREE_TYPE (TREE_TYPE (decl)));
}
Listing 4.4-13: only the parts of the type the name does not show
(gcc/cp/class.cc:1903-1915).
For a function, the part checked is the return type, unless the return type is
already in the mangled name, as it is for a function template instance
(mangle.cc:846-852). The helper marks the tags that the
parameter types already carry, with the comment "A function's parameter types
are part of the signature, so we don't need to inherit any tags that are also
in them" (class.cc:1844-1850). It finds a tag by walking each
type's enclosing scopes up to the global namespace, so the tag on __cxx11 is
found (class.cc:1752-1772). Any tag that is left is added to
the function's own abi_tag attribute, and the mangler writes it after the
name:
unsigned i; tree str;
FOR_EACH_VEC_ELT (*vec, i, str)
{
write_string ("B");
write_unsigned_number (TREE_STRING_LENGTH (str) - 1);
write_identifier (TREE_STRING_POINTER (str));
}
Listing 4.4-14: write_abi_tags (gcc/cp/mangle.cc:1723-1729).
So std::string make() becomes _Z4makeB5cxx11v under the new ABI and stays
_Z4makev under the old one. The tag on the namespace itself is never written,
because get_abi_tags returns nothing for a namespace
(mangle.cc:526-527). The tag reaches a mangled name only through
the functions and variables it is copied to. The demangler in libiberty prints a
B tag as [abi:cxx11] (libiberty/cp-demangle.c:5100-5105).
binutils carries the same code (libiberty/cp-demangle.c:5102,
binutils 2.45), so binutils tools print the same [abi:cxx11]. The Dual ABI
page names that tag as the second form of this link error
(using.xml:1467-1475). -Wabi-tag makes the
front end warn when it adds such a tag
(class.cc:1693-1697).
One library, both strings: cow-string-inst.cc
The library must define both versions of every exported std::string member.
It does that by compiling one instantiation file twice. string-inst.cc picks
the new ABI by default:
#ifndef _GLIBCXX_USE_CXX11_ABI
// Instantiations in this file use the new SSO std::string ABI unless included
// by another file which defines _GLIBCXX_USE_CXX11_ABI=0.
# define _GLIBCXX_USE_CXX11_ABI 1
#endif
Listing 4.4-15: libstdc++-v3/src/c++11/string-inst.cc:32-36.
and cow-string-inst.cc includes it with the macro already at 0:
#define _GLIBCXX_USE_CXX11_ABI 0
#include "string-inst.cc"
Listing 4.4-16: libstdc++-v3/src/c++11/cow-string-inst.cc:29-30.
The two objects define different mangled names, so both link into one
libstdc++.so. The version script then files them in different nodes. The old
names (_ZNSs...) are in GLIBCXX_3.4, as Listing 4.4-9's gaps require. The
new names are under the comment "ABI-tagged std::basic_string" in
GLIBCXX_3.4.21, the GCC 5.1 node (gnu.ver:1765-1767).
Listing 4.4-7 shows the result for append: one member function, two exports,
two versions.
The dual ABI therefore needed no new soname. A program built with GCC 4.9 that
calls append refers to _ZNSs6appendERKSs at version GLIBCXX_3.4, and the
GCC 15 baseline still lists that symbol (Listing 4.4-7).
Reproducing the std::__cxx11 link error
Two files are enough. lib.cc defines the function, and main.cc calls it:
$ printf '#include <string>\nvoid use(const std::string&) {}\n' > lib.cc
$ printf '#include <string>\nvoid use(const std::string&);\nint main() { use("x"); }\n' > main.cc
$ g++ -c -D_GLIBCXX_USE_CXX11_ABI=0 lib.cc
$ nm lib.o | grep use
$ g++ main.cc lib.o
These commands were not run for this book. By Listing 4.4-12, nm shows
_Z3useRKSs in lib.o, and main.cc, compiled with the default, references
the __cxx11 name, so the last command fails with an undefined reference.
Remove the -D and the link succeeds. Add std::string make() { return {}; }
to lib.cc and compile it twice, with and without the -D, and nm -C shows
make[abi:cxx11]() only in the default build.
The Dual ABI page documents the cure under Troubleshooting: rebuild the
library with the new ABI, or compile your own code with the macro at 0
(using.xml:1467-1475).
Three things to carry away
The soname has been libstdc++.so.6 since GCC 3.4, because each release only
adds. The release number is in the REVISION field of libtool_VERSION, which
only the real file name shows.
The loader checks version names, not symbols. A program needs every node it
used. It runs on any newer library, and fails before main on an older library
that lacks one of those nodes.
__cxx11 renames the new std::string in two ways. The namespace changes
every name that contains the type, and the abi_tag changes functions that only
return it.
Things that surprise people
-std=c++98 does not select the old std::string. The default value of
_GLIBCXX_USE_CXX11_ABI is the same for every dialect. The Dual ABI page
documents this, so that C++03 and C++11 code can link together
(using.xml:1386-1392).
A class with a std::string member has one mangled name under both ABIs.
Its layout changes and its name does not, so a mismatch links and fails at run
time. The Dual ABI page says so, and points to -Wabi-tag
(using.xml:1477-1484).
--with-default-libstdcxx-abi=gcc4-compatible still ships both strings. It
changes only the header default, and the manual says it "does not change the
library ABI" (configure.xml:406-417). --disable-libstdcxx-dual-abi removes
the new string from the library.
--enable-symvers=gnu-versioned-namespace changes the soname to
libstdc++.so.8. It sets libtool_VERSION=8:0:0 and its own version script
(acinclude.m4:4248-4250), and it turns the dual ABI off
(:4880-4883). The library then puts nearly all of
std in an inline namespace __8 (c++config:389-393). A
program built for libstdc++.so.6 cannot use it.
Documentation coverage
The libstdc++ manual owns this subject, and its pages are rendered at the pin.
ABI Policy and Guidelines (libstdc++-v3/doc/xml/manual/abi.xml)
covers the soname history, the version-name history, the allowed and prohibited
changes, and make check-abi. Dual ABI
(doc/xml/manual/using.xml:1350) covers the two strings, the macro and the
troubleshooting. Configure (doc/xml/manual/configure.xml:309,
:395 and :406) covers --enable-symvers, --disable-libstdcxx-dual-abi
and --with-default-libstdcxx-abi, and Macros
(doc/xml/manual/using.xml:1218) covers _GLIBCXX_USE_CXX11_ABI. The GCC
manual documents abi_tag under C++ Attributes
(gcc/doc/extend.texi:30298), and -Wabi-tag and -fabi-version under
C++ Dialect Options (gcc/doc/invoke.texi:3762 and :2934).
Outside GCC, the ld manual documents -soname and version scripts
under VERSION. The install manual mentions none of the libstdc++
configure options in this chapter.
What is not documented:
- That the release counter is the REVISION field of
libtool_VERSION, and that libtool turns6:34:0intolibstdc++.so.6.0.34. - The manual's version tables stop at GCC 14.1.0. At the pin, the library is
libstdc++.so.6.0.34, andGLIBCXX_3.4.34is the newest node. Neither has a row in the file-name table (abi.xml:233-285) or the version-name table (:313-365). - That the version script goes through the C preprocessor with the target's
config.h, and that each target's extra symbols are spliced in at the "DO NOT DELETE" line. - That
check-abifails any added symbol that does not carry the newest version name, and that the base node's globs leave out everystd::basic_sname. - How the namespace reaches a mangled name: the lost
Ssabbreviation, and the front end's rule that tags only the return type and only when the parameters do not already carry the tag.
Next: Chapter 4.5 chooses between static and shared runtimes, and shows why two shared objects that each carry their own libstdc++ cannot catch each other's exceptions.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
4.5 Static or shared runtimes: one copy of libstdc++, or two
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
You build a plugin with -static-libstdc++, so that it loads into hosts that
have an older libstdc++.so.6. A colleague builds a second plugin the same way.
Code in the first plugin throws a std::runtime_error, and a handler in the
second plugin catches it. That part works. Then the handler calls back into the
first plugin to rethrow, and the process aborts with terminate called without an active exception. An exception is active. It is active in the other copy of the
C++ runtime.
The folklore says that a static libstdc++ in two shared objects "breaks
catch". At the pin the catch works, and the rethrow fails. A static runtime
is a private copy of its code and of its state. libstdc++ compares exception
types by name, so a catch matches across copies, but the per-thread exception
stack is state, and each copy reads only its own.
This chapter closes Part IV, and it pays off
Chapter 1.11, which showed how
-static-libstdc++ becomes a -Wl,-Bstatic wrap around one -l. It also
assumes Chapter 4.2 for the split
between libgcc.a, libgcc_eh.a and libgcc_s.so,
Chapter 4.3 for the unwinder and the personality
routine, and Chapter 4.4 for symbol versioning.
-static, -static-pie, -static-libgcc, -static-libstdc++: four mechanisms
The GCC manual documents each of these options under Link Options:
-static "prevents linking with the shared libraries", -static-libgcc forces
the static libgcc, and -static-libstdc++ links libstdc++ statically "without
necessarily linking other libraries statically". The names suggest one switch
with three strengths. The source has four separate mechanisms:
| Option | What it changes | Where |
|---|---|---|
-static | the whole link: -static to ld, crt1.o and crtbeginT.o, -lgcc -lgcc_eh, no --eh-frame-hdr | target specs, such as gnu-user64.h:67 and gnu-user.h:51-61 |
-static-pie | -static -pie --no-dynamic-linker to ld, rcrt1.o and crtbeginS.o, -lgcc -lgcc_eh, and --eh-frame-hdr | the same target specs |
-static-libgcc | the libgcc spec only: -lgcc -lgcc_eh instead of libgcc_s | the rewritten libgcc spec, Chapter 4.2 |
-static-libstdc++ | one library: -Wl,-Bstatic -lstdc++ -Wl,-Bdynamic | g++spec.cc, Chapter 1.11 |
The four do not compose the way their names suggest. -static-libstdc++ does
not touch libgcc. g++ starts with shared_libgcc = 1
(g++spec.cc:136-138). -static-libgcc clears it
(:231-232), a compiler without a shared libgcc clears
it (:297-301), and -static suppresses it
(:227-228). Otherwise the driver adds -shared-libgcc:
if (shared_libgcc && !static_link)
generate_option (OPT_shared_libgcc, NULL, 1, CL_DRIVER,
&new_decoded_options[j++]);
Listing 4.5-1: g++ adds -shared-libgcc unless told otherwise
(gcc/cp/g++spec.cc:444-446).
So g++ -shared -static-libstdc++ links a private copy of libstdc++ and the
shared libgcc_s. The objects in the process then share one unwinder, and
each object that used -static-libstdc++ has its own libsupc++, the part of
libstdc++ that implements throw and catch. Chapter 4.2 explains why g++
wants the shared libgcc. This chapter is about the second copy of libsupc++.
-static does one more thing on GNU/Linux that is easy to miss. The target
passes --eh-frame-hdr to the linker only when the link is not static:
#if defined(HAVE_LD_EH_FRAME_HDR)
#define LINK_EH_SPEC "%{!static|static-pie:--eh-frame-hdr} "
#endif
Listing 4.5-2: no --eh-frame-hdr under -static
(gcc/config/gnu-user.h:108-110).
The static start file changes to match. crtbeginT.o is crtstuff.c compiled
with -DCRTSTUFFT_O (libgcc/Makefile.in:1053-1054). That macro
removes USE_PT_GNU_EH_FRAME on glibc (crtstuff.c:106-119), so
USE_EH_FRAME_REGISTRY takes its place (:139-141), and the
start file calls __register_frame_info on the executable's .eh_frame at
startup (:468-493). A static executable registers its own
unwind tables. In a dynamic one the unwinder walks the loaded objects with
dl_iterate_phdr (unwind-dw2-fde-dip.c:569).
Chapter 4.3 covers both lookups.
What libstdc++.a holds: the same PIC objects, without versions
-static-libstdc++ -shared works only if the archive members are
position-independent. libstdc++ makes sure of that. When shared libraries are
enabled, its configure sets -prefer-pic and -D_GLIBCXX_SHARED for libtool
(libstdc++-v3/configure.ac:137-146). The libsupc++ and src/c++*
directories compile each source once, with both flags, into convenience
libraries (src/Makefile.am:235-237,
libsupc++/Makefile.am:148-151). Both libstdc++.a and
libstdc++.so are made from those libraries
(src/Makefile.am:142-148). The reason for the PIC objects is in a
comment:
# Why are objects destined for libstdc++.a compiled with -fPIC? First,
# because -fPIC is not harmful to use for objects destined for static
# libraries. In addition, using -fPIC will allow the use of static
# libstdc++.a in the creation of other C++ shared libraries.
Listing 4.5-3: libstdc++.a is built for shared objects on purpose
(libstdc++-v3/src/Makefile.am:245-248).
Two things differ between the archive and the shared object. The compatibility
sources in src/ are compiled a second time for the archive, without
-D_GLIBCXX_SHARED (src/Makefile.am:239-243), and the code
that keeps old symbol versions is inside #if ... defined(_GLIBCXX_SHARED)
(src/c++98/compatibility.cc:28-30). The comment says why:
# static lib == linked against only this version, should not need compat
# shared lib == linked against potentially all compat versions
Listing 4.5-4: compatibility symbols are for the shared library only
(libstdc++-v3/src/Makefile.am:229-230).
The version script is also a link option of libstdc++.so only
(src/Makefile.am:163-164, :337). An archive
member has no symbol versions. Chapter 4.4 covers
what those versions buy the shared library.
Default visibility: why a plugin exports the libstdc++ it copied
The more important difference is visibility. libsupc++ declares its ABI
functions inside #pragma GCC visibility push(default)
(libsupc++/cxxabi.h:48), and <typeinfo> does the same
(typeinfo:44). A shared object that links members of
libstdc++.a gets them as global symbols with default visibility, so the
linker exports them from that shared object with the rest of its API.
libgcc does the opposite. Its configure sets
vis_hide='-fvisibility=hidden -DHIDE_EXPORTS' when the compiler supports
hidden visibility (libgcc/configure.ac:549-555), and the C
objects for libgcc.a and libgcc_eh.a are compiled with it
(libgcc/Makefile.in:510-512,
static-object.mk:16-17). The libgcc_s objects are not
(shared-object.mk:17). A shared object that links
libgcc.a keeps the copy to itself. A shared object that links libstdc++.a
exports it.
Two copies in one process: -shared -static-libstdc++ and --exclude-libs
Link two shared objects with -static-libstdc++, and each gets its own copy of
every member it uses: __cxa_begin_catch, the personality routine
__gxx_personality_v0, and typeinfo for std::runtime_error. That type_info
lives in libstdc++ because the class's first virtual function, its destructor
(<stdexcept>:246), is defined there
(src/c++98/stdexcept.cc:70). Whether a call
in one object reaches that object's own copy depends on how the symbols were
bound, and there are two cases.
In the default case both objects export the same names. The dynamic loader then
decides, when the program runs, which definition each reference reaches. Run
time is outside this book. Chapter 4.4 is its one deliberate excursion there,
and the <typeinfo> comment in the next section names one loader setting,
RTLD_LOCAL, under which it says type names are not merged.
The second case is decided at link time. GNU ld's --exclude-libs option takes
a list of archives, or ALL, and for ELF targets "symbols affected by this
option will be treated as hidden" (the ld manual, binutils 2.45
ld/ld.texi:538-547). GCC never passes it. A plugin build that
adds -Wl,--exclude-libs,ALL binds every reference to libstdc++ inside the
plugin to the plugin's own copy, and exports none of it. Two such plugins hold
two copies for certain. The rest of this chapter reads what each copy does
with an exception that the other copy made.
What a catch compares: type_info::operator==
Chapter 4.3 describes how the personality routine scans a frame's handlers. For
each catch clause it calls get_adjusted_ptr, which asks the type of the
clause whether it accepts the thrown type
(eh_personality.cc:223-243). The thrown type comes from the
exception header, which __cxa_throw in the thrower's copy filled in
(eh_throw.cc:64). The catch type comes from the catching
frame's tables, so it is the catcher's copy. For a class, the test starts with
one comparison:
if (*this == *thr_type)
return true;
Listing 4.5-5: __class_type_info::__do_catch begins with operator==
(libstdc++-v3/libsupc++/class_type_info.cc:37-38).
So the whole question is what operator== does with two type_info objects at
different addresses. The Itanium C++ ABI expects them never to exist: "After
linking and loading, only one std::type_info structure is accessible via the
external name defined by this ABI for any particular complete type symbol", and
so "two type_info structures describe the same type if and only if they are the
same structure (at the same address)" (Itanium C++ ABI, §2.9.3).
Two private copies of libstdc++ break that premise, and libstdc++ does not rely
on it. Its header explains:
// Determine whether typeinfo names for the same type are merged (in which
// case comparison can just compare pointers) or not (in which case strings
// must be compared), and whether comparison is to be implemented inline or
// not. We used to do inline pointer comparison by default if weak symbols
// are available, but even with weak symbols sometimes names are not merged
// when objects are loaded with RTLD_LOCAL, so now we always use strcmp by
// default. For ABI compatibility, we do the strcmp inline if weak symbols
// are available, and out-of-line if not. Out-of-line pointer comparison
Listing 4.5-6: why the names are compared as strings
(libstdc++-v3/libsupc++/typeinfo:53-60). The default,
__GXX_MERGED_TYPEINFO_NAMES 0, follows at :71-74.
The comparison itself:
type_info::operator==(const type_info& __arg) const _GLIBCXX_NOEXCEPT
{
if (std::__is_constant_evaluated())
return this == &__arg;
if (__name == __arg.__name)
return true;
#if !__GXX_TYPEINFO_EQUALITY_INLINE
// ABI requires comparisons to be non-inline.
return __equal(__arg);
#elif !__GXX_MERGED_TYPEINFO_NAMES
// Need to do string comparison.
return __name[0] != '*' && __builtin_strcmp (__name, __arg.name()) == 0;
#else
return false;
#endif
}
Listing 4.5-7: type_info::operator==
(libstdc++-v3/libsupc++/typeinfo:197-214).
The same name pointer is a fast match. Otherwise the two mangled names are
compared with strcmp, so typeinfo for std::runtime_error from one copy
equals the one from the other copy. The Arm EABI moves the comparison out of
line (gcc/config/arm/bpabi.h:96-101), and the out-of-line
version in tinfo.cc does the same strcmp
(tinfo.cc:39-52).
The one exception is a name that starts with *. The C++ front end adds that
prefix when the type's name declaration is not public, "so that comparisons
will be done by pointer rather than string comparison"
(gcc/cp/rtti.cc:385-409, called at :958).
Those are types with internal linkage, which no other object can name in a
catch anyway.
Before GCC 4.5, two copies of a
type_infodid not compare equal on ELF targets. Atreleases/gcc-4.4.0,__GXX_MERGED_TYPEINFO_NAMESwas 1 whenever the target had weak symbols (typeinfo:61-69), and the inlineoperator==compared only the name pointers (:120-121).releases/gcc-4.5.0made 0 the default (typeinfo:65-68). The folklore that a second libstdc++ breakscatchdescribes GCC 4.4 and older.
What a second copy splits: __cxa_get_globals
The type test needs no shared state. Other parts of exception handling do. The
C++ ABI defines one record per thread, with the stack of exceptions currently
caught and the count of exceptions in flight
(unwind-cxx.h:155-162). libstdc++ stores it in a
thread-local variable:
namespace
{
abi::__cxa_eh_globals*
get_global() _GLIBCXX_NOTHROW
{
static __thread abi::__cxa_eh_globals global;
return &global;
}
} // anonymous namespace
extern "C" __cxa_eh_globals*
__cxxabiv1::__cxa_get_globals_fast() _GLIBCXX_NOTHROW
{ return get_global(); }
extern "C" __cxa_eh_globals*
__cxxabiv1::__cxa_get_globals() _GLIBCXX_NOTHROW
{ return get_global(); }
Listing 4.5-8: one record per thread, and per copy
(libstdc++-v3/libsupc++/eh_globals.cc:46-62).
A static variable in a function is one object per copy of the code. Two copies
of eh_globals.o give each thread two records. Follow the plugin case through
them, with plugin A throwing and rethrowing, and plugin B catching:
- A's
__cxa_throwadds 1 to A's count of exceptions in flight (eh_throw.cc:83-84). - B's personality routine matches the type, as the previous section showed.
B's
__cxa_begin_catchpushes the exception onto B's stack and subtracts 1 from B's count (eh_catch.cc:44,:74-80). - A's code runs
throw;, which calls A's__cxa_rethrow. A's stack is empty.
extern "C" void
__cxxabiv1::__cxa_rethrow ()
{
__cxa_eh_globals *globals = __cxa_get_globals ();
__cxa_exception *header = globals->caughtExceptions;
globals->uncaughtExceptions += 1;
// Watch for luser rethrowing with no active exception.
if (header)
{
...
}
std::terminate ();
}
Listing 4.5-9: __cxa_rethrow, abridged
(libstdc++-v3/libsupc++/eh_throw.cc:101-137).
std::terminatein A's copy calls A's handler (eh_terminate.cc:56-59). The default is the verbose handler. It asks A's copy for the current exception, which reads A's empty stack (eh_type.cc:36-50), and prints the message for "an attempt to rethrow when there is no suitable exception":
else
fputs("terminate called without an active exception\n", stderr);
Listing 4.5-10: the message from the opening of this chapter
(libstdc++-v3/libsupc++/vterminate.cc:92-93. The comment that
names the rethrow case is at :54-56.)
The same split reaches every function that reads the record.
std::current_exception() in A returns an empty exception_ptr while B is
handling the exception (eh_ptr.cc:145-151).
std::uncaught_exceptions() in A still returns 1 after B's handler has finished,
because A added 1 and only B subtracted (eh_catch.cc:147-156).
Freeing the exception survives the split. The thrower stores function
pointers in the exception object: the destructor, the terminate handler that
was current at the throw, and the cleanup function
(eh_throw.cc:65-72). When B finishes its handler,
__cxa_end_catch calls _Unwind_DeleteException
(eh_catch.cc:121-126), which calls the stored cleanup
(libgcc/unwind.inc:281-285). So A's copy frees what A's
copy allocated. The terminate handlers stay split: a std::set_terminate call
in B sets B's copy only, and A's std::terminate reads A's.
Watching it: two shared objects, one rethrow
Three small files reproduce the opening. Nobody ran these commands for this book at the pin. The results described below are what the source cited above predicts.
// a.cc
#include <stdexcept>
void a_throw () { throw std::runtime_error ("from a"); }
void a_rethrow () { throw; }
// b.cc
#include <cstdio>
#include <stdexcept>
void a_throw ();
void a_rethrow ();
extern "C" void b_run ()
{
try
{
try { a_throw (); }
catch (const std::runtime_error &)
{
std::fputs ("caught in b\n", stderr);
a_rethrow ();
}
}
catch (const std::runtime_error &e)
{
std::fprintf (stderr, "caught again: %s\n", e.what ());
}
}
/* main.c */
void b_run (void);
int main (void) { b_run (); return 0; }
Listing 4.5-11: a thrower, a catcher, and a C main with no C++ runtime of its
own.
First with one copy, the g++ default:
$ g++ -shared -fPIC -o liba.so a.cc
$ g++ -shared -fPIC -o libb.so b.cc -L. -la
$ gcc -o main main.c -L. -lb -la
$ LD_LIBRARY_PATH=. ./main
Listing 4.5-12: the control, with the shared libstdc++.
Both handlers run. The rethrow finds the exception on the one stack, and the
outer handler prints caught again: from a. LD_LIBRARY_PATH only lets the
loader find the two libraries in the current directory.
Then with two private copies:
$ g++ -shared -fPIC -static-libstdc++ -Wl,--exclude-libs,ALL -o liba.so a.cc
$ g++ -shared -fPIC -static-libstdc++ -Wl,--exclude-libs,ALL -o libb.so b.cc -L. -la
$ LD_LIBRARY_PATH=. ./main
$ nm -D --defined-only libb.so | grep -c __cxa_begin_catch
Listing 4.5-13: the same program, with a hidden libstdc++ in each object.
caught in b still prints, because B's catch matched A's type by name
(Listing 4.5-7). Then A's __cxa_rethrow finds A's stack empty, and the process
aborts with terminate called without an active exception (Listings 4.5-9 and
4.5-10). If the inner catch had not matched, the message would name the type
instead: "terminate called after throwing an instance of"
(vterminate.cc:67). So the message tells you which test
failed. The nm count is 0 with --exclude-libs and at least 1 without it,
which shows the export difference from the previous section.
Two variations are worth a run. Drop -Wl,--exclude-libs,ALL, and the result
depends on the dynamic loader, which is outside this book. Add
-static-libgcc, and each object also gets a hidden unwinder from
libgcc_eh.a. The manual asks for the shared libgcc in every object that
throws or catches across libraries, and Chapter 4.2 explains that rule.
Why the defaults are what they are: g++ and --with-boot-ldflags
The g++ default is the shared libstdc++ and the shared libgcc. In that
configuration every object in the process uses one libsupc++ and one unwinder,
so every piece of state in this chapter exists once, and no object needs a
special link option.
-static-libstdc++ fits where no exception and no throw; crosses into
another copy: an executable that loads no C++ plugins, or a plugin with a plain
C API that catches all its own exceptions. The manual's reason for the option
is to "freeze the version of libstdc++ used by the program without going all
the way to a fully static link"
(invoke.texi:19415-19426).
GCC uses that choice for itself. In stages 2 and 3 of a bootstrap, the default
linker flags are -static-libstdc++ -static-libgcc
(configure.ac:1947-1962). Stage 1 uses the same pair when the
build compiler supports it (:1918-1934). The install manual
documents both defaults, under --with-stage1-ldflags and
--with-boot-ldflags, on its Configuration page
(gcc/doc/install.texi:2516-2532). GCC's own sources are compiled with
-fno-exceptions -fno-rtti (gcc/configure.ac:641-644), and its
programs are executables, so none of the state in this chapter has a second
copy to disagree with. Chapter 2.5 covers
the bootstrap itself.
The switch behind both defaults records the opposite case. It is on only when
the tree contains gcc/configure (configure.ac:1526-1530),
and its comment says why:
# Whether or not to use -static-libstdc++ and -static-libgcc. The
# default is yes if gcc is being built; no otherwise. The reason for
# this default is that gdb is sometimes linked against GNU Source
# Highlight, which is a shared library that uses C++ exceptions. In
# this case, -static-libstdc++ will cause crashes.
Listing 4.5-14: the static runtime, switched off for a program that shares
exceptions with a library (configure.ac:1905-1909).
The comment names the symptom and not the mechanism. The option it introduces,
--with-static-standard-libraries, has a --help string
(configure.ac:1910-1916) and no entry in the install
manual.
Bare metal: no libgcc_s, and --disable-libstdcxx-verbose
On a bare-metal target the choice is already made. t-slibgcc is the fragment
that sets SHLIB = true (gcc/config/t-slibgcc:1-2), and the
driver defines ENABLE_SHARED_LIBGCC only when SHLIB is set and shared
libraries are enabled (gcc/Makefile.in:2611).
*-*-linux* adds the fragment (config.gcc:888-895).
arm*-*-eabi* builds its fragment list from arm/t-arm, arm/t-arm-elf and
arm/t-bpabi, without it (config.gcc:1497-1511). So an
arm-none-eabi driver keeps the plain -lgcc spec that Chapter 1.3 showed
before the rewrite, g++ never adds -shared-libgcc
(g++spec.cc:297-301), and -static-libgcc changes
nothing. The manual says the same: "If no shared version of libgcc was built
when the compiler was configured, these options have no effect"
(invoke.texi:19340-19347).
With no dynamic loader, every runtime is an archive, and the linker copies each member into the one image at most once. The second-copy problem cannot happen. The question becomes size: which members the image pulls in, and how much of each it keeps. Two libstdc++ build settings decide most of it.
libstdc++ compiles every source with -ffunction-sections -fdata-sections when
the compiler accepts them (acinclude.m4:131-159, used in
CONFIG_CXXFLAGS at Makefile.in:413-415). A link with the
linker's --gc-sections can then drop unused functions inside a member, and
not only whole members.
The default terminate handler is the other setting, and its comment states the cost:
/* We default to the talkative, informative handler in a normal hosted
library. This pulls in the demangler, the dyn-string utilities, and
elements of the I/O library. For a low-memory environment, you can return
to the earlier "silent death" handler by configuring GCC with
--disable-libstdcxx-verbose and rebuilding the library.
In a freestanding environment, we default to this latter approach. */
Listing 4.5-15: what the verbose handler costs
(libstdc++-v3/libsupc++/eh_term_handler.h:27-32).
The libstdc++ manual documents --disable-libstdcxx-verbose on its
Configure page
(libstdc++-v3/doc/xml/manual/configure.xml:382-392). The option sets
_GLIBCXX_VERBOSE to 0 (acinclude.m4:3425-3438), and the
handler becomes std::abort (eh_term_handler.h:34-39). A
toolchain configured --with-newlib builds a hosted libstdc++ by default
(acinclude.m4:3368-3377), so it gets the verbose handler
unless you configure it away. Whether to compile with -fno-exceptions at all
is Chapter 4.3's question.
The other runtimes: -static-libasan, -static-libgfortran, -static-libgo
libstdc++ is not the only runtime with a static switch. The other language
runtimes and the sanitizers use the same -Bstatic and -Bdynamic wrap,
written either in a language driver or in a spec. Two common runtimes have no
switch at all:
| Library | Pulled in by | Static switch | Implemented in |
|---|---|---|---|
| libstdc++ | g++ | -static-libstdc++ | g++spec.cc:235-243 |
| libgfortran | gfortran | -static-libgfortran | gfortranspec.cc:163-178, :255-258 |
| libgo | gccgo | -static-libgo | gospec.cc:230-233, :370-391 |
| libasan, libtsan, liblsan, libhwasan | -fsanitize= | -static-libasan and so on | gcc.cc:771-841, on GNU/Linux gnu-user.h:129-155 |
| libubsan | -fsanitize=undefined | -static-libubsan | gcc.cc:843-852 |
| libgomp | -fopenmp, -fopenacc | none | gcc.cc:1171-1172 |
| libssp | -fstack-protector*, if the C library lacks it | none | gcc.cc:994-1003 |
The manual documents the sanitizer switches next to -static-libgcc under Link
Options (invoke.texi:19375-19414). Two rules in the specs
are not in that text. On GNU/Linux, -static-libasan links the runtime with
--whole-archive into an executable, and links no libasan at all into a
shared object. The comment explains: "the executable should be compiled with
-static-libasan in that case" (gnu-user.h:129-133). That is this
chapter's rule written into a spec: a runtime with global state gets one copy,
in the executable. And -static with -fsanitize=address is not a static ASan
link. It is an error, "cannot specify -static with -fsanitize=address"
(gcc.cc:1114-1119).
Three things to carry away
A static runtime is a private copy of its code and its state. libstdc++'s archive is built to go into shared objects, and its symbols are exported unless you hide them.
A catch matches across copies, because libstdc++ compares type names.
Pointer comparison was the default on targets with weak symbols only up to
GCC 4.4.
throw;, std::current_exception and std::uncaught_exceptions see only
their own copy. The per-thread exception record is a static variable in
eh_globals.cc.
Things that surprise people
-static-libstdc++ does not make libgcc static. g++ still adds
-shared-libgcc, so the process keeps one unwinder.
A plugin built with -static-libstdc++ exports the libstdc++ functions it
copied. libgcc's archive is hidden, and libstdc++'s is not. Add
-Wl,--exclude-libs,ALL to hide them.
-static-libgcc does nothing on arm-none-eabi. No shared libgcc exists
there, and the driver never rewrites the libgcc spec.
gcc -static -fsanitize=address is an error, and -shared -static-libasan
links no ASan runtime into the shared object.
Documentation coverage
The GCC manual's Link Options node (gcc/doc/invoke.texi:19067)
documents -static-pie (:19285), -static (:19319), -shared-libgcc and
-static-libgcc with the exception rationale (:19340), the sanitizer switches
(:19375-19414) and -static-libstdc++ (:19415). The install manual's
Configuration page documents the static defaults of
--with-stage1-ldflags and --with-boot-ldflags (gcc/doc/install.texi:2516
and :2528). The libstdc++ manual's Configure page
documents --disable-libstdcxx-verbose
(libstdc++-v3/doc/xml/manual/configure.xml:382). The Itanium C++ ABI
specifies type_info equality as address equality (§2.9.3).
What is not documented:
- What happens when two shared objects each link
libstdc++.a. No manual covers it. The options are documented one by one, and the interaction is not. - That
catchstill matches across copies, because libstdc++ comparestype_infonames withstrcmp. Only the<typeinfo>comment says so, and the Itanium ABI describes address comparison. - That
throw;,std::current_exception()andstd::uncaught_exceptions()read per-copy state, and that a rethrow in the wrong copy terminates with "without an active exception". - That
libstdc++.ais position-independent on purpose, without compatibility symbols or symbol versions. OnlyMakefile.amcomments say so. - That
libgcc.ais compiled with hidden visibility andlibstdc++.ais not, so only libstdc++ is re-exported by a shared object. - That
-staticon GNU/Linux drops--eh-frame-hdr, and thatcrtbeginT.oregisters the unwind tables itself. - That
-static-libasanlinks nothing into a-sharedlink on GNU/Linux. --with-static-standard-libraries, which exists only as aconfigure --helpstring.
Next: Part V goes inside cc1, and starts with the three representations every
function passes through, and why GCC needs all three.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
5.1 GENERIC, GIMPLE and RTL: three representations, and why there are three
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
You ask cc1 to show its work on a nine-line function, and you get three files
that do not look like the same program. In the first, your for loop is already
a set of labels and gotos. In the second, variables that you never declared
appear, with names such as _1, and your && is gone. In the third, there is no
% at all, but there is an instruction with two results and a register that
your code never mentioned.
Each file is in a different language, and cc1 uses all three on purpose.
GENERIC has the shape of the source. GIMPLE is flat and has the same form on
every target. RTL describes the target's instructions. Two conversions connect
them, and nearly everything else in the compiler works inside one of the three.
This chapter assumes Chapter 1.1, where the driver runs
cc1 and cc1 writes the .s file. Everything in this chapter happens inside
that one process.
count.c: the example for all of Part V
Every chapter in Part V uses this one function, so that their dumps agree:
int
count_divisible (const long long *v, int n, long long d)
{
int count = 0;
for (int i = 0; i < n; i++)
if (v[i] != 0 && v[i] % d == 0)
count++;
return count;
}
It has a loop, a short-circuit &&, and a 64-bit remainder. On x86-64 the
remainder is one instruction. On a Cortex-M4 it is a call into libgcc. Chapters
5.5 and 5.6 are built on that difference, and this chapter shows it once, in the
RTL section.
Ask for one dump from each representation:
$ gcc -O2 -c -fdump-tree-original -fdump-tree-gimple -fdump-rtl-expand count.c
$ ls count.c.*
Each flag writes one file next to the object file. Its name is the source file
name, a pass number, a phase letter and the dump name, so the three files end in
.original, .gimple and .expand. The GCC manual documents the dump options
and this naming rule under Developer Options.
Chapter 5.2 explains where the numbers come
from.
Add -raw to a tree dump, as in -fdump-tree-original-raw, to see the data
structures instead of C-like text. The same manual page documents raw as "a
raw representation of the tree". In that form the original dump prints each
node with its name from tree.def (tree-dump.cc:257-262).
The gimple dump prints each assignment as gimple_assign, followed by the
name of its operation in angle brackets
(gimple-pretty-print.cc:654-656).
No compiler ran while this chapter was written, so it shows no dump text. Each description of a dump below comes from the code that prints it.
GENERIC: nested tree nodes with codes from tree.def
A front end parses your function into tree nodes. Every node starts with a
code (tree-core.h:1116-1117), and the macro TREE_CODE reads it
(tree.h:324). An expression node also holds its operands:
struct GTY(()) tree_exp {
struct tree_typed typed;
location_t locus;
tree GTY ((length ("TREE_OPERAND_LENGTH ((tree)&%h)"))) operands[1];
};
Listing 5.1-1: the operands of an expression are more trees
(gcc/tree-core.h:1670-1674).
An operand can be any tree, including another expression. So an expression
nests as deep as the source does. The C parser turns % into TRUNC_MOD_EXPR,
== into EQ_EXPR and && into TRUTH_ANDIF_EXPR
(c/c-parser.cc:10277-10336). A subscript on a pointer becomes
a load through a pointer sum (c/c-typeck.cc:3429-3431), and the
front end scales the index by the size of the element
(c-family/c-common.cc:3484-3500). The right half of the
condition in count.c, v[i] % d == 0, is one tree. This sketch leaves out the
type conversions:
EQ_EXPR
├── TRUNC_MOD_EXPR
│ ├── INDIRECT_REF
│ │ └── POINTER_PLUS_EXPR
│ │ ├── PARM_DECL v
│ │ └── i times sizeof (long long)
│ └── PARM_DECL d
└── INTEGER_CST 0
Each code is one line in tree.def, with a printable name and the number of
operands:
/* Four kinds of remainder that go with the four kinds of division: */
/* The sign of the remainder is that of the dividend. */
DEFTREECODE (TRUNC_MOD_EXPR, "trunc_mod_expr", tcc_binary, 2)
Listing 5.1-2: C's % in the tree vocabulary
(gcc/tree.def:750-753).
GENERIC knows what the source language knows: types, declarations, scopes, and
expressions with side effects in any position. The internals manual defines it
by its vocabulary: "If you can express it with the codes in gcc/tree.def, it's
GENERIC" (GENERIC).
Why GENERIC: every front end hands over the same thing
While a front end parses, it may use any representation of its own (Parsing pass). What it hands to the rest of the compiler is GENERIC. The C front end does that at the end of every function body:
/* Genericize before inlining. Delay genericizing nested functions
until their parent function is genericized. Since finalizing
requires GENERIC, delay that as well. */
if (DECL_INITIAL (fndecl) && DECL_INITIAL (fndecl) != error_mark_node
&& !undef_nested_function)
{
if (!decl_function_context (fndecl))
{
invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
c_genericize (fndecl);
...
cgraph_node::finalize_function (fndecl, false);
}
Listing 5.1-3: the hand-off from the C front end, abridged
(gcc/c/c-decl.cc:11521-11541).
c_genericize converts "from C frontend trees to GENERIC"
(c-family/c-gimplify.cc:747-751). The C parser builds a for
loop as a FOR_STMT (c/c-parser.cc:9299). That code comes from
c-common.def (:63), not from tree.def, so it is not
GENERIC. c_genericize rewrites the loop into labels and gotos
(Chapter 5.4 shows how), and only then writes the
original dump
(:785-805). That is why the original dump shows no for.
The Fortran front end builds GENERIC from a private representation of its own.
It writes the same dump, under the comment "Output the GENERIC tree"
(fortran/trans-decl.cc:8198-8199), and then calls the same
cgraph_node::finalize_function (:8228). After that call, no code
needs to know which language the function came from.
GENERIC is the contract between a front end and the rest of GCC. Each front end can produce it without the others, and every pass downstream is shared. That is why Part V never opens a front end.
GIMPLE: gimple tuples whose operands are still trees
The first arrow, from GENERIC to GIMPLE, is gimplify_function_tree in
gimplify.cc. It is not a pass in passes.def. cgraph_node::analyze calls it
when the call graph analyses a function, just before the lowering passes run
(cgraphunit.cc:684-699). It replaces the body:
/* The tree body of the function is no longer needed, replace it
with the new GIMPLE body. */
seq = NULL;
gimple_seq_add_stmt (&seq, bind);
gimple_set_body (fndecl, seq);
Listing 5.1-4: the GENERIC body is dropped
(gcc/gimplify.cc:21055-21059).
At its end, the same function writes the gimple dump
(gimplify.cc:21155-21160).
Chapter 5.4 follows the conversion itself.
A GIMPLE statement is a gimple object from gimple.h, not a tree. Its first
field is a code from gimple.def (gimple.h:220-226), such as
GIMPLE_ASSIGN, GIMPLE_COND or GIMPLE_CALL. The rule that makes GIMPLE flat
is in the comment on the assignment:
/* GIMPLE_ASSIGN <SUBCODE, LHS, RHS1[, RHS2]> represents the assignment
statement
LHS = RHS1 SUBCODE RHS2.
SUBCODE is the tree code for the expression computed by the RHS of the
assignment. It must be one of the tree codes accepted by
get_gimple_rhs_class. If LHS is not a gimple register according to
is_gimple_reg, SUBCODE must be of class GIMPLE_SINGLE_RHS.
LHS is the operand on the LHS of the assignment. It must be a tree node
accepted by is_gimple_lvalue.
RHS1 is the first operand on the RHS of the assignment. It must always be
present. It must be a tree node accepted by is_gimple_val.
RHS2 is the second operand on the RHS of the assignment. It must be a tree
node accepted by is_gimple_val. This argument exists only if SUBCODE is
of class GIMPLE_BINARY_RHS. */
DEFGSCODE(GIMPLE_ASSIGN, "gimple_assign", GSS_WITH_MEM_OPS)
Listing 5.1-5: one operation, simple operands
(gcc/gimple.def:82-101).
is_gimple_val accepts "an identifier or a constant"
(gimple-expr.cc:833-850). An operand cannot be an expression.
So a GIMPLE assignment does one operation, and the gimplifier moves each inner
operation into a statement of its own, with a temporary for its result. The
internals manual gives the smallest case under Operands:
a = b + c + d
T1 = b + c;
a = T1 + d;
Listing 5.1-6: the manual's before and after
(gcc/doc/gimple.texi:563-568).
Apply the same rule to the tree for v[i] % d == 0. Each interior node becomes a
statement: the scaled index, the pointer sum, the load, the remainder. The
comparison with zero does not become an assignment. A GIMPLE_COND holds a
comparison code, two simple operands, and the labels for its two outcomes
(gimple.def:33-46). Its code "must be of class
tcc_comparison". TRUTH_ANDIF_EXPR is of class tcc_expression
(tree.def:830), so a && cannot be the condition of a GIMPLE_COND.
The gimplifier breaks it "into the equivalent sequence of conditionals"
(gimplify.cc:5108-5114), and Chapter 5.4 follows that code.
Two facts about GIMPLE confuse people who read its source.
GIMPLE statements are tuples, but their operands are trees. The internals
manual says it in one line: "All gimple operands are of type tree"
(gimple.texi:656). A variable,
a constant and a temporary in GIMPLE are the same kind of tree node that
GENERIC used. The first GIMPLE was built from trees, as the manual records in
its GIMPLE chapter, and the tuples kept trees as their
operands. So code in the middle end calls TREE_CODE on GIMPLE operands, and
the functions in gimplify.cc pass tree * arguments.
GIMPLE uses the tree codes for its operations. The remainder in a GIMPLE
assignment is still TRUNC_MOD_EXPR, stored in the statement's subcode:
/* The SUBCODE field can be used for tuple-specific flags for tuples
that do not require subcodes. Note that SUBCODE should be at
least as wide as tree codes, as several tuples store tree codes
in there. */
unsigned int subcode : 16;
Listing 5.1-7: a tree code inside a GIMPLE tuple
(gcc/gimple.h:256-260).
gimple_assign_rhs_code returns that field as an enum tree_code
(gimple.h:2895-2910). So to find every place where the compiler
handles % before the target appears, search for TRUNC_MOD_EXPR. The one name
finds the front end, the gimplifier and the GIMPLE passes.
Why GIMPLE: one form for every target
GIMPLE has no nested expressions and no structured control flow, and its statements have the same form on every target. The internals manual names what that buys: "GIMPLE is used for target and language independent optimizations (e.g., inlining, constant propagation, tail call elimination, redundancy elimination, etc)" (Tree SSA). A pass that sees one operation per statement, with simple operands, finds every use of a value without a walk through nested trees. It is written once, and it runs for x86-64 and for Arm.
The pass list shows where the weight is. passes.def has 381 NEXT_PASS lines.
285 come before pass_expand, where the function is GIMPLE, and 94 come after
it (passes.def:453).
"Target-independent" does not mean that GIMPLE knows nothing about the target.
The type sizes are the target's: the sizeof (long long) in the index
arithmetic came from it. Some passes also ask the target questions. For example,
the vectorizer asks whether masked stores are expensive
(tree-vectorizer.cc:1409-1410). What GIMPLE does not contain is
the target's instructions. TRUNC_MOD_EXPR is the same statement whether or not
the machine can divide.
SSA names: why the dumps say count_5, _3 and d_7(D)
Most GIMPLE passes need the function in static single assignment (SSA) form.
Each name is assigned in exactly one place. Where two control paths meet with
different values, a PHI node merges them into a new name. The internals
manual explains the form, with an example of a merge, under SSA.
An SSA name is a tree with the code SSA_NAME (tree.def:1031).
It holds the variable that it is a version of, and a pointer to the one GIMPLE
statement that sets it (tree-core.h:1690-1697). So the two
data structures point at each other: statements hold trees, and SSA names point
back at statements. The dump printer spells an SSA name like this:
case SSA_NAME:
if (SSA_NAME_IDENTIFIER (node))
{
...
}
pp_underscore (pp);
pp_decimal_int (pp, SSA_NAME_VERSION (node));
if (SSA_NAME_IS_DEFAULT_DEF (node))
pp_string (pp, "(D)");
if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (node))
pp_string (pp, "(ab)");
break;
Listing 5.1-8: how a dump spells an SSA name, abridged
(gcc/tree-pretty-print.cc:3740-3758).
The omitted lines print the name of the variable. Read the names in the title with that code:
count_5is a version of the variablecount: the variable's name, an underscore, and a version number._3has no name. It is a temporary with no user variable behind it (tree.h:2137-2143).d_7(D)is a default definition: the value thatdhas when the function starts. A default definition is made for a variable whose first use in the function is a read (tree.h:2176-2182). For a parameter, that value is the argument.
The version number does not count assignments to one variable. The comment on
SSA_NAME_VERSION says "in tree SSA, version numbers are not per variable and
may be recycled" (tree.h:2160-2162). The version is the
name's index in one table that holds every SSA name of the function
(tree-ssanames.cc:382-388). So count_3 and _3 never exist in
one function at the same time.
SSA is a property that GIMPLE is put into, and it happens in two steps. The
gimplifier makes its own temporaries SSA names at once. It opens its context
with SSA on (gimplify.cc:20807-20808), and each new temporary of a
register type becomes an SSA name:
if (allow_ssa
&& gimplify_ctxp->into_ssa
&& is_gimple_reg_type (TREE_TYPE (val)))
{
t = make_ssa_name (TYPE_MAIN_VARIANT (TREE_TYPE (val)));
if (! gimple_in_ssa_p (cfun))
{
const char *name = get_name (val);
if (name)
SET_SSA_NAME_VAR_OR_IDENTIFIER (t, create_tmp_var_name (name));
}
}
Listing 5.1-9: temporaries are SSA names from the start
(gcc/gimplify.cc:686-697).
The inner if gives a temporary an identifier when its value has a name.
create_tmp_var_name builds that identifier from the name and a counter
(gimple-expr.cc:421-436), so not every temporary prints as a bare
_3.
Your own variables, count and i, are still plain variables in the gimple
dump. A later pass named ssa renames them and inserts the PHI nodes
(tree-into-ssa.cc:2458-2469, at passes.def:56).
Chapter 5.4 follows that pass. Its descriptor declares that it provides
PROP_ssa, a bit that the pass manager keeps for each function
(tree-pass.h:212). The expand pass requires that bit, as
Listing 5.1-12 shows.
RTL: rtx expressions with a machine mode, in a chain of insns
RTL is a different data structure again. An rtx starts with two fields:
struct GTY((desc("0"), tag("0"),
chain_next ("RTX_NEXT (&%h)"),
chain_prev ("RTX_PREV (&%h)"))) rtx_def {
/* The kind of value the expression has. */
ENUM_BITFIELD(machine_mode) mode : MACHINE_MODE_BITSIZE;
/* The kind of expression this is. */
ENUM_BITFIELD(rtx_code) code: RTX_CODE_BITSIZE;
Listing 5.1-10: every rtx has a mode and a code
(gcc/rtl.h:312-319).
The codes come from rtl.def, and the mode is a machine mode, such as DImode
for a 64-bit integer. In the dumps, the mode follows the code after a colon, so
(reg:SI 38) is a reg in SImode. The internals manual documents this
notation under Machine Modes. A function in RTL is a chain of
insns. Some insns are instructions, and others are labels, jump tables and notes
(Insns). Inside an instruction, every assignment is a SET, and
an instruction that assigns more than one location wraps its SETs in a
PARALLEL (rtl.def:289-295).
RTL knows three things that GIMPLE does not.
Registers. A reg with a number below FIRST_PSEUDO_REGISTER is a machine
register. Above it, the number names a pseudo register, and "the compiler's
strategy is to generate code assuming an unlimited number of such pseudo
registers, and later convert them into hard registers or into memory
references" (Regs and Memory). Expand writes pseudos. The
register allocator, pass_ira and pass_reload
(passes.def:511-512), turns them into machine registers.
Modes instead of types. long long becomes DImode. RTL records the size
and kind of a value, not the C type.
The target's instructions. An instruction in RTL must match a pattern that the target's machine description defines. Here is how the x86-64 port describes its divide instruction:
(define_expand "<u>divmod<mode>4"
[(parallel [(set (match_operand:SWIM248 0 "register_operand")
(any_div:SWIM248
(match_operand:SWIM248 1 "register_operand")
(match_operand:SWIM248 2 "nonimmediate_operand")))
(set (match_operand:SWIM248 3 "register_operand")
(<paired_mod>:SWIM248 (match_dup 1) (match_dup 2)))
(clobber (reg:CC FLAGS_REG))])])
Listing 5.1-11: one x86-64 instruction gives the quotient and the remainder
(gcc/config/i386/i386.md:11371-11378).
SWIM248 and any_div are iterators, so this one pattern covers several modes,
and signed and unsigned division. Chapter 5.6
explains iterators. Read the body as RTL: a PARALLEL of two SETs, one with
div and one with mod, and a clobber that says the flags register is
destroyed. The machine computes both results at once and changes the flags, and
RTL must say so, because the register allocator and the later passes rely on
it. The x86-64 port has no pattern that computes only a remainder, so for %
expand falls back to this one (expmed.cc:5281-5299). The
DI member of SWIM248 applies only with TARGET_64BIT
(i386.md:1191-1192), so with -m32 this pattern has no 64-bit form.
The Arm port defines integer division only in SImode, and only for cores with
a divide instruction (config/arm/arm.md:5129-5135). An
arm-none-eabi compiler uses the Arm EABI (config.gcc:1497-1503,
config/arm/bpabi.h:27-30), and for that ABI the port names a library
function for 64-bit division with remainder
(config/arm/arm.cc:2637-2639). With no instruction to use,
expand calls that function and keeps the remainder
(expmed.cc:5343-5361). So for
arm-none-eabi-gcc -O2 -mcpu=cortex-m4, the same GIMPLE statement becomes a call
to __aeabi_ldivmod in RTL. libgcc supplies that function
(libgcc/config/arm/bpabi.S:174-188).
Chapter 4.1 followed such helpers from the
library side, and Chapter 5.5 shows where expand makes
the choice.
Why RTL: allocation and instruction selection need the machine
The passes after expand choose instructions, assign registers, schedule, and
print assembly. Each of those needs the facts in Listing 5.1-11: which operands
must be registers, which registers an instruction destroys, which modes exist.
GIMPLE does not carry them, by design. RTL carries them in every insn. The
textual form of RTL is also the language of the machine description (RTL
Representation). Reading an RTL dump and reading a .md file is
the same skill, which Chapter 5.6 uses.
The two arrows: gimplify_function_tree and pass_expand
| GENERIC | GIMPLE | RTL | |
|---|---|---|---|
| Data structure | tree (tree-core.h) | gimple with tree operands (gimple.h) | rtx (rtl.h) |
| Codes | tree.def, plus front-end files such as c-common.def | gimple.def, plus tree codes for operations | rtl.def |
| Built by | the front end (c_genericize for C) | gimplify_function_tree | pass_expand |
| First dump | -fdump-tree-original | -fdump-tree-gimple | -fdump-rtl-expand |
| Target instructions | no | no | yes |
The first arrow is a function call, as Listing 5.1-4 showed. The second arrow is a pass, and its descriptor states the change of representation:
const pass_data pass_data_expand =
{
RTL_PASS, /* type */
"expand", /* name */
OPTGROUP_NONE, /* optinfo_flags */
TV_EXPAND, /* tv_id */
( PROP_ssa | PROP_gimple_leh | PROP_cfg
| PROP_gimple_lcx
| PROP_gimple_lvec
| PROP_gimple_lva), /* properties_required */
PROP_rtl, /* properties_provided */
( PROP_ssa | PROP_gimple ), /* properties_destroyed */
0, /* todo_flags_start */
0, /* todo_flags_finish */
};
Listing 5.1-12: expand needs SSA GIMPLE, makes RTL, and destroys the GIMPLE
(gcc/cfgexpand.cc:6973-6987).
pass_expand is an RTL_PASS, and it is the line in passes.def that splits
the list in two:
NEXT_PASS (pass_warn_function_noreturn);
NEXT_PASS (pass_expand);
NEXT_PASS (pass_rest_of_compilation);
PUSH_INSERT_PASSES_WITHIN (pass_rest_of_compilation)
NEXT_PASS (pass_instantiate_virtual_regs);
Listing 5.1-13: the boundary in the pass list
(gcc/passes.def:451-457).
Every pass above that line works on GIMPLE. Every pass inside
pass_rest_of_compilation works on RTL, and the last of them, pass_final,
prints the assembly (passes.def:563). No pass converts back.
Chapter 5.3 explains how the pass manager reads
this file.
So when a dump surprises you, first ask which representation it is in. A
GENERIC or GIMPLE dump comes from a front end, from the gimplifier, or from a
pass that has no notion of instructions. An RTL dump comes from expand or from a
pass that sees the target. The answer tells you which half of passes.def to
read.
Three things to carry away
GENERIC is what every front end hands over, GIMPLE is what the shared optimisers work on, and RTL is what the target's instructions are written in.
There are two arrows: gimplify_function_tree, a function call, and
pass_expand, a pass. Every other pass works inside one representation.
GIMPLE is not a separate world from trees. Its operands are tree nodes, its
operations are tree codes, and an SSA name is a tree that points back at a
statement.
Things that surprise people
The original dump has no for loop. The C front end turns loops into
gotos in c_genericize, before it writes that dump.
_7 and count_7 cannot both exist. SSA version numbers index one table
for the whole function, and they say nothing about how often a variable
is assigned.
The gimple dump is half in SSA. Temporaries are SSA names from the start.
Your own variables become SSA names only in the later ssa pass.
Gimplification is not in passes.def. cgraph_node::analyze calls it
directly, so you will not find it in the pass list.
Documentation coverage
The internals manual is the primary source for this chapter, and it is strong.
It has a chapter for each representation: GENERIC
(gcc/doc/generic.texi:9), GIMPLE (gcc/doc/gimple.texi:6),
and RTL Representation (gcc/doc/rtl.texi:5). Its
Tree SSA chapter (gcc/doc/tree-ssa.texi:9) compares the
three, and its SSA node (:440) explains versions and PHI nodes.
The Passes chapter (gcc/doc/passes.texi:7) describes the
parsing, gimplification and RTL generation steps. This chapter adds the reasons
for three representations and the route from each dump to its source.
The GCC manual documents the dump options in
Developer Options (gcc/doc/invoke.texi:20326): the dump file name
(:20349-20362), -fdump-rtl-expand (:20496-20498), -fdump-tree- with its
options (:20897-20906), and raw (:20928-20930).
What is not documented:
- The dump names
originalandgimple. The GCC manual lists neither among its tree dumps. Only the internals manual mentions-fdump-tree-gimple(gimple.texi:68-69), and neither manual mentions-fdump-tree-original. - That the front end, not a pass, writes the
originaldump, and that the C front end has turned loops intogotos before it does. - That gimplification is a function call from the call graph and not a pass in
passes.def. - That temporaries are SSA names from the start of gimplification, while user
variables become SSA names in the
ssapass. - How a dump spells an SSA name:
name_N,_N,(D)and(ab). The rule that version numbers are shared across variables is only in a comment intree.h. - That expand requires
PROP_ssaand destroys the GIMPLE properties. - The internals manual says that the C and C++ front ends convert "directly from
front end trees to GIMPLE" and not first to GENERIC (
gimple.texi:56-66). At 15.2 the C front end callsc_genericize, which says it converts "from C frontend trees to GENERIC", and gimplification follows. The manual's paragraph describes an older design.
Next: how cc1 names its dump files, where the number in a name such as
count.c.NNNt.gimple comes from, and how to find the pass that changed your
code.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
5.2 Reading the dumps: from a file name to the pass that wrote it
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
You add -fdump-tree-all to see what the optimiser did to a loop. The directory
fills with files named like count.c.007t.gimple. A colleague on GCC 14 sends
the same dump as count.c.006t.gimple. A script that opened
count.c.005t.original finds nothing after the upgrade. Each file came from one
step inside cc1, and the name says which step, once you know how GCC builds it.
A dump file name is the base name, a number from one counter, a letter for the
kind of dump, and the pass name. cc1 hands out the numbers when it starts,
before it reads -O2.
This chapter assumes Chapter 5.1, for the three
representations and for count.c, the function that all of Part V compiles, and
Chapter 1.4, for how -dumpdir and
-dumpbase place every auxiliary file.
Nothing here needs a GCC build. The commands run on an installed gcc, and every
source file below can be read on the GCC mirror at the pin. The chapter shows no
compiler output, because the book reads the pin as source. Where the source fixes
a result, the text says what you will see.
The four parts of count.c.007t.gimple: get_dump_file_name
$ gcc -O2 -c -fdump-tree-all -fdump-rtl-all count.c
$ ls count.c.*
One function in gcc/dumpfile.cc builds every one of those names:
/* If available, use the command line dump filename. */
if (dfi->pfilename)
return xstrdup (dfi->pfilename);
if (dfi->num < 0)
dump_id[0] = '\0';
else
{
/* (null), LANG, TREE, RTL, IPA. */
char suffix = " ltri"[dfi->dkind];
if (snprintf (dump_id, sizeof (dump_id), ".%03d%c", dfi->num, suffix) < 0)
dump_id[0] = '\0';
}
if (part != -1)
{
char part_id[8];
snprintf (part_id, sizeof (part_id), ".%i", part);
return concat (dump_base_name, dump_id, part_id, dfi->suffix, NULL);
}
else
return concat (dump_base_name, dump_id, dfi->suffix, NULL);
Listing 5.2-1: get_dump_file_name (gcc/dumpfile.cc:340-362).
Read count.c.007t.gimple against the last line:
count.cisdump_base_name. The driver passes-dumpdirand-dumpbase count.ctocc1, as Chapter 1.4 showed, andfinish_optionsjoins the two (gcc/opts.cc:1066-1085). The base keeps the.c. With-c, the files land next tocount.o. The GCC manual documents this placement, and the examplefoo.c.???r.final, under-oin Overall Options (invoke.texi:1780-1801)..007is the dump's number, printed with%03d. The zero padding makeslslist the files in number order.tis the kind. The string" ltri"is indexed byenum dump_kind, whose values areDK_none,DK_lang,DK_tree,DK_rtlandDK_ipa(gcc/dumpfile.h:63-70). Solis a front-end dump,ta tree dump,ran RTL dump andian IPA dump. GENERIC and GIMPLE are both made oftreenodes (Chapter 5.1), so both gett. The GENERIC dump.originalis atfile..gimpleis the suffix. For a pass, it is a dot, the pass name and an instance number.
The first branch is the escape hatch. -fdump-tree-gimple=out.txt sets
pfilename, and that name replaces all four parts. The names stdout, - and
stderr open the standard streams instead of a file
(dumpfile.cc:370-385).
The Developer Options node of the GCC manual documents this rule, and the four
letters (Developer Options, invoke.texi:20349-20362). It also
says that "the pass number is determined by the order passes are registered with
the compiler's pass manager". The rest of this chapter reads that order in the
source.
One counter for every dump: dump_register
Every dump that registers while cc1 runs gets its number from one line,
int num = m_next_dump++; (dumpfile.cc:221). The counter
starts at 1 (:183), and the same counter serves all four
letters. No two dumps in one cc1 share a number, so the letter never decides
the order of an ls.
A few dumps are not passes. They sit in a static table, and they get their numbers here:
lang_hooks.register_dumps (this);
/* If this assert fails, some FE registered more than
FIRST_ME_AUTO_NUMBERED_DUMP - FIRST_AUTO_NUMBERED_DUMP
dump files. Bump FIRST_ME_AUTO_NUMBERED_DUMP accordingly. */
gcc_assert (m_next_dump <= FIRST_ME_AUTO_NUMBERED_DUMP);
m_next_dump = FIRST_ME_AUTO_NUMBERED_DUMP;
dump_files[TDI_original].num = m_next_dump++;
dump_files[TDI_gimple].num = m_next_dump++;
dump_files[TDI_nested].num = m_next_dump++;
Listing 5.2-2: register_dumps (gcc/dumpfile.cc:263-271).
The front end registers its own dumps first. C++ registers four, .class,
.module, .raw and .coro, which become 001l to 004l
(gcc/cp/cp-objcp-common.cc:605-617). C registers none, because its
hook is the empty default (gcc/langhooks.cc:339-341). Then the
counter jumps to FIRST_ME_AUTO_NUMBERED_DUMP, which is 6
(dumpfile.cc:109-110), whatever the front end did. So at the pin,
for C and C++ alike, .original is 006t, .gimple is 007t and .nested is
008t. The first pass takes the next number.
Three IPA entries in the same table never get a number. .cgraph,
.type-inheritance and .ipa-clones keep the 0 they start with
(dumpfile.cc:101-103), so their files carry 000i.
GCC 15 moved the start of the middle-end numbers up by one. At
releases/gcc-14.2.0,FIRST_ME_AUTO_NUMBERED_DUMPis 5 (gcc/dumpfile.cc:108), and C++ registers three dumps (gcc/cp/cp-objcp-common.cc:602-609). GCC 15 added.coroand raised the constant to 6. GCC 14 writescount.c.005t.original, and GCC 15 writescount.c.006t.original, for a C file that has no C++ in it.
Pass dumps follow passes.def, depth first: register_dump_files
The pass manager's constructor builds the tree of passes from
pass-instances.def, a copy of passes.def that the build generates
(gcc/Makefile.in:2681-2684).
Chapter 5.3 shows how that file lists and
instantiates the passes. After it builds the tree, the constructor registers the
dumps, list by list:
register_dump_files (all_lowering_passes);
register_dump_files (all_small_ipa_passes);
register_dump_files (all_regular_ipa_passes);
register_dump_files (all_late_ipa_passes);
register_dump_files (all_passes);
Listing 5.2-3: the end of the pass_manager constructor (gcc/passes.cc:1654-1658).
Each call walks one list:
do
{
if (pass->name && pass->name[0] != '*')
register_one_dump_file (pass);
if (pass->sub)
register_dump_files (pass->sub);
pass = pass->next;
}
while (pass);
Listing 5.2-4: register_dump_files (gcc/passes.cc:899-909).
The comment above the registration code states the rule in one sentence: "We want
to do this depth first, and independent of whether the pass is enabled or not"
(passes.cc:823-825). Three things follow.
A pass group's members come right after the group. pass_all_optimizations
holds most of the GIMPLE optimisers (gcc/passes.def:198-382),
and its own name, *all_optimizations
(passes.cc:550), starts with a star.
A name that starts with * gets no number and no file. The internals manual
documents this, and the space prefix, under Pass manager
(gcc/doc/passes.texi:170-176). A pass named no-opt dfinit dumps as dfinit
(gcc/df-core.cc:761).
One list holds the GIMPLE and the RTL passes. all_passes ends its GIMPLE
part with pass_expand (passes.def:453). The RTL passes
follow inside pass_rest_of_compilation, down to pass_final
(passes.def:455-563). So the t files of the passes come
before the r files, and the r files start at expand. Three tree dumps that
register late are the exception, and they appear below, next to register_pass.
final is not the last numbered pass. pass_df_finish comes after it
(passes.def:565), and its name is dfinish
(df-core.cc:831).
The numbers give the order in which one function meets the passes. The manual
calls this "generally the same as the order of execution". They do not give the
time order across functions. The comment above the constructor says that the
lowering passes run on every function before the IPA passes start
(passes.cc:1555-1576).
Reading the suffix and the switch: ccp2, split2, -fdump-tree-ccp
register_one_dump_file makes the suffix and the switch names together
(gcc/passes.cc:846-892). The suffix is a dot, the pass name and
an instance number. The type of the pass picks the letter and the switch prefix:
ipa- and i for IPA passes, tree- and t for GIMPLE passes, rtl- and r
for the rest. Chapter 5.3 shows where the name and the instance number come
from. Three facts are enough to read a file name.
A pass listed once has no instance number, as in .expand and .final. A
pass listed more than once is numbered 1, 2 and so on, in passes.def order.
pass_ccp appears five times (passes.def:80, :204,
:260, :354 and :396), so the files are ccp1
to ccp5.
A trailing digit is not always an instance number. split1 to split5 are
five different passes, with the digit in the name itself
(gcc/recog.cc:4481, :4526). .split2 is not
the second instance of a pass called split.
Each dump has two switch names, tree-ccp2 for one instance and tree-ccp
as a glob for all of them (passes.cc:877-878). The matching
code tries exact names first:
for (i = TDI_none + 1; i != TDI_end; i++)
any |= dump_switch_p_1 (arg, &dump_files[i], false);
/* Don't glob if we got a hit already */
if (!any)
for (i = TDI_none + 1; i != TDI_end; i++)
any |= dump_switch_p_1 (arg, &dump_files[i], true);
for (i = 0; i < m_extra_dump_files_in_use; i++)
any |= dump_switch_p_1 (arg, &m_extra_dump_files[i], false);
if (!any)
for (i = 0; i < m_extra_dump_files_in_use; i++)
any |= dump_switch_p_1 (arg, &m_extra_dump_files[i], true);
Listing 5.2-5: exact names, then globs (gcc/dumpfile.cc:1927-1940).
So -fdump-tree-ccp2 enables one dump, and -fdump-tree-ccp enables all five.
-fdump-tree-all is a switch whose entry has no suffix, and it enables every
dump of its kind (dumpfile.cc:1912-1915). It turns on t dumps
only. Add -fdump-rtl-all and -fdump-ipa-all for the other kinds.
-fdump- itself is one option, Joined, in gcc/common.opt
(common.opt:1608-1610). The option parser accepts any text
after it, and dump_switch_p checks that text against the dumps that registered.
A typo gets "unrecognized command-line option" with a "did you mean" hint
(dumpfile.cc:1942-1955). So the valid -fdump- switches are the
dumps that registered in your cc1. The manual's procedure for finding one starts
from -fdump-passes, under -fdump-tree (Developer Options,
invoke.texi:20977-21002).
Words after the pass name, such as -details in -fdump-tree-vect-details, are
split at each -, and an = starts a file name
(dumpfile.cc:1817-1878). The same node documents each
word. One detail it does not give: details also turns on the three message
kinds that -fopt-info prints (dumpfile.cc:128-130).
Numbered before -O2 is read: general_init and the gate
The counter runs at cc1 start-up:
/* Create the singleton holder for global state. This creates the
dump manager. */
g = new gcc::context ();
/* Allow languages and middle-end to register their dumps before the
optimization passes. */
g->get_dumps ()->register_dumps ();
/* Create the passes. */
g->set_passes (new gcc::pass_manager (g));
Listing 5.2-6: general_init (gcc/toplev.cc:1145-1154).
toplev::main calls general_init at toplev.cc:2296 and
decode_options at :2331. The number of a built-in pass depends
on the cc1 binary, not on -O, -f or -m. The options decide something else:
which files appear.
gate_status = pass->gate (cfun);
gate_status = override_gate_status (pass, current_function_decl, gate_status);
...
if (!gate_status)
{
...
current_pass = NULL;
return false;
}
...
pass_init_dump_file (pass);
Listing 5.2-7: execute_one_pass, abridged (gcc/passes.cc:2605-2644).
A pass whose gate says no returns before its dump file opens. A pass that runs
writes the function after it runs, even if it changed nothing
(passes.cc:2734-2735). So a missing number means that the pass
did not run, or that its kind of dump was not enabled. A file identical to the one
before it means that the pass ran and changed nothing.
-Og shows the effect. At -O2, the *all_optimizations group runs, with
the gate optimize >= 1 && !optimize_debug (passes.cc:568-571).
At -Og, the *all_optimizations_g group runs instead, with the gate
optimize >= 1 && optimize_debug (passes.cc:606-609). The
pass_ccp inside the -Og group is the fifth in passes.def. Its gate reads
flag_tree_ccp (gcc/tree-ssa-ccp.cc:3063), which is on from level 1
(opts.cc:597), and -Og selects level 1
(opts.cc:796-800). So after IPA, an -Og compile writes ccp5 and
none of ccp2 to ccp4, and ccp5 has the same number that it would have at
-O2. At -O0 the flag is off, and no ccp file appears.
$ gcc -O2 -c -fdump-tree-all count.c && ls count.c.* > o2.txt && rm count.c.*
$ gcc -Og -c -fdump-tree-all count.c && ls count.c.* > og.txt && rm count.c.*
$ diff o2.txt og.txt
Each line of that diff is a pass that ran at one level and not at the other. A file that both levels wrote has the same name in both lists.
What moves a number: the release, the target, register_pass
Three things change the numbers, and no optimisation option is among them.
The release. passes.def changes between releases, and so did
FIRST_ME_AUTO_NUMBERED_DUMP. The manual says that "the numeric codes are not
stable and may change from one version of GCC to another"
(invoke.texi:21001-21002). Match dumps by name in scripts:
count.c.*t.ccp2, count.c.*r.expand.
The target. pass-instances.def is built from passes.def and
$(PASSES_EXTRA). x86 adds config/i386/i386-passes.def
(gcc/config/i386/t-i386:23), and Arm adds arm-passes.def
(gcc/config/arm/t-arm:205). These files insert passes at named places:
INSERT_PASS_AFTER (pass_postreload_cse, 1, pass_insert_vzeroupper);
INSERT_PASS_AFTER (pass_late_combine, 1, pass_stv, false /* timode_p */);
Listing 5.2-8: two x86 passes join the list
(gcc/config/i386/i386-passes.def:27-28).
At the pin, every x86 insertion lands in the RTL part, the first one after
pass_rtl_ifcvt (i386-passes.def:39, passes.def:471).
Arm inserts one pass, bti, before pass_shorten_branches
(arm-passes.def:21). So gcc on x86-64 and arm-none-eabi-gcc,
both 15.2, agree on every t number and on the number of expand. Their later
r numbers differ.
register_pass after start-up. A pass that joins the list after the
constructor goes through pass_manager::register_pass
(passes.cc:1499-1553), and takes the next free numbers, above
every built-in pass. Plugins do this. So does the SH port, from its
option-override hook (gcc/config/sh/sh.cc:792-817). This is the
case that the manual describes: passes "numbered higher than the pass named
final, even if they are executed earlier" (invoke.texi:20356-20359). The manual also lists "target-specific
passes" there. That holds for SH, but not for x86, Arm and AArch64
(gcc/config/aarch64/t-aarch64:152), which merge their passes at
build time and number them in sequence.
Three tree dumps also register after the pass manager: .statistics,
.earlydebug and .debug (toplev.cc:1158-1159). With
-fdump-tree-all, any of them that is written sorts after the RTL files.
Diffing consecutive dumps to find the pass that changed your code
Each file holds the function as it stood after its pass
(passes.cc:2734-2735). So compare each file with the one before
it, and the first difference names the pass that made it. The manual does not
teach this technique.
changed () {
set -- count.c.[0-9][0-9][0-9]$1.*
while [ $# -ge 2 ]; do
cmp -s "$1" "$2" || echo "$1 -> $2"
shift
done
}
changed t
changed r
Run it in the directory of the dumps. Each line names a pair of consecutive files
that differ. The second file of the pair is the pass to read, with
diff -u on the two files. Keep the two letters apart, because a GIMPLE dump and
an RTL dump never compare as text. Run the loop on plain dumps first. A -details
dump adds the pass's own notes, so every pair would differ. When you have the
pass, run again with -fdump-tree-<pass>-details for its reasoning.
Four things can mislead the diff.
A * pass changes code and writes nothing. *strip_predict_hints replaces
each __builtin_expect call with its first argument
(gcc/predict.cc:4307-4370, name at :4377). Its
change shows up in the next named file.
IPA passes write i files. With -fdump-tree-all alone, a change that an IPA
pass made, such as inlining, appears in the next t file. Add -fdump-ipa-all
to give those passes files of their own.
.original and .gimple are not pass dumps. The C front end writes
.original (gcc/c-family/c-gimplify.cc:785-797) and the
gimplifier writes .gimple (gcc/gimplify.cc:21160). Their
difference is the whole of gimplification, which
Chapter 5.4 reads.
Two compilations are not two passes. To compare one dump from two compilers,
or from two option sets, use -fdump-noaddr and -fdump-unnumbered. The manual
documents both as aids to diff (Developer Options,
invoke.texi:20688 and :20700).
From a dump name to the source file: the pass's name string
The text after the number is the pass's name field, minus the instance number
and minus any prefix before a space. Search for it as a string in a checkout of
the pin:
$ grep -rn '"ccp",' gcc --include='*.cc'
The hit to keep is the one inside a pass_data initializer:
const pass_data pass_data_ccp =
{
GIMPLE_PASS, /* type */
"ccp", /* name */
OPTGROUP_NONE, /* optinfo_flags */
TV_TREE_CCP, /* tv_id */
( PROP_cfg | PROP_ssa ), /* properties_required */
0, /* properties_provided */
0, /* properties_destroyed */
0, /* todo_flags_start */
TODO_update_address_taken, /* todo_flags_finish */
};
Listing 5.2-9: the descriptor that names ccp (gcc/tree-ssa-ccp.cc:3036-3047).
That is the file. The class next to it, pass_ccp, holds the gate and the
execute method (tree-ssa-ccp.cc:3049-3067). The factory
make_pass_ccp (:3077) is what NEXT_PASS (pass_ccp, ...) in
passes.def calls. Count those NEXT_PASS lines to place ccp2: it is the
second, at passes.def:204. An RTL dump works the same way.
"expand", finds gcc/cfgexpand.cc:6976, the entry point of
Chapter 5.5. Chapter 5.3 takes the descriptor and its
fields apart.
-fopt-info: the second stream of every dump
Each dump has two streams: pstream, the dump file, and alt_stream, the
-fopt-info output (gcc/dumpfile.h:295-331). The internals
manual describes both under Dump files and streams
(gcc/doc/optinfo.texi:81-107). A message that a pass prints with
dump_printf_loc can go to either stream, or to both.
-fopt-info picks passes by group, and a pass joins groups in its descriptor. The
group comes from optinfo_flags (passes.cc:879), every
IPA pass is in ipa (:864), and a pass with no group goes into
OTHER (:883-884). No keyword names OTHER
(dumpfile.cc:171-180), so only optall reaches those
passes. The vectorizer, vect, is in both loop and vec
(gcc/tree-vectorizer.cc:1224-1228).
The GCC manual documents the keywords and the defaults under -fopt-info
(Developer Options, invoke.texi:21006-21141). In the code, a
missing message kind becomes optimized, a missing group becomes all groups, and
a missing file becomes stderr (dumpfile.cc:2053-2068).
This is the command for "why did this loop not vectorise?":
$ gcc -O2 -c -fopt-info-vec-missed count.c
At -O2 the vectorizer runs, with the very-cheap cost model
(opts.cc:664-665, :679-680). Each line starts
with file:line:column: missed: (dumpfile.cc:473-490). If the
vectorizer analyses the loop and gives up, it prints this:
if (!loop_vinfo)
if (dump_enabled_p ())
if (opt_problem *problem = loop_vinfo.get_problem ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"couldn't vectorize loop\n");
problem->emit_and_clear ();
}
Listing 5.2-10: the top-level "missed" message (gcc/tree-vectorizer.cc:1099-1106).
The reason comes from problem->emit_and_clear (). The analysis recorded it deep
in its call stack, where messages count as internals, and emit_and_clear
prints it again at the top level, marked MSG_PRIORITY_REEMITTED
(gcc/optinfo.cc:114-129). The design comment in
gcc/opt-problem.h:27-108 explains why. The two streams filter in
opposite ways:
-fopt-infokeeps user-facing and re-emitted messages, and drops internals (dumpfile.cc:1973-1976). Add-internalsto see them.- A dump file keeps user-facing messages and internals, and drops the re-emitted
copy (
dumpfile.cc:1827-1831).
So -fdump-tree-vect-details shows each step of the analysis, with the reason
where it happened. -fopt-info-vec-missed shows the loop and its reason on
your terminal.
The last dump is the assembly: -dp
The .s file can carry the same trail. With -S -dp, final writes a comment
after the first line of each instruction:
fprintf (asm_out_file, "\t%s %d\t",
ASM_COMMENT_START, INSN_UID (debug_insn));
...
int num = INSN_CODE (debug_insn);
fprintf (asm_out_file, "%s", insn_data[num].name);
if (insn_data[num].n_alternatives > 1)
fprintf (asm_out_file, "/%d", which_alternative);
Listing 5.2-11: output_asm_name, abridged (gcc/final.cc:3213-3226).
The number is the insn's UID, the same number that follows insn at the start
of each instruction in the RTL dumps (gcc/print-rtl.cc:934-941). The
name is the machine-description pattern that matched, and the alternative after
the /. The GCC manual documents -dp under Developer Options
(invoke.texi:20661), and -fverbose-asm under
Code Gen Options (invoke.texi:19870).
Chapter 5.6 follows a pattern name into the
.md file.
$ gcc -O2 -S -dp count.c
Breadcrumbs: which dump answers which question
| Question | Where to look |
|---|---|
| Which pass changed this statement? | -fdump-tree-all or -fdump-rtl-all, the changed loop, then diff -u on the pair |
| Which source file holds that pass? | the dump suffix as a "name", string, then NEXT_PASS in passes.def |
| Did the pass run at all? | whether its file exists, or -fdump-passes (Chapter 5.3) |
| Why did this loop not vectorise? | -fopt-info-vec-missed, then -fdump-tree-vect-details |
| Which pattern made this instruction? | -S -dp, then the .md file (Chapter 5.6) |
| Why does my colleague's file have another number? | another release, another target's passes, or a plugin |
| What does the compiler think my types are? | -dM -E (Chapter 2.6) |
Three things to carry away
The name is base, number, letter and pass. " ltri" gives the letter, and
the pass's name string gives the suffix.
The number is registration order, fixed before options. One counter, depth
first through passes.def, so -O2 decides which files appear but not their
numbers.
Diff neighbours, then grep the name. The first changed pair names the pass,
and the pass_data string names its file.
Things that surprise people
-fdump-tree-ccp asks for five dumps. Without an instance number the switch
is a glob over ccp1 to ccp5.
.split2 is a pass, not an instance. Some pass names end in a digit.
A t file can sort after final. .statistics, .earlydebug and .debug
register after every pass.
final is not the last RTL dump. dfinish comes after it.
Upgrading from GCC 14 to 15 renumbers .original. A script that matches
005t stops matching.
Documentation coverage
The GCC manual documents the dump options in Developer Options
(gcc/doc/invoke.texi:20326): the naming rule at :20349-20362, -dp at
:20661, -fdump-noaddr and -fdump-unnumbered at :20688 and :20700,
-fdump-passes at :20880, -fdump-tree with its option words at :20897,
and -fopt-info at :21006. Where dumps land is documented under
-o in Overall Options (:1768, with the dump example at
:1780-1801). The internals manual documents the star and space rules for pass
names in Pass manager (gcc/doc/passes.texi:146), and the two
streams and the optimisation groups in Optimization info
(gcc/doc/optinfo.texi).
What is not documented:
- That one counter numbers every dump, of all four letters, and that the middle end restarts it at 6 whatever the front end registered. It was 5 before GCC 15.
- That the numbers are fixed before
cc1reads its options, so-Ochanges which files appear and never their numbers. - That x86, Arm and AArch64 insert their target passes at build time, so those
passes are numbered in sequence. The manual says target-specific passes are
numbered after
final, which holds only for passes registered at run time, such as SH's. - That a pass whose name starts with
*can change the code and write no dump, as*strip_predict_hintsdoes. - That a trailing digit can be part of a pass name, as in
split2. - That
.cgraph,.type-inheritanceand.ipa-clonesalways carry000i. - The diff technique, and the route from a dump name to its
pass_datastring and itsNEXT_PASSlines. - That
-fopt-infodrops internal messages and keeps re-emitted ones, while a dump file does the opposite.
Next: the pass manager itself, how passes.def becomes the tree of passes that
this chapter numbered, and how a gate decides whether a file appears.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
5.3 The pass manager: from passes.def to ccp2
GCC 15.2.0. To run the commands: an installed compiler, and a GCC checkout for the two grep searches.
At -O2, the dump directory from Chapter 5.2 holds four files whose names end
in ccp1 to ccp4, the dumps of ccp, conditional constant propagation. You
want to switch off the second one and compare the output. -fdump-tree-ccp
worked a moment ago, so you try -fdisable-tree-ccp. cc1 reports "unknown
pass tree-ccp specified in -fdisable". Both options take a pass name. Only one
of them accepts ccp.
The pass manager builds, names and numbers every pass once, when cc1 starts,
from gcc/passes.def. After that it only walks the tree it built, and asks each
pass whether it wants to run. Every pass name that an option accepts comes from
that startup code.
Four pieces of code do this work. gen-pass-instances.awk counts the
NEXT_PASS lines of passes.def when GCC is built. When cc1 starts, the
pass_manager constructor builds one object for each line, and
register_one_dump_file gives each object the names that options match, which
explains the -fdisable-tree-ccp error. execute_one_pass then asks the gates,
for each function.
This chapter assumes Chapter 5.1, for GIMPLE, RTL and
the count.c example, and Chapter 5.2, for
the dump files, their numbers and the options that write them. It also uses
Chapter 1.13 for -flto and lto1,
Chapter 2.1 for the target makefile fragments, and
Chapter 2.4 for the files that the build
generates.
passes.def holds five lists, and each list is a tree
gcc/passes.def fills the five pass lists of cc1, and its macros nest passes
inside other passes, so each list is a tree. The tree fixes the order in which a
function meets the passes, and the nesting decides which of them run. One macro
in pass_manager.h names the five lists:
#define GCC_PASS_LISTS \
DEF_PASS_LIST (all_lowering_passes) \
DEF_PASS_LIST (all_small_ipa_passes) \
DEF_PASS_LIST (all_regular_ipa_passes) \
DEF_PASS_LIST (all_late_ipa_passes) \
DEF_PASS_LIST (all_passes)
Listing 5.3-1: the five pass lists (gcc/pass_manager.h:28-33).
Three of the lists hold IPA (interprocedural analysis) passes, which see the
whole translation unit at once. The other two, all_lowering_passes and
all_passes, work on one function at a time.
In passes.def, each list opens with INSERT_PASSES_AFTER and closes with
TERMINATE_PASS_LIST, and each NEXT_PASS adds one pass to the end of the
current list. PUSH_INSERT_PASSES_WITHIN opens a sub-list under the last pass
added, and POP_INSERT_PASSES closes it. The first pass_ccp is two levels
down:
NEXT_PASS (pass_local_optimization_passes);
PUSH_INSERT_PASSES_WITHIN (pass_local_optimization_passes)
NEXT_PASS (pass_fixup_cfg);
NEXT_PASS (pass_rebuild_cgraph_edges);
NEXT_PASS (pass_local_fn_summary);
NEXT_PASS (pass_early_inline);
NEXT_PASS (pass_warn_recursion);
NEXT_PASS (pass_all_early_optimizations);
PUSH_INSERT_PASSES_WITHIN (pass_all_early_optimizations)
NEXT_PASS (pass_remove_cgraph_callee_edges);
NEXT_PASS (pass_early_object_sizes);
/* Don't record nonzero bits before IPA to avoid
using too much memory. */
NEXT_PASS (pass_ccp, false /* nonzero_p */);
Listing 5.3-2: the early local passes, with the first pass_ccp
(gcc/passes.def:67-80).
pass_local_optimization_passes and pass_all_early_optimizations are
containers, passes that do no work of their own. The passes under a container
run only if the container agrees to run.
cgraphunit.cc: when each pass list runs
gcc/cgraphunit.cc, the call graph (cgraph) code, runs the five lists at
different points, not one after the other. The order matters when you read
dumps: ccp1 runs on every function in the file before IPA inlining starts, and
all_passes then takes one function at a time. A comment above the constructor
of the pass manager gives the order, and each arrow in it points from a routine
to the list that the routine runs:
/* Construct the pass tree. The sequencing of passes is driven by
the cgraph routines:
finalize_compilation_unit ()
for each node N in the cgraph
cgraph_analyze_function (N)
cgraph_lower_function (N) -> all_lowering_passes
If we are optimizing, compile is then invoked:
compile ()
ipa_passes () -> all_small_ipa_passes
-> Analysis of all_regular_ipa_passes
* possible LTO streaming at compilation time *
-> Execution of all_regular_ipa_passes
* possible LTO streaming at link time *
-> all_late_ipa_passes
expand_all_functions ()
for each node N in the cgraph
expand_function (N) -> Transformation of all_regular_ipa_passes
-> all_passes
*/
Listing 5.3-3: who runs which list (gcc/passes.cc:1555-1576).
Three function names in that comment no longer exist in gcc/cgraphunit.cc.
In GCC 15.2.0, these calls in that file run the lists, in this order:
| List | Run by | Source |
|---|---|---|
all_lowering_passes | cgraph_node::analyze, for each function | cgraphunit.cc:699 |
all_small_ipa_passes | ipa_passes | cgraphunit.cc:2226-2231 |
all_regular_ipa_passes | ipa_passes | cgraphunit.cc:2283-2286 |
all_late_ipa_passes | symbol_table::compile | cgraphunit.cc:2381 |
all_passes | cgraph_node::expand, for each function | cgraphunit.cc:1859 |
An IPA list still reaches single functions. When an IPA pass has a sub-list of
GIMPLE passes, the pass manager runs that sub-list on each function in turn
(passes.cc:3114-3121). The early passes of Listing 5.3-2, ccp1
among them, form such a sub-list.
gen-pass-instances.awk numbers every NEXT_PASS
gen-pass-instances.awk gives every NEXT_PASS line an instance number, and the
pass manager reads its output, pass-instances.def, instead of passes.def.
That output exists only in the build directory, and a target's own passes join
the generic ones there. The make rule shows both inputs:
pass-instances.def: $(srcdir)/passes.def $(PASSES_EXTRA) \
$(srcdir)/gen-pass-instances.awk
$(AWK) -f $(srcdir)/gen-pass-instances.awk \
$(srcdir)/passes.def $(PASSES_EXTRA) > pass-instances.def
Listing 5.3-4: the rule for pass-instances.def
(gcc/Makefile.in:2681-2684).
The script counts the instances of each pass and adds the count as a second
argument. Its header comment gives an example:
NEXT_PASS (pass_warn_unused_result); becomes
NEXT_PASS (pass_warn_unused_result, 1);
(gcc/gen-pass-instances.awk:17-26). A line with extra arguments
becomes NEXT_PASS_WITH_ARG or NEXT_PASS_WITH_ARGS (:222-235).
The five NEXT_PASS (pass_ccp, ...) lines become instances 1 to 5, in the order
in which they appear in the file (:214-220). An -O2 compile
writes only ccp1 to ccp4, because the fifth instance sits in the -Og
group, whose gate says no at -O2.
A pass runs again only if passes.def names it again, because the walk over a
list goes from each pass to the next and never back (Listing 5.3-9). Each
occurrence runs the same code at a different point in the tree, sometimes with
a different parameter, and the comments next to them say why. The first ccp
runs before IPA with nonzero_p false: "Don't record nonzero bits before IPA to
avoid using too much memory." (Listing 5.3-2). The fourth has its own reason:
"Run CCP to compute alignment and nonzero bits."
(passes.def:353-354).
$(PASSES_EXTRA) is how a target adds its own passes. The x86 makefile fragment
appends config/i386/i386-passes.def to it (t-i386:23). That file
places each pass relative to a generic pass and one of its instances:
INSERT_PASS_AFTER (pass_postreload_cse, 1, pass_insert_vzeroupper);
INSERT_PASS_AFTER (pass_late_combine, 1, pass_stv, false /* timode_p */);
/* Run the 64-bit STV pass before the CSE pass so that CONST0_RTX and
CONSTM1_RTX generated by the STV pass can be CSEed. */
INSERT_PASS_BEFORE (pass_cse2, 1, pass_stv, true /* timode_p */);
Listing 5.3-5: x86 passes placed among the generic ones
(gcc/config/i386/i386-passes.def:27-31).
Each line names a generic pass, the instance of it to follow or precede, the new
pass and its argument. The second line adds pass_stv, with timode_p false,
after the first instance of pass_late_combine. The script writes each inserted
pass into its output at that point
(gen-pass-instances.awk:129-144) and counts it like any
NEXT_PASS line, so pass_stv has two instances. The instance number of a
target pass counts the lines that the script wrote, not only the lines in
passes.def. The Arm and AArch64 fragments do the same (t-arm:205,
t-aarch64:152), so the pass tree of an x86-64 cc1 is not the
pass tree of an arm-none-eabi cc1.
The pass_manager constructor: make_pass_ccp once, clone () after
The pass_manager constructor builds one pass object for each line of
pass-instances.def. The factory function of a pass, here make_pass_ccp,
makes the first instance, and every later instance is a clone () of the
first. Each object later gets its own names and answers its own gate, so the
number of ccp passes in cc1 is fixed here.
pass-instances.def is included three times. In pass_manager.h it declares
one field for each instance, so pass_ccp_1 to pass_ccp_5 are members of the
class (pass_manager.h:111-136). The constructor in passes.cc
includes it first to set every field to NULL
(passes.cc:1586-1594), and then to build the tree, with these
definitions. Watch the test on NUM, which picks the factory or the clone:
#define NEXT_PASS(PASS, NUM) \
do { \
gcc_assert (PASS ## _ ## NUM == NULL); \
if ((NUM) == 1) \
PASS ## _1 = make_##PASS (m_ctxt); \
else \
{ \
gcc_assert (PASS ## _1); \
PASS ## _ ## NUM = PASS ## _1->clone (); \
} \
p = next_pass_1 (p, PASS ## _ ## NUM, PASS ## _1); \
} while (0)
#define NEXT_PASS_WITH_ARG(PASS, NUM, ARG) \
do { \
NEXT_PASS (PASS, NUM); \
PASS ## _ ## NUM->set_pass_param (0, ARG); \
} while (0)
Listing 5.3-6: what each NEXT_PASS does at startup
(gcc/passes.cc:1620-1637).
next_pass_1 links the new object into the current list
(passes.cc:1350-1360), and PUSH_INSERT_PASSES_WITHIN points
the current list at the sub field of its pass (:1613-1615). An
extra argument in passes.def becomes a call to set_pass_param. The base class
makes both clone and set_pass_param an internal error
(passes.cc:81-92), so a pass that occurs twice in passes.def
must override clone, and a pass that takes an argument must override
set_pass_param.
Chapter 5.2 showed that the dump numbers are
fixed before cc1 reads -O2, and the constructor is the reason. It runs from
general_init (toplev.cc:1153-1154), which toplev::main calls
at :2296, and toplev::main decodes the command line later, at
:2331. So the pass tree exists before cc1 reads your
options. -O0 and -O2 get the same tree, the same instance numbers and the
same dump numbers, and the options decide only which passes agree to run.
pass_data and opt_pass: the descriptor and the methods of a pass
Every pass is a pass_data descriptor, shared by its instances, and an
opt_pass object for each instance. The descriptor holds the name that the
dump options and -fdisable- match, and the object holds the gate that decides
whether the instance runs. Chapter 5.2 found
pass_data_ccp by searching for its name.
struct pass_data is the "Metadata for a pass, non-varying across all instances
of a pass" (tree-pass.h:39-64). class opt_pass derives from it
and adds the methods and the links of one instance (:71-113). In
the ccp pass, watch name, properties_required and the four methods of the
class:
const pass_data pass_data_ccp =
{
GIMPLE_PASS, /* type */
"ccp", /* name */
OPTGROUP_NONE, /* optinfo_flags */
TV_TREE_CCP, /* tv_id */
( PROP_cfg | PROP_ssa ), /* properties_required */
0, /* properties_provided */
0, /* properties_destroyed */
0, /* todo_flags_start */
TODO_update_address_taken, /* todo_flags_finish */
};
class pass_ccp : public gimple_opt_pass
{
public:
pass_ccp (gcc::context *ctxt)
: gimple_opt_pass (pass_data_ccp, ctxt), nonzero_p (false)
{}
/* opt_pass methods: */
opt_pass * clone () final override { return new pass_ccp (m_ctxt); }
void set_pass_param (unsigned int n, bool param) final override
{
gcc_assert (n == 0);
nonzero_p = param;
}
bool gate (function *) final override { return flag_tree_ccp != 0; }
unsigned int execute (function *) final override
{
return do_ssa_ccp (nonzero_p);
}
private:
/* Determines whether the pass instance records nonzero bits. */
bool nonzero_p;
}; // class pass_ccp
Listing 5.3-7: the ccp pass (gcc/tree-ssa-ccp.cc:3036-3072).
Read the descriptor from the top:
typeisGIMPLE_PASS,RTL_PASS,SIMPLE_IPA_PASSorIPA_PASS(tree-pass.h:31-37). It selects the dump prefix.nameis the "Terse name of the pass used as a fragment of the dump file name. If the name starts with a star, no dump happens." (tree-pass.h:45-47).tv_idnames the timer that the pass manager starts around the pass (passes.cc:2646-2648).- The three
properties_*sets say what the IR must have before the pass, and what the pass adds and removes.ccpneeds a CFG (control flow graph) and SSA form. todo_flags_startandtodo_flags_finishask the pass manager to do common work before and after the pass.ccpasks forTODO_update_address_taken, which runsexecute_update_addresses_takenwhen optimizing (passes.cc:2078-2079). That is the work behind the comment after the first threepass_ccplines inpasses.def: "After CCP we rewrite no longer addressed locals into SSA form if possible."
The class supplies four methods. gate decides whether the pass runs, and here
it tests flag_tree_ccp, which -O1 and higher set (opts.cc:597).
The GCC manual documents -ftree-ccp and that default under
Optimize Options. execute does the work, and clone and
set_pass_param exist because ccp occurs five times and takes one argument.
The base class gives gate a default of true, and an execute that does
nothing (passes.cc:94-104), so a container such as
pass_all_early_optimizations overrides only gate.
The other pass kinds use the same descriptor with a different base class.
gimple_opt_pass and rtl_opt_pass add nothing to opt_pass
(tree-pass.h:115-133). ipa_opt_pass_d adds the hooks that
split an IPA pass into a summary stage, an execute stage and a transform of each
function (:141-193). Listing 5.3-3 calls the same stages
Analysis, Execution and Transformation, and with -flto the summaries are
streamed to disk between the first two. The internals manual describes the
stages under IPA passes.
How ccp becomes tree-ccp2: register_one_dump_file
The 2 in tree-ccp2 comes from a second count, which the constructor makes on
the objects, and not from the Awk script. register_one_dump_file turns that
count and the name field into the strings that the options match, and the
strings it makes for ccp explain the -fdisable-tree-ccp error.
next_pass_1 calls add_pass_instance, which keeps the count in
static_pass_number (passes.cc:1317-1345). The first instance
starts at -1 and holds the number of copies as a negative value. Each clone
decrements that value and takes the negated result. After the second
NEXT_PASS (pass_ccp) the first instance holds -2 and the clone holds 2, and
after the fifth the first instance holds -5 and the clones hold 2 to 5. A pass
whose name starts with * is not counted.
When the tree is complete, register_dump_files walks it depth first and
registers each pass whose name does not start with *
(passes.cc:896-910). The comment above it says that the walk
is "independent of whether the pass is enabled or not"
(:823-825). Each registration builds the names of one instance:
/* See below in next_pass_1. */
num[0] = '\0';
if (pass->static_pass_number != -1)
sprintf (num, "%u", ((int) pass->static_pass_number < 0
? 1 : pass->static_pass_number));
...
name = strchr (pass->name, ' ');
name = name ? name + 1 : pass->name;
dot_name = concat (".", name, num, NULL);
...
flag_name = concat (prefix, name, num, NULL);
glob_name = concat (prefix, name, NULL);
...
id = dumps->dump_register (dot_name, flag_name, glob_name, dkind,
optgroup_flags,
true);
set_pass_for_id (id, pass);
full_name = concat (prefix, pass->name, num, NULL);
register_pass_name (pass, full_name);
Listing 5.3-8: the names of one pass instance, abridged
(gcc/passes.cc:846-890).
The ternary prints a negative static_pass_number as 1, so the first instance
is ccp1. A pass with one instance keeps -1 and gets no number, so the expand
pass is rtl-expand, not rtl-expand1. The prefix comes from type, not from
the position of the pass in the tree. For the second ccp instance, the listing
builds four strings:
| String | Value | Used by |
|---|---|---|
dot_name | .ccp2 | the end of the dump file name |
flag_name | tree-ccp2 | -fdump-tree-ccp2 |
glob_name | tree-ccp | -fdump-tree-ccp, for every instance |
full_name | tree-ccp2 | -fenable-, -fdisable- and -fdump-passes |
-fdump- and -fdisable- read different strings. -fdump- first looks for an
exact switch, and only if none matches does it try the glob names
(dumpfile.cc:1935-1940). tree-ccp matches the glob name of all
five instances. -fdisable- looks the name up in the map of full names, which
holds only tree-ccp1 to tree-ccp5, and reports an unknown pass
(passes.cc:1091-1097). To switch off the second instance,
you write -fdisable-tree-ccp2.
The GCC manual states the rule for -fenable- and -fdisable- under
Developer Options: if a pass is "statically invoked in the compiler
multiple times, the pass name should be appended with a sequential number
starting from 1". It does not say that a dump option without the number takes
every instance.
dump_register also gives out the number in the dump file name, from a counter
that increases by one for each registration
(dumpfile.cc:215-221).
Chapter 5.2 follows that number into the file
name, and shows why it does not change with -O and why a pass added after the
constructor gets a late number. Plugins add their passes that way, through the
PLUGIN_PASS_MANAGER_SETUP event (plugin.cc:458-461). The
plugin API is the internals manual's to document, and it covers this event under
Interacting with the pass manager.
gate and execute_one_pass: one pass tree for -O0, -O2 and -Og
One pass tree serves -O0, -O2 and -Og because execute_one_pass asks
each pass for its gate before it runs anything, and the answer of a container
covers every pass below it. The walk over a list asks a container first, and
walks its sub-list only if the answer is yes. In Listing 5.3-9, watch the if
that calls execute_one_pass and then descends into pass->sub:
static void
execute_pass_list_1 (opt_pass *pass)
{
do
{
gcc_assert (pass->type == GIMPLE_PASS
|| pass->type == RTL_PASS);
if (cfun == NULL)
return;
if (execute_one_pass (pass) && pass->sub)
execute_pass_list_1 (pass->sub);
pass = pass->next;
}
while (pass);
}
Listing 5.3-9: walking a list (gcc/passes.cc:2758-2773).
execute_one_pass returns false when the pass does not run, and then the
sub-list does not run either. next is followed in both cases. In all_passes
the walk happens once for each function, so each gate gets each function as its
argument. The assertion admits GIMPLE and RTL passes only. The IPA lists use
the other walker, the one that runs a GIMPLE sub-list on each function in turn.
The answer for one pass comes from three places, in the lines that Chapter 5.2 quoted for the dump files:
/* Check whether gate check should be avoided.
User controls the value of the gate through the parameter "gate_status". */
gate_status = pass->gate (cfun);
gate_status = override_gate_status (pass, current_function_decl, gate_status);
/* Override gate with plugin. */
invoke_plugin_callbacks (PLUGIN_OVERRIDE_GATE, &gate_status);
if (!gate_status)
Listing 5.3-10: the gate decision in execute_one_pass
(gcc/passes.cc:2603-2611).
First comes the gate of the pass. Then override_gate_status applies
-fenable- and -fdisable- to that answer: a disabled pass does not run, and
an enabled pass runs even if its own gate said no, as long as the walk reaches
it (passes.cc:2434-2450). Last, a plugin can change the
answer. When the answer is yes, execute_one_pass opens the dump file, runs the
start TODOs, checks properties_required when checking is enabled, calls
execute, runs the finish TODOs and writes the dump
(passes.cc:2644-2740). A dump file exists only for an instance
that ran.
The two large GIMPLE groups in all_passes are containers, and their gates test
the same two variables in opposite ways. *all_optimizations returns
optimize >= 1 && !optimize_debug (passes.cc:568-571), and
*all_optimizations_g returns optimize >= 1 && optimize_debug
(:606-609). -Og sets optimize to 1 and optimize_debug
to 1 (opts.cc:795-801), so -Og selects the second group. For the
ccp instances of count.c, the gates give this result:
| Instance | Container | -O0 | -O2 | -Og |
|---|---|---|---|---|
ccp1 | pass_all_early_optimizations | does not run | runs | runs |
ccp2 to ccp4 | *all_optimizations | does not run | runs | does not run |
ccp5 | *all_optimizations_g | does not run | does not run | runs |
At -O0 the containers say no, and the instances inside them would also say no,
because -O0 does not set flag_tree_ccp. -fenable- changes only the answer
of the pass it names, and a container that says no stops the walk before that
pass is asked. The two container names start with a star
(passes.cc:550, :588), so neither container
has a dump file or an option. No -fenable- can name them, so if you compile
with -O0 -fenable-tree-ccp2, ccp2 still does not run.
pass_expand in all_passes: GIMPLE and RTL passes in one list
all_passes holds both the GIMPLE passes and the RTL passes, with pass_expand
as an ordinary NEXT_PASS between them. The RTL passes follow it in the same
list, under pass_rest_of_compilation, so one walk of one list takes each
function from GIMPLE to RTL:
NEXT_PASS (pass_expand);
NEXT_PASS (pass_rest_of_compilation);
PUSH_INSERT_PASSES_WITHIN (pass_rest_of_compilation)
NEXT_PASS (pass_instantiate_virtual_regs);
Listing 5.3-11: where all_passes changes from GIMPLE to RTL
(gcc/passes.def:453-457).
cgraph_node::expand makes one call to execute_pass_list with all_passes
for each function (cgraphunit.cc:1859), and that one call
goes all the way to pass_final (passes.def:563). The boundary
is in the descriptor of the expand pass, as properties:
const pass_data pass_data_expand =
{
RTL_PASS, /* type */
"expand", /* name */
OPTGROUP_NONE, /* optinfo_flags */
TV_EXPAND, /* tv_id */
( PROP_ssa | PROP_gimple_leh | PROP_cfg
| PROP_gimple_lcx
| PROP_gimple_lvec
| PROP_gimple_lva), /* properties_required */
PROP_rtl, /* properties_provided */
( PROP_ssa | PROP_gimple ), /* properties_destroyed */
0, /* todo_flags_start */
0, /* todo_flags_finish */
};
Listing 5.3-12: the expand pass descriptor
(gcc/cfgexpand.cc:6973-6987).
expand needs SSA form and lowered GIMPLE. It provides PROP_rtl, and it
destroys PROP_ssa and PROP_gimple. After each pass, execute_one_pass
asserts that an RTL pass did not run on a function that still has
PROP_gimple (passes.cc:2742-2744). What expand does inside
its execute is the subject of Chapter 5.5.
-flto without -ffat-lto-objects: cc1 stops after the IPA summaries
With -flto and no -ffat-lto-objects, cc1 stops after the summaries of the
regular IPA passes, although a normal compile runs all three IPA lists in cc1.
A plain -flto compile therefore writes no RTL dump. The execute stage runs in
lto1 at link time, and Chapter 1.13 shows
how the driver gets there.
The regular IPA passes first compute their summaries
(cgraphunit.cc:2252-2253). With -flto, cc1 writes those
summaries into the object (:2272-2276). It skips the execute
stage of the regular IPA passes unless you also give -ffat-lto-objects
(:2283-2286). Without that option, symbol_table::compile
then returns before the late IPA list and before all_passes
(:2354-2361), so cc1 runs no expand and no RTL pass.
At link time, lto1 runs the same code with in_lto_p set, and that test lets
it execute the regular IPA list. The internals manual describes lto1 in its
LTO chapter. The GCC manual documents -ffat-lto-objects under
Optimize Options.
Checking gates with -fdump-passes: each pass asked alone
-fdump-passes prints the whole pass tree, with the answer that each pass gives
alone for the current options. It gives you the names that -fdisable-
accepts, but it does not apply the gate of a container, so an ON line does not
prove that a pass runs. The GCC manual documents it in one sentence under
Developer Options: it prints on standard error "the list of
optimization passes that are turned on and off by the current command-line
options".
$ gcc -O2 -fdump-passes -c count.c 2>&1 | grep -E 'ccp|all_optimizations'
$ gcc -Og -fdump-passes -c count.c 2>&1 | grep -E 'ccp|all_optimizations'
$ gcc -O2 -fdisable-tree-ccp2 -fdump-passes -c count.c 2>&1 | grep ccp
finalize_compilation_unit calls the printer once for each translation unit,
before it compiles any function (cgraphunit.cc:2569-2570).
The printer walks the five lists (passes.cc:1008-1024) and
indents each level by three columns. For each pass it prints the full name, such
as tree-ccp2, or the star name of a container, then ON or OFF
(:963-983). When -fenable- or -fdisable- changed the
answer, it adds (FORCED_ON) or (FORCED_OFF), so the third command marks
tree-ccp2 as (FORCED_OFF).
At -O2 the printer shows tree-ccp5 as ON, because flag_tree_ccp is set,
below a line that shows *all_optimizations_g as OFF, and the fifth instance
still does not run. In the same way, if you add -fenable-tree-ccp2 at -O0,
the printer shows tree-ccp2 as ON, marked (FORCED_ON), although ccp2
does not run. The printer also
asks the gates about a dummy function with an empty body
(passes.cc:1011, function.cc:4981-5003), not about
count_divisible. A gate that reads the function, such as the gate of
*pre_slp_scalar_cleanup (passes.cc:772-776), can give a
different answer for your code.
From .ccp2 to tree-ssa-ccp.cc: finding the source of a pass
A dump file that ends in .ccp2 leads to tree-ssa-ccp.cc in four steps. The
first three follow the route of Chapter 5.2,
from the dump name to the pass_data string and the NEXT_PASS lines. The
fourth reads the gates above the instance, because they decide whether the file
appears at all:
- Split the name.
ccpis thenamefield of the descriptor, and2is the instance number. - Find the descriptor. Search the source for the name as a string. The search
finds
pass_data_ccpingcc/tree-ssa-ccp.cc, and the class next to it holds thegateand theexecute. - Find the position. The factory of that class is
make_pass_ccp, so thepasses.defentry ispass_ccp. The secondNEXT_PASS (pass_ccpline in the file is instance 2 (passes.def:204). - Read the gates above it. Instance 2 is in the sub-list of
pass_all_optimizations, so it runs only if that gate and its own gate agree.
$ grep -rn '"ccp", /\* name \*/' gcc/
$ grep -n 'NEXT_PASS (pass_ccp' gcc/passes.def
Step 2 matters because the name and the class do not always agree. evrp and
vrp are two descriptors for one class, pass_vrp, and passes.def calls the
first one pass_early_vrp (tree-vrp.cc:1277-1301,
:1357-1367). For a target pass, search the *-passes.def file of
the target as well as passes.def. Its instance number counts the lines that
the Awk script wrote, not only the lines in passes.def.
Three things to carry away
The pass tree is built once, before cc1 reads its options. -O changes
which gates say yes. It does not change the tree, the names or the numbers.
ccp2 is the second NEXT_PASS (pass_ccp) line, not the second run. An
instance can exist in the tree and never run.
The gate of a container decides for its whole sub-list. That is how -O0,
-O2 and -Og share one tree, and no -fenable- can open a container that
says no.
Things that surprise people
-fdisable-tree-ccp is an error. Only the dump options fall back to the
name without the instance number.
GIMPLE passes and RTL passes are in one list. all_passes runs from
pass_fixup_cfg through pass_expand to pass_final, for each function.
With -flto and no -ffat-lto-objects, cc1 runs no RTL pass. It stops
after the IPA summaries.
-fdump-passes can print ON for a pass that never runs. It does not
apply the gate of the container above the pass.
Documentation coverage
The GCC manual documents the options. Developer Options
(gcc/doc/invoke.texi:20326) gives the dump file name and its numbering rule
(:20349-20362), -fdump-passes (:20879-20882), a procedure to find the dump
of a pass (:20977-21003), and -fenable- and -fdisable- with examples
(:21202-21273). Optimize Options gives -ftree-ccp
(:14073) and -ffat-lto-objects (:15216).
The internals manual has a Passes chapter
(gcc/doc/passes.texi:7). Its Pass manager node
(:146-180) is short. It names tree-optimize.c, a file that does not exist in
GCC 15.2.0. It states the rules for star names and for names with a space, and
it ends with a TODO. The Tree SSA passes node gives the source
file of each pass, ccp at :710-715. Interacting with the pass
manager (gcc/doc/plugins.texi:264) documents
register_pass for plugins.
What is not documented:
- The format of
passes.def, its five lists and its nesting, and the Awk script that turns it intopass-instances.def. - That an instance number counts
NEXT_PASSlines, so an instance can exist and never run. - That a pass that occurs twice must implement
clone, and a pass with an argument must implementset_pass_param. - That the gate of a container decides for its whole sub-list, and that
-O0,-O2and-Ogselect their passes this way. - That the GIMPLE passes and the RTL passes share
all_passes, withexpandas one pass among them. - Which code runs which list. Only the comment in Listing 5.3-3 says it, and some of its function names are out of date.
- That
-fdump-passesasks each gate alone, about an empty dummy function. - That
-fdump-tree-NAMEwithout a number matches every instance. - That the tree and the dump numbers exist before
cc1reads its options. The manual says that "target-specific passes" get numbers abovefinal. In GCC 15.2.0 that is true for passes thatregister_passadds at run time, such as those of SH. It is not true for the x86, Arm and AArch64 passes thatPASSES_EXTRAadds.
Next: 5.4 Gimplification: from GENERIC to GIMPLE in SSA form.
The gimplifier turns count.c into GIMPLE, and its && becomes more statements
than the source suggests.
5.4 Gimplification: from GENERIC to GIMPLE in SSA form
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
You compile count.c with -fdump-tree-original and -fdump-tree-gimple and
put the two dumps side by side. The first still shows the if from the source,
with its &&. In the second, that if is two ifs, each with two gotos,
and one v[i] is a run of new statements. You open passes.def to find the
pass that did this, and it is not there. The .gimple dump already has names such as _1, but no PHI node
appears until the .ssa dump, several passes later.
Gimplification is a recursive rewrite that runs before the pass list, and SSA form arrives in two steps. The gimplifier flattens expressions and makes control flow explicit. Two passes then build the control flow graph and put the function into SSA form.
This chapter assumes Chapter 5.1, for count.c, the
three representations and the definition of SSA, and
Chapter 5.2 and
Chapter 5.3, for dump file names and
passes.def.
Where gimplification runs: gimplify_function_tree
The C front end finishes a function in finish_function. It calls
c_genericize, then hands the function to the call graph with
cgraph_node::finalize_function (c/c-decl.cc:11520-11540).
Later, the call graph analyses each function, and that is where the gimplifier
runs:
/* Make sure to gimplify bodies only once. During analyzing a
function we lower it, which will require gimplified nested
functions, so we can end up here with an already gimplified
body. */
if (!gimple_has_body_p (decl))
gimplify_function_tree (decl);
/* Lower the function. */
if (!lowered)
{
if (first_nested_function (this))
lower_nested_functions (decl);
gimple_register_cfg_hooks ();
bitmap_obstack_initialize (NULL);
execute_pass_list (cfun, g->get_passes ()->all_lowering_passes);
Listing 5.4-1: cgraph_node::analyze gimplifies, then runs the first pass
list (gcc/cgraphunit.cc:684-699).
gimplify_function_tree is a plain function call. It comes before
all_lowering_passes, the first list in passes.def
(passes.def:30-46). It writes the .gimple dump itself, as
its last statement (gimplify.cc:21160). c_genericize writes
the .original dump in the same way (c-family/c-gimplify.cc:785-803).
Both dumps are fixed entries in the dump table, not pass dumps
(dumpfile.cc:104-105). register_dumps numbers them "before
the optimization passes" (dumpfile.cc:255-270). -fdump-passes
prints the pass lists from all_lowering_passes onward
(passes.cc:1009-1024), so it never lists either of them.
Five dumps show the whole transformation. Two come from function calls and three from passes:
| Dump | Written by | Shows |
|---|---|---|
original | c_genericize, in the front end | GENERIC, with C loops already turned into gotos |
gimple | gimplify_function_tree | High GIMPLE: flat statements, labels, nested scopes |
lower | pass_lower_cf (gimple-low.cc:223) | Low GIMPLE: no scopes, one return |
cfg | pass_build_cfg (tree-cfg.cc:394) | basic blocks and edges |
ssa | pass_build_ssa (tree-into-ssa.cc:2461) | SSA names for every register variable, and PHI nodes |
Ask for all five in one run:
$ gcc -O2 -c count.c -fdump-tree-original -fdump-tree-gimple \
-fdump-tree-lower -fdump-tree-cfg -fdump-tree-ssa-details
$ ls count.c.*t.*
This book's machine has no GCC, so nobody ran these commands for this chapter.
Each dump shape that the chapter describes comes from the code that prints it,
cited at that point. The GCC manual documents -fdump-tree-SWITCH and the
-details, -vops and -raw suffixes under Developer Options.
It does not name the original or gimple dumps.
The loop is gone before the gimplifier starts: genericize_c_loop
The C parser builds a FOR_STMT (c/c-parser.cc:9299), a tree
code that c-common.def adds to GENERIC (c-family/c-common.def:63).
c_genericize walks the body and replaces every loop before it writes the
.original dump (c-family/c-gimplify.cc:765-779):
/* Expand to gotos. */
tree top = build1 (LABEL_EXPR, void_type_node,
create_artificial_label (start_locus));
...
if (cond && !integer_nonzerop (cond))
{
/* Canonicalize the loop condition to the end. This means
generating a branch to the loop condition. Reuse the
continue label, if there is no incr expression. */
Listing 5.4-2: genericize_c_loop, abridged
(gcc/c-family/c-gimplify.cc:352-365).
So the for in count.c reaches the gimplifier as a sequence of four parts:
a jump to an entry label, the body, the increment, and the condition with a
goto back to the top (c-family/c-gimplify.cc:397-438). The .original dump shows
that shape. The if is still a COND_EXPR with an && inside it
(c/c-typeck.cc:13112-13120). v[i] is an indirection through a
pointer sum, because v is a pointer
(c/c-typeck.cc:3419-3431). The sum multiplies the index by the
element size (c-family/c-common.cc:3477-3500).
That leaves two lowerings for the gimplifier in this function. One flattens the
expression v[i]. The other splits the &&.
The contract of gimplify_expr: a predicate and a fallback
gimplify_body gimplifies the saved body of the function with one call to
gimplify_stmt and wraps the result in a single GIMPLE_BIND
(gimplify.cc:20792-20870). Every expression then goes
through one function. Its comment states the contract:
/* Convert the GENERIC expression tree *EXPR_P to GIMPLE. If the
expression produces a value to be used as an operand inside a GIMPLE
statement, the value will be stored back in *EXPR_P. This value will
be a tree of class tcc_declaration, tcc_constant, tcc_reference or
an SSA_NAME. The corresponding sequence of GIMPLE statements is
emitted in PRE_P and POST_P.
...
enum gimplify_status
gimplify_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p,
bool (*gimple_test_f) (tree), fallback_t fallback)
Listing 5.4-3: gimplify_expr, abridged (gcc/gimplify.cc:19260-19265
and :19339-19341).
Three of the parameters do the work:
pre_pis the statement list that the caller is building. Every statement that the expression needs goes there, in order.gimple_test_fis a predicate, chosen by the caller. It says which form the caller can accept in its slot:is_gimple_valfor an operand of an arithmetic statement,is_gimple_regfor an address that is about to be dereferenced,is_gimple_stmtfor a whole statement. The full comment lists them and points atgimple.cc(gimplify.cc:19320-19322).fallbacksays what to make when the result does not pass the predicate: an rvalue, an lvalue, or nothing (gimplify.cc:19324-19333).
The body is a loop. It first offers the node to the front end's
lang_hooks.gimplify_expr, then switches on the tree code, and repeats "until
the toplevel node remains the same" (gimplify.cc:19416-19445,
:20392). After the loop, the predicate decides:
if (gimple_seq_empty_p (internal_post) && (*gimple_test_f) (*expr_p))
goto out;
...
else if ((fallback & fb_rvalue) && is_gimple_reg_rhs_or_call (*expr_p))
{
/* An rvalue will do. Assign the gimplified expression into a
new temporary TMP and replace the original expression with
TMP. First, make sure that the expression has a type so that
it can be assigned into a temporary. */
gcc_assert (!VOID_TYPE_P (TREE_TYPE (*expr_p)));
*expr_p = get_formal_tmp_var (*expr_p, pre_p);
}
Listing 5.4-4: the predicate check and the temporary, abridged
(gcc/gimplify.cc:20556-20591).
This is the whole flattening mechanism. If the result fits the slot, it stays.
If it does not, get_formal_tmp_var appends tmp = <expression> to pre_p
and returns tmp, which always fits. The lvalue branch that the listing skips
does the same with the address of the expression
(gimplify.cc:20566-20582).
The temporaries are already SSA names: internal_get_tmp_var
get_formal_tmp_var calls internal_get_tmp_var
(gimplify.cc:729-733), and that function decides what kind of
temporary to make:
if (allow_ssa
&& gimplify_ctxp->into_ssa
&& is_gimple_reg_type (TREE_TYPE (val)))
{
t = make_ssa_name (TYPE_MAIN_VARIANT (TREE_TYPE (val)));
Listing 5.4-5: a temporary of register type is an SSA name
(gcc/gimplify.cc:686-690).
gimplify_body sets into_ssa for every function body, because it calls
push_gimplify_context (true) (gimplify.cc:20807-20808,
:382-390). So each temporary of scalar type is an SSA_NAME
from the start. It is defined once, by the statement that the gimplifier just
built. The pretty-printer prints an SSA name as an optional identifier, an
underscore and a version number (tree-pretty-print.cc:3740-3755).
A temporary gets an identifier only when its value is a named declaration
(gimplify.cc:691-696, tree.cc:11912-11936). A
computed value, such as a product or a load, has none, and prints as _1,
_2 and so on.
Lowering one: v[i] becomes a chain of temporaries
Follow the condition of the outer if, v[i] != 0, through
gimplify_expr. Each row is one recursive call. The predicate is the one that
the caller in the row above passes:
| GENERIC node | Case in gimplify_expr | Predicate | Result |
|---|---|---|---|
v[i] != 0 | tcc_comparison, then expr_2 | is_gimple_condexpr_for_cond | both operands gimplified for is_gimple_val |
*(v + offset) | INDIRECT_REF | is_gimple_val | becomes a MEM_REF, which fails the predicate: a load into a temporary |
v + offset | POINTER_PLUS_EXPR | is_gimple_reg | fails the predicate: the address goes into a temporary |
index * 8 | tcc_binary, expr_2 | is_gimple_val | fails: the byte offset goes into a temporary |
conversion of i | CASE_CONVERT | is_gimple_val | fails: the widened index goes into a temporary |
v, i, 8, 0 | tcc_declaration, tcc_constant | is_gimple_val | pass unchanged |
This table is a trace of the source, not dump output. The cases are at
gimplify.cc:19607-19665 for the conversion and the
indirection, and at :20284-20356 for the pointer sum, the
comparison and the multiplication. The pointer sum is the shortest of them:
case POINTER_PLUS_EXPR:
{
enum gimplify_status r0, r1;
r0 = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p,
post_p, is_gimple_val, fb_rvalue);
r1 = gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p,
post_p, is_gimple_val, fb_rvalue);
recalculate_side_effects (*expr_p);
ret = MIN (r0, r1);
break;
}
Listing 5.4-6: a binary node only asks its operands to be values
(gcc/gimplify.cc:20284-20294).
The case never makes a temporary for the sum itself. It only makes its two
operands into values. The check in Listing 5.4-4 then finds that a sum is not
an is_gimple_reg, and stores it. Because the inner call returns before the
outer check runs, the temporaries appear innermost first: the conversion, the
multiplication, the address, the load. That is the run of _N lines that the
.gimple dump shows before the outer if.
The second operand of the &&, v[i] % d == 0, repeats the same chain for
its own v[i], then adds one statement for %. The internals manual says that
the gimplifier "tries to always evaluate identical expressions into the same
temporary". The table that does that is in lookup_tmp_var
(gimplify.cc:629-671). A temporary of register type takes the
SSA branch of Listing 5.4-5 instead, so lookup_tmp_var never sees it. In a
function body, each v[i] gets its own chain.
Lowering two: && becomes two GIMPLE_CONDs in shortcut_cond_expr
The if reaches gimplify_cond_expr (gimplify.cc:19483-19484).
Before it gimplifies the condition, it checks for a short-circuit operator:
/* Break apart && and || conditions. */
if (TREE_CODE (TREE_OPERAND (expr, 0)) == TRUTH_ANDIF_EXPR
|| TREE_CODE (TREE_OPERAND (expr, 0)) == TRUTH_ORIF_EXPR)
{
expr = shortcut_cond_expr (expr, next_cond_uid ());
Listing 5.4-7: gimplify_cond_expr hands && and || to
shortcut_cond_expr (gcc/gimplify.cc:5547-5551).
count.c's if has no else, and that selects the simplest of the
rewrites:
/* First do simple transformations. */
if (!else_se)
{
/* If there is no 'else', turn
if (a && b) then c
into
if (a) if (b) then c. */
while (TREE_CODE (pred) == TRUTH_ANDIF_EXPR)
{
/* Keep the original source location on the first 'if'. */
location_t locus = EXPR_LOC_OR_LOC (expr, input_location);
TREE_OPERAND (expr, 0) = TREE_OPERAND (pred, 1);
/* Set the source location of the && on the second 'if'. */
if (rexpr_has_location (pred))
SET_EXPR_LOCATION (expr, rexpr_location (pred));
then_ = shortcut_cond_expr (expr, condition_uid);
then_se = then_ && TREE_SIDE_EFFECTS (then_);
pred = TREE_OPERAND (pred, 0);
expr = build3 (COND_EXPR, void_type_node, pred, then_, NULL_TREE);
SET_EXPR_LOCATION (expr, locus);
}
}
Listing 5.4-8: if (a && b) c becomes two nested ifs
(gcc/gimplify.cc:5128-5149).
The rewrite is still GENERIC: two COND_EXPRs, the inner one in the then arm
of the outer one. When no && or || is left, the function returns the new
tree (gimplify.cc:5176-5179), and gimplify_cond_expr
gimplifies it as a statement (:5553-5567). Each of
the two ifs now takes the ordinary path. Its condition is gimplified for
is_gimple_condexpr_for_cond, which produces the chains of the previous
section. Then the if becomes one statement with a label for each arm:
cond_stmt = gimple_build_cond (pred_code, arm1, arm2, label_true,
label_false);
Listing 5.4-9: a GIMPLE_COND carries both of its destinations
(gcc/gimplify.cc:5624-5625).
The function then emits the true label, the then arm and the false label
after the condition (gimplify.cc:5633-5700). The printer writes
a GIMPLE_COND that has labels as if (...) goto L; else goto M;
(gimple-pretty-print.cc:1124-1140), and an unnamed label as
<D. followed by its declaration UID (tree-pretty-print.cc:2693-2709).
That is the if (_N != 0) goto <D.…>; else goto <D.…>; shape in the
.gimple dump. The two false labels end up next to each other, because the
inner if ends where the outer one does.
With an else arm that has side effects, the simple rewrite does not apply.
shortcut_cond_r then builds jumps directly, and its comment shows the shape:
/* Turn if (a && b) into
if (a); else goto no;
if (b) goto yes; else goto no;
(no:) */
Listing 5.4-10: the general form of && in a condition
(gcc/gimplify.cc:4950-4954).
An && whose value you store, as in x = a && b, takes one more step.
gimplify_expr first turns it into a && b ? true : false
(gimplify.cc:19534-19551). gimplify_cond_expr gives that
conditional a temporary, assigns the temporary in each arm, and gimplifies the
if that results (gimplify.cc:5477-5536). That if goes
through Listing 5.4-7 like any other. The internals manual describes the value
form under Logical Operators.
One more rewrite in count.c is easy to miss. count++ is a post-increment,
but gimplify_self_mod_expr treats it as a pre-increment when nothing uses the
value: "Faster to treat as prefix if result is not used"
(gimplify.cc:3681-3684). It becomes the assignment
count = count + 1 (:3740-3744), with no temporary.
High GIMPLE to Low GIMPLE: pass_lower_cf
The .gimple dump still has nested scopes. The printer writes each
GIMPLE_BIND as a pair of braces with its local declarations at the top
(gimple-pretty-print.cc:1193-1219). pass_lower_cf removes
them. Its file opens with the list of what it does:
/* The differences between High GIMPLE and Low GIMPLE are the
following:
1- Lexical scopes are removed (i.e., GIMPLE_BIND disappears).
2- GIMPLE_TRY and GIMPLE_CATCH are converted to abnormal control
flow and exception regions are built as an on-the-side region
hierarchy (See tree-eh.cc:lower_eh_constructs).
3- Multiple identical return statements are grouped into a single
return and gotos to the unique return site. */
Listing 5.4-11: High and Low GIMPLE (gcc/gimple-low.cc:46-56).
The if statements are not in that list. They were already a condition and two
gotos when the gimplifier finished.
Basic blocks from labels: pass_build_cfg
pass_build_cfg runs a few passes later in the same list
(passes.def:41). build_gimple_cfg cuts the statement list
into blocks, removes unused labels, then makes the edges
(tree-cfg.cc:220-256). The cutting rule is two functions.
stmt_ends_bb_p ends a block after any control statement
(tree-cfg.cc:2904-2907). stmt_starts_bb_p starts one at a label,
except when the statement before it is an artificial label
(tree-cfg.cc:2862-2879). The gimplifier makes its labels with
create_artificial_label (gimplify.cc:5597-5613). So the two
false labels from the nested ifs open one block, not two.
The edges replace the labels:
e = make_edge (bb, then_bb, EDGE_TRUE_VALUE);
e->goto_locus = gimple_location (then_stmt);
e = make_edge (bb, else_bb, EDGE_FALSE_VALUE);
if (e)
e->goto_locus = gimple_location (else_stmt);
/* We do not need the labels anymore. */
gimple_cond_set_true_label (entry, NULL_TREE);
gimple_cond_set_false_label (entry, NULL_TREE);
Listing 5.4-12: a GIMPLE_COND's labels become two edges
(gcc/tree-cfg.cc:1310-1318).
From here on, a GIMPLE_COND has no labels. The printer writes its
destinations from the edges, as goto <bb N>;
(gimple-pretty-print.cc:3062-3086, :3048),
and starts each block with a <bb N> line (:2982). Look for
those two changes when you compare the .lower and .cfg dumps.
SSA form and PHI nodes: pass_build_ssa
The CFG pass is in all_lowering_passes. The SSA builder is not. It is the
second pass of pass_build_ssa_passes, in the next list,
all_small_ipa_passes (passes.def:49-56). The gate of
pass_build_ssa_passes tests for errors and for LTO, not for -O
(passes.cc:414-418). The entry point of pass_build_ssa states
the algorithm:
/* Main entry point into the SSA builder. The renaming process
proceeds in four main phases:
1- Compute dominance frontier and immediate dominators, needed to
insert PHI nodes and rename the function in dominator tree
order.
2- Find and mark all the blocks that define variables.
3- Insert PHI nodes at dominance frontiers (insert_phi_nodes).
4- Rename all the blocks (rewrite_blocks) and statements in the program.
Steps 3 and 4 are done using the dominator tree walker
(walk_dominator_tree). */
Listing 5.4-13: the four phases of pass_build_ssa
(gcc/tree-into-ssa.cc:2440-2454). The code follows the same
four steps at :2490-2528.
Phase 4 explains why the gimplifier's _N names survive unchanged. The
renamer skips every operand that is already an SSA name:
FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_ALL_USES)
{
tree var = USE_FROM_PTR (use_p);
if (TREE_CODE (var) == SSA_NAME)
continue;
gcc_checking_assert (DECL_P (var));
SET_USE (use_p, get_reaching_def (var));
}
Listing 5.4-14: only declarations are renamed
(gcc/tree-into-ssa.cc:1363-1370).
The definitions get the same treatment (tree-into-ssa.cc:1374-1398).
So only the variables that count.c names are renamed: count, i, and the
parameters. Each assignment to count gets a new name with the identifier
count and a new version. A parameter has no assignment in the body. Its first
use gets a default definition (tree-into-ssa.cc:1203-1228),
which the printer marks with (D) (tree-pretty-print.cc:3754-3755).
So the .ssa dump compares i against n as a name such as n_7(D).
Where the PHIs go: insert_phi_nodes_for
Phase 3 gives insert_phi_nodes_for one variable and the iterated dominance
frontier of the blocks that assign it (tree-into-ssa.cc:950-958).
The function first drops the blocks where a PHI would be "obviously useless",
from the blocks where the variable is live on entry
(:974-976). Then it creates a PHI in each block that is left.
With -details, it reports each one:
if (dump_file && (dump_flags & TDF_DETAILS))
{
fprintf (dump_file, "creating PHI node in block #%d for ", bb_index);
print_generic_expr (dump_file, var, TDF_SLIM);
fprintf (dump_file, "\n");
}
Listing 5.4-15: the -details trace of PHI insertion
(gcc/tree-into-ssa.cc:985-990).
In count.c, i is assigned before the loop and in the increment. Listing
5.4-2 moved the loop condition to the bottom, so both assignments reach the
block that tests i < n. That block is where i needs a PHI. count has
the same two assignments that reach the test: count = 0, and whatever value
leaves the body. It has one more merge inside the body. The block after the two
ifs is reached with count incremented, or not incremented on either false
edge. By this reasoning, count.c gets three PHIs. The -details lines name
the blocks, so you can check the reasoning against your own dump.
A PHI prints with a leading #, as # count_N = PHI <count_A(3), count_B(5)>.
The number in parentheses after each argument is the index of the predecessor
block that the value comes from (gimple-pretty-print.cc:2438-2487).
Memory is not renamed this way. The Tree SSA passes node
of the internals manual says that other variables get virtual operands
instead. The dump hides virtual PHIs unless you add -vops
(gimple-pretty-print.cc:3011-3020).
Three things to carry away
Gimplification is a function call, not a pass. cgraph_node::analyze calls
gimplify_function_tree before the first pass list, so passes.def and
-fdump-passes never show it.
gimplify_expr flattens with one rule. It rewrites a node until it stops
changing. If the result does not fit the caller's predicate, the result goes
into a new temporary.
SSA form arrives in two steps. The gimplifier makes its own temporaries
SSA names. pass_build_ssa renames the variables that you wrote and inserts
the PHI nodes.
Things that surprise people
An && in the .original dump may not short-circuit. When optimising,
fold_truth_andor turns a && b into a non-short-circuit TRUTH_AND_EXPR if
both sides are simple comparisons that cannot trap
(fold-const.cc:9677-9734). It does this only when
LOGICAL_OP_NON_SHORT_CIRCUIT is true. A target can define that macro, and
the default is a branch cost of at least 2 (:6240-6243). The C
parser folds every condition with c_fully_fold
(c/c-parser.cc:8423-8433), which folds &&
(c/c-fold.cc:532-562). The printer writes both codes as &&
(tree-pretty-print.cc:4739-4741). The gimplifier turns the
non-short-circuit form into a bitwise & and one if
(gimplify.cc:20225-20270). -fdump-tree-original-raw prints the
tree code names, truth_andif_expr or truth_and_expr
(c-family/c-gimplify.cc:799-801, tree-dump.cc:261-262).
count.c's && stays short-circuit, because a load through v is not a
simple operand (fold-const.cc:5072-5095).
count++ has no post-increment in GIMPLE. A post-increment whose value is
unused becomes count = count + 1.
Documentation coverage
The internals manual describes the result well. The GIMPLE node
(gcc/doc/gimple.texi:6) defines the representation, and its
Temporaries (:522), Operands (:553) and
Logical Operators (:636) nodes give the flattening rules with
examples. Gimplification pass
(gcc/doc/passes.texi:107) names gimplify_function_tree and
gimplify_expr and documents the language hook's return values.
Tree SSA passes (passes.texi:446) has one paragraph
each for the lowering, CFG and SSA passes (:472-509). SSA
(gcc/doc/tree-ssa.texi:440) explains SSA names and PHI nodes. The GCC manual
documents the dump options under Developer Options
(gcc/doc/invoke.texi:20895-20975).
What is not documented, or is out of date at 15.2:
- The predicate and fallback contract of
gimplify_expr. It is only in the comment above the function. - That
cgraph_node::analyzecalls the gimplifier.passes.texi:50-52says that "the C front end manually invokes the gimplifier". At 15.2 the front end callsc_genericizeandcgraph_node::finalize_function. - That
c_genericizelowers C loops togotos before gimplification. Chapter 5.1 covers the stalegimple.texitext that says the C front end has no genericization step. - Which pass makes
ifstatements into jumps. The "Lower control flow" entry (passes.texi:472-480) gives that job topass_lower_cf. At 15.2 the gimplifier does it, andpass_lower_cfdoes the three things in Listing 5.4-11. - That temporaries of register type are SSA names from the gimplifier, so the
reuse that Temporaries describes (
gimple.texi:527-532) does not happen in function bodies. - The no-
elserewrite of&&into nestedifs. Logical Operators excludes the condition of aGIMPLE_CONDand does not say what happens there. - That the
originalandgimpledumps are not passes. Developer Options does not name them, and-fdump-passesdoes not list them. - That
TRUTH_AND_EXPRandTRUTH_ANDIF_EXPRprint the same. tree-ssa.texi:464-465places the renamer intree-ssa.cc. It is intree-into-ssa.cc.
Next: expand, where the GIMPLE of this chapter first meets the target, and
v[i] % d must become either an instruction or a call.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
5.5 Expand and optabs: where the target first appears
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
Compile count.c for a Cortex-M4, and the assembly calls __aeabi_ldivmod, a
function that your source never names. Compile the same file for x86-64, and
there is no call. The v[i] % d is one division instruction. In GIMPLE, that
line is the same % statement on both targets. Something after GIMPLE made the
decision.
$ gcc -O2 -S -o - count.c | grep ldivmod # no match
$ arm-none-eabi-gcc -O2 -mcpu=cortex-m4 -S -o - count.c | grep ldivmod
That something is the expand pass. Expand asks the target how to do each
operation, and it asks through optabs: one table per operation, indexed by
machine mode, that holds an instruction pattern or a library function name.
When the table has no pattern for the mode, expand builds the operation from
other entries, and a library call is the last of them.
This chapter assumes Chapter 5.1, for count.c and the
three representations, Chapter 5.2, for the dump
file names, and Chapter 5.3, for the pass list
that pass_expand belongs to. Chapter 4.1
explains the library that supplies __aeabi_ldivmod.
pass_expand::execute in cfgexpand.cc: out of SSA, then block by block
Chapter 5.1 showed the descriptor of pass_expand
(Listing 5.1-12) and its place in passes.def (Listing 5.1-13). The pass requires
SSA GIMPLE and a CFG, provides PROP_rtl, and destroys the GIMPLE. It belongs to
all_passes, the same list as the RTL passes (passes.def:188,
:453-457), and Chapter 5.3 explains the lists. It is an
RTL_PASS, so the pass manager files its dump with the RTL dumps, under the option
-fdump-rtl-expand (passes.cc:860-875).
These are the main steps of pass_expand::execute:
- It takes the function out of SSA form.
rewrite_out_of_ssagroups the SSA names into partitions, and each partition gets one pseudo register (cfgexpand.cc:7011-7013). Chapter 5.1 explained pseudo registers. Register allocation assigns hardware registers to them later. - It removes the PHI nodes.
expand_phi_nodesputs RTL copies on the CFG edges instead (:7209,tree-outof-ssa.cc:1011-1014). - It expands the basic blocks in order (
cfgexpand.cc:7230-7232).
The CFG survives the change. The comment above the descriptor says that the
conversion is "per basic block" and that it preserves and updates the tree CFG
(:6962-6969).
expand_gimple_stmt and TER: where the RTL for a statement goes
Each statement in a block goes to expand_gimple_stmt, with one exception:
def_operand_p def_p;
def_p = SINGLE_SSA_DEF_OPERAND (stmt, SSA_OP_DEF);
if (def_p != NULL)
{
/* Ignore this stmt if it is in the list of
replaceable expressions. */
if (SA.values
&& bitmap_bit_p (SA.values,
SSA_NAME_VERSION (DEF_FROM_PTR (def_p))))
continue;
}
last = expand_gimple_stmt (stmt);
maybe_dump_rtl_for_gimple_stmt (stmt, last);
Listing 5.5-1: statements that TER forwarded are skipped
(gcc/cfgexpand.cc:6471-6484).
SA.values holds the result of TER, temporary expression replacement.
rewrite_out_of_ssa runs TER when -ftree-ter is in effect
(tree-outof-ssa.cc:1408, :1082-1084). -O1 and higher
turn that option on (opts.cc:606). The structure that carries the
result says: "For an SSA name version V bit V is set iff TER decided that its
definition should be forwarded" (tree-outof-ssa.h:31-33). Expand
does not expand a forwarded statement at its own position. When expand finds that
SSA name as an operand of a later statement, it gets the defining statement and
expands it there (expr.cc:11374-11386). So expand can see
v[i] % d == 0 as one expression, and not as two statements.
This is important when you read the dump. With the details option, expand writes
each statement that it expands, and then the RTL that it emitted for that
statement:
static void
maybe_dump_rtl_for_gimple_stmt (gimple *stmt, rtx_insn *since)
{
if (dump_file && (dump_flags & TDF_DETAILS))
{
fprintf (dump_file, "\n;; ");
print_gimple_stmt (dump_file, stmt, 0,
TDF_SLIM | (dump_flags & TDF_LINENO));
fprintf (dump_file, "\n");
print_rtl (dump_file, since ? NEXT_INSN (since) : since);
}
}
Listing 5.5-2: the ;; header in the expand dump
(gcc/cfgexpand.cc:2754-2765).
A forwarded statement gets no ;; header. If TER forwards the % into the
comparison that tests its result, the RTL for the modulo is under the if. The
same dump tells you which names TER forwarded. Before the first block, it lists
them under the heading Replacing Expressions, one replace with --> line for
each name (tree-ssa-ter.cc:745-761, called at
tree-outof-ssa.cc:1085-1086).
From the statement, the path to the division code is short. An assignment to an
SSA name goes to expand_expr_real_gassign (cfgexpand.cc:4301),
which collects the operation code and its operands and calls expand_expr_real_2
(expr.cc:11200-11203). That function is one large switch on the
tree code. For TRUNC_MOD_EXPR it expands the two operands and calls
expand_expr_divmod (expr.cc:10381-10406). That helper has one
special case. At -O2, if both operands are "known to be positive when
interpreted as signed", it expands the operation as signed and as unsigned. Then
it keeps the cheaper sequence (:9698-9740). In count.c, nothing
tells the compiler that v[i] and d are positive. So the remainder goes
directly to expand_divmod in expmed.cc (:9742).
The optab table: optabs.def and optab_handler
Each operation that expand can ask about has an entry in optabs.def. These are
the entries for division:
OPTAB_NL(sdiv_optab, "div$a3", DIV, "div", '3', gen_int_fp_signed_fixed_libfunc)
...
OPTAB_NC(sdivmod_optab, "divmod$a4", UNKNOWN)
OPTAB_NC(udivmod_optab, "udivmod$a4", UNKNOWN)
OPTAB_NL(smod_optab, "mod$a3", MOD, "mod", '3', gen_int_libfunc)
OPTAB_NL(umod_optab, "umod$a3", UMOD, "umod", '3', gen_int_libfunc)
Listing 5.5-3: the division optabs, abridged (gcc/optabs.def:139,
:146-149).
An OPTAB_NL line gives the optab, the standard pattern name, the RTL code, and
three fields that make a default library function name. $a stands for the mode,
so "mod$a3" in DImode is the pattern name moddi3. The comment at the top of
the file explains the letters (optabs.def:20-46). An OPTAB_NC
line has no library fields. So sdivmod_optab has a pattern name, divmod$a4, but
no default library function (gensupport.cc:3768).
One function asks the question:
/* Return the insn used to implement mode MODE of OP, or CODE_FOR_nothing
if the target does not have such an insn. */
inline enum insn_code
optab_handler (optab op, machine_mode mode)
{
unsigned scode = (op << 20) | mode;
gcc_assert (op > LAST_CONV_OPTAB);
return raw_optab_handler (scode);
}
Listing 5.5-4: optab_handler (gcc/optabs-query.h:34-43).
The answer is an insn_code, which is the number of one named pattern in the
machine description of the target, or CODE_FOR_nothing. The build generates the
table behind raw_optab_handler from the .md files. The table gives a pattern
only while the condition of that pattern is true for the target options of the
current function (genopinit.cc:405, :461-468).
Thus -mcpu and -m32 can change the answer.
Chapter 5.6 explains how a define_expand
named divmoddi4 becomes CODE_FOR_divmoddi4.
The internals manual documents the contract of each standard name, under
Standard Pattern Names For Generation: what each operand
means, and which names a port should define. That node is the list of questions
that expand can ask. Read it together with optabs.def.
optab_libfunc and set_optab_libfunc: the library column
The table has a second column. optab_libfunc (optab, mode) gives the library
function for the operation, or null
(optabs-libfuncs.cc:102-135). GCC makes the default names when
it first needs them, from the fields in optabs.def: two underscores, the
operation name, the mode name in lower case, and the number of operands
(:137-149). Thus smod_optab in DImode is __moddi3. For an
integer operation, gen_int_libfunc makes a name only for modes between one word
and two words wide, or as wide as long long if that is wider
(:187-205).
A port changes this column in its TARGET_INIT_LIBFUNCS hook. init_optabs fills
the pattern column from the machine description, sets some fixed names, and then
calls the hook (optabs-libfuncs.cc:871,
:905). The hook calls set_optab_libfunc, which accepts a
null name (:807-829). A null entry stays null, because
GCC makes a default name only when the table has no entry for that optab and mode
(:120-131). So a port can remove a default name, and not only change
it. The internals manual documents the hook under
Implicit Calls to Library Routines.
optab_methods: pattern, wider mode, library call
The functions that read the table do not stop at the first "no". Each caller passes a method that says how far the fallback can go:
/* Passed to expand_simple_binop and expand_binop to say which options
to try to use if the requested operation can't be open-coded on the
requisite mode. Either OPTAB_LIB or OPTAB_LIB_WIDEN says try using
a library call. Either OPTAB_WIDEN or OPTAB_LIB_WIDEN says try
using a wider mode. OPTAB_MUST_WIDEN says try widening and don't
try anything else. */
enum optab_methods
{
OPTAB_DIRECT,
OPTAB_LIB,
OPTAB_WIDEN,
OPTAB_LIB_WIDEN,
OPTAB_MUST_WIDEN
};
Listing 5.5-5: the fallback methods (gcc/optabs.h:168-183).
expand_binop expands most operations with two operands. It tries these in
order, and the method limits each step:
- A pattern in the requested mode (
optabs.cc:1529-1548). - A pattern in a wider mode (
:1647-1652). - A sequence of word-sized operations. GCC has sequences for logical operations
one word at a time, double-word shifts, additions with carries,
multiplications, and a modulo by a constant (
:1720,:1773,:1975,:2097,:2145). - A library function in the requested mode (
:2193-2238). - A library function in a wider mode (
:2240-2268).
A library call does not appear in the RTL as a plain call. Expand puts the call
in a block. The last instruction in the block has a REG_EQUAL note with the
operation, for example (mod:DI a b) (optabs.cc:2228-2233,
:4164-4173). In the words of the comment on
emit_libcall_block, the result is "logically equivalent to" that operation, and
the note tells the RTL passes so.
expand_divmod: the remainder ladder
Division and modulo do not go to expand_binop directly. They go to
expand_divmod, because a target can have a division pattern, a modulo pattern,
one pattern that gives both results, or none. For a constant divisor,
expand_divmod has long special cases. In count.c, d is a parameter, so expand
gets to the general code at the end.
First, expand_divmod selects a compute mode. This is the first mode, from the
mode of the operands upwards, that has a pattern for division or for
division-and-modulo. If there is none, it is the first mode that has a library
function for one of them (expmed.cc:4366-4386). Then it starts
on the remainder:
/* Try to produce the remainder without producing the quotient.
If we seem to have a divmod pattern that does not require widening,
don't try widening here. We should really have a WIDEN argument
to expand_twoval_binop, since what we'd really like to do here is
1) try a mod insn in compute_mode
2) try a divmod insn in compute_mode
3) try a div insn in compute_mode and multiply-subtract to get
remainder
4) try the same things with widening allowed. */
remainder
= sign_expand_binop (compute_mode, umod_optab, smod_optab,
op0, op1, target,
unsignedp,
((optab_handler (optab2, compute_mode)
!= CODE_FOR_nothing)
? OPTAB_DIRECT : OPTAB_WIDEN));
if (remainder == 0)
{
/* No luck there. Can we do remainder and divide at once
without a library call? */
remainder = gen_reg_rtx (compute_mode);
if (! expand_twoval_binop ((unsignedp
? udivmod_optab
: sdivmod_optab),
op0, op1,
NULL_RTX, remainder, unsignedp))
remainder = 0;
}
Listing 5.5-6: patterns first (gcc/expmed.cc:5272-5299).
If both fail, expand_divmod tries a division pattern, "but not a library call"
(:5305-5333). With a quotient, it computes the remainder as
X - Y * (X / Y) (:5365-5371). Without a quotient, only
library functions are left:
/* No divide instruction either. Use library for remainder. */
remainder = sign_expand_binop (compute_mode, umod_optab, smod_optab,
op0, op1, target,
unsignedp, methods);
/* No remainder function. Try a quotient-and-remainder
function, keeping the remainder. */
if (!remainder
&& (methods == OPTAB_LIB || methods == OPTAB_LIB_WIDEN))
{
remainder = gen_reg_rtx (compute_mode);
if (!expand_twoval_binop_libfunc
(unsignedp ? udivmod_optab : sdivmod_optab,
op0, op1,
NULL_RTX, remainder,
unsignedp ? UMOD : MOD))
remainder = NULL_RTX;
}
Listing 5.5-7: library functions last (gcc/expmed.cc:5345-5361).
methods is OPTAB_LIB_WIDEN here, which is the default value of that parameter
(expmed.h:713-714). For the long long remainder in count.c,
the two targets give these answers:
| Step | Question | x86-64 | arm-none-eabi, Cortex-M4 |
|---|---|---|---|
| 1 | mod pattern in DImode? | no | no |
| 2 | divmod pattern in DImode? | divmoddi4 | no |
| 3 | div pattern in DImode? | not asked | no |
| 4 | mod library function? | not asked | null, set by the port |
| 5 | divmod library function? | not asked | __aeabi_ldivmod |
The next two sections show where each answer comes from.
x86-64: divmoddi4 answers step 2
Chapter 5.1 showed the pattern that answers step 2, as Listing 5.1-11: one
<u>divmod<mode>4 expander in i386.md that sets a div and a mod in one
parallel, with a DImode form only for TARGET_64BIT. In the optab table, its
DImode signed form is the entry for sdivmod_optab, divmoddi4
(optabs.def:146). i386.md has no mod pattern, and its
div<mode>3 pattern is for floating-point modes only
(i386.md:11346-11350). The internals manual recommends this design
for a machine with an instruction that gives both results. Such a port defines
divmodm4, and it does not define divm3 or modm3
(md.texi:6209-6213).
So step 1 fails and step 2 succeeds. expand_twoval_binop gets the pattern from
the optab and calls maybe_expand_insn (optabs.cc:2475-2493).
That call is the boundary between expand and the machine description:
rtx_insn *
maybe_gen_insn (enum insn_code icode, unsigned int nops,
class expand_operand *ops)
{
gcc_assert (nops == (unsigned int) insn_data[(int) icode].n_generator_args);
if (!maybe_legitimize_operands (icode, 0, nops, ops))
return NULL;
switch (nops)
{
...
case 4:
return GEN_FCN (icode) (ops[0].value, ops[1].value, ops[2].value,
ops[3].value);
Listing 5.5-8: expand calls the generator of the pattern, abridged
(gcc/optabs.cc:8177-8197).
maybe_legitimize_operands tries to make each operand satisfy the predicate of
the pattern, and fails without emitting code if it cannot
(:8131-8170). GEN_FCN (icode) is insn_data[icode].genfun
(genopinit.cc:275), a function that the build generates from the
pattern. Here expand stops and the machine
description starts. Chapter 5.6 follows the generator.
The expander has no C body, so the RTL that it emits is its template: the
parallel of Listing 5.1-11, with a div:DI and a mod:DI in two pseudo
registers. count.c uses only the mod:DI result.
Cortex-M4: __aeabi_ldivmod from arm_init_libfuncs
Chapter 5.1 showed that the Arm port defines integer division only in SImode
(arm.md:5129-5153). Its modsi3 pattern is also for SImode
only, and it accepts only a constant divisor (arm.md:12459-12470).
So steps 1 to 3 fail for DImode.
Step 4 asks for a modulo library function, and the port removed it:
/* Long long. Table 9. */
set_optab_libfunc (smul_optab, DImode, "__aeabi_lmul");
set_optab_libfunc (sdivmod_optab, DImode, "__aeabi_ldivmod");
set_optab_libfunc (udivmod_optab, DImode, "__aeabi_uldivmod");
...
/* We don't have mod libcalls. Fortunately gcc knows how to use the
divmod libcalls instead. */
set_optab_libfunc (smod_optab, DImode, NULL);
set_optab_libfunc (umod_optab, DImode, NULL);
set_optab_libfunc (smod_optab, SImode, NULL);
set_optab_libfunc (umod_optab, SImode, NULL);
Listing 5.5-9: arm_init_libfuncs, abridged
(gcc/config/arm/arm.cc:2637-2640,
:2668-2673).
arm_init_libfuncs is the TARGET_INIT_LIBFUNCS hook of the port
(arm.cc:540-541). It sets these names only for the BPABI
(:2573-2576), which arm-none-eabi uses, as Chapter 5.1
showed. Without the null entries, step 4 would find the default name
__moddi3.
Step 5 finds __aeabi_ldivmod and keeps half of its result:
/* The value returned by the library function will have twice as
many bits as the nominal MODE. */
auto return_size = 2 * GET_MODE_BITSIZE (mode);
if (!smallest_int_mode_for_size (return_size).exists (&libval_mode))
return false;
start_sequence ();
libval = emit_library_call_value (libfunc, NULL_RTX, LCT_CONST,
libval_mode,
op0, mode,
op1, mode);
/* Get the part of VAL containing the value that we want. */
libval = simplify_gen_subreg (mode, libval, libval_mode,
targ0 ? 0 : GET_MODE_SIZE (mode));
insns = get_insns ();
end_sequence ();
/* Move the into the desired location. */
emit_libcall_block (insns, targ0 ? targ0 : targ1, libval,
gen_rtx_fmt_ee (code, mode, op0, op1));
Listing 5.5-10: expand_twoval_binop_libfunc
(gcc/optabs.cc:2553-2571).
For two DImode operands, the call returns a TImode value, and the remainder is
the second half. The function in libgcc has the same contract. For a 32-bit Arm
core, libgcc builds it from bpabi.S (lib1funcs.S:2258-2264).
The comment there says that the quotient comes back in r0:r1 and the remainder
in r2:r3 (libgcc/config/arm/bpabi.S:174-184). The
REG_EQUAL note on the final move records (mod:DI op0 op1).
The calling convention is in the RTL from this point. emit_library_call_value_1
asks the target hook function_arg for the register of each argument
(calls.cc:4412) and hard_libcall_value for the register of the
result (:4776). Then emit_call_1 emits the call instruction
(:4794). So the expand dump for the Cortex-M4 has moves into
hard registers, a call_insn to a symbol_ref named __aeabi_ldivmod, and a
move out of the TImode result.
The mode changes the answer: int on Cortex-M4 and Cortex-M0
Change the type of v and d to int, and the Cortex-M4 answer changes. The
divsi3 pattern has the condition TARGET_IDIV
(arm.md:5129-5140). For Thumb code, that condition is the
hardware-divide bit of the architecture (arm.h:354-355,
arm.cc:3933). The Cortex-M4 is an armv7e-m core. Its feature
group, ARMv7em, includes ARMv7m, which includes tdiv
(arm-cpus.in:1266-1274, :568-573,
:293-294). Step 1 finds the
modsi3 pattern, but that pattern wants a constant divisor, and d is in a
register. maybe_legitimize_operands rejects the operand, and expand continues.
Step 2 finds no pattern. Step 3 succeeds, and expand emits a 32-bit division, a
multiplication and a subtraction.
The Cortex-M0 is an armv6s-m core, and its feature group has no tdiv
(arm-cpus.in:474-478, :285). There, steps 1 to 4
fail, and step 5 finds __aeabi_idivmod (arm.cc:2648). It is
the same C, the same ladder, and a different answer for each core.
Before expand: .DIVMOD in pass_optimize_widening_mul
Expand is where the target first changes the representation. It is not the only
pass that reads the optab tables. If a function computes a / b and a % b, the
widening_mul pass (passes.def:364) can replace both with
one call to the internal function DIVMOD. It does this only when
target_supports_divmod_p agrees (tree-ssa-math-opts.cc:5650-5673).
That needs a divmod pattern, or a divmod library function together with the
TARGET_EXPAND_DIVMOD_LIBFUNC hook and no division pattern in that mode or a
wider one. The Arm port defines the hook (arm.cc:800-801).
count.c has a % and no /. The pass does not change a modulo that has no
matching division (tree-ssa-math-opts.cc:5797,
:5823-5824). That is why the GIMPLE for count.c has the same
% statement on both targets. If the loop also used v[i] / d, both targets
would pass that test: x86-64 has divmoddi4, and the Cortex-M4 has
__aeabi_ldivmod and the hook. The GIMPLE could then change before expand
runs.
Seeing it: -fdump-rtl-expand-details
The GCC manual documents -fdump-rtl-expand ("Dump after RTL generation") and
the details option under Developer Options, and -mcpu under
ARM Options. Compile count.c once for each target, in two
directories. A compile with -c and no -o writes its dumps to the current
directory (gcc.cc:5113-5118). Both compilers give the expand dump
the same name, because both ports insert their own passes after expand
(i386-passes.def:27-39, arm-passes.def:21).
Chapter 5.2 explains the numbers.
$ mkdir x86 cm4
$ (cd x86 && gcc -O2 -c -fdump-rtl-expand-details ../count.c)
$ (cd cm4 && arm-none-eabi-gcc -O2 -mcpu=cortex-m4 -c \
-fdump-rtl-expand-details ../count.c)
$ grep -n 'mod:DI' x86/count.c.*r.expand cm4/count.c.*r.expand
$ grep -n 'ldivmod' cm4/count.c.*r.expand
The two dumps were not produced for this chapter. The source shows what to look
for. Both files contain mod:DI. In x86, it is in the parallel of
Listing 5.1-11. In cm4, it is in the REG_EQUAL note after the call, and the
second grep finds the symbol_ref in the call_insn. Search for the ;; header
of each statement to find the GIMPLE that the RTL came from.
Three things to carry away
Expand asks the target about each operation, through one table.
optab_handler gives a pattern or CODE_FOR_nothing, and optab_libfunc gives a
function name or null.
A library call is the last step of the ladder, not a separate mechanism.
expand_divmod tries a modulo pattern, a division-and-modulo pattern and a
division pattern before it asks for a library function.
The port supplies the library names. TARGET_INIT_LIBFUNCS replaces the
default names, and a null entry removes one. That is why the Cortex-M4 calls
__aeabi_ldivmod and never __moddi3.
Things that surprise people
-O0 does not remove the call. The ladder in expand_divmod is the only way
that expand can compute a long long remainder on the Cortex-M4. It is not an
optimisation. At -O0 TER is off, so the % gets its own ;; header in the
details dump.
A core with a division instruction can still call a library function. The
Cortex-M4 divides 32-bit values in hardware. A long long modulo is still a call.
The RTL still says mod. After the call, a REG_EQUAL note records the
operation that the call computes.
x86-64 has no moddi3 pattern. The remainder is the second output of
divmoddi4.
Documentation coverage
The GCC manual documents -fdump-rtl-expand and the details
option in Developer Options (gcc/doc/invoke.texi:20496-20498 and
:20931-20933), and -mcpu in ARM Options (:24131). The internals
manual documents the standard pattern names in
Standard Names (gcc/doc/md.texi:4798), with
divmodm4 at :6203-6219 and modm3 at :5551. It
documents TARGET_INIT_LIBFUNCS and TARGET_EXPAND_DIVMOD_LIBFUNC in
Library Calls (gcc/doc/tm.texi:5866-5874 and :7905-7908),
and the default __moddi3 in Integer library routines
(gcc/doc/libgcc.texi:84). Its RTL passes node lists the
source files of RTL generation (gcc/doc/passes.texi:878-898).
What is not documented:
- That
cfgexpand.ccis the entry point of RTL generation. The list in the RTL passes node does not name it. - That TER moves the RTL of a forwarded statement under the statement that uses
it, in the
detailsdump, and that the same dump lists the forwarded names underReplacing Expressions. - The order in which
expand_binoptries a pattern, a wider mode, word-sized operations and library functions. - The order of the remainder ladder in
expand_divmod, and that it asks for a library function only after three pattern attempts. - That a null
set_optab_libfuncentry stops GCC from making the default name. - That the Arm port has no modulo library functions and uses the remainder half
of
__aeabi_ldivmod. The Arm Run-time ABI defines that function, and no GCC manual names it. - The
TARGET_INIT_LIBFUNCStext says thatset_optab_libfuncandinit_one_libfuncare inoptabs.cc. At the pin they are inoptabs-libfuncs.cc(:781,:807). The text comes fromtarget.def:2658.
Next: how the divmod<mode>4 text in i386.md becomes the CODE_FOR_divmoddi4
and the generator function that expand called.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
5.6 How a machine description becomes an instruction
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
The Arm port names gen_addsi3 in 42 places in gcc/config/arm/arm.cc, for
example to add an offset to a base register (arm.cc:8309).
Search the checkout for its definition and you find none. Ask the compiler
which pattern made an instruction, and it can answer *arm_addsi3, a name that
no C function can have. Both names come from gcc/config/arm/arm.md, and
neither is defined in C anywhere in the repository.
cc1 never reads a .md file. Generator programs read it while GCC builds,
and write the C that cc1 runs: a gen_ function for each named pattern, one
recogniser for all patterns, and the tables that join them. The name of a
pattern decides which of these it gets.
This chapter assumes Chapter 5.1, for RTL and the
count.c example, Chapter 5.5, for how expand picks a
named pattern through an optab, and
Chapter 2.4, for the generated files in
build/gcc/. The target is the one from Chapter 5.5:
arm-none-eabi-gcc -O2 -mcpu=cortex-m4.
md_file: the input that every generator reads
configure chooses one file per target. config.gcc sets cpu_type=arm for
every arm*-*-* triple (config.gcc:375-376), and a target that
names no md_file gets $cpu_type/$cpu_type.md
(configure.ac:1943-1944). The makefile adds one shared file in
front:
md_file=$(srcdir)/common.md $(srcdir)/config/@md_file@
Listing 5.6-1: two files make the machine description
(gcc/Makefile.in:608).
common.md holds what all targets share, such as the r constraint
(common.md:48-49). arm.md includes the rest of the port: the
iterators, predicates and constraints (arm.md:397-403), one
pipeline description per core, cortex-m4.md among them
(:460), and the Thumb-2 patterns in thumb2.md
(:13135). Each generator rule in gcc/Makefile.in runs a
build/gen* program over $(md_file) and writes into build/gcc/
(Makefile.in:2742-2806). These are the generators this
chapter follows:
| Generator | Writes | What cc1 gets |
|---|---|---|
gencodes | insn-codes.h | enum insn_code, one CODE_FOR_ per named pattern |
genflags | insn-flags.h | a HAVE_ macro and a gen_ prototype per named pattern |
genemit | insn-emit-N.cc | the gen_ functions, and the bodies of splits |
genrecog | insn-recog-N.cc, insn-recog.h | recog and split_insns |
genoutput | insn-output.cc | insn_data[]: names, output templates, operand data |
genopinit | insn-opinit.cc, insn-opinit.h | the optab table that Chapter 5.5 reads |
genattrtab | insn-attrtab.cc, insn-dfatab.cc, insn-latencytab.cc | attribute functions and scheduler tables |
genpreds | insn-preds.cc, tm-preds.h, tm-constrs.h | predicate and constraint functions |
Most of them also read insn-conditions.md. genconditions collects the C
condition of every pattern into a program that the build compiler compiles and
runs, and its output records which conditions are constant
(Makefile.in:2809-2820). A condition can "turn out to be always
false when the compiler is built", and then most generators "can simply ignore
the entire pattern"
(genconditions.cc:20-26).
The numbered files are recent. At releases/gcc-13.3.0, insn-emit.cc and
insn-recog.cc were single files (Makefile.in:2447-2449).
GCC 14 split the emitter (Makefile.in:238-242 at
releases/gcc-14.1.0), and GCC 15 split the recogniser into the same number of
files (Makefile.in:243-246). Chapter 2.4 covers the build side.
define_expand "addsi3": one named pattern, four generated artefacts
This is the pattern behind gen_addsi3:
(define_expand "addsi3"
[(set (match_operand:SI 0 "s_register_operand")
(plus:SI (match_operand:SI 1 "s_register_operand")
(match_operand:SI 2 "reg_or_int_operand")))]
"TARGET_EITHER"
"
if (TARGET_32BIT && CONST_INT_P (operands[2]))
{
arm_split_constant (PLUS, SImode, NULL_RTX,
INTVAL (operands[2]), operands[0], operands[1],
optimize && can_create_pseudo_p ());
DONE;
}
"
)
Listing 5.6-2: the addsi3 expander
(gcc/config/arm/arm.md:905-919).
A define_expand has a name, an RTL template, a condition, and C code that runs
before the template is used. addsi3 is a standard name: the operation, the
mode SI, and the operand count. Each match_operand has a predicate and no
constraint string. The expander only builds RTL, and a define_insn with
constraints must match the result later. The condition is TARGET_EITHER,
which the port defines as 1 (arm.h:148). In 32-bit code, for
a constant operand, the C code calls arm_split_constant, which emits "a sequence
of insns to handle a large constant" (arm.cc:4740-4752),
and then DONE. For a register operand the C code does nothing, and the
template becomes the insn. The internals manual documents these outcomes under
Overview and Expander Definitions, and the
standard names under Standard Names.
Four generators turn this one form into four things.
gencodes gives it a number. It writes one enumerator per named pattern:
static void
gen_insn (md_rtx_info *info)
{
const char *name = XSTR (info->def, 0);
int truth = maybe_eval_c_test (XSTR (info->def, 2));
/* Don't mention instructions whose names are the null string
or begin with '*'. They are in the machine description just
to be recognized. */
if (name[0] != 0 && name[0] != '*')
{
if (truth == 0)
printf (",\n CODE_FOR_%s = CODE_FOR_nothing", name);
else
printf (",\n CODE_FOR_%s = %d", name, info->index);
}
}
Listing 5.6-3: where CODE_FOR_addsi3 comes from
(gcc/gencodes.cc:31-47).
info->index counts every define_insn and define_expand in md_file, in
order. It starts at 1, "to make 0 available for CODE_FOR_nothing"
(gensupport.cc:3140-3141), the first value in insn-codes.h
(gencodes.cc:69). A pattern whose condition is always false
keeps its name with the value CODE_FOR_nothing, so C code that names it still
compiles.
genflags gives it a HAVE_addsi3 macro, whose value is the condition,
and a prototype for gen_addsi3 (genflags.cc:107,
:178-195).
genemit writes gen_addsi3. The function opens an insn sequence, copies
its arguments into operands[], pastes in the C code, emits the template, and
returns the sequence (genemit.cc:458-565). Two macros give
DONE and FAIL their meaning:
static void
emit_c_code (const char *code, bool can_fail_p, const char *name, FILE *file)
{
if (can_fail_p)
fprintf (file, "#define FAIL return (end_sequence (), _val)\n");
else
fprintf (file, "#define FAIL _Pragma (\"GCC error \\\"%s cannot FAIL\\\"\")"
" (void)0\n", name);
fprintf (file, "#define DONE return (_val = get_insns (), "
"end_sequence (), _val)\n");
Listing 5.6-4: DONE and FAIL are return statements
(gcc/genemit.cc:311-320).
DONE returns what the C code emitted, so the template is never reached.
FAIL returns _val, which is still null (genemit.cc:511), and
the caller must find another way. For an optab behind an internal function in
internal-fn.def, a FAIL is a compile error in the generated file instead
(genemit.cc:934-936). Above each function, genemit writes the
.md file and line that it came from (genemit.cc:964-975).
genopinit puts it in the optab table. optabs.def gives the pattern
names of add_optab as "add$P$a3" (optabs.def:118), where
$a stands for a mode name in lower case (:29-33).
genopinit tests every pattern name against these shapes
(genopinit.cc:41-47, gensupport.cc:3896-3918).
addsi3 fits, so the table gets a CODE_FOR_addsi3 entry, enabled by
HAVE_addsi3 (genopinit.cc:364-368,
:405). The lookup returns the entry only while that flag is
set (:461-468). The same file defines GEN_FCN as
insn_data[CODE].genfun (genopinit.cc:275). Chapter 5.5 follows
expand from the optab to that call. This chapter starts where the call lands, in
gen_addsi3.
*arm_addsi3: a star means "recognise only"
The insn that gen_addsi3 emits must later match a define_insn. For an
SImode addition in 32-bit code, this is the pattern:
(define_insn_and_split "*arm_addsi3"
[(set (match_operand:SI 0 "s_register_operand" "=rk,l,l ,l ,r ,k ,r,k ,r ,k ,r ,k,k,r ,k ,r")
(plus:SI (match_operand:SI 1 "s_register_operand" "%0 ,l,0 ,l ,rk,k ,r,r ,rk,k ,rk,k,r,rk,k ,rk")
(match_operand:SI 2 "reg_or_int_operand" "rk ,l,Py,Pd,rI,rI,k,rI,Pj,Pj,L ,L,L,PJ,PJ,?n")))]
"TARGET_32BIT"
"@
add%?\\t%0, %0, %2
add%?\\t%0, %1, %2
add%?\\t%0, %1, %2
add%?\\t%0, %1, %2
add%?\\t%0, %1, %2
add%?\\t%0, %1, %2
add%?\\t%0, %2, %1
add%?\\t%0, %1, %2
addw%?\\t%0, %1, %2
addw%?\\t%0, %1, %2
sub%?\\t%0, %1, #%n2
sub%?\\t%0, %1, #%n2
sub%?\\t%0, %1, #%n2
subw%?\\t%0, %1, #%n2
subw%?\\t%0, %1, #%n2
#"
Listing 5.6-5: one addition, sixteen alternatives
(gcc/config/arm/arm.md:940-961).
The star turns off three of the four artefacts. The comment in Listing 5.6-3
gives the reason: such patterns are "in the machine description just to be
recognized". gencodes, genflags and genemit skip them
(genflags.cc:167-171, genemit.cc:419-423), and
find_optab rejects them on its first line (gensupport.cc:3901-3902).
So there is no CODE_FOR_ and no gen_ function, and no C code can ask for
this pattern by name. It still takes a number from the same count as addsi3,
an entry in insn_data[], and a place in the recogniser.
genrecog turns all the define_insn forms into one decision tree. Its header
comment states the contract of the function it writes:
recog returns -1 if the rtx is not valid. If the rtx is valid,
recog returns a nonnegative number which is the insn code number
for the pattern that matched. This is the same as the order in the
machine description of the entry that matched. This number can be
used as an index into various insn_* tables, such as insn_template,
insn_outfun, and insn_n_operands (found in insn-output.cc).
Listing 5.6-6: what recog returns
(gcc/genrecog.cc:26-31).
The tree tests the shape of the RTL first, then modes and predicates, then
match_dups, and the C condition last (genrecog.cc:56-70).
Here the condition is TARGET_32BIT, which is true in ARM state and in Thumb-2
(arm.h:162). The arm in the name is older than Thumb-2. A
Cortex-M4 uses this pattern, although it has no ARM state.
define_insn_and_split is a shorthand. When gensupport.cc reads it, it makes
a define_insn and a define_split from the same RTL, and removes the
constraints from the split's copy (gensupport.cc:1132-1180).
Every generator sees the two forms. A later section covers the split half.
Predicates and constraints: reg_or_int_operand and Py
Each match_operand in Listing 5.6-5 has two strings. The first is a
predicate. genpreds turns predicates.md into C functions, and recog calls
them, so a predicate decides whether the insn matches at all:
;; Reg, subreg(reg) or const_int.
(define_predicate "reg_or_int_operand"
(ior (match_code "const_int")
(match_operand 0 "s_register_operand")))
Listing 5.6-7: operand 2 is a register or any integer
(gcc/config/arm/predicates.md:226-229).
The second string holds the constraints, one per alternative, separated by
commas. Read Listing 5.6-5 in columns, and count alternatives from 0, as
which_alternative does. Alternative 2 wants operand 0 in a low register
(l), operand 1 in the same register as operand 0 (0), and operand 2 to be a
Py constant:
(define_constraint "Py"
"@internal In Thumb-2 state a constant in the range 0 to 255"
(and (match_code "const_int")
(match_test "TARGET_THUMB2 && ival >= 0 && ival <= 255")))
Listing 5.6-8: one constraint
(gcc/config/arm/constraints.md:277-280).
Predicates and constraints work at different times. Before register allocation
an operand is usually a pseudo register, which has no hard register yet. The
predicate accepts it, and the insn is recognised. The register allocator then
picks an alternative whose constraints it can satisfy, and
Chapter 5.7 shows that choice in the dumps.
At the end, final prints the template with the same index:
output.multi[which_alternative] (final.cc:2023-2035). The
@ that opens the template string in Listing 5.6-5 makes it one template per
line, in alternative order, as Output Template documents.
Some of these letters are also asm constraints. The GCC manual documents l,
k, I and L for inline assembly, in the Arm table under
Machine Constraints, because extend.texi includes the
internals manual's md.texi (extend.texi:12620,
md.texi:2153). Constraints marked @internal, such as Py,
Pj and Pd, are in neither manual. Their only documentation is the string in
constraints.md.
arch and enabled: alternatives that a CPU switches off
Sixteen alternatives serve ARM state and Thumb-2 together. Attributes remove the alternatives that do not apply:
[(set_attr "length" "2,4,4,4,4,4,4,4,4,4,4,4,4,4,4,16")
(set_attr "predicable" "yes")
(set_attr "predicable_short_it" "yes,yes,yes,yes,no,no,no,no,no,no,no,no,no,no,no,no")
(set_attr "arch" "t2,t2,t2,t2,*,*,*,a,t2,t2,*,*,a,t2,t2,*")
(set (attr "type") (if_then_else (match_operand 2 "const_int_operand" "")
(const_string "alu_imm")
(const_string "alu_sreg")))
]
Listing 5.6-9: the attributes of *arm_addsi3
(gcc/config/arm/arm.md:973-980).
arch takes one value per alternative: t2 for Thumb-2 only, a for ARM state
only, and * for the default, any (arm.md:143-154).
arch_enabled turns each value into yes or no with a C test, such as
TARGET_THUMB2 for t2 (arm.md:172-174). The enabled attribute
is no wherever arch_enabled is no (arm.md:253-269). The
compiler knows the name enabled: it never uses an alternative for which
enabled is no. The internals manual documents this under
Disable Insn Alternatives.
-mcpu=cortex-m4 alone gives Thumb code. The Arm driver adds -mthumb for a
Thumb-only CPU when the command line has neither -marm nor -mthumb
(arm.h:2546-2553). So alternatives 7 and 12, the two marked
a, are off for every addition in count.c.
define_split and the "#" template
The last alternative takes any constant (?n), and its template is "#". In
the words of final.cc, a "#" template "means that this insn must be split"
(final.cc:2805-2806).
The second half of the define_insn_and_split says how:
"TARGET_32BIT
&& CONST_INT_P (operands[2])
&& !const_ok_for_op (INTVAL (operands[2]), PLUS)
&& (reload_completed || !arm_eliminable_register (operands[1]))"
[(clobber (const_int 0))]
"
arm_split_constant (PLUS, SImode, curr_insn,
INTVAL (operands[2]), operands[0],
operands[1], 0);
DONE;
"
Listing 5.6-10: the split condition and the split body
(gcc/config/arm/arm.md:962-972).
The condition selects a constant that no single add accepts. The RTL
(clobber (const_int 0)) is a placeholder, because the C code emits the new
insns itself and ends with DONE, as the expander in Listing 5.6-2 did.
genemit writes that C code into a split function, and genrecog writes
split_insns, which matches an insn against every define_split
(genrecog.cc:42-44).
The split passes call split_insns. The first, split1
(recog.cc:4481), runs before register allocation
(passes.def:500). final is the last resort: a "#" that
reaches it is split there, but only on a target without a length attribute
(final.cc:2805-2822). Arm has one
(arm.md:140-141), so on Arm the split passes must split every
"#" insn before final.
The host compiler shows a whole pattern that must split. On x86-64, count.c's
% goes through the <u>divmod<mode>4 expander
(i386.md:11371). Its result has the shape of *divmod<mode>4,
whose only template is "#" and whose split condition is reload_completed
(i386.md:11607-11616). After register allocation it splits
into a sign extension and *<u>divmod<mode>4_noext, whose template prints the
divide instruction (:11868-11878). Chapter 5.7 shows what
reload did in between.
Insn attributes: type for the scheduler, predicable for define_cond_exec
The attributes in Listing 5.6-9 feed two more mechanisms.
type is alu_imm when operand 2 is a constant and alu_sreg when it is not.
The pipeline descriptions read it, together with tune, an attribute whose
values are the CPU names from arm-cpus.in (arm-tune.md:1-2,
:23-55). For -mcpu=cortex-m4 the name is cortexm4
(arm-cpus.in:1266-1267), and this reservation applies:
;; ALU and multiply is one cycle.
(define_insn_reservation "cortex_m4_alu" 1
(and (eq_attr "tune" "cortexm4")
(ior (eq_attr "type" "alu_imm,alus_imm,logic_imm,logics_imm,\
alu_sreg,alus_sreg,logic_reg,logics_reg,\
...
"cortex_m4_ex")
Listing 5.6-11: an ALU insn on a Cortex-M4, abridged
(gcc/config/arm/cortex-m4.md:31-48).
genattrtab writes the attribute functions, such as get_attr_type, into
insn-attrtab.cc, and the scheduler's tables into insn-dfatab.cc and
insn-latencytab.cc (Makefile.in:2788-2796). genautomata
writes insn-automata.cc (Makefile.in:2726). The scheduler
never compares the string alu_imm. It calls the generated functions. The
internals manual documents the attribute language under
Insn Attributes, and the pipeline forms under
Processor pipeline description.
predicable "yes" connects the pattern to the port's one define_cond_exec:
(define_cond_exec
[(match_operator 0 "arm_comparison_operator"
[(match_operand 1 "cc_register" "")
(const_int 0)])]
"TARGET_32BIT
&& (!TARGET_NO_VOLATILE_CE || !volatile_refs_p (PATTERN (insn)))"
""
[(set_attr "predicated" "yes")]
)
Listing 5.6-12: the Arm predicate
(gcc/config/arm/arm.md:12236-12244).
For each predicable define_insn, gensupport.cc builds a second insn. Its RTL
wraps the original in a cond_exec with this condition, and its name is new:
new_name = XNEWVAR (char, strlen XSTR (insn_elem->data, 0) + 4);
sprintf (new_name, "*p %s", XSTR (insn_elem->data, 0));
Listing 5.6-13: the name of the predicated copy
(gcc/gensupport.cc:2321-2322).
So the recogniser knows a pattern called *p *arm_addsi3, which is in no .md
file. When a pass makes the addition conditional, the insn matches that copy.
The %? in each template is where arm_print_operand writes the condition
(arm.cc:24237-24239). The internals manual documents
define_cond_exec under Conditional Execution.
Iterators: <Us>mulsidi3 is two expanders
A modern .md file writes many patterns once, with iterators:
(define_expand "<Us>mulsidi3"
[(set (match_operand:DI 0 "s_register_operand")
(mult:DI
(SE:DI (match_operand:SI 1 "s_register_operand"))
(SE:DI (match_operand:SI 2 "s_register_operand"))))]
"TARGET_32BIT"
{
emit_insn (gen_<US>mull (gen_lowpart (SImode, operands[0]),
gen_highpart (SImode, operands[0]),
operands[1], operands[2]));
DONE;
}
)
Listing 5.6-14: a widening multiply, signed and unsigned
(gcc/config/arm/arm.md:2420-2432).
SE is a code iterator over sign_extend and zero_extend
(iterators.md:383). <Us> and <US> are code attributes, which map
each code to a string:
;; Assembler mnemonics for signedness of widening operations.
(define_code_attr US [(sign_extend "s") (zero_extend "u")])
(define_code_attr Us [(sign_extend "") (zero_extend "u")])
Listing 5.6-15: the strings behind <US> and <Us>
(gcc/config/arm/iterators.md:2093-2095).
So Listing 5.6-14 is two expanders: mulsidi3, which calls gen_smull, and
umulsidi3, which calls gen_umull. A mode iterator does the same over modes.
QHSI lists QI, HI and SI (iterators.md:39), so
extend<mode>di2 defines extendqidi2, extendhidi2 and extendsidi2
(arm.md:5588-5590).
The reader expands iterators before any generator sees a form: read_rtx passes
each one to apply_iterators (read-rtl.cc:1516). Every
generator therefore sees concrete names, and genflags reports an "unresolved
iterator" if a < survives (genflags.cc:152-156). The internals
manual documents the syntax under Iterators.
For you, the consequence is that grep umulsidi3 finds no .md file. A build
directory can print the description after expansion. The mddump target runs
genmddump over $(md_file) (Makefile.in:2861-2863). It writes
the description "with expanded iterators" to tmp-mddump.md, with a
;; file: line comment before each form
(genmddump.cc:21-23, :51). This recipe was
not run at the pin:
$ cd build/gcc && make mddump && grep -n -A3 '"umulsidi3"' tmp-mddump.md
From an instruction back to arm.md: -dp and -fdump-rtl-vregs
An obvious route is to read an insn code in -fdump-rtl-expand and look it up
in insn-codes.h. Neither step works, as this section shows. These two
commands do work, with an installed cross compiler and no build directory:
$ arm-none-eabi-gcc -O2 -mcpu=cortex-m4 -S -dp count.c
$ arm-none-eabi-gcc -O2 -mcpu=cortex-m4 -c -fdump-rtl-vregs count.c
-dp makes final add a comment to the assembler line of each insn. The GCC
manual documents -dp under Developer Options. The comment
holds the insn's UID, its cost and length, the pattern name from insn_data[],
and /N for the alternative when the pattern has more than one
(final.cc:3208-3233). On Arm the comment starts with @
(aout.h:318-320).
The name can differ from the one in an earlier dump. After register
allocation, thumb2_reorg in arm.cc converts instructions "to their
cc-clobbering variant if possible, since that allows us to use smaller
encodings" (arm.cc:19410-19411). An addition between low
registers can then match *thumb2_addsi_short, which clobbers the condition
codes (thumb2.md:1296-1300).
The RTL dumps print the same name. An insn's code comes after its location
(rtl.def:145), and print-rtl.cc writes the code, and then the name in braces when the code is not
negative:
if (flag_dump_unnumbered
&& (is_insn || NOTE_P (in_rtx)))
fputc ('#', m_outfile);
else
fprintf (m_outfile, " %d", value);
if (is_insn && &INSN_CODE (in_rtx) == &XINT (in_rtx, idx)
&& XINT (in_rtx, idx) >= 0
&& (name = get_insn_name (XINT (in_rtx, idx))) != NULL)
fprintf (m_outfile, " {%s}", name);
Listing 5.6-16: the code and the pattern name in a dump
(gcc/print-rtl.cc:526-535).
The expand dump is the wrong place to look. Every new insn starts with code -1
(emit-rtl.cc:4134), and gen_addsi3 does not recognise what it
emits. Recognition happens on demand, in recog_memoized, which calls recog
once and stores the result in the insn (recog.h:318-324). So
most insns in the expand dump show -1 and no name. The pass after expand,
vregs (passes.def:453-457), walks every insn
(function.cc:1980-1994) and, apart from a few special cases
that involve virtual registers, calls extract_insn on it, which recognises
the insn (recog.cc:2875-2880). The .vregs dump is the
first in which almost every insn carries its pattern name.
Chapter 5.2 explains the dump file names.
Do not search for the number. It is the pattern's position in this build's
md_file (Listing 5.6-6), so another release, target or configuration gives
another number. For a star name it also leads nowhere, because insn-codes.h
has no entry for it (Listing 5.6-3). Search for the name:
$ grep -n '"\*arm_addsi3"' gcc/config/arm/*.md
That finds the define_insn_and_split at arm.md:940. If a name is not found,
the generators made it. Remove a leading *p to get the predicated original,
or look for the name written with an iterator. In a build directory the number
indexes insn_data[] in insn-output.cc, whose name field is the string the
dump printed (genoutput.cc:411-421). The gen_ functions in
insn-emit-N.cc each carry the /* file:line */ comment from
genemit, so a grep for arm.md:905 there finds gen_addsi3.
Three things to carry away
A .md file is input to the generators, never to cc1. Every gen_
function, every CODE_FOR_ and the recogniser exist only in build/gcc/.
The name decides the role. A standard name gets a gen_ function and an
optab entry. A * name only takes part in recognition, and *p names and
iterator names are made by the generators.
Find a pattern by its name, not its number. -dp and the dumps from
vregs onwards print the name. The number is a position in one build's
machine description.
Things that surprise people
The expand dump shows no pattern names. Nothing has asked recog yet. Use
the vregs dump or a later one.
*arm_addsi3 matches Thumb-2 code. Its condition is TARGET_32BIT, which
covers Thumb-2, and its arch attribute switches off the ARM-only
alternatives.
grep umulsidi3 gcc/config/arm/*.md finds nothing. An iterator writes that
name when the description is read.
Documentation coverage
The internals manual documents the machine description language in its
Machine Desc chapter, gcc/doc/md.texi: the
Overview (md.texi:55), Patterns
(:103), Predicates (:879), Constraints
(:1240), Disable Insn Alternatives (:4375),
Standard Names (:4798), Expander Definitions
(:9050), Insn Splitting (:9264),
Insn Attributes (:10059),
Processor pipeline description (:10852),
Conditional Execution (:11372) and
Iterators (:11851). The GCC manual includes the constraint
nodes for asm users, with the Arm table under
Machine Constraints (md.texi:1916, Arm at :2153, included at
extend.texi:12620). -dp is in Developer Options
(invoke.texi:20660-20665).
What is not documented:
- A list of the generators and the files that each writes. The Passes node
names a few, and still calls the emitter one file,
insn-emit.cc(passes.texi:891-900). - That
define_insnanddefine_expandshare one numbering from 1, that 0 isCODE_FOR_nothing, and that a*pattern has a number but noCODE_FOR_. - That insns in the expand dump carry no code, and that
vregsis the first pass to recognise them all. - That
define_cond_execmakes patterns named*p NAME. - That
make mddumpprints the description after iterator expansion. - The
@internalconstraints, such asPy, outsideconstraints.md.
Next: register allocation, where IRA and LRA pick one alternative for each insn,
and final prints its template.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
5.7 How a pseudo becomes %rdx: IRA, LRA and final
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
The expand dump of count.c is full of registers such as (reg:DI 101). The
.s file has %rax, %rdx and sometimes an
operand such as 8(%rsp). Between the two, the pseudo registers of RTL
became the general registers of x86-64, and some values went to the stack. You look in the dump list for the pass that did it and find one called
reload. On x86-64 at the pin, the old reload pass never runs. The dump
named reload is written by LRA, and the pass before it, ira, made most of
the decisions.
This chapter assumes Chapter 5.2 for dump file
names, Chapter 5.3 for how a pass name becomes a
-fdump- flag, and Chapter 5.6 for
constraints and alternatives in a define_insn. It uses count.c from
Chapter 5.1. Register allocation is a deep subject.
This chapter does not teach its algorithms. It shows which file decided where a
value lives, which dump line records that decision, and how final turns the
result into text.
pass_ira and pass_reload: two passes, one table
The two passes are adjacent in passes.def, late in the RTL list
(passes.def:511-512):
NEXT_PASS (pass_ira);
NEXT_PASS (pass_reload);
Listing 5.7-1: the register allocation passes in the pass list
(gcc/passes.def:511-512).
Both are defined in ira.cc. Their descriptors give the names "ira" and
"reload" (ira.cc:6103-6136, :6148-6179), so the
dump flags are -fdump-rtl-ira and -fdump-rtl-reload. Both gates return
!targetm.no_register_allocation, so a target that does not allocate registers
at all skips both.
The ira pass is the integrated register allocator. For each pseudo it
chooses a hard register, or decides that the pseudo lives in memory. The header
comment of ira.cc names the method: "a regional register allocator performing
graph coloring on a top-down traversal of nested regions", where a region is
the whole function or a loop (ira.cc:21-38). The internals manual
describes the same allocator under RTL passes.
IRA does not rewrite the RTL with its answer. It writes the answer into a table:
hard_regno = ALLOCNO_HARD_REGNO (a);
regno = ALLOCNO_REGNO (a);
reg_renumber[regno] = (hard_regno < 0 ? -1 : hard_regno);
Listing 5.7-2: IRA's answer, one entry per pseudo, -1 for memory
(gcc/ira.cc:2486-2488), in setup_reg_renumber.
reg_renumber is the "Vector of substitutions of register numbers, used to map
pseudo regs into hardware regs" (regs.h:179-186). So the RTL at
the end of the .ira dump still uses pseudos. The assignment is in the side
table, and the next pass reads it.
The next pass is reload, and its execute calls do_reload. That function
picks one of two implementations:
if (ira_use_lra_p)
{
...
ira_destroy ();
lra (ira_dump_file, internal_flag_ira_verbose);
...
}
else
{
df_set_flags (DF_NO_INSN_RESCAN);
build_insn_chain ();
need_dce = reload (get_insns (), ira_conflicts_p);
}
Listing 5.7-3: one pass, two allocators, abridged
(gcc/ira.cc:5974-6000).
ira_use_lra_p is set once from a target hook, ira_use_lra_p = targetm.lra_p ()
(ira.cc:1659). The hook's documentation in target.def says that
"The default version of this target hook returns true. New ports should use LRA,
and existing ports are encouraged to convert" (target.def:5792-5800),
and default_lra_p does return true (targhooks.cc:1317-1320).
The x86, Arm and AArch64 back ends at the pin do not override the hook, so they
use LRA. LRA reads IRA's table through lra_get_regno_hard_regno, which returns
reg_renumber[regno] (lra-int.h:446-450).
Why there are two allocators: ira.cc and lra.cc
The split is a division of work, not two rival algorithms. IRA works on the whole function and decides where each pseudo lives. It knows register classes and costs, but it does not make each instruction valid. LRA, the local register allocator, takes IRA's answer and works one instruction at a time. Its job is in its header comment:
In brief LRA works by iterative insn process with the final goal is
to satisfy all insn and address constraints:
o New reload insns (in brief reloads) and reload pseudos might be
generated;
o Some pseudos might be spilled to assign hard registers to
new reload pseudos;
o Recalculating spilled pseudo values (rematerialization);
o Changing spilled pseudos to stack memory or their equivalences;
o Allocation stack memory changes the address displacement and
new iteration is needed.
Listing 5.7-4: what LRA is for (gcc/lra.cc:34-43).
The same comment opens with "The Local Register Allocator (LRA) is a replacement
of former reload pass" (lra.cc:22-23). That is where the dump
name comes from. The pass kept the name reload when LRA replaced the old
implementation behind it. Listing 5.7-3 shows that the old implementation is
still there for targets that ask for it.
Reading IRA's answer: Disposition: in the .ira dump
Run the allocator dumps on the shared example:
$ gcc -O2 -c -fdump-rtl-ira -fdump-rtl-reload count.c
$ grep -n -A8 '^Disposition:' count.c.*r.ira
The GCC manual lists -fdump-rtl-ira under Developer Options,
with the description "Dump after iterated register allocation". The pass is the
integrated allocator, as its own header comment says. The same node does not
list -fdump-rtl-reload. The flag exists because the pass is named reload.
The Disposition: block is IRA's assignment, printed by one function:
fprintf (f, " %4d:r%-4d", ALLOCNO_NUM (a), ALLOCNO_REGNO (a));
if ((bb = ALLOCNO_LOOP_TREE_NODE (a)->bb) != NULL)
fprintf (f, "b%-3d", bb->index);
else
fprintf (f, "l%-3d", ALLOCNO_LOOP_TREE_NODE (a)->loop_num);
if (ALLOCNO_HARD_REGNO (a) >= 0)
fprintf (f, " %3d", ALLOCNO_HARD_REGNO (a));
else
fprintf (f, " mem");
Listing 5.7-5: one entry of the Disposition: list
(gcc/ira.cc:714-722), in ira_print_disposition.
Each entry is an allocno, IRA's name for the live range of one pseudo in one
region (ira.cc:59-60). An entry has four fields: the allocno
number, then r and the pseudo number, then b and a basic block or l and a
loop, then the hard register. An entry that ends in mem is a pseudo IRA left
in memory. The hard register is a number, not a name. On x86-64
the numbers are the constants at the top of i386.md: AX_REG is 0, DX_REG
is 1, CX_REG is 2, and R8_REG to R15_REG are 36 to 43
(i386.md:417-460).
Two conditions control the block. It is printed at the end of do_coloring when
internal_flag_ira_verbose > 1 (ira-color.cc:3863-3864). That
flag comes from -fira-verbose=, whose default is 5
(common.opt:2222-2224), so a plain -fdump-rtl-ira prints it.
The GCC manual documents -fira-verbose under Developer Options,
including the rule that a value of 10 or more sends the same text to standard
error. Also, ira_color runs color, and so do_coloring, only when
ira_conflicts_p is true (ira-color.cc:5400-5403). The
value is ira_conflicts_p = optimize > 0 (ira.cc:5646). At
-O0 the cheaper fast_allocation prints the list instead
(ira-color.cc:5377-5378).
The block is IRA's first answer, not its last. color runs
move_spill_restore after do_coloring (ira-color.cc:5258-5268),
and LRA can still change an assignment. The final word is in the .reload dump.
The constraint that IRA does not settle: *divmod<mode>4
On x86-64, count.c's 64-bit modulo is an instruction with fixed registers.
Chapter 5.6 showed how a pattern like this becomes a recogniser. Here are its
operand constraints:
(define_insn_and_split "*divmod<mode>4"
[(set (match_operand:SWIM248 0 "register_operand" "=a")
(div:SWIM248 (match_operand:SWIM248 2 "register_operand" "0")
(match_operand:SWIM248 3 "nonimmediate_operand" "rm")))
(set (match_operand:SWIM248 1 "register_operand" "=&d")
(mod:SWIM248 (match_dup 2) (match_dup 3)))
(clobber (reg:CC FLAGS_REG))]
Listing 5.7-6: the signed divide-and-modulo pattern
(gcc/config/i386/i386.md:11607-11613).
The quotient must be in a. The dividend must be in the same register as the
quotient (0). The remainder must be in d, and it is an earlyclobber
operand (&), written before the instruction has finished with its inputs. The
divisor can be in any general register or in memory (rm). The internals manual
documents these letters in Simple Constraints,
Constraint Modifier Characters and, for a and d, the
x86 entry of Machine Constraints.
This is why the chapter title says %rdx. The remainder of v[i] % d cannot go
anywhere else. IRA uses constraints to set costs and preferences, and it does
not change the instruction. Its header comment says that it "creates copies for
operands of an insn which should be assigned to the same hard-register due to
constraints in the machine description (it usually results in removing a move
generated in reload to satisfy the constraints)"
(ira.cc:119-123). So IRA tries to put the dividend and the
quotient in one register. When its choice still does not match a constraint,
LRA makes the instruction valid with a copy, for example into %rax before the
division or out of %rdx after it.
Inside the reload dump: lra_constraints, lra_assign, lra_spill
LRA is a loop. The inner loop fixes instructions and assigns registers until no instruction needs a change. The outer loop then turns any pseudo that is still without a register into memory, which changes addresses, so it goes round again:
for (;;)
{
for (;;)
{
bool reloads_p = lra_constraints (lra_constraint_iter == 0);
...
lra_inheritance ();
...
bool spill_p = !lra_assign (fails_p);
...
}
...
if (! lra_need_for_spills_p ())
break;
...
if (lra_remat ())
...
lra_spill ();
...
}
...
lra_final_code_change ();
Listing 5.7-7: the shape of lra, abridged
(gcc/lra.cc:2451-2601).
Each sub-pass writes to the .reload dump whenever the dump is open. Three
kinds of line answer most questions.
Choosing alt N in insn U: is written by lra-constraints.cc when it
settles which constraint alternative an instruction uses, followed by the
pattern name in braces (lra-constraints.cc:4483-4500). final
does not read this choice. It finds an alternative again through
constrain_operands_cached (recog.cc:2798-2806), as the
final.cc section shows.
Inserting insn reload before: and after: follow an instruction that
needed a copy to satisfy a constraint. lra_process_new_insns prints the
instruction, then the new copies, in slim RTL (lra.cc:1918-1968).
The title string comes from its caller, for example
lra-constraints.cc:4944. If IRA's choice for the modulo in
Listing 5.7-6 does not match 0 or =&d, the copy that fixes it is recorded
here.
Slot N regnos (width = W): R... means pseudos went to the stack. It is
printed by lra_spill after it gives stack slots to the pseudos that have no
hard register:
if (lra_dump_file != NULL)
{
for (i = 0; i < slots_num; i++)
{
fprintf (lra_dump_file, " Slot %d regnos (width = ", i);
print_dec (slots[i].size, lra_dump_file, SIGNED);
fprintf (lra_dump_file, "):");
Listing 5.7-8: the spill record (gcc/lra-spills.cc:664-670).
lra_spill runs only when lra_need_for_spills_p finds a referenced pseudo
whose reg_renumber entry is still negative
(lra-spills.cc:603-614). So a Slot line in the .reload
dump is the proof that a value lives on the stack. The numbers after the colon
are the pseudos that share that slot. A pseudo can share a slot with
another only when they do not conflict, as the file's header comment explains
(lra-spills.cc:22-35).
At the end, lra_final_code_change replaces each pseudo with its hard register
in place, by SET_REGNO (regno_reg_rtx[i], hard_regno)
(lra-spills.cc:741-744). The register keeps its old number
in ORIGINAL_REGNO, which "for a pseudo register turned into a hard reg ...
will hold the old pseudo register number" (rtl.h:1928-1931).
The RTL printer shows both: the hard register number and name
(print-rtl.cc:549-554), then the old pseudo number in brackets
(:603-604). That is how you follow pseudo 101 from the expand
dump to %rdx in the RTL at the end of the .reload dump.
Forcing a spill with -ffixed-reg
count.c has few live values, and x86-64 has enough registers for them. To see
a Slot line, take registers away. -ffixed-reg makes the register named
reg unavailable to generated code. The GCC manual documents it under
Code Gen Options, and says that the names come from the
target's REGISTER_NAMES:
$ gcc -O2 -S -dp -fdump-rtl-ira -fdump-rtl-reload \
-ffixed-rbx -ffixed-rbp -ffixed-r8 -ffixed-r9 -ffixed-r10 \
-ffixed-r11 -ffixed-r12 -ffixed-r13 -ffixed-r14 -ffixed-r15 \
count.c
$ grep -n ' mem' count.c.*r.ira
$ grep -n 'Slot' count.c.*r.reload
$ grep -n 'idiv' count.s
This book did not run these commands at the pin. The machine it was written on has no GCC. What follows is what the source says about them, not an output transcript. Your pseudo numbers and stack offsets will be your own.
The names are accepted. decode_reg_name_and_count matches r8 to r15
against REGISTER_NAMES, and rbx and rbp against the x86
ADDITIONAL_REGISTER_NAMES table (varasm.cc:1012-1047,
i386.h:2079-2084). fix_register rejects a request for
the stack or frame pointer only when it is not "fixed and call-used". -ffixed-
asks for exactly that (opts-global.cc:427-430,
reginfo.cc:674-720). A fixed register reaches IRA through
fixed_reg_set and fixed_nonglobal_reg_set, and IRA copies the second into
no_unit_alloc_regs (reginfo.cc:377-378,
:410, ira.cc:516).
That leaves five general registers: %rax, %rdx, %rcx, %rsi and %rdi.
At the division, Listing 5.7-6 takes two of them. The loop needs at least four
more values across the division: something that says where it is in v,
something that says where to stop, count, and d. Six values do not fit in
five registers, so at that point at least one value lives somewhere else. The
divisor's rm constraint means idiv can read d from memory directly.
"Somewhere else" can mean a register of another class. lra-spills.cc can
spill a general register into a vector register when the target's
TARGET_SPILL_CLASS hook allows it. The dump then says Spill rN into hrM (lra-spills.cc:48-53,
:298-299). The x86 hook never allows it at the pin, because
its condition starts with a literal 0 &&:
ix86_spill_class (reg_class_t rclass, machine_mode mode)
{
if (0 && TARGET_GENERAL_REGS_SSE_SPILL
Listing 5.7-9: x86 spilling to SSE registers, switched off
(gcc/config/i386/i386.cc:25103-25105).
So on x86-64 the value goes to a stack slot, and you can expect a Slot line in
the .reload dump. Expect a mem entry in IRA's Disposition: too, unless
the decision to spill was LRA's and not IRA's.
final.cc: from RTL to text, and -dp
final is the last pass inside pass_late_compilation
(passes.def:549-564). It is not the last RTL pass:
pass_df_finish follows it (passes.def:565), with the dump
name dfinish (df-core.cc:831). The execute of pass_final calls
rest_of_handle_final, which calls final_start_function_1 for the start of
the function and final_1 for the body (final.cc:4235-4250).
final_1 walks the instructions in order and calls final_scan_insn on each
(final.cc:1963-1983). For an ordinary instruction, the work is
in this order:
/* Try to recognize the instruction.
If successful, verify that the operands satisfy the
constraints for the instruction. Crash if they don't,
since `reload' should have changed them so that they do. */
insn_code_number = recog_memoized (insn);
...
if (! constrain_operands_cached (insn, 1))
fatal_insn_not_found (insn);
...
/* Find the proper template for this insn. */
templ = get_insn_template (insn_code_number, insn);
...
/* Output assembler code from the template. */
output_asm_insn (templ, recog_data.operand);
Listing 5.7-10: one instruction becomes text, abridged
(gcc/final.cc:2741-2846), in final_scan_insn_1.
The comment states the contract between the allocator and final. After
reload, which on most targets means LRA, every instruction satisfies one
alternative of its pattern. constrain_operands finds it and sets
which_alternative (recog.cc:3096-3104).
get_insn_template uses that number to pick the alternative's output template
(final.cc:2022-2038). Templates come from the .md file
through the generated insn-output.cc, which genoutput writes. The internals
manual names that file in its RTL passes entry for Final.
output_asm_insn copies the template and expands each %N through
output_operand (final.cc:3543-3553). output_operand asserts
that no pseudo reaches it:
/* X must not be a pseudo reg. */
if (!targetm.no_register_allocation)
gcc_assert (!x || !REG_P (x) || REGNO (x) < FIRST_PSEUDO_REGISTER);
Listing 5.7-11: the last check on the allocator
(gcc/final.cc:3637-3639).
The target's TARGET_PRINT_OPERAND hook then prints the operand. The template
of *divmod<mode>4 in Listing 5.7-6 is "#", and its split condition is
"reload_completed" (i386.md:11614-11616). After reload it
becomes a sign extension and an instruction that matches
*<u>divmod<mode>4_noext, whose template is
"<sgnprefix>div{<imodesuffix>}\t%3" (i386.md:11868-11878).
With div and DImode the iterators give idiv and the suffix q
(i386.md:1101-1103,
:1239). %3 is the divisor. If d was spilled, %3 prints as
a stack address and not a register name.
-dp: which pattern and which alternative
-dp makes final write a comment after each instruction. The GCC manual
documents it under Developer Options, with -dP, which also
prints the RTL. -dp sets flag_print_asm_name
(opts.cc:3657-3659). The comment is written by output_asm_name:
fprintf (asm_out_file, "\t%s %d\t",
ASM_COMMENT_START, INSN_UID (debug_insn));
fprintf (asm_out_file, "[c=%d",
insn_cost (debug_insn, optimize_insn_for_speed_p ()));
if (HAVE_ATTR_length)
fprintf (asm_out_file, " l=%d",
get_attr_length (debug_insn));
fprintf (asm_out_file, "] ");
int num = INSN_CODE (debug_insn);
fprintf (asm_out_file, "%s", insn_data[num].name);
if (insn_data[num].n_alternatives > 1)
fprintf (asm_out_file, "/%d", which_alternative);
Listing 5.7-12: the -dp comment (gcc/final.cc:3213-3226).
So each annotated line has this form, with # as the comment start on x86-64
(x86-64.h:26-27):
<instruction> # <insn UID> [c=<cost> l=<length>] <pattern name>/<alternative>
The UID is the number of the instruction in the RTL dumps. The /N part
appears only for a pattern with more than one alternative. It is the
alternative that constrain_operands found in final, so it can differ from a
Choosing alt line if passes after reload changed the instruction, or if two
alternatives match. With -dp, a line of assembly leads back to a pattern in
the .md file and to an instruction in the dumps.
reload1.cc is still in the tree
The old pass is still built. Its header comment in reload1.cc describes the
method. Reload frees some hard registers as "reload regs" and copies values
into them where an instruction needs a register. It spills the pseudos that
lived in those registers (reload1.cc:47-79). A target gets it by returning false from
TARGET_LRA_P. Alpha does so with hook_bool_void_false
(alpha.cc:10813-10814). SH returns sh_lra_flag
(sh.cc:12611-12614), which is the -mlra option with an initial
value of 0 (sh.opt:301-303). So SH uses reload unless you pass
-mlra. The GCC manual's target pages show the state of a few more. The PDP-11 Options and
VAX Options say that -mlra selects LRA and that reload is the
default there. The ARC Options and FT32 Options
say that -mlra "Does nothing" now.
On such a target the .reload dump is written by reload1.cc, and the LRA
lines in this chapter do not appear in it. The Disposition: block in the
.ira dump is the same on both.
Three things to carry away
IRA decides, LRA makes it valid. IRA writes one hard register or -1 per
pseudo into reg_renumber, and LRA fixes each instruction to its constraints,
adding copies and stack slots.
The reload dump is LRA's on most targets. do_reload runs lra when
targetm.lra_p () is true, which is the default.
final trusts the allocator. It picks the alternative that the operands
satisfy, prints that alternative's template, and crashes if a pseudo or an
invalid operand reaches it.
Things that surprise people
Disposition: is not the final allocation. It is printed after coloring,
before move_spill_restore and before LRA. Check the .reload dump for the
final answer.
x86 never spills general registers to SSE registers at the pin. The tuning
flag X86_TUNE_GENERAL_REGS_SSE_SPILL is still defined
(x86-tune.def:432-435), but ix86_spill_class disables it
with 0 &&.
Documentation coverage
The internals manual describes the allocator, reload, LRA and final in its
RTL passes node (gcc/doc/passes.texi:1057-1118 and
:1160-1164). Its file list for LRA names lra-assign.c, but the file at the
pin is lra-assigns.cc. The TARGET_LRA_P and TARGET_SPILL_CLASS hooks are in
the Register Classes node (gcc/doc/tm.texi:3050 and
:3113). Constraint letters are in Simple Constraints
(gcc/doc/md.texi:1293), Constraint Modifier Characters
(md.texi:1773) and Machine Constraints (md.texi:1916, the
x86 entry at :4042).
The GCC manual documents -ffixed-reg in Code Gen Options
(gcc/doc/invoke.texi:20059). Developer Options documents
-fdump-rtl-ira (invoke.texi:20526), -fdump-rtl-postreload (:20560), -dp
and -dP (:20660, :20666) and -fira-verbose (:21443). The -mlra entries
are at invoke.texi:23282 (ARC), :26859 (FT32), :30922 (PDP-11) and
:34802 (VAX).
What is not documented:
- That
-fdump-rtl-reloadexists, and that on LRA targets it dumps LRA. The Developer Options list skips it, and calls IRA "iterated" register allocation. - The format of IRA's
Disposition:block, and that a hard register appears there as a number from the target's register constants. - The LRA dump vocabulary:
Choosing alt,Inserting insn reload,Slot,Spill rN into hrM. - That
reg_renumberis the handoff from IRA to LRA, and that RTL afterirastill uses pseudos. - The
-dpcomment format beyond "pattern and alternative", including the insn UID that links it to the RTL dumps. - That the x86 spill class is disabled in the source.
- SH's
-mlra. The SH Options node does not list it.
Next: Part VI starts with the testsuite, where a dg-final line scans the
dumps and assembly that this part taught you to read.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
6.1 Writing a test: how dg- comments drive DejaGnu
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
You have a test that checks the assembly. It is a dg-do compile test with a
scan-assembler line, and it passes. You want it to check the result of the
code too, so you change dg-do compile to dg-do run. The run passes. The scan
line now reports UNRESOLVED, and the log says that the output file does not
exist. The C code is valid, and so is every directive.
A GCC test declares its whole behaviour in comments in the test file. Each
dg- comment is a Tcl command, and the harness procedures that run it agree on
file names only by convention. dg-do run writes an executable.
scan-assembler reads a .s file that nothing wrote.
This chapter opens Part VI. The earlier parts were for someone who uses or builds a toolchain. This part is for someone who is about to change GCC and send the change upstream. If you do not plan to do that, you can stop before this part.
This chapter assumes Chapter 3.7,
which runs the whole testsuite against a built toolchain and explains target
boards and .sum files. It also uses the stop options -S and -c from the
table in Chapter 1.1. Chapter 3.7 tests a toolchain.
This chapter writes the test that goes with a change, and runs only that test.
A test is a C file with Tcl in its comments: pr63637-1.c
Here is a complete test from gcc/testsuite/gcc.dg:
/* PR rtl-optimization/63637 */
/* { dg-do compile } */
/* { dg-options "-O2" } */
int
foo (void)
{
int a, b, c;
asm ("# Magic instruction" : "=r" (a));
asm ("# Magic instruction" : "=r" (b));
asm ("# Magic instruction" : "=r" (c));
return a + b + c;
}
/* { dg-final { scan-assembler-times "# Magic instruction" 1 } } */
Listing 6.1-1: a whole test (gcc/testsuite/gcc.dg/pr63637-1.c:1-15).
Three directives say everything the harness needs to know:
dg-do compilecompiles with-Sand keeps the assembly file.compileis also the default when a test has nodg-do(sourcebuild.texi:1044-1063).dg-options "-O2"replaces the default options of the directory with-O2.dg-final { scan-assembler-times "# Magic instruction" 1 }runs after the compile. It counts the matches of the regular expression in the.sfile, and passes only if the count is exactly 1.
The three asm statements are identical. The test expects one copy of their
text in the output. The first line names the bug report that the test came from.
The internals manual documents every directive and its arguments, in
Directives and Final Actions. It also says
where the directives come from. "Some of these are defined within DejaGnu and
others are local to the GCC testsuite"
(sourcebuild.texi:1029-1031). The manual calls
dg-options, dg-error and dg-final DejaGnu directives. The commands inside
dg-final, such as scan-assembler, are GCC's
(sourcebuild.texi:3546-3547), and so is every dg-require-*.
Each directive is a Tcl procedure called with its line number
DejaGnu reads the test file, finds each { dg-... } group in it, and calls it as
a Tcl command. It puts the line number of the comment in front of the arguments.
gcc-dg.exp loads DejaGnu's dg.exp first
(gcc-dg.exp:17), and then defines its own dg-final, which takes
the place of DejaGnu's. It shows the line number:
proc dg-final { args } {
upvar dg-final-code final-code
if { [llength $args] > 2 } {
error "[lindex $args 0]: too many arguments"
}
set line [lindex $args 0]
set code [lindex $args 1]
set directive [lindex $code 0]
switch $directive {
gdb-test {
set code [linsert $code 1 $line]
}
}
append final-code "$code\n"
}
Listing 6.1-2: dg-final (gcc/testsuite/lib/gcc-dg.exp:111-126).
dg-final runs nothing when DejaGnu reads it. It appends its Tcl code to
dg-final-code, and upvar makes that name refer to a local variable of the
procedure that called it. That procedure is DejaGnu's dg-test, which runs the
test. After the compile, and after the run if there is one, dg-test evaluates
the collected code in the order of the file
(sourcebuild.texi:1358-1363).
The other GCC directives work the same way. dg-additional-options appends to
dg-extra-tool-flags (gcc-defs.exp:284-285).
dg-require-effective-target drops the line number and edits dg-do-what
(target-supports-dg.exp:241-264). A helper in the same file
states the rule in its comment. It looks for "the 'dg-do-what' variable living
inside DejaGnu's 'dg-test' procedure, as a local variable"
(target-supports-dg.exp:61-62). So a GCC directive is a
procedure that edits the state of dg-test while dg-test reads the file.
That is all the Tcl a test writer needs. A test writer does not need to know
expect.
gcc.dg/dg.exp: which driver runs your file
The make rule that runs the C testsuite ends in one command,
$(RUNTEST) --tool $(check_p_tool) $(RUNTESTFLAGS), where the tool is gcc
(gcc/Makefile.in:4709). The testsuite's README says what
--tool is for. It "is mainly used to find the testsuite directories for a
particular tool when several testsuites are in the same directory"
(gcc/testsuite/README:53-56). For the tool gcc, these are the
gcc.* directories: gcc.dg, gcc.c-torture, gcc.target and others.
DejaGnu runs each .exp file in them, and each .exp file chooses its own
tests. Here is the driver for the top of gcc.dg:
# Load support procs.
load_lib gcc-dg.exp
# If a testcase doesn't have special options, use these.
global DEFAULT_CFLAGS
if ![info exists DEFAULT_CFLAGS] then {
set DEFAULT_CFLAGS " -ansi -pedantic-errors"
}
# Initialize `dg'.
dg-init
# Main loop.
dg-runtest [lsort [glob -nocomplain $srcdir/$subdir/*.\[cSi\]]] \
"" $DEFAULT_CFLAGS
# C/C++ common tests.
dg-runtest [lsort [glob -nocomplain $srcdir/c-c++-common/*.\[cSi\]]] \
" -Wc++-compat " ""
# All done.
dg-finish
Listing 6.1-3: the gcc.dg driver (gcc/testsuite/gcc.dg/dg.exp:19-40).
Four facts follow from these lines, and each one decides where your test goes.
The glob does not go down into subdirectories. dg.exp runs the files at the
top of gcc.dg and nothing below it. A file in gcc.dg/torture belongs to
dg-torture.exp, which is seven lines long and calls gcc-dg-runtest instead
(gcc.dg/torture/dg-torture.exp:1-7). gcc-dg-runtest compiles
each test once for each set of options in its list
(gcc-dg.exp:742-748). The default list goes from -O0 to
-Os (gcc-dg.exp:93-99). Put a test there when the bug
appears only at some optimization levels.
A test with no dg-options gets -ansi -pedantic-errors. That is the third
argument of dg-runtest, the default options of the directory. A dg-options
line replaces them (sourcebuild.texi:1080-1083). An empty
one, dg-options "", replaces them with nothing, as in vla-init-1.c
(gcc.dg/vla-init-1.c:5).
c-c++-common runs twice. gcc.dg/dg.exp runs it as C, with
-Wc++-compat. g++.dg/dg.exp runs the same files as C++
(g++.dg/dg.exp:49). A test that must hold for both languages goes
there.
A target directory can opt out completely. gcc.target/i386/i386.exp
returns before it runs a single test if the target is not x86
(gcc.target/i386/i386.exp:19-22). On an AArch64 build, nothing in
that directory runs, and nothing reports it as skipped.
The internals manual lists the C directories and what each one is for, under
C Tests. Its Test Idioms node gives the naming
rule: a test for bug report N is prN-1.c
(sourcebuild.texi:937-946).
dg-do names the output file, and scan-assembler assumes the name
The dg-do keyword reaches GCC as the do_what argument of gcc-dg-test-1.
That procedure chooses the kind of output and its name:
"compile" {
set compile_type "assembly"
set output_file "[file rootname [file tail $prog]].s"
}
Listing 6.1-4: the output of dg-do compile
(gcc/testsuite/lib/gcc-dg.exp:244-247).
pr63637-1.c compiles to pr63637-1.s, in the directory where runtest runs.
The scan procedure never receives that name. It rebuilds it:
# This must match the rule in gcc-dg.exp.
set output_file "[file rootname [file tail $filename]].s"
set files [glob -nocomplain $output_file]
if { $files == "" } {
verbose -log "$testcase: output file does not exist"
unresolved "$testcase scan-assembler-times $pp_pattern $times"
return
}
Listing 6.1-5: scan-assembler-times finds its file by name
(gcc/testsuite/lib/scanasm.exp:493-501).
The comment is the contract between the two files, and nothing checks it.
scan-assembler and scan-assembler-not build the same name
(scanasm.exp:104-113). Now look at dg-do run. Its output is
./pr63637-1.exe, and the compile writes no .s file
(gcc-dg.exp:266-271). The scan finds no file and reports
UNRESOLVED. That is the failure from the start of this chapter. A test that
scans the assembly stays a dg-do compile test. Check the run in a second test.
The dump scans work the same way. scan-dump, which scan-tree-dump and its
relatives use, builds a glob pattern from the test's file name and the dump
suffix. If no file matches, it reports UNRESOLVED
(scandump.exp:103-110).
Chapter 5.2 explains how GCC names dump files.
A scan directive adds options to the compile: -fno-ident
Before it compiles, gcc-dg-test-1 reads the collected dg-final code. For each
directive that has a procedure named <directive>_required_options, it adds the
options that procedure returns (gcc-dg.exp:286-299). Every
scan of the assembly gets such a procedure:
proc set_required_options_for { test } {
if { [info proc $test] == "" } {
perror "$test does not exist"
exit 1
}
proc ${test}_required_options {} {
global gcc_set_required_options
upvar 1 extra_tool_flags extra_tool_flags
if {[regexp -- "^scan-assembler" [info level 0]]
&& ![string match "*-fident*" $extra_tool_flags]} {
# Do not let .ident confuse assembler scan tests
return [list $gcc_set_required_options "-fno-ident"]
}
return $gcc_set_required_options
}
}
Listing 6.1-6: options that a scan forces
(gcc/testsuite/lib/target-supports.exp:12704-12719).
So pr63637-1.c is not compiled with -O2 alone. The compile also gets
-fno-ident. When the target supports LTO, gcc_set_required_options holds
-ffat-lto-objects (gcc-dg.exp:101-103). The comment above the
variable gives the reason: some torture options "cause intermediate code output,
unusable for testing using e.g. scan-assembler"
(gcc-dg.exp:77-79). The GCC manual documents -fno-ident under
Code Gen Options with one sentence: "Ignore the #ident
directive". The option also removes a line that GCC writes itself. At the end
of every assembly file, the compiler emits an .ident directive. Its text is
GCC: , then the package string and the version
(gcc/toplev.cc:563-576). -fno-ident stops it. Without the
option, a pattern that looks for a digit or for GCC would match that line.
dg-error and dg-warning: one message, one line, one column
A test for a diagnostic puts the directive on the line that must get the message:
/* { dg-do compile } */
void
foo (int n)
{
switch (n)
case 0: case 3: case 0.2: case 5:; /* { dg-error "21:case label does not reduce to an integer constant" } */
}
Listing 6.1-7: a dg-error test with a column
(gcc/testsuite/gcc.dg/case-bogus-1.c:1-8).
This test has no dg-options, so it compiles with -ansi -pedantic-errors. The
directive is on line 7, so the error must be for line 7. The 21: at the start
of the expression is a column. Column 21 is where the third case starts.
DejaGnu's dg-error knows nothing about columns. GCC renames it to
saved-dg-error and puts a wrapper in its place that calls process-message
(gcc-dg.exp:1123-1133). The wrapper rewrites the expression
before DejaGnu stores it:
if [regexp {^-:} $expmsg] {
# The expected column is -, so shouldn't appear.
set expmsg [string range $expmsg 2 end]
} elseif [regexp {^[0-9]+:} $expmsg column] {
# The expression in the directive included a column number.
# Remove it from the original expression and move it
# to the proper place in the search expression.
set expmsg [string range $expmsg [string length $column] end]
set column "$column "
} elseif [string match "" [lindex $newentry 0]] {
# The specified line number is 0; don't expect a column number.
} else {
# There is no column number in the search expression, but we
# should expect one in the message itself.
set column {[0-9]+: }
}
set expmsg "$column$msgprefix\[^\n\]*$expmsg"
Listing 6.1-8: how GCC rewrites a message expression
(gcc/testsuite/lib/gcc-dg.exp:1262-1278).
For dg-error the prefix is (fatal )?error:, and for dg-warning it is
warning: (gcc.exp:113-114). So the directive in Listing 6.1-7
looks for 21: (fatal )?error:, then any text, then the message. Without a
column, it accepts any column. With -:, it expects none. dg-message uses the
same code with no prefix (gcc-dg.exp:1287-1290). It is the
directive for a note: that comes with an error, as in decl-4.c
(gcc.dg/decl-4.c:4-5).
DejaGnu passes the compiler output through GCC's gcc-dg-prune, which calls
prune_gcc_output (gcc-dg.exp:396). That procedure removes the
lines that GCC does not want tests to see, such as "In function" headers and
include stacks
(prune.exp:43-58). Compiler output that no message directive
handles is an excess error, and the compile fails
(sourcebuild.texi:1300-1304). So a test fails if the compiler
emits a diagnostic that no directive expects.
The output must have the same form on every host. gcc-dg.exp sets LC_ALL and
LANG to C "so that we get the same error messages as expected"
(gcc-dg.exp:39-41). prune.exp adds -fdiagnostics-plain-output to
TEST_ALWAYS_FLAGS (prune.exp:21-30), and
gcc_target_compile puts those flags first on every compile
(gcc.exp:137-142). The GCC manual documents the option under
Diagnostic Message Formatting Options. It lists the options that
it implies, among them -fno-diagnostics-show-caret, and says that it "may be
useful when running dejagnu" (invoke.texi:5334-5337).
The manual does not say that the testsuite adds it to every compile.
dg-require-effective-target: a probe compile in target-supports.exp
A test that needs a property of the target says so, and the harness checks the
property by compiling a small program. The checks are procedures named
check_effective_target_<keyword>, and is-effective-target calls the one that
matches the keyword (target-supports.exp:10301-10310). Here is
lp64:
proc check_effective_target_lp64 { } {
return [check_no_compiler_messages lp64 object {
int dummy[sizeof (int) == 4
&& sizeof (void *) == 8
&& sizeof (long) == 8 ? 1 : -1];
}]
}
Listing 6.1-9: the lp64 keyword
(gcc/testsuite/lib/target-supports.exp:3885-3891).
On a target that is not LP64, the array has size -1 and the compiler reports an
error. check_no_compiler_messages returns true only if the compile printed
nothing (target-supports.exp:187-202). It writes the program
to a file and compiles it with the same ${tool}_target_compile that compiles
the tests (target-supports.exp:46-125). It keeps the answer
in et_cache, with one entry for each keyword and target name
(target-supports.exp:140-159). So the probe sees the multilib
options of the board, as the test does. It does not see the dg-options of the
test, except for keywords whose names end in _nocache
(sourcebuild.texi:1496-1500).
When the answer is false, dg-require-effective-target changes the second
element of dg-do-what to N (target-supports-dg.exp:262-264).
The test is then "skipped and reported as unsupported"
(sourcebuild.texi:1383-1384). The internals manual
documents the keywords under Effective-Target Keywords, and says
that the directive "must appear after any dg-do directive"
(sourcebuild.texi:1189-1197).
target-supports.exp has 14,395 lines at the pin, and 771 of them start with
proc check_effective_target_. It is the file you will read most often when
you write tests. Before you write a probe of your own, search it for the
property that you need.
RUNTESTFLAGS="dg.exp=…": running only your test
Running the testsuite needs a built GCC tree. Nobody ran the commands in this
section at the pin for this book. The install manual documents the method under
Testing: run make check-gcc in the gcc directory of the build
tree, and select tests with RUNTESTFLAGS. Its example is
RUNTESTFLAGS="old-deja.exp=9805*". The text after name.exp= is a list of glob
patterns, separated by white space (install.texi:3448-3488).
For the test in Listing 6.1-1:
$ cd objdir/gcc
$ make check-gcc RUNTESTFLAGS="dg.exp=pr63637-1.c"
The part before = must name the driver of the directory where the test is.
dg.exp= finds a file at the top of gcc.dg or in c-c++-common. A file in
gcc.dg/torture needs dg-torture.exp=. Name the wrong driver and no test
runs. Nothing fails either, so check that the summary counts at least one test.
The rest of the run is in gcc/Makefile.in. check-gcc is in
lang_checks_parallelized, and check-c is an alias for it
(gcc/c/Make-lang.in:174-180). So it goes through the
parallelized rule (gcc/Makefile.in:4657-4686), and that rule
starts one or more check-parallel-gcc jobs
(gcc/Makefile.in:4688-4713). Each job changes to its own
directory, testsuite/gcc for the first one, and runs runtest --tool gcc with
your RUNTESTFLAGS. A driver runs a file only if DejaGnu's runtest_file_p
says that the file is in your list. The loop in GCC's gcc-dg-runtest shows the
check (gcc-dg.exp:726-730). With make -j, several
runtest processes go through the same drivers. A marker file decides which
process runs each batch of ten tests (gcc-defs.exp:180-197),
and contrib/dg-extract-results.sh merges their .sum and .log files
(gcc/Makefile.in:4677-4680). The results go to
testsuite/gcc/gcc.sum and gcc.log.
check-gcc at the top level is not check-gcc in gcc/
The name means two different things. In the top-level build directory,
check-gcc changes to gcc and runs make check there
(Makefile.in:12847-12853). In gcc/, check depends on one
check-<language> target for each language that you configured
(gcc/Makefile.in:4581-4583, gcc/configure.ac:7385-7389).
So the top-level check-gcc runs the testsuite of every language that you
configured, each with your RUNTESTFLAGS. The top-level target for C alone is
check-gcc-c (Makefile.in:64243-64248). The top-level
Makefile passes RUNTESTFLAGS down to gcc/ (Makefile.in:869).
Read the result in gcc.sum. A check reports its own line. For
scan-assembler-times, the line holds the test name, the directive, the pattern
and the count (scanasm.exp:508-514). Run the test once without your fix
and once with it. A test that passes on the old compiler does not test your
change. Chapter 3.7 explains the
status codes in .sum files, and how to compare two runs.
Reproducing one test's compile by hand
You can read a test, and repeat its compile, with no build tree. This is also how
you debug a test that fails: take one compile out of the harness and run it
yourself. The install manual says that the .log files "contain a detailed log
of the compiler invocations" (install.texi:3563-3565). After a
run, copy the command from gcc.log. The compiler in that command is
GCC_UNDER_TEST, which the harness gets from DejaGnu's find_gcc
(gcc.exp:101-106). In a build tree it gets a -B option, so
that it does not use "GCC files from the install tree"
(gcc/Makefile.in:4523-4526).
Without a build, rebuild the command from the directives. For Listing 6.1-1, the
pieces are the plain-output flag from TEST_ALWAYS_FLAGS, the dg-options, the
-fno-ident from the scan, and -S from dg-do compile:
$ curl -sO https://raw.githubusercontent.com/gcc-mirror/gcc/releases/gcc-15.2.0/gcc/testsuite/gcc.dg/pr63637-1.c
$ LC_ALL=C gcc -fdiagnostics-plain-output -O2 -fno-ident -S pr63637-1.c -o pr63637-1.s
$ grep -o '# Magic instruction' pr63637-1.s | wc -l
The directive passes when the count is 1. grep -o counts each match, as Tcl's
regexp -all does in scan-assembler-times (scanasm.exp:508).
Nobody ran these commands at the pin for this book, so this chapter shows no
output. An installed compiler of another version can give another count. The
test is a statement about the compiler in the tree under test.
For Listing 6.1-7, the default options of the driver take the place of
dg-options:
$ LC_ALL=C gcc -fdiagnostics-plain-output -ansi -pedantic-errors -S case-bogus-1.c
The test passes if the output has a line for line 7, column 21, with error:
and the expected text, and no other diagnostic. With the command in a shell, you
can add the dump options of Chapter 5.2 and
read the dumps. The test file does not change.
Three things to carry away
A GCC test is a source file whose dg- comments are Tcl commands. DejaGnu
calls each one with its line number, and GCC's directives edit the local
variables of DejaGnu's dg-test.
dg-do and the scan directives agree on file names only by convention.
scan-assembler reads the .s file that dg-do compile writes, and it adds
-fno-ident to the compile.
make check-gcc RUNTESTFLAGS="dg.exp=name.c" in gcc/ runs one test. The
.exp name must be the driver of the test's directory. At the top level, use
check-gcc-c.
Things that surprise people
dg-do run with scan-assembler gives UNRESOLVED. No .s file exists
for the scan to read.
A directory of target tests can vanish without a trace.
gcc.target/i386/i386.exp returns at once on a target that is not x86, and the
.sum file does not mention its tests.
The top-level make check-gcc tests every configured language. It is
make check in gcc/. check-gcc-c is the C testsuite alone.
A wrong .exp= name runs nothing, and reports nothing. Check that the
summary counts at least one test.
Documentation coverage
The install manual documents make check, the check-<language> targets,
RUNTESTFLAGS, the name.exp=pattern syntax, and the .sum and .log files
under Testing (gcc/doc/install.texi:3393, selected tests at
:3448). It requires DejaGnu 1.5.3 or later (:574). The internals manual
documents the testsuites in its Testsuites chapter
(gcc/doc/sourcebuild.texi:912). Every directive is in
Directives (:1026), the scans in
Final Actions (:3543), the keywords in
Effective-Target Keywords (:1484) and the C directories in
C Tests (:3909). The GCC manual documents
-fdiagnostics-plain-output (gcc/doc/invoke.texi:5334) and -fno-ident
(:19858).
What is not documented:
- That a directive is a Tcl procedure, called with its line number, which edits
the local variables of DejaGnu's
dg-test. - That
gcc.dg/dg.expruns only the top ofgcc.dg, plusc-c++-common, and that the.exp=name must match the driver of the test's directory. - That
scan-assemblerfinds its file by name, so it givesUNRESOLVEDin adg-do runtest. - That an assembly scan adds
-fno-identto the compile, and-ffat-lto-objectswhen the target supports LTO. The manual entry for-fno-identmentions only#ident, not the.identline that GCC writes itself. - That every compile in the testsuite gets
-fdiagnostics-plain-outputand runs withLC_ALL=C. - That a
dg-errorexpression with no column still requires a column in the message, and that a leadingN:requires exactly column N. - That the top-level
check-gccruns the testsuite of every configured language. - The C Tests node says that
gcc.dgtests run with-ansi -pedantic(sourcebuild.texi:3924).dg.expuses-ansi -pedantic-errors.
Next: the .texi files in gcc/doc that this chapter cites by line, how they
become the manuals, and why a patch never edits tm.texi.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
6.2 The manuals are source: reading gcc/doc
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
A warning ends in [-Wunused-variable]. Compile with -fdiagnostics-urls=always
in a terminal that shows links, and that text links to
https://gcc.gnu.org/onlinedocs/gcc-15.2.0/gcc/Warning-Options.html#index-Wno-unused-variable.
The compiler knows the address of its own manual, down to the release and the
anchor. The anchor comes from one line in the GCC tree:
@opindex Wno-unused-variable, at gcc/doc/invoke.texi:7846.
Every Documentation coverage section in this book gave you the same pair: a page
on gcc.gnu.org and a gcc/doc/*.texi:LINE citation. They are one text in two
forms. A script in the tree runs makeinfo over the .texi files at a release
tag, and the pages are its output. The files come with every checkout, grep
reads them, and their line numbers belong to the same tag as the code. This
chapter shows how a file becomes a page and which file owns which subject. Then it
shows how to get from a symptom to the right node, and the one manual file that
you must not edit: tm.texi.
This chapter assumes Chapter 2.1, for the layout of a
checkout, and Chapter 2.4, for generated files and
the s-* stamp rules that remake them.
From .texi to page: maintainer-scripts/update_web_docs_git
The pages under onlinedocs/ come from maintainer-scripts/update_web_docs_git.
Its first comment states the job: "Generate HTML documentation from GCC Texinfo
docs" (:3). Its -r option names a release
(:65-79), and the script clones that release's tag:
if [ "$RELEASE" = "master" ]; then
git clone -q $GITROOT gcc
else
git clone -q -b releases/gcc-$RELEASE $GITROOT gcc
fi
rm -rf gcc/.git
Listing 6.2-1: the docs are built from a tag
(maintainer-scripts/update_web_docs_git:133-138).
With -r 15.2.0, that is releases/gcc-15.2.0, the pin of this book. The script
then deletes every file that is not a .texi file, except a short list of helpers
(:147-160), and puts what is left in docs-sources.tar
(:163). It writes a gcc-vers.texi with the version number and the
bug URL (:169-180). It runs makeinfo --html once for each manual
(:186-203) and copies the pages and the tar files to the web
directory (:279-295). On 2026-10-22,
onlinedocs/gcc-15.2.0/ listed docs-sources.tar, gcc.pdf
and gcc-html.tar beside the gcc/, gccint/ and cpp/ directories.
So the 15.2.0 pages and this book's citations read the same files at the same tag. That is why the book can put a line number next to each page.
The deletion step has two consequences.
Nothing is built. The script never runs configure or make. A .texi file
that the build generates cannot reach the web unless it is also in the repository.
The internals manual states the rule: "All Texinfo files that are parts of manuals
must be version-controlled, even if they are generated files, for the generation of
online manuals to work" (sourcebuild.texi:429-431). tm.texi is such a
file, and the tm.texi section below shows what that costs a contributor.
The install manual has one copy. The script builds it only from master:
# Finally, generate the installation documentation
if [ "$RELEASE" = "master" ]; then
SOURCEDIR=$WORKDIR/gcc/gcc/doc
DESTDIR=$WWWBASE_PREFORMATTED/install
export SOURCEDIR
export DESTDIR
$WORKDIR/gcc/gcc/doc/install.texi2html
Listing 6.2-2: the install manual comes from master only
(maintainer-scripts/update_web_docs_git:314-320).
That is why https://gcc.gnu.org/install/ has no gcc-15.2.0 form, and why this
book cites install.texi:LINE for the install manual. The line at the tag is the
only pinned copy. install.texi2html also names the install pages itself. It runs
makeinfo ten times, each time with a -D flag that selects one part of
install.texi, and writes configure.html, build.html, test.html and seven
others (install.texi2html:49-59). The Configuration node becomes
configure.html because install.texi wraps it in @ifset configurehtml
(install.texi:729), not because of its node name.
Page names: from @node to .html
For the other manuals, makeinfo writes one HTML file per node, and the file name
comes from the node name. The Texinfo manual documents the rule under
HTML Xref Node Name Expansion. ASCII letters and digits stay. Each
space becomes -. Every other ASCII character becomes _00 and its hexadecimal
code, so - becomes _002d and + becomes _002b. GCC's script then changes
every _002d back to -, in the contents and in the file names
(update_web_docs_git:251-262). The result:
| Node | Page |
|---|---|
Environment Variables | Environment-Variables.html |
Invoking G++ | Invoking-G_002b_002b.html |
Gcov-tool | Gcov-tool.html, not Gcov_002dtool.html |
poly_int (internals manual) | poly_005fint.html |
With the rule, you can write the URL of any node:
https://gcc.gnu.org/onlinedocs/gcc-15.2.0/, the manual's directory, a /, and
the page.
Which manual owns what: gcc.texi, gccint.texi, cpp.texi, install.texi
gcc/doc/ holds 58 .texi files, plus tm.texi.in, install.texi2html and two
directories (gcc/doc/). Only a few of the files are manuals. A manual
is a root file that starts with \input texinfo, names its Info file with
@setfilename (gcc.texi:1-3), and includes the other files as its
chapters. The internals manual documents the layout under
Texinfo Manuals. The manuals for GCC and for C and C++ are
in doc/*.texi. Other front ends keep theirs in their own directories, and
doc/include/ holds the files that several manuals share
(sourcebuild.texi:387-391).
| Manual | Root file | Rendered under | Read it for |
|---|---|---|---|
| Using GCC | gcc/doc/gcc.texi | onlinedocs/gcc-15.2.0/gcc/ | options (invoke.texi), extensions, attributes and built-ins (extend.texi) |
| GCC Internals | gcc/doc/gccint.texi | onlinedocs/gcc-15.2.0/gccint/ | source tree and testsuite (sourcebuild.texi), .opt files (options.texi), passes, GENERIC, GIMPLE, RTL, md.texi, tm.texi, libgcc |
| The C Preprocessor | gcc/doc/cpp.texi | onlinedocs/gcc-15.2.0/cpp/ | directives, predefined macros |
| cpplib internals | gcc/doc/cppinternals.texi | onlinedocs/gcc-15.2.0/cppinternals/ | libcpp |
| Installing GCC | gcc/doc/install.texi | gcc.gnu.org/install/ | prerequisites, configure flags, build, test |
The root files list their chapters. gcc.texi includes invoke.texi and 20 other
chapters (gcc.texi:172-199). gccint.texi includes
sourcebuild.texi, md.texi and tm.texi among its own
(gccint.texi:140-177). Front ends and runtime libraries have
their own roots, for example gcc/fortran/gfortran.texi, gcc/ada/gnat_ugn.texi,
gcc/d/gdc.texi and libgomp/libgomp.texi. The web script's MANUALS list names
every root that it renders (update_web_docs_git:32-50).
One file, two manuals: @set INTERNALS
A file can be a chapter of more than one manual. contribute.texi is the plainest
case. Both gcc.texi and gccint.texi include it (gcc.texi:187,
gccint.texi:140). Its 24 lines send you to
https://gcc.gnu.org/contribute.html, which is not in the tree
(contribute.texi:13-19). Chapter 6.3
and Chapter 6.4 take you to that page.
md.texi is in both manuals too, and a flag decides how much of it each one gets:
@c INTERNALS is used by md.texi to determine whether to include the
@c whole of that file, in the internals manual, or only the part
@c dealing with constraints, in the user manual.
@clear INTERNALS
Listing 6.2-3: the user manual clears the flag (gcc/doc/gcc.texi:4-7).
gccint.texi sets it (:7), and the user manual reaches md.texi
through extend.texi (:12620). The preprocessor options work the
same way, without a flag. cppopts.texi, cppdiropts.texi, cppwarnopts.texi
and cppenv.texi are chapters of the cpp manual
(cpp.texi:4715-4736) and of the GCC manual
(invoke.texi:9459, :19004,
:19494, :38155).
So one grep hit can be two rendered pages, and a patch to cppopts.texi
changes two manuals. When this book cites one of these shared files, it links
the page in the manual that the chapter was reading.
From a symptom to a node: @opindex, @defmac, @item
The Texinfo commands make the sources easy to search. Almost everything a user can
name has one next to it: an index entry such as @opindex or @vindex, a
definition such as @defmac, or the @item of a table. An index entry also makes
an HTML anchor, named index- and the entry. The compiler's own URL code expects
that form (gcc/opts.cc:3803-3805). The table gives one grep for
each kind of name:
| You have | grep for | Hit at the pin |
|---|---|---|
| an option or a warning | @opindex Wunused-variable | invoke.texi:7845 |
| a configure flag | @item --with-sysroot | install.texi:2709 |
| a target macro | @defmac BIGGEST_ALIGNMENT | tm.texi.in:987 (and tm.texi:1110) |
| a target hook | @hook TARGET_ASM_FILE_END | tm.texi.in:5173 |
| a built-in | @defbuiltin{long __builtin_expect | extend.texi:17578 |
| a function attribute | @cindex @code{noinline} function attribute | extend.texi:2795 |
| an environment variable | @vindex GCC_EXEC_PREFIX | invoke.texi:38056 |
@defbuiltin is a GCC macro for @deftypefn {Built-in Function}, defined in
doc/include/gcc-common.texi (:69-71). The other commands are
plain Texinfo.
A hit gives you a line. To get the page, find the last @node above it. In a
checkout of releases/gcc-15.2.0:
$ grep -n '@opindex Wunused-variable' gcc/doc/*.texi
gcc/doc/invoke.texi:7845:@opindex Wunused-variable
$ grep -n '^@node' gcc/doc/invoke.texi | awk -F: '$1 < 7845' | tail -1
6122:@node Warning Options
The node Warning Options becomes Warning-Options.html,
in the manual whose root includes invoke.texi, which is gcc. The anchor is
#index-Wunused-variable from line 7845, or #index-Wno-unused-variable from
line 7846. That is the URL from the start of this chapter.
The compiler does the same lookup: .opt.urls
The compiler does not grep at run time. A developer runs the lookup once, and the
result is in the source tree. Next to each .opt file is a .opt.urls file:
Wunused-variable
UrlSuffix(gcc/Warning-Options.html#index-Wno-unused-variable)
Listing 6.2-4: one entry (gcc/c-family/c.opt.urls:936-937).
The first line of the file says "Autogenerated by regenerate-opt-urls.py from
gcc/c-family/c.opt and generated HTML" (:1). The
make regenerate-opt-urls target runs that script over the pages that make html
wrote (gcc/Makefile.in:3830-3839). The internals manual documents
UrlSuffix and the target under Option properties, and says to
run it "when adding new options" (options.texi:600-616).
When a diagnostic names an option, make_option_url joins the suffix to
DOCUMENTATION_ROOT_URL (gcc/opts.cc:3816-3828). configure sets
that root:
docroot_url_suffix=
changequote(,)dnl
case "$gcc_version" in
*.[123456].0) docroot_url_suffix="gcc-$gcc_version/";;
*.[123456].1) docroot_url_suffix="gcc-`echo $gcc_version | sed 's/1$/0/'`/";;
esac
changequote([,])dnl
DOCUMENTATION_ROOT_URL="https://gcc.gnu.org/onlinedocs/$docroot_url_suffix"
Listing 6.2-5: the default documentation root (gcc/configure.ac:1104-1111).
gcc_version is the content of gcc/BASE-VER (configure.ac:31), which
is 15.2.0 at the pin (BASE-VER). So a 15.2.0 compiler links to
onlinedocs/gcc-15.2.0/. A trunk version such as 16.0.0 matches neither pattern
and links to the unversioned pages. The install manual documents this default, and
--with-documentation-root-url, which replaces it, under
Configuration. The GCC manual documents -fdiagnostics-urls,
and the environment variables that can turn it off, under
Diagnostic Message Formatting Options.
tm.texi is generated from tm.texi.in and target.def
Grep for a target hook by its full name:
$ grep -n 'TARGET_ASM_FILE_END' gcc/doc/*.texi
gcc/doc/tm.texi:8383:@deftypefn {Target Hook} void TARGET_ASM_FILE_END (void)
gcc/doc/tm.texi:8392:should define @code{TARGET_ASM_FILE_END} to this function. If you
Both hits are in tm.texi, the Target Macros chapter of the internals manual. You
should edit neither line. tm.texi is the output of a generator, and the glob
*.texi does not match its input, tm.texi.in. Nothing in tm.texi says so. It
has no "generated" header, and no .texi file names tm.texi.in, target.def or
the generator.
The generator is genhooks. Its first comment says that it processes "target.def
to create initialization macros definition in target-hooks-def.h and documentation
in target-hooks.texi" (gcc/genhooks.cc:1-2). The output file is
tm.texi now, but the job is the same. With -d and a file name, it writes the
documentation (:317-327). The text has three places.
The hook and its text are in target.def. Each DEFHOOK gives a name, a
documentation string in Texinfo, a type, the parameters and the default:
/* Output any boilerplate text needed at the end of a translation unit. */
DEFHOOK
(file_end,
"Output to @code{asm_out_file} any text which the assembler expects\n\
to find at the end of a file. The default is to output nothing.",
void, (void),
hook_void_void)
Listing 6.2-6: a hook and its documentation (gcc/target.def:710-716).
The full name is not on those lines. HOOK_PREFIX is "TARGET_ASM_" from
target.def:32. genhooks compiles target.def into a table, joins
the prefix to file_end, and makes the result upper case
(genhooks.cc:24-38, :42-50). So
grep TARGET_ASM_FILE_END gcc/target.def finds nothing. Grep for (file_end,.
The position is in tm.texi.in. An @hook line says where the hook's text
goes. The text around it is ordinary Texinfo:
@hook TARGET_ASM_FILE_END
@deftypefun void file_end_indicate_exec_stack ()
Some systems use a common convention, the @samp{.note.GNU-stack}
special section, to indicate whether or not an object file relies on
the stack being executable. If your system uses this convention, you
should define @code{TARGET_ASM_FILE_END} to this function. If you
need to do other things in that hook, have your hook function call
this function.
@end deftypefun
Listing 6.2-7: the hook's place, and hand-written text after it
(gcc/doc/tm.texi.in:5173-5182).
The result is in tm.texi. genhooks -d copies tm.texi.in and replaces each
@hook line with a @deftypefn or @deftypevr block that it makes from the hook's
fields (genhooks.cc:201-248):
@deftypefn {Target Hook} void TARGET_ASM_FILE_END (void)
Output to @code{asm_out_file} any text which the assembler expects
to find at the end of a file. The default is to output nothing.
@end deftypefn
@deftypefun void file_end_indicate_exec_stack ()
Some systems use a common convention, the @samp{.note.GNU-stack}
special section, to indicate whether or not an object file relies on
the stack being executable. If your system uses this convention, you
should define @code{TARGET_ASM_FILE_END} to this function. If you
need to do other things in that hook, have your hook function call
this function.
@end deftypefun
Listing 6.2-8: the generated text (gcc/doc/tm.texi:8383-8395),
rendered as part of File Framework.
Target macros such as BIGGEST_ALIGNMENT have no DEFHOOK. Their @defmac text is
in tm.texi.in, and genhooks copies it unchanged. That is why the table above
shows two hits for it.
The split between target.def and tm.texi.in has a reason, and genhooks gives
it. A hook whose documentation string is empty gets only its signature, and its
text can then live in tm.texi.in:
When the doc field is "", @deftypefn/@deftypevr and the hook signature
is emitted, but not the matching @end. This allows all the free-form
documentation to be placed in IN_FNAME, to work around GPL/GFDL
licensing incompatibility issues. */
Listing 6.2-9: why some text is not in target.def
(gcc/genhooks.cc:93-96).
target.def is C source under the GPL (target.def:4-7). The
internals manual is under the GFDL (gccint.texi:31-33). A program
copies each documentation string from one licence into the other, and the build
asks you to confirm that you may do that.
genhooks also checks that its inputs agree. A documented hook with no @hook
line stops it with "No place specified to document hook"
(genhooks.cc:148-149). An @hook line for a hook it does not
know stops it with "No documentation for hook" (:183-184). Two
@hook lines for one hook stop it with "Duplicate placement"
(:126-127). The comment above the function says that a hook with
no @hook line "is emitted after the hook that precedes it in target.def"
(:76-78). The code does not do that. It stops.
The s-tm-texi check
The gcc/Makefile.in rule s-tm-texi runs genhooks -d on tm.texi.in, writes
the result to tm.texi in the build directory, and compares it with the copy in
the source tree (gcc/Makefile.in:2951-2959):
@if cmp -s $(srcdir)/doc/tm.texi tm.texi; then \
$(STAMP) $@; \
elif test $(srcdir)/doc/tm.texi -nt $(srcdir)/doc/tm.texi.in \
&& ( test $(srcdir)/doc/tm.texi -nt $(srcdir)/target.def \
|| test $(srcdir)/doc/tm.texi -nt $(srcdir)/c-family/c-target.def \
|| test $(srcdir)/doc/tm.texi -nt $(srcdir)/common/common-target.def \
|| test $(srcdir)/doc/tm.texi -nt $(srcdir)/d/d-target.def \
|| test $(srcdir)/doc/tm.texi -nt $(srcdir)/rust/rust-target.def \
); then \
echo >&2 ; \
echo You should edit $(srcdir)/doc/tm.texi.in rather than $(srcdir)/doc/tm.texi . >&2 ; \
false; \
else \
echo >&2 ; \
echo Verify that you have permission to grant a GFDL license for all >&2 ; \
echo new text in $(objdir)/tm.texi, then copy it to $(srcdir)/doc/tm.texi. >&2 ; \
false; \
fi
Listing 6.2-10: the check (gcc/Makefile.in:2960-2977).
The check has three results, and two of them stop the build:
- The two files are the same. The rule writes its stamp, and the build continues.
- The source
tm.texiis newer thantm.texi.inand newer than one of the.deffiles. The rule concludes that you editedtm.texiby hand, and tells you to edittm.texi.in. - In all other cases, the rule assumes that the inputs changed and the source
tm.texidid not. It asks you to confirm the GFDL permission and to copy the new file into the source tree.
The check runs in every build of gcc/, also on a machine with no makeinfo.
all.internal and all.cross depend on doc (Makefile.in:2217-2220).
When configure finds no usable makeinfo (configure.ac:1258-1271),
doc still depends on info, so that the prerequisites of the Info files are
checked (Makefile.in:3679-3686). doc/gccint.info depends on the source
tm.texi (:3711-3714), and that file depends on s-tm-texi
(:2897-2898). build/genhooks.o depends on target.def and
the other .def files (:3284-3286), so a changed documentation
string rebuilds genhooks and runs the check again.
So the procedure for a new hook is:
- Write the
DEFHOOKintarget.def, with its documentation string. - Add an
@hookline at the right place intm.texi.in, and any free text around it. - Build. Because you changed
tm.texi.in, the sourcetm.texiis not newer than it, and the build stops with the GFDL message. - Copy
tm.texifrom thegccbuild directory togcc/doc/tm.texi, and commit all three files.
For a changed documentation string, the last step is the same: commit the
tm.texi that the build wrote. tm.texi is a generated file that you commit. The
web script needs it in the repository, because the script never builds anything.
Building the manuals yourself: make html, makeinfo, man gcc
In a build tree, the gcc directory has the usual targets. When configure found
makeinfo, make info writes doc/gcc.info, doc/gccint.info, doc/cpp.info,
doc/gccinstall.info and doc/cppinternals.info
(Makefile.in:3688-3691, :3750-3754).
make html writes one directory per manual under HTML/gcc-15.2.0/
(:770, :3814-3820), and it builds the install manual
with install.texi2html here too (:3823-3828). The
internals manual documents these targets under Texinfo Manuals.
The install manual lists the Texinfo and TeX versions that they need under
Prerequisites.
One sentence in the internals manual is out of date. It says that make info
"generates the manuals in the source directory"
(sourcebuild.texi:411-414). At the pin, the Info files stay in the
build directory. The srcinfo target copies them into the source tree
(Makefile.in:3693-3694), and info depends on srcinfo only when
you configure with --enable-generated-files-in-srcdir
(gcc/configure.ac:306-329). The install manual documents that flag
under Configuration, and says that it is mainly for release
tarballs.
You do not need a build tree to read a manual as Info. Each manual includes
gcc-common.texi, which includes gcc-vers.texi
(gcc-common.texi:11), and only the build writes that file
(Makefile.in:3726-3738). Write it yourself, as the web script does.
Then call makeinfo with the flags and the include paths of the doc/%.info rule
(Makefile.in:356, :3750-3754). From the top
of a checkout:
$ src=$PWD
$ mkdir -p /tmp/gccdoc && cd /tmp/gccdoc
$ printf '%s\n' "@set version-GCC $(cat $src/gcc/BASE-VER)" \
'@clear DEVELOPMENT' "@set srcdir $src/gcc" \
'@set BUGURL @uref{https://gcc.gnu.org/bugs/}' > gcc-vers.texi
$ makeinfo --no-split -I . -I $src/gcc/doc -I $src/gcc/doc/include \
-o gcc.info $src/gcc/doc/gcc.texi
$ info ./gcc.info -n 'Environment Variables'
Nobody ran this recipe at the pin. The machine that this chapter was written on
has no makeinfo. Each line comes from GCC's own scripts. The four @set lines
copy update_web_docs_git:169-180, and the makeinfo options copy
Makefile.in:3752-3753. @set srcdir is necessary, because
invoke.texi includes @value{srcdir}/../libiberty/at-file.texi
(invoke.texi:2339). The info syntax is from the
Invoking Info node of the Info manual. Use gccint.texi in place
of gcc.texi for the internals manual.
man gcc is invoke.texi
The gcc(1) man page is a third form of the same file. The build makes gcc.pod
from invoke.texi with contrib/texi2pod.pl, then runs pod2man on it
(Makefile.in:3891-3893, :360,
:3869-3873). Comments in the source select the parts.
@c man begin OPTIONS at invoke.texi:179 and @c man end at
:37288 put every option section in the man page. The section
ends just before the Spec Files node, so man gcc has no spec language. The
internals manual documents the @c man comments under
Man Page Generation. A man page has no nodes and no anchors. When
man gcc and a web page seem to disagree, compare the invoke.texi line that both
came from.
Documentation outside Texinfo: libstdc++, jit, libgdiagnostics
Three parts of the tree use other systems. The libstdc++ manual is DocBook XML
under libstdc++-v3/doc/xml/. Its HTML is in the repository under
libstdc++-v3/doc/html/, and make doc-html-docbook-regenerate rewrites it
(libstdc++-v3/doc/Makefile.am:557-561). Its API reference comes from
Doxygen, with make doc-html-doxygen
(documentation_hacking.xml:297-307). The libstdc++ manual documents
both under Documentation Hacking. The jit and
libgdiagnostics manuals use Sphinx (update_web_docs_git:233-249).
The internals manual says nothing about any of them. Its Documentation node ends
with "FIXME: document the documentation for runtime libraries somewhere"
(sourcebuild.texi:375-376).
Three things to carry away
The rendered manual is makeinfo run over gcc/doc/*.texi at a release tag.
A .texi:LINE at the same tag is the most exact citation that you can give.
Grep the Texinfo command, then find the @node above it. The node name gives
the page, and an index entry gives the anchor.
Never edit tm.texi by hand. Edit target.def and tm.texi.in, build, then
commit the tm.texi that the build wrote.
Things that surprise people
grep gcc/doc/*.texi finds the generated file and misses its source. The glob
matches tm.texi and not tm.texi.in, and the full hook names are not in
target.def.
The install manual has no versioned copy. The web script builds it only from
master. For a release, read install.texi at the release tag.
A build with no makeinfo still checks tm.texi. It writes no Info files, but
s-tm-texi runs and can stop the build.
Documentation coverage
The internals manual documents the manuals' layout, the make targets and the web
script under Texinfo Manuals (gcc/doc/sourcebuild.texi:384).
That node is part of Documentation (:366). The same manual
documents man pages under Man Page Generation (:437), and
.opt.urls under Option properties
(gcc/doc/options.texi:600). The install manual documents the Texinfo
prerequisite under Prerequisites
(gcc/doc/install.texi:613), and --with-documentation-root-url (:819) and
--enable-generated-files-in-srcdir (:1955) under
Configuration. The GCC manual documents -fdiagnostics-urls
under Diagnostic Message Formatting Options
(gcc/doc/invoke.texi:5515). The Texinfo manual documents the node-name rule under
HTML Xref Node Name Expansion.
What is not documented:
- That
tm.texiis generated fromtm.texi.inand the hook.deffiles bygenhooks. No.texifile names any of them, andtm.texihas no "generated" header. - The
s-tm-texicheck, its two messages, and that it runs in every build, with or withoutmakeinfo. - That the
genhooksheader comment describes an unplaced hook that the code rejects. - That
onlinedocs/gcc-X.Y.Z/is built from the release tag with every non-Texinfo file deleted, and that the install manual is built only frommaster. - GCC's
_002drewrite, which makes its page names differ from plainmakeinfooutput. - That the anchors in
.opt.urlscome from@opindexlines. - That
make infowrites to the source directory only with--enable-generated-files-in-srcdir. The Texinfo Manuals node says otherwise (sourcebuild.texi:411-414).
Next: the conventions that a patch is judged against, from GNU formatting to the
ChangeLog entry that now goes in the commit message, and the contrib/ scripts
that check both.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
6.3 GNU conventions: the style checker, and the ChangeLog in the commit message
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
You fix one function in gcc/tree-ssa-alias.cc. You add an entry to
gcc/ChangeLog, as older guides tell you to, and you run git gcc-verify on
the commit. It reports FAILED, and the error says: "ChangeLog, DATESTAMP,
BASE-VER and DEV-PHASE updates should be done separately from normal commits"
(git_commit.py:370-373).
Your entry is correct. It is in the wrong place. Since May 2020, a GCC
ChangeLog entry is part of the commit message, and a parser in
contrib/gcc-changelog/ decides whether it is well formed. The ChangeLog
files are output: a daily job writes them from the commit history. The layout
has a checker too, contrib/check_GNU_style.py, and you can run both before
anyone reviews your commit.
This chapter assumes Chapter 2.1 for the directory
map, because every ChangeLog entry belongs to a directory. It also assumes
Chapter 6.1, because a change with a new test
writes a second entry, for gcc/testsuite/.
Chapter 6.4 takes the finished commit to the
mailing list.
GNU rules, GCC rules, and the tree: codingconventions.html and .dir-locals.el
Two documents state the conventions, and neither is in the tree. The GNU Coding
Standards apply to every GNU package. Their Formatting and
Comments nodes set the C layout, and Change Logs
sets the entry format. The GCC Coding Conventions page adds
rules "beyond those in the GNU Coding Standards". The
contribution page says that "All contributions must conform to
the GNU Coding Standards". The GCC manual's Contributing
node does not restate either. Its text is a pointer to
https://gcc.gnu.org/contribute.html
(gcc/doc/contribute.texi:13-19). The web pages change
without a release. This chapter quotes them as they read on 2026-10-26.
Neither page marks where GNU ends and GCC begins. The table sorts the rules by where they are written, and adds the files in the tree that encode each one.
| Rule | GNU Coding Standards | GCC Coding Conventions | In the tree |
|---|---|---|---|
| Function name, and its opening brace, in column one | Formatting | no rule | contrib/clang-format |
A space before ( | Formatting | no rule | check_GNU_style.py, contrib/clang-format |
| Two columns per indent level, block braces on their own lines | Formatting, by example | C++ cases only | contrib/vimrc, check_GNU_style.py |
| A tab for every eight columns of indent | no rule | no rule | .dir-locals.el, contrib/vimrc, .gitattributes, check_GNU_style.py, contrib/clang-format |
| Break a long expression before an operator | Formatting | no rule | check_GNU_style.py, contrib/clang-format |
| Line length | 79 characters or less | at most 80 columns | checker: 80, editors: 79 |
| Two spaces after a full stop | Comments | for Texinfo only | check_GNU_style.py |
* file (function): change. | Change Logs | ChangeLogs | contrib/gcc-changelog/ |
| Entry in the commit message, files generated | allowed | required | contrib/gcc-changelog/ |
Two rows stand out. The tab rule is in no document. Only the tree states
it. And the documents disagree on line length by one column. The checker
follows GCC's 80 (check_GNU_style_lib.py:78-91). The editor
settings follow GNU's 79: fill-column is 79 in
.dir-locals.el, and textwidth is 79 in
contrib/vimrc.
GNU layout in one function: access_check in gcc.cc
One short function in the driver shows most of the GNU layout:
/* Check whether NAME can be accessed in MODE. This is like access,
except that it never considers directories to be executable. */
static int
access_check (const char *name, int mode)
{
if (mode == X_OK)
{
struct stat st;
if (stat (name, &st) < 0
|| S_ISDIR (st.st_mode))
return -1;
}
return access (name, mode);
}
Listing 6.3-1: a function in GNU layout (gcc/gcc.cc:3007-3023).
Read it from the top:
- The comment is two complete sentences. There are two spaces after the first
full stop, and two before
*/. The second line starts under the text, with no*. The GNU Comments node asks for the two spaces "so that the Emacs sentence commands will work". NAMEandMODEare in capitals. The same node writes a parameter in upper case "when you are speaking about the value rather than the variable itself".- The return type has its own line, so the name starts in column one. The GNU
Formatting node says that this "helps people to search for
function definitions".
grep -n '^access_check' gcc/gcc.ccfinds the definition and none of the calls. - Every call has a space before its
(:stat (name, &st). - The braces of the
ifbody are on their own lines, two columns in from theif. The body is two columns further in. - The long condition breaks before
||, not after it.
The listing cannot show which white space is a tab. Two of its lines start with one:
$ sed -n '3017,3019p' gcc/gcc.cc | cat -A
if (stat (name, &st) < 0$
^I || S_ISDIR (st.st_mode))$
^Ireturn -1;$
Indentation goes in steps of two columns, and each full eight columns of it is
one tab. return -1; is at column 8, so it is one tab. The || line is at
column 10, so it is a tab and two spaces.
One more GNU rule is invisible. The Formatting node asks for form feeds "to
divide the program into pages at logical places". gcc/gcc.cc has 30 lines
that hold only a form feed (grep -c $'^\f$' gcc/gcc.cc). Python's
str.splitlines treats a form feed as a line break, so it counts different
line numbers. This book reads them with sed -n and grep -n.
The tab rule: contrib/vimrc, .dir-locals.el and .gitattributes
The tab rule is in the editor settings that the tree ships. Emacs reads
.dir-locals.el, which selects the GNU style for C and C++ and sets
indent-tabs-mode to t (.dir-locals.el:21-27). Vim users
source contrib/vimrc:
if l:ext != "py"
setlocal tabstop=8
setlocal softtabstop=2
setlocal shiftwidth=2
setlocal noexpandtab
endif
Listing 6.3-2: the indent settings (contrib/vimrc:36-41).
shiftwidth=2 is the indent step. tabstop=8 is the width of a tab.
noexpandtab keeps the tabs. The settings skip Python files.
.gitattributes turns the rule into a git warning:
*.[cCh] whitespace=indent-with-non-tab,space-before-tab,trailing-space
*.cc whitespace=indent-with-non-tab,space-before-tab,trailing-space
ChangeLog whitespace=indent-with-non-tab,space-before-tab,trailing-space
Listing 6.3-3: whitespace classes for C, C++ and ChangeLog
(.gitattributes:4-6).
indent-with-non-tab "treats a line that is indented with space characters
instead of the equivalent tabs as an error" (git-config).
git diff --check reports these errors. With git 2.43, in a scratch repository
that has the same attribute line, a new line indented with eight spaces gives:
$ git diff --check
a.c:6: indent with spaces.
+ y = 1;
The command exits with status 2. A line indented with six spaces passes,
because six spaces are less than one tab. git diff --check needs no
contrib/ script, so run it before every commit.
contrib/clang-format encodes the GNU brace placement, SpaceBeforeParens: Always and UseTab: Always (:27-53,
:215-217). Its header asks for clang-format 7.0.1, and
applies it through clang-format-diff to the lines a patch touches
(contrib/clang-format:16-25).
The tree does not obey its own rules everywhere. In the same file as
Listing 6.3-1, remove_outfile_spec_function has a comment with * at the
start of each line. It also has a statement indented with eight spaces
(gcc/gcc.cc:10491-10510). The GCC Coding Conventions
page expects this: "Some existing code may not follow these conventions, but
they must be used for new code." It also asks you to send changes that only fix
the conventions apart from any other change. So the rules apply to the lines you
add. A reformat of the lines around them is a separate patch.
Running contrib/check_GNU_style.py on a diff
This chapter was written without a GCC checkout, so the contrib/ commands
below were not run. Where the chapter says what a script prints, it cites the
line that prints it.
$ pip3 install unidiff termcolor
$ git diff | contrib/check_GNU_style.py -
$ git diff > my.patch
$ contrib/check_GNU_style.py -f quickfix my.patch
The script reads a patch file, or standard input when the name is -
(contrib/check_GNU_style.py:29-45). Without unidiff and
termcolor it stops with status 3 and tells you what to install
(check_GNU_style_lib.py:25-55). Two filters decide what it
checks:
for pfile in patch.added_files + patch.modified_files:
t = pfile.target_file.lstrip('b/')
# Skip testsuite files
if 'testsuite' in t or t.endswith('.py'):
continue
for hunk in pfile:
delta = 0
for line in hunk:
if line.is_added and line.target_line_no != None:
for check in checks:
line_chomp = line.value.replace('\n', '')
e = check.check(t, line.target_line_no, line_chomp)
if e != None:
errors.append(e)
Listing 6.3-4: the lines that are checked
(contrib/check_GNU_style_lib.py:281-295).
The script skips every path that contains testsuite, and every Python file.
In the other files, it checks only the added lines. The checker judges the lines you add,
and it never reads a test. Each check that matches adds an error:
| Message | What it matches | Source |
|---|---|---|
lines should not exceed 80 characters | more than 80 columns, a tab counted as 8 | :78-91 |
blocks of 8 spaces should be replaced with tabs | eight spaces anywhere in the line | :93-102 |
a space should not precede a tab | a space, then a tab | :104-114 |
trailing whitespace | white space at the end | :116-127 |
dot, space, space, new sentence | a word, a full stop, one space or three or more, a word | :129-139 |
dot, space, space, end of comment | the wrong spacing before */, or no full stop | :141-162 |
there should be exactly one space between function name and parenthesis | f( or f ( | :164-178 |
there should be no space before a left square bracket | a [i], except in .md files | :180-193 |
there should be no space before closing parenthesis | f (a ) | :195-205 |
braces should be on a separate line | ) { or else { | :207-218 |
trailing operator | an indented line that ends in an operator | :220-230 |
The default output groups the errors by message, and the script exits with 1 if
there is any error. -f quickfix writes errors.err for Vim instead
(:297-319).
The parenthesis check skips every line that contains #define. C requires that
exception. The cpp manual documents it under
Function-like Macros: a space between the macro name and the
parenthesis "does not define a function-like macro, it defines an object-like
macro whose expansion happens to begin with a pair of parentheses". So a
function-like macro is defined as #define MAX(a, b), with no space.
The checks are regular expressions, and some give false positives. e.g. the
matches the sentence check. The brace check warns: "This will give false
positives for C99 compound literals." Use the output as a list of places to
look. The older shell version, contrib/check_GNU_style.sh, says the same in
its usage text: the checks "are not always accurate, and complete"
(check_GNU_style.sh:24-38). After you run
contrib/gcc-git-customization.sh, git gcc-style HEAD sends a commit
through the Python checker (gcc-git-customization.sh:33-37).
The ChangeLog entry: * file (function): change.
The entry format is GNU's, from the Style of Change Logs node.
The first entry after the release line in gcc/ChangeLog shows every part:
2025-08-07 Uros Bizjak <ubizjak@gmail.com>
Backported from master:
2025-08-06 Uros Bizjak <ubizjak@gmail.com>
PR target/96226
* config/i386/predicates.md (and_operator): New operator.
* config/i386/i386.md (splitter after *<rotate_insn><mode>3_mask):
Use and_operator to match AND RTX and use its mode
in the split pattern.
Listing 6.3-5: a generated entry (gcc/ChangeLog:5-14).
- The header line is a date, two spaces, a name, two spaces and an address in
angle brackets (
git_commit.py:789-798,git_repository.py:63). - Every other line starts with a tab.
PR target/96226names the Bugzilla component and bug number.- Each change is
* file (entity): description.The file path is relative to the directory that owns thisChangeLog, heregcc/. The entity in parentheses is a function, a macro or a type. In a machine description it names a pattern, and a pattern with no name is given by its position:splitter after *<rotate_insn><mode>3_mask. The description is a sentence, and long lines continue after a tab. - The
Backported from master:block is how the job records a cherry-pick. It writes the original author and date under the backport's own header (git_commit.py:831-840). The text is fixed, whatever branch the commit came from. Chapter 6.4 says when a backport is allowed.
Two content rules are GNU-wide. Name each entity in full, so that a search for the name finds the entry. And keep the reason out of the entry. The Change Log Concepts node says: "The best place to explain how parts of the new code work with other code is in comments in the code, not in the change log". The entry says what changed. The free text above it in the commit message says why.
mklog.py uses set phrases: New file., New test., Removed.,
Regenerate., and Move to... with ...here. for a rename
(mklog.py:267-285). The contribution page asks you to note a
regenerated file, as in * configure: Regenerate.
One ChangeLog per directory: default_changelog_locations
GNU lets a directory keep its own ChangeLog or share its parent's. GCC fixes
the choice in code. default_changelog_locations lists the directories that
own a ChangeLog, 59 of them at the pin
(git_commit.py:27-87). A file belongs to the
nearest listed directory above it (:680-686).
So gcc/cp/ has its own ChangeLog, apart from gcc/. gcc/config/i386/ is
not in the list, so its files go in gcc/ChangeLog with paths that start with
config/i386/, as in Listing 6.3-5. gcc/testsuite/ has its own file. A C++
front-end fix with a test therefore needs at least two blocks, one for
gcc/cp/ and one for gcc/testsuite/. A file under the wrong block fails with
wrong ChangeLog location, and the message names the right one
(:779-787).
The commit message is the entry: contrib/gcc-changelog/git_commit.py
The scripts arrived on 2020-05-13
(contrib/ChangeLog:2071-2076). On 2020-05-25 Jakub
Jelinek turned on the strict mode of the server hook. His announcement on the
gcc list says that "ChangeLog entry should be solely in the commit
message". The daily script "will be updating the ChangeLog files for you"
(gcc list, 2020-05-25). The ChangeLogs
section of the GCC Coding Conventions page documents the parts that the parser
accepts, with an example. git_commit.py is the definition. It finds the entry
by looking for the first line that looks like a ChangeLog line:
def parse_lines(self, all_are_ignored):
body = self.info.lines
for i, b in enumerate(body):
if not b:
continue
if (changelog_regex.match(b) or self.find_changelog_location(b)
or star_prefix_regex.match(b) or pr_regex.match(b)
or dr_regex.match(b) or author_line_regex.match(b)
or b.lower().startswith(CO_AUTHORED_BY_PREFIX)):
self.changes = body[i:]
return
if not all_are_ignored:
self.errors.append(Error('cannot find a ChangeLog location in '
'message'))
Listing 6.3-6: where the entry starts
(contrib/gcc-changelog/git_commit.py:451-465).
Everything above that line is free text: the subject, an empty line, and your explanation. Everything from that line down is the entry. A message for a middle-end fix with a test looks like this (the PR number and test name are invented):
alias: Check that the offset fits in a HWI
Explain the bug and the fix here. This text goes to the git log and
the mailing list, but not to the ChangeLog files.
PR tree-optimization/12345
gcc/ChangeLog:
* tree-ssa-alias.cc (ao_ref_init_from_ptr_and_range): Check
the pointer offset fits in a HWI when represented in bits.
gcc/testsuite/ChangeLog:
* gcc.dg/pr12345.c: New test.
A PR line above the first location line goes into every block
(:548-554). The form of the subject line belongs to
Chapter 6.4. Apart from the empty line after it, the parser reads the subject
only for PR numbers. A PR component/number in the subject must use a valid
component, and the entry must name the same PR
(:351-358, :391-393). The parser does
not check the length of the subject.
The errors you will meet most often:
| Message | What it rejects | Source |
|---|---|---|
Expected empty second line in commit message | a subject that continues on line 2 | :329-330 |
cannot find a ChangeLog location in message | a message with no entry | :463-465 |
line should start with a tab | an entry line indented with spaces | :566-568 |
first line should start with a tab, an asterisk and a space | a block that does not start with * | :589-592 |
line exceeds 100 character limit | a line over 100 columns, a tab counted as 8 | :477-481 |
missing PR component, invalid PR component | PR 12345, or a component not in bug_components | :507-516, :89-143 |
changed file not mentioned in a ChangeLog | a modified file with no entry | :766-767 |
unchanged file mentioned in a ChangeLog | an entry for a file that the commit does not touch | :714-721 |
missing description of a change | (name): with no text after it | :620-628 |
bad parentheses wrapping | a ( with no ) by the end of the block | :630-634 |
The 100-column limit is for the entry only. Code lines stop at 80.
The parser is lenient in four places. The date and author line is optional,
because git records both (:800-825). The location line is
optional when all the files in a block belong to one ChangeLog
(:653-671). A new file with no entry gets New file.
automatically, and a warning (:749-755). Some
directories need no entry at all, for example libsanitizer/ and
gcc/go/gofrontend/ (:145-155). The parser reads trailers too.
Co-Authored-By: adds an author to every block, and the parser skips
Reviewed-by: and its relatives
(:188-190, :524-531). The
(cherry picked from commit ...) line that git cherry-pick -x writes is what
makes the job write Backported from master: (:533-541).
The error from the start of the chapter comes from this block:
# Allow complete deletion of ChangeLog files in a commit
project_files = [f for f in self.info.modified_files
if (self.is_changelog_filename(f[0], allow_suffix=True) and f[1] != 'D')
or f[0] in misc_files]
ignored_files = [f for f in self.info.modified_files
if self.in_ignored_location(f[0])]
if len(project_files) == len(self.info.modified_files):
# All modified files are only MISC files
return
elif project_files:
err = 'ChangeLog, DATESTAMP, BASE-VER and DEV-PHASE updates ' \
'should be done separately from normal commits\n' \
'(note: ChangeLog entries will be automatically ' \
'added by a cron job)'
self.errors.append(Error(err))
return
Listing 6.3-7: the ChangeLog file guard
(contrib/gcc-changelog/git_commit.py:360-375).
A commit that changes only ChangeLog files, or the version files, returns
before the parser looks for an entry. That is how you correct an entry after
the job wrote it: edit the ChangeLog file alone, in its own commit, as the
2020 announcement advises.
Check a commit, or a patch file, before you send it:
$ contrib/gcc-git-customization.sh
$ git gcc-verify
$ git gcc-verify -p -n 3
$ contrib/gcc-changelog/git_email.py 0001-alias-Check-offset.patch
git gcc-verify runs git_check_commit.py on HEAD, or on the last three
commits with -n 3. -p prints the entries it parsed (git_check_commit.py:31-45). For each commit it
prints Checking <hash>: OK or FAILED, then one ERR: line per error
(:53-73). It needs the GitPython package
(git_repository.py:23-29). git_email.py checks a file from
git format-patch without a repository. It needs python-dateutil and
unidiff (git_email.py:26-30, :95-105).
A skeleton to fill in: contrib/mklog.py and git gcc-commit-mklog
contrib/mklog.py reads a diff and writes the skeleton of an entry. The
skeleton has the location lines, a * file (function): line for each file,
and the PR lines that the script finds in new tests
(mklog.py:184-334). Its test file shows the
output for a diff that adds two macros to gcc/config/riscv/riscv.h:
EXPECTED1 = '''\
gcc/ChangeLog:
* config/riscv/riscv.h (C_S_BITS):
(CSW_MAX_OFFSET):
'''
Listing 6.3-8: the expected skeleton for one header
(contrib/test_mklog.py:65-71).
The skeleton stops at the colon. The script knows where you changed code, not
what you changed. git gcc-verify rejects the skeleton as it stands. A
(name): line followed by another item, or by nothing, is a "missing
description of a change" (git_commit.py:179,
:620-628). Write a description after each colon.
For a new file under a testsuite directory, mklog.py reads the first ten
lines for a PR component/number comment. It also takes a number from a file
name such as pr50209.c (mklog.py:210-243). A number from a
file name has no component, so the line reads PR 50209
(test_mklog.py:242-262), and the checker rejects it as a
missing PR component. -p asks Bugzilla for the component and the title,
and corrects the line (mklog.py:151-164). -b adds PR
numbers that you give.
$ pip3 install requests unidiff
$ git diff | contrib/mklog.py -p
$ git gcc-commit-mklog -b 12345
mklog.py imports requests and unidiff when it starts, so it needs both
even without -p (mklog.py:38-40).
git gcc-commit-mklog runs git commit with GCC_FORCE_MKLOG=1 set
(git-commit-mklog.py:44-60). Only with that variable does the
prepare-commit-msg hook, which gcc-git-customization.sh offers to install,
do anything (gcc-git-customization.sh:145-157,
prepare-commit-msg:32-37). It sends the staged diff to
git gcc-mklog -c (prepare-commit-msg:81), which puts the
skeleton after your text and before any Signed-off-by: trailer. With an empty
subject and exactly one PR, it also writes a subject of the form
component: [PRnnnnn] (mklog.py:425-447).
Who writes the ChangeLog files: git_update_version.py
On master and the release branches,
contrib/gcc-changelog/git_update_version.py writes the ChangeLog files once
a day. It walks back to the last Daily bump. commit by gccadmin@gcc.gnu.org
(:111-123), and runs each newer commit through the same
parser:
def prepend_to_changelog_files(repo, folder, git_commit, add_to_git):
if not git_commit.success:
logging.info(f"While processing {git_commit.info.hexsha}:")
for error in git_commit.errors:
logging.info(error)
raise AssertionError()
for entry, output in git_commit.to_changelog_entries(use_commit_ts=True):
full_path = os.path.join(folder, entry, 'ChangeLog')
logging.info('writing to %s' % full_path)
if os.path.exists(full_path):
with open(full_path) as f:
content = f.read()
else:
content = ''
with open(full_path, 'w+') as f:
f.write(output)
if content:
f.write('\n\n')
f.write(content)
if add_to_git:
repo.git.add(full_path)
Listing 6.3-9: one commit becomes text at the top of each ChangeLog
(contrib/gcc-changelog/git_update_version.py:65-85).
Each entry goes on top of the old file contents. Then the job writes the date
to gcc/DATESTAMP and commits Daily bump. (:148-155).
The bump commit changes only ChangeLog files and DATESTAMP, so it passes
the guard in Listing 6.3-7.
A commit that the parser rejects would stop the job with an AssertionError.
The server runs the same check earlier, on a push to master or a release
branch, and refuses the push. The hook configuration is not in the tree, and
the only record this chapter found is from May 2020. The day after the strict
mode started, a contributor posted a refused push to releases/gcc-10. In it,
the server quotes the message from Listing 6.3-7 under
remote: *** ChangeLog format failed: (gcc list, 2020-05-26).
The job passes use_commit_ts=True (git_update_version.py:71).
So for a normal commit the file gets the commit date, not the date line you
wrote, but it keeps the names (git_commit.py:800-825).
Three things to carry away
The ChangeLog entry goes in the commit message, and the ChangeLog files are
generated. A commit that edits one together with other files fails
git gcc-verify and the push.
contrib/gcc-changelog/git_commit.py defines the format. Run
git gcc-verify before you send, and write a description after every colon
that mklog.py leaves empty.
The tab rule is in the tree, not in either document. Two columns per level, a tab for each eight, and only on the lines you add.
Things that surprise people
git gcc-verify accepts * file.c: with nothing after it. The
empty-description check needs a name in parentheses
(git_commit.py:179). mklog.py writes such a line for
every test file you modify (test_mklog.py:242-262).
The date you write is not the date in the ChangeLog file. The daily job
uses the commit date.
A line of exactly 80 columns passes check_GNU_style.py. GCC allows 80. The
GNU Coding Standards ask for 79, and so do the editor settings in the tree.
check_GNU_style.py never checks a test. It skips every path that contains
testsuite.
Documentation coverage
The GCC manual's Contributing node
(gcc/doc/contribute.texi:5, included at gcc/doc/gcc.texi:187 and
gcc/doc/gccint.texi:140) only points to https://gcc.gnu.org/contribute.html.
The internals manual lists *ChangeLog* under
Miscellaneous Docs as "Change log files for various parts of GCC"
(gcc/doc/sourcebuild.texi:495-497), and does not say how they are written.
The cpp manual documents the macro rule behind the #define exception under
Function-like Macros (gcc/doc/cpp.texi:1327-1330).
Chapter 6.2 shows how these .texi files
become the rendered pages.
The rules themselves are on web pages outside the tree, read on 2026-10-26: the
GNU Coding Standards nodes Formatting,
Comments, Change Logs and
Style of Change Logs, and GCC's
Coding Conventions, whose ChangeLogs section lists the parts
the parser accepts. Contributing names contrib/check_GNU_style.sh and
git gcc-commit-mklog, and
Read-write Git access lists the git gcc-* aliases.
What is not documented:
- The tab rule. Neither document states it.
.dir-locals.el,contrib/vimrc,.gitattributesand the checker do. - That
check_GNU_style.pychecks only added lines, and skips every path that containstestsuiteand every Python file. - The list of directories that own a
ChangeLog, and the rule that a file belongs to the nearest one above it. - The 100-column limit on entry lines.
- That the skeleton from
mklog.pyfailsgit gcc-verifyuntil you write the descriptions, and that a PR number taken from a file name has no component. - That a commit which changes only
ChangeLogfiles skips the entry check. This is the way to correct a generated entry. Only the 2020 list message describes it. - That the daily job writes the commit date, not the date in the message.
Next: how a patch gets proposed: reading MAINTAINERS, posting to
gcc-patches, and what a submission must hold besides its ChangeLog entry.
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.
6.4 How a patch gets proposed: MAINTAINERS, gcc-patches and backports
Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).
The process in this chapter was checked on 2026-10-26, against the
gcc.gnu.org pages that the first table dates. The source files are pinned.
The process is not, and it changes without a release.
You have a fix for GCC. It bootstraps, and it has a test. You look in the tree
for the rules on how to submit it. gcc/doc/contribute.texi is 24 lines long
and sends you to a web page. MAINTAINERS gives you several hundred names and
no procedure. The procedure is on four web pages, and the tools that serve it
are in contrib/. The pages change on any day. The tools change with each
release. On the day this chapter was checked, they disagreed in three places.
This chapter reads the files and the pages side by side, and then follows one
real patch from the gcc-patches list into the 15.2.0 release tree.
This chapter assumes Chapter 6.1, for the test
that a patch adds, and Chapter 6.3, for the
ChangeLog entry in the commit message and the checker in
contrib/gcc-changelog/. Chapter 2.5 and
Chapter 3.7 explain the bootstrap and
the test run that a submission reports.
There is no command that shows this mechanism working, because review is people
reading mail. This is the one chapter in the book with no observable. What you
can open is the record that a patch leaves: the archived mail, the Bugzilla
entry, the commits, and the ChangeLog entry in the release tree. The
contrib/ commands below were not run for this book, which has no GCC
checkout. Each claim about them comes from the script at the pin.
Where the rules live: contribute.texi, MAINTAINERS and four web pages
The GCC manual and the internals manual include the same file for the process,
and it is a pointer. Chapter 6.2 explains
how the gcc/doc sources become the manuals.
If you would like to work on improvements to GCC, please read the
advice at these URLs:
@smallexample
@uref{https://gcc.gnu.org/contribute.html}
@uref{https://gcc.gnu.org/contributewhy.html}
@end smallexample
Listing 6.4-1: the manual's advice on contributing
(gcc/doc/contribute.texi:13-19).
So the rules come from six places. Two are in the tree and four are not:
| Source | What it holds | Version |
|---|---|---|
MAINTAINERS | who may approve and who may commit, and the DCO list | pinned |
contrib/ | git aliases, the ChangeLog checker, the backport script | pinned |
contribute.html | what a submission contains, subject lines, testing | modified 2026-07-23 |
gitwrite.html | write-access levels, obvious fixes, committing | modified 2026-07-21 |
develop.html | development stages, release-branch policy, reverts | modified 2026-09-11 |
dco.html | the Signed-off-by: rule | no date on the page |
The pages are the project's policy for work on master today. The files tell
you what one release's tools do. Where the two disagree, this chapter says so
at the claim.
Reading MAINTAINERS: who may approve what
MAINTAINERS is at the top of the tree. It describes itself as a list of
"people who are permitted to make changes to various parts of the compiler and
associated libraries", and asks you not to contact them directly to report
problems (MAINTAINERS:4-8). Most of its sections are levels of
authority, and gitwrite.html gives the levels their names:
- Global Reviewers (
:32) can approve a change to any part of the compiler. - CPU Port, OS Port, Language Front Ends and Various
Maintainers (
:55,:136,:158,:177) have localized write permission. They commit to their area without approval, and they approve other people's changes there. - Reviewers (
:276) have localized review permission. They approve changes in their area, but their own patches need someone else's approval. - Write After Approval (
:328) is everyone else with commit access. They commit only after the appropriate maintainer approves.
The file itself states two of the rules that go with these levels:
Note that while global reviewers can approve changes to any part of
the compiler or associated libraries, they still need approval for
their own patches from other maintainers or reviewers.
Also note that maintainership of any area covers changes to web pages,
docs, and the testsuite related to that.
Listing 6.4-2: two rules in the file's own text
(MAINTAINERS:48-53).
It repeats the first rule for maintainers who change code outside their area
(:273-274) and for reviewers (:324-326). The
second rule means the owner of an area also approves its tests and its
documentation.
gitwrite.html adds a sentence that the file does not have: "We have not put
any technical enforcement in place, rather we rely on everyone to follow the
appropriate policies." The tree agrees. The ChangeLog checker skips a
Reviewed-by: line and six other trailers, and records nothing from them
(contrib/gcc-changelog/git_commit.py:188-190,
:530-531). The checker keeps no record of who approved a
patch.
Finding your reviewer: areas, not paths
The first column of an area section is free text, not a path pattern. You
search it for the nearest area name. For a change to gcc/tree-sra.cc, these
are the nearest lines:
middle-end Jeff Law <jeffreyalaw@gmail.com>
middle-end Ian Lance Taylor <ian@airs.com>
middle-end Richard Biener <rguenther@suse.de>
*vrp, ranger Aldy Hernandez <aldy@quesejoda.com>
*vrp, ranger Andrew MacLeod <amacleod@redhat.com>
tree-ssa Andrew MacLeod <amacleod@redhat.com>
Listing 6.4-3: area names, as people wrote them
(MAINTAINERS:242-247).
If no area fits, a global reviewer fits. Richard Biener is in both lists
(:34), and the patch that this chapter traces went to him.
The Write After Approval section has three columns: name, Bugzilla account and
email (:330). The account is the person's login on
gcc.gnu.org. To copy a maintainer on a Bugzilla entry, add @gcc.gnu.org to
that account name (:18-20). An entry in this section gives commit
access. It gives no right to approve.
At the pin, a new committer adds their own line by hand, and
contrib/check-MAINTAINERS.py checks the sort order (:26-27) of
four sections (check-MAINTAINERS.py:123-129).
This changed on master after 15.2. Since 2026-07-07, MAINTAINERS is
generated from MAINTAINERS.yml by contrib/gen-MAINTAINERS.py, and
check-MAINTAINERS.py is gone (commit 89d27e50). Neither the
releases/gcc-16.1.0 nor the releases/gcc-16.2.0 tag has the YAML file.
contribute.html and gitwrite.html already describe the YAML procedure, so
they are wrong for a 15.2, 16.1 or 16.2 tree.
FSF assignment or Signed-off-by: the DCO section of MAINTAINERS
The first question a new contributor meets is legal: can the project accept
your code? As of 2026-10-26, contribute.html gives three routes:
- An FSF copyright assignment. The FSF prefers it for large contributions.
The common forms are an assignment for one change, an assignment for all
future changes, and an employer disclaimer when an employer or school owns
the work. To get the forms, ask on
gcc@gcc.gnu.orgor ask the maintainer who handles your contribution, and copyassign@gnu.org. - A Developer Certificate of Origin (DCO) sign-off. You add a
Signed-off-by:line with a known identity, not an anonymous one.git commit -sadds the line for you (dco.html). By signing, you certify that you have the right to submit the code under the file's license. - Nothing, for small changes that the FSF does not count as legally significant.
A committer can certify the DCO once, for all future commits, with a line in the
last section of MAINTAINERS:
Contributing under the DCO
By adding your name and email to this section, you certify that all your
subsequent contributions to GCC are made under the terms of the Developer's
Certificate of Origin Version 1.1. See https://gcc.gnu.org/dco.html for more
information.
Listing 6.4-4: the DCO list (MAINTAINERS:927-932).
dco.html requires a Signed-off-by: line for any contribution that neither
an FSF assignment nor this list covers. contribute.html adds that an entry is
permanent once you have committed with its email address. A new address needs
a new entry. dco.html puts the Signed-off-by: line at the end of the
explanation. The ChangeLog checker skips the line, so it can also follow the
ChangeLog entries (git_commit.py:188-190). The checker
does not check that the line is there.
What a gcc-patches mail must carry
contribute.html lists five things that every submission needs:
- A description of the problem and of how the patch fixes it, with the Bugzilla PR number if there is one.
- A test case, or the reason why you cannot add one. Chapter 6.1 covers writing it.
- A ChangeLog entry, as plain text. Chapter 6.3
covers its format, and
git gcc-commit-mklogwrites a skeleton. - A testing statement: the host and target triples you tested on, and the result.
- The patch, including every regenerated file, each noted in the
ChangeLog, for example
* configure: Regenerate.
Send one logical change per patch, and keep formatting changes apart from real
ones. Send the patch as plain text, or as a text/x-patch or text/plain MIME
part. Do not send it as an attachment or in base64. A documentation change also
needs make info and make dvi to run without errors.
The testing that item 4 reports depends on what you changed. As of 2026-10-26,
contribute.html asks for this:
| Your change touches | Required testing |
|---|---|
| anything outside a front end, or the C or C++ front end | make bootstrap, then make -k check, from the top of the build tree, all default languages |
| the C++ front end | the above, and make -C gcc -k check-c++-all for every standard level |
| another front end, or a runtime library other than libgcc | build that library, and check that its language's tests did not regress |
| the Ada front end | a full bootstrap, because the front end is written in Ada |
In every case, you test exactly the change you submit, in a tree with no other
change. You compare the results with a run before the patch, or with recent
posts to gcc-testresults. The install manual documents make check under
Testing. Chapter 2.5
explains what make bootstrap does, and
Chapter 3.7 compares two runs with
contrib/compare_tests.
The mail is the commit message: git_email.py
contribute.html says that the subject line of your mail "will become the first
line of the commit message". The checker for a patch file builds the commit
message in the same way:
subject_patch_regex = re.compile(r'^\[PATCH( \d+/\d+)?\] ')
...
if subject:
subject = subject_patch_regex.sub('', subject)
header = list(takewhile(lambda line: line != '', lines))
# Note: commit message consists of email subject, empty line, email body
message = [subject] + lines[len(header):]
Listing 6.4-5: from mail to commit message
(contrib/gcc-changelog/git_email.py:35 and
:67-71).
The body ends at the first --- line (:51), which is the line
that git format-patch writes above the diffstat. So the ChangeLog entries go
above that line, and they are part of the message. You can check a patch file
before you send it:
$ contrib/gcc-changelog/git_email.py 0001-my-fix.patch
It prints OK and the ChangeLog entries that the commit will produce, or the
errors (:135-143). It needs the Python modules unidiff and
dateutil (:26, :30).
The subject line: [PATCH v2 3/7] component: summary [PRnnnnn]
As of 2026-10-26, contribute.html gives a subject line five parts:
- A classifier in square brackets:
[PATCH],[PATCH v2]for a second version,[PATCH 3/7]for one patch of a series,[RFC]for discussion, or[COMMITTED]for a patch that needed no approval. It is the only part that is not committed. - Component tags, each followed by a colon:
libstdc++:,combine:,vax: testsuite:. They tell the right maintainers to read the patch. - An optional series identifier, followed by
-. - A short summary, distinct from other patches.
- An optional bug number, as
[PR12345], with no component and no space.
The whole line, without the classifier, should be 75 characters or fewer. The
body still carries the full PR component/12345 form, so that Bugzilla notices
the commit. The checker enforces that half of the rule:
subject_pr_regex = re.compile(r'(^|\W)PR\s+(?P<component>[a-zA-Z0-9+-]+)/(?P<pr>\d{4,7})')
subject_pr2_regex = re.compile(r'[(\[]PR\s*(?P<pr>\d{4,7})[)\]]')
...
if self.subject_prs:
self.errors.append(Error('PR %s in subject but not in changelog' %
', '.join(self.subject_prs), self.info.lines[0]))
Listing 6.4-6: a PR in the subject must also be in the ChangeLog
(contrib/gcc-changelog/git_commit.py:173-174 and
:391-393).
A PR component/nnnnn line in the ChangeLog part removes the number from the
set (:519-520). Round brackets work as well as square
ones. The checker does not measure the subject. Its 100-column limit applies to
ChangeLog lines (:477-481), and its only test on the subject
is that the next line is empty (:329-330).
The classifier rule and Listing 6.4-5 disagree. git format-patch -v2 writes
[PATCH v2], but subject_patch_regex removes only [PATCH] and
[PATCH n/m]. For a [PATCH v2], [RFC] or [COMMITTED] file,
git_email.py keeps the classifier in the subject that it checks.
Sending it: git send-email and sendemail.to
contrib/gcc-git-customization.sh sets up a checkout for this work. It defines
the git gcc-* aliases (:25-37), offers to install the
prepare-commit-msg hook (:145-157), and sets the address:
# Tell git send-email where patches go.
# ??? Maybe also set sendemail.tocmd to guess from MAINTAINERS?
git config sendemail.to 'gcc-patches@gcc.gnu.org'
Listing 6.4-7: the list, but no reviewer
(contrib/gcc-git-customization.sh:44-46).
The ??? comment records that the script does not pick reviewers from
MAINTAINERS. You find the reviewer yourself and copy them:
$ git format-patch -1
$ git send-email --cc=reviewer@example.org 0001-my-fix.patch
git send-email uses sendemail.to when you give no --to. Its
documentation gives its default threading: every mail after
the first one replies to the first one. That is the shape contribute.html
asks for in a series. The first mail is [PATCH 0/N], which
git format-patch --cover-letter writes, and patches 1 to N reply to it. The
cover letter is not committed, so it should hold nothing important that the
patches do not also say.
A second version starts a new thread. Its cover letter says what changed and
which patches did not change. Then you reply to the old thread with a pointer to
the new one. If nobody answers in about two weeks, contribute.html says to
send a follow-up to the same list, with a short summary and the archive URL of
the first mail.
If you do not have commit access, say so in the submission. When the patch is
approved, tell the approver. The person who commits it for you uses
git commit --author, so that the commit names you (gitwrite.html).
One patch end to end: PR 117423
The traced patch is a wrong-code fix in scalar replacement of aggregates (SRA),
in gcc/tree-sra.cc (:1). It is small, it went through review,
and a backport put it in the 15.2.0 tree, so the last step is a file at the
pin.
2025-07-17: the [PATCH] mail
Bugzilla PR 117423 was filed on 2024-11-03. At the time of writing, its
summary is "[13 Regression] union not written to with particular layout since
r10-6321-g636e80eea24b78", and its keyword is wrong-code. Martin Jambor
assigned it to himself on 2025-07-17 and posted the fix that evening:
From: Martin Jambor <mjambor@suse.cz>
To: GCC Patches <gcc-patches@gcc.gnu.org>
Cc: Richard Biener <rguenther@suse.de>
Subject: [PATCH] tree-sra: Fix grp_covered flag computation when totally
scalarizing (PR117423)
Date: Thu, 17 Jul 2025 22:35:28 +0200
Hi,
testcase of PR 117423 shows a flaw in the fancy way we do "total
scalarization" in SRA now. ...
Bootstrapped and tested on x86_64-linux, I'm also running a bootstrap
and testing on aarch64-linux as I'm writing this but will know the
results only tomorrow. OK for master and later for all active release
branches if it passes there too?
Thanks,
Martin
gcc/ChangeLog:
2025-07-17 Martin Jambor <mjambor@suse.cz>
PR tree-optimization/117423
* tree-sra.cc (analyze_access_subtree): Fix computation of grp_covered
flag.
gcc/testsuite/ChangeLog:
2025-07-17 Martin Jambor <mjambor@suse.cz>
PR tree-optimization/117423
* gcc.dg/tree-ssa/pr117423.c: New test.
---
gcc/testsuite/gcc.dg/tree-ssa/pr117423.c | 49 ++++++++++++++++++++++++
gcc/tree-sra.cc | 9 ++++-
2 files changed, 56 insertions(+), 2 deletions(-)
Listing 6.4-8: the posting, abridged: the description and the diff are cut
(message on gcc-patches).
All five parts are there. The description explains the flaw. The test is an
execution test at -O1 (gcc/testsuite/gcc.dg/tree-ssa/pr117423.c:1-2).
There is one ChangeLog entry for each directory that has a ChangeLog. The
testing statement names one host and promises a second. The diffstat shows the
patch. The subject has the component tag tree-sra: and the PR in round
brackets, which subject_pr2_regex accepts. Without the classifier, it is 78
characters long.
The approval request is also there, and the Cc: line shows why. Jambor is a
reviewer for the callgraph (MAINTAINERS:279) and has write
after approval (:561). tree-sra.cc is outside his area, so
he needed an approval, and he copied a global reviewer.
2025-07-18: OK. and the commit r16-2347
Biener replied at 09:09 the next morning. Below the quoted request,
his answer is "OK." and a thank-you. That word approved the question it
answered, so it covered master and the release branches.
Jambor committed the patch to master the same day, as commit
7375909e. Its message is the mail without the greeting, the
testing statement, the question and the signature. Its first line is the
mail's subject without [PATCH]. A bot then added a comment to the Bugzilla
entry. It begins "The master branch has been updated by Martin Jambor", and it
names the commit r16-2347-g7375909e9d9e7de23acb4b1e0a965d8faf1943c4.
That rN-M form is GCC's name for a commit. git gcc-descr
(gcc-git-customization.sh:25) runs contrib/git-descr.sh, which
runs git describe --match 'basepoints/gcc-[0-9]*' and changes the
basepoints/gcc- prefix to r (contrib/git-descr.sh:21-25). The
bug summary uses the same form, r10-6321, for the commit that caused the
regression.
2025-07-23: git gcc-backport and cherry-pick -x
Five days later the fix reached releases/gcc-15, as commit
420b1632 (r15-10058). Its message is the master message with
one more line at the end:
(cherry picked from commit 7375909e9d9e7de23acb4b1e0a965d8faf1943c4)
git cherry-pick -x writes that line, and that command is what the
gcc-backport alias runs (gcc-git-customization.sh:29):
subprocess.run('git cherry-pick -x %s' % args.revision, shell=True)
subprocess.run(fixup_script, shell=True)
Listing 6.4-9: a backport is a cherry-pick
(contrib/git-backport.py:34-35).
The second script repairs file names in the ChangeLog part of the message when
they point to files that now end in .cc
(contrib/git-fix-changelog.py:22-23).
gitwrite.html describes an older script. It says the alias runs
git cherry-pick -x "and reverts all modifications of ChangeLog files". That
was GCC 11's git-backport.py. After the cherry-pick, it restored every
ChangeLog file that the commit had changed
(releases/gcc-11.1.0: contrib/git-backport.py:26-38).
At 15.2, the script does not touch ChangeLog files.
At the pin: Backported from master: in gcc/ChangeLog
The ChangeLog checker reads the cherry picked from commit line
(git_commit.py:182). A cron job writes each commit into the
branch's ChangeLog files (:370-373). For a backport, it adds a
header:
if self.cherry_pick_commit or self.revert_commit:
original_author = self.original_info.author
output += self.format_authors_in_changelog([original_author],
current_timestamp)
if self.revert_commit:
output += '\tRevert:\n'
else:
output += '\tBackported from master:\n'
Listing 6.4-10: the backport header
(contrib/gcc-changelog/git_commit.py:831-838).
The result is in every 15.2.0 tree:
2025-07-23 Martin Jambor <mjambor@suse.cz>
Backported from master:
2025-07-18 Martin Jambor <mjambor@suse.cz>
PR tree-optimization/117423
* tree-sra.cc (analyze_access_subtree): Fix computation of grp_covered
flag.
Listing 6.4-11: the end of the trace
(gcc/ChangeLog:276-283).
The outer date is the backport. The inner date is the master commit. It is
not the 2025-07-17 in the mail, because for a cherry-pick the generator takes
the date from the original commit (git_commit.py:809-815).
gcc/testsuite/ChangeLog has the same entry for the test
(:783-789), and the fix itself is at
gcc/tree-sra.cc:2898-2901.
Bugzilla records two more backports. releases/gcc-14 got a cherry-pick of the
same master commit on 2025-08-20 (r14-11970), and releases/gcc-13 got the
fix on 2025-09-17 (r13-9891).
Branch policy: stages on master, regressions on releases/gcc-N
Why could this fix go to three release branches? develop.html (modified
2026-09-11) sets the rules, in stages on master:
- Stage 1 lasts at least four months. Any change can go in, and large work merges from development branches.
- Stage 3 lasts about two months. Only bug fixes, and new ports that change nothing else, can go in. Stage 2 was abandoned with GCC 4.4.
- Stage 4 takes regression fixes, and "other important bugs like wrong-code, rejects-valid or build issues". It lasts until the next Stage 1. The page adds: "Note that the same constraints apply to release branches."
The release branch is cut when master has no P1 regressions. After that, a
bug-fix release takes fixes for regressions and serious bugs. A backport should
not make the compiler reject code that it accepted before, unless accepting it
gave incorrect object code or code with undefined behaviour.
PR 117423 qualifies twice. It is a regression since r10-6321, and it is
wrong code. master was in GCC 16 Stage 1, which started on 2025-04-17, so
the fix needed only review. The backport went to releases/gcc-15 16 days
before 15.2 was released on 2025-08-08. Both dates are from develop.html.
Two smaller rules complete the picture. gitwrite.html lets anyone with
commit access commit an obvious fix without approval and copy it to
gcc-patches. Its test is: "will the person who objects to my work the most be
able to find a fault with my fix?" Such a mail uses the [COMMITTED]
classifier. develop.html lets two people with write access to the area revert
a patch that breaks an important target. They must first report the problem to
the author and wait 48 hours for a promise of a fix. You can always revert your
own patch without approval.
Three things to carry away
MAINTAINERS says who, and the web pages say how. Nothing enforces the
approval rules.
The gcc-patches mail is the commit. The subject becomes the first line,
and the body above --- becomes the message, ChangeLog entries included.
A backport is git cherry-pick -x of a master commit. Its
(cherry picked from commit line becomes Backported from master: in the
branch's ChangeLog.
Things that surprise people
An LGTM approves nothing unless it comes from someone MAINTAINERS lists
for that area. gitwrite.html asks for approval by "the appropriate
maintainers".
The 75-character subject limit is advice. The traced subject has 78 characters, and the checker does not measure subjects.
Backported from master: is a fixed string. git_commit.py writes it for
every cherry-pick (:838), whatever branch the original
commit is on.
Two scripts in contrib/ still drive Subversion. prepare_patch.sh and
patch_tester.sh call svn (prepare_patch.sh:57,
patch_tester.sh:164). GCC's own aliases treat SVN as history: the
svn-rev alias finds a commit by its From-SVN: line
(gcc-git-customization.sh:20-21).
Documentation coverage
The Contributing node is the only manual text on the process
(gcc/doc/contribute.texi:5). The GCC manual includes it at
gcc/doc/gcc.texi:187, and the internals manual includes it as its own
Contributing node at gcc/doc/gccint.texi:140. It links
contribute.html and contributewhy.html, and states no rule. The install
manual documents make check in its Testing node
(gcc/doc/install.texi:3393), but not the testing that a submission needs.
What no manual documents:
- The sections of
MAINTAINERS, the approval levels and the DCO list. The file documents itself in part, andgitwrite.htmlnames the levels. - The FSF and DCO routes, the contents of a submission, the subject-line format
and the testing levels.
contribute.htmlanddco.htmldocument them. - The stage policy and the backport rules.
develop.htmldocuments them. - The
git gcc-*aliases.gitwrite.htmldescribes them. - That a PR number in the subject must also be in the ChangeLog part
(
git_commit.py:391-393). None of the four pages says so.
Where the pages and the pin disagree, as of 2026-10-26:
contribute.htmlandgitwrite.htmldescribeMAINTAINERS.ymlandcontrib/gen-MAINTAINERS.py. At the pin, and in 16.1 and 16.2, you editMAINTAINERSby hand and check it withcontrib/check-MAINTAINERS.py.gitwrite.htmlsays thatgit gcc-backportrevertsChangeLogchanges. The script did that in GCC 11. At 15.2 it does not.contribute.htmllists[PATCH v2],[RFC]and[COMMITTED]as classifiers.contrib/gcc-changelog/git_email.pyremoves only[PATCH]and[PATCH n/m].
All source references in this chapter are to GCC 15.2.0
(releases/gcc-15.2.0). Line numbers in other releases will differ; the
surrounding code rarely does. Where behaviour itself changed across a major
version, it is flagged inline.