Section 12.10

Link-time optimization (LTO)

Definition

Link-time optimization (LTO) is a build method in which the compiler optimizes all of a program’s source files together, when they are linked, instead of one file at a time. Without LTO, each file becomes machine code on its own, and the optimizer cannot see function bodies in other files. With LTO, the compiler’s output for each file holds its intermediate representation §3.37 (IR), the compiler’s internal form of the program. At link time the compiler reads the IR of all files, optimizes across them, and only then generates machine code.

The idea

A compiler normally works on one translation unit at a time: one source file with the header files it includes. Suppose config.c contains int log_level(void) { return 0; } and main.c contains if (log_level() > 2) log_msg("step");. Compiling main.c, the compiler sees only a declaration of log_level, a promise that such a function exists somewhere. It must emit a real call and a real test, and the linker §12.4, the tool that joins compiled files into one program, must include log_msg because a call to it exists. The program carries code that can never run.

LTO postpones the decisions that need the whole program until the whole program is visible. At link time the compiler sees that log_level returns 0, so the test 0>20 > 2 is false, so the call to log_msg can go, and if nothing else calls log_msg, the function can go too. Two transformations that a compiler already performs inside one file now cross file boundaries: inlining, which copies a function’s body into its caller in place of the call, and constant propagation, which replaces values known at compile time with those constants. The price is that the functions and calls written in the source are no longer a reliable list of the functions and calls in the program.

How it works

With the option -flto, the compilers GCC §12.17 (GNU Compiler Collection; GNU stands for GNU’s Not Unix) and Clang still write one object file, the compiler’s output file, for each source file, but that file holds IR: GCC writes it into sections whose names begin with .gnu.lto_, and Clang writes LLVM §12.18 bitcode, the file form of the IR of LLVM (a name that began as Low Level Virtual Machine and is now used as a plain name), the compiler framework that Clang is built on. The linker reaches the compiler through a linker plugin, a module supplied with the compiler that the linker loads; LLVM’s own linker, lld, has this built in. The build then runs these steps.

  1. Each source file is parsed and lightly optimized, and its IR is written to its object file. By default, GCC’s LTO object files hold IR only, with no machine code.

  2. The linker reads all inputs in the usual order, learns through the plugin which symbols (named functions and variables) each IR file defines and uses, and decides which definition every name refers to.

  3. The linker tells the compiler, for every symbol, whether anything outside the IR refers to it: an object file compiled without LTO, a library, assembly code, the linker script §12.5 or the program’s exported interface. A symbol that nothing outside refers to can be treated as private to the program.

  4. The compiler merges the IR and optimizes across function boundaries: it inlines across files, propagates constants into called functions, removes functions with no remaining caller, and merges functions whose code is identical.

  5. The compiler generates machine code, often in several parts in parallel, and returns object files to the linker, which assigns addresses and writes the program.

To keep large builds fast, LLVM also offers ThinLTO, its scalable mode, in which each file keeps its own IR and imports from other files only the functions selected for inlining.

Afterwards, each function of the source is in one of these states.

A standalone copy survives when something the compiler cannot see may call the function: its address is stored where unknown code can use it, it is exported, it is referenced from assembly or from the linker script, or an attribute protects it. In GCC, __attribute__((noinline)) prevents inlining only, __attribute__((noipa)) also prevents copies and other cross-function changes, and __attribute__((used)) forces the compiler to emit the function even when nothing seems to call it.

Worked example

File scale.c contains int scale(int x, int k) { return x * k; }. File main.c calls scale(v, 4) once in each pass of a loop that runs 1000 times, where v is a sensor reading. Nothing else calls scale.

Without LTO, the program contains a function scale with a multiply instruction, and the loop calls it 1000 times. A tool that counts calls with a probe at the entry address of scale, a hook that runs each time execution reaches that address, counts 1000.

With LTO, the compiler sees the body of scale while compiling the loop and inlines the call, so the loop computes v * 4 itself. It then replaces the multiplication by a left shift of 2 bits, a cheaper instruction, because shifting a binary number left by 2 bits multiplies it by 22=42^2 = 4. For v=5v = 5: 5 is 101 in binary; shifted left by 2 bits it is 10100, which is 16+4=20=5×416 + 4 = 20 = 5 \times 4. The function scale now has no caller and is removed. The program’s symbol table §12.8 has no entry scale, and the probe has no address to attach to. Had scale been marked __attribute__((used)), a copy would remain and the probe could attach, but it would count 0, because the loop no longer calls the copy. The source computes scale(v, 4) 1000 times in both builds; only the shape of the machine code differs.

Stated precisely

LTO carries the guarantee of any compiler optimization §3.39: for every input on which the program has no undefined behavior §4.12, the program built with LTO has the observable behavior that the source describes. In C, observable behavior is the sequence of accesses to volatile objects (objects marked as changeable from outside the program), the data written to files, and the input and output of interactive devices. The guarantee rests on three assumptions.

  1. Consistent declarations: every file declares each shared function and variable with the same type. LTO can expose a mismatch that separate compilation hid; GCC warns about some with -Wlto-type-mismatch.

  2. Visible outside references: every use from outside the IR is visible to the linker or declared. A function that is called only from assembly text inside a C string, found by name at run time, or called by code outside the program, such as a bootloader §6.30, must be marked, for example with __attribute__((used)), or exported.

  3. No undefined behavior: code whose behavior the language leaves undefined may behave differently once more of the program is visible to the optimizer.

Nothing is promised about the shape of the result: which functions exist as symbols, their addresses and sizes, the number of calls, the stack space each function uses, or the order of code in memory.

Limits and common mistakes

LTO optimizes only what is in IR form. A precompiled library, such as the C library of most toolchains §12.2, and assembly files stay opaque to it unless they too were built with LTO.

Object files inspected before the link describe neither the final code nor its size. Inspect the linked program: its symbol table, a disassembly, or the map file in which the linker reports what it placed where. Stack use, code size and timing measured per function before inlining do not describe the inlined program, and a probe on a function’s entry address misses its inlined calls.

The final link does the work that the per-file compile steps did before, so it is slower and needs more memory. The GCC manual recommends compiling all files of one link with the same options and repeating those options at link time.

A check that one build profile §6.44 (a named set of build settings) keeps a given function separate says nothing about another build profile, with different options or another compiler version.

Questions answered

Which function boundaries disappear after inlining or constant propagation?

A function’s boundary, meaning its own entry point and code and the call instruction that reaches it, disappears at every call that the compiler inlines, and the whole function disappears when, after inlining and constant propagation, nothing refers to it any more. Inlining copies the function’s body into the caller in place of the call. Constant propagation replaces values known at compile time with constants, which can make a test always false and so delete a call entirely. With link-time optimization (LTO), in which the compiler optimizes all source files together when they are linked, both happen across source files.

Besides being kept or removed, a function can be inlined at some calls and kept for others, replaced by a specialized copy for a constant argument, split into pieces, or merged with an identical function. A standalone copy survives when something outside the compiler’s view may call it: its address escapes to unknown code, it is exported, it is referenced from assembly or the linker script, or an attribute protects it. The only reliable answer for one build is the linked program itself, read through its symbol table and disassembly, not the source.

Related entries: Compiler flag (§12.3), Symbol table (§12.8), Dead-code elimination (§12.11), Static versus dynamic instrumentation (§14.25), Compiler optimization (§3.39), Intermediate representation (IR) (§3.37), Linker (§12.4). Further reading: [186].