87

GCC, MSVC, LLVM, and probably other toolchains have support for link-time (whole program) optimization to allow optimization of calls among compilation units.

Is there a reason not to enable this option when compiling production software?

14
  • 4
    See Why not always use compiler optimization?. The answers there are equally applicable here.
    – Mankarse
    May 19, 2014 at 11:43
  • 2
    @Mankarse He asks "when compiling production software" so most of the answers there doesn't apply.
    – Ali
    May 19, 2014 at 11:52
  • 1
    @user2485710: Do you have documentation for incompatibility with ld? What I read in the current gcc docs (gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html) and in a somewhat old wiki (gcc.gnu.org/wiki/LinkTimeOptimization) either says nothing about ld incompatibilities (gcc docs) or explicitly states compatibility (wiki). Judging from the mode of lto operation, namely having additional information in the object files, my guess would be that the object files maintain compatibility. May 19, 2014 at 12:05
  • 1
    Enabling -O2 makes a difference of ca. +5 seconds on a 10 minute build here. Enabling LTO makes a difference of ca +3 minutes, and sometimes ld runs out of address space. This is a good reason to always compile with -O2 (so the executables that you debug are binary-identical with the ones you'll ship!) and not to use LTO until it is mature enough (which includes acceptable speed). Your mileage may vary.
    – Damon
    May 19, 2014 at 13:23
  • 1
    @Damon: The release build is not the build I've been debugging, but the build which survived testing. Test gets a separate build anyhow, installed on a clean machine (so I know the install package isn't missing any dependencies).
    – MSalters
    May 19, 2014 at 14:41

8 Answers 8

64

I assume that by "production software" you mean software that you ship to the customers / goes into production. The answers at Why not always use compiler optimization? (kindly pointed out by Mankarse) mostly apply to situations in which you want to debug your code (so the software is still in the development phase -- not in production).

6 years have passed since I wrote this answer, and an update is necessary. Back in 2014, the issues were:

  • Link time optimization occasionally introduced subtle bugs, see for example Link-time optimization for the kernel. I assume this is less of an issue as of 2020. Safeguard against these kinds of compiler and linker bugs: Have appropriate tests to check the correctness of your software that you are about to ship.
  • Increased compile time. There are claims that the situation has significantly improved since 2014, for example thanks to slim objects.
  • Large memory usage. This post claims that the situation has drastically improved in recent years, thanks to partitioning.

As of 2020, I would try to use LTO by default on any of my projects.

14
  • 2
    I agree with such answer. I also have no clue why not to use LTO by default. Thanks for confirmation.
    – Honza
    May 19, 2014 at 12:24
  • 3
    @Honza: Probably because it tends to use massive amounts of resources. Try compiling Chromium, Firefox, or LibreOffice with LTO... (FYI: At least one of them is not even compilable on 32-bit machines with GNU ld, even without LTO, simply because the working set does not fit in virtual address space!) May 19, 2014 at 12:47
  • 16
    May introduce? Unless the compiler is broken, it won't. May uncover? Sure. As can any other optimization of broken code. Oct 14, 2018 at 17:42
  • 1
    Developers are impatient and LTO is slow. That's why
    – Bogi
    May 24, 2020 at 11:21
  • 2
    @Deduplicator You do realize that the answer was written in 2014, right? At the time, the implementation of LTO was still somewhat buggy; see also the article I linked to.
    – Ali
    May 24, 2020 at 11:37
13

This recent question raises another possible (but rather specific) case in which LTO may have undesirable effects: if the code in question is instrumented for timing, and separate compilation units have been used to try to preserve the relative ordering of the instrumented and instrumenting statements, then LTO has a good chance of destroying the necessary ordering.

I did say it was specific.

8

If you have well written code, it should only be advantageous. You may hit a compiler/linker bug, but this goes for all types of optimisation, this is rare.

Biggest downside is it drastically increases link time.

10
  • Why does it increase compile time? Isn't it the case that the compiler stops compilation at a certain point (it generates some internal representation of the code, and puts this into the object file instead of the fully compiled code), so it should be faster instead?
    – geza
    Nov 8, 2018 at 13:46
  • 1
    Because the compiler must now create the GIMPLE bytecode as well as the object file so the linker has enough information to optimise. Creating this GIMPLE bytecode has overhead.
    – ericcurtin
    Nov 8, 2018 at 15:16
  • As far as I know, when using LTO, the compiler generates only the bytecode, i.e., no processor specific assembly is emitted. So it should be faster.
    – geza
    Nov 8, 2018 at 17:12
  • The GIMPLE is part of the object file alright gcc.gnu.org/onlinedocs/gccint/LTO-Overview.html
    – ericcurtin
    Nov 8, 2018 at 17:50
  • It has additional compile time overhead on any codebase if you time it
    – ericcurtin
    Nov 8, 2018 at 17:50
2

Apart from to this,

Consider a typical example from embedded system,

void function1(void) { /*Do something*/} //located at address 0x1000 
void function2(void) { /*Do something*/} //located at address 0x1100
void function3(void) { /*Do something*/} //located at address 0x1200

With predefined addressed functions can be called through relative addresses like below,

 (*0x1000)(); //expected to call function2
 (*0x1100)(); //expected to call function2
 (*0x1200)(); //expected to call function3

LTO can lead to unexpected behavior.

updated:

In automotive embedded SW development,Multiple parts of SW are compiled and flashed on to a separate sections. Boot-loader, Application/s, Application-Configurations are independently flash-able units. Boot-loader has special capabilities to update Application and Application-configuration. At every power-on cycle boot-loader ensures the SW application and application-configuration's compatibility and consistence via Hard-coded location for SW-Versions and CRC and many more parameters. Linker-definition files are used to hard-code the variable location and some function location.

3
  • This is an interesting comment because LTO could potentially cause the linker to inline small and rarely used functions. I tested a slightly different example with GCC 9.2.1 and Clang 8.0.0 on Fedora and it worked fine. The only difference was that I used an array of function pointers: ``` typedef int FUNC(); FUNC *ptr[3] = {func1, func2, func3}; return (*ptr)() + (*(ptr+1))() + (*(ptr+2))(); ``` Oct 29, 2019 at 9:26
  • You used a linker script to make sure those symbols end up at those addresses? And you call from elsewhere using hard-coded absolute addresses, instead of symbols? That seems inefficient for most ISAs. Or are you talking about function pointers? May 15, 2022 at 13:02
  • @PeterCordes: Yes, functions and certain constant variables such as sw versions, CRC are placed at a fixed location. Bootloader will ensure the compatibility of the sw before jumping to appropriate section. Linker definition files are used to place the symbols at fixed location. May 16, 2022 at 6:17
0

Given that the code is implemented correctly, then link time optimization should not have any impact on the functionality. However, there are scenarios where not 100% correct code will typically just work without link time optimization, but with link time optimization the incorrect code will stop working. There are similar situations when switching to higher optimization levels, like, from -O2 to -O3 with gcc.

That is, depending on your specific context (like, age of the code base, size of the code base, depth of tests, are you starting your project or are you close to final release, ...) you would have to judge the risk of such a change.

One scenario where link-time-optimization can lead to unexpected behavior for wrong code is the following:

Imagine you have two source files read.c and client.c which you compile into separate object files. In the file read.c there is a function read that does nothing else than reading from a specific memory address. The content at this address, however, should be marked as volatile, but unfortunately that was forgotten. From client.c the function read is called several times from the same function. Since read only performs one single read from the address and there is no optimization beyond the boundaries of the read function, read will always when called access the respective memory location. Consequently, every time when read is called from client.c, the code in client.c gets a freshly read value from the address, just as if volatile had been used.

Now, with link-time-optimization, the tiny function read from read.c is likely to be inlined whereever it is called from client.c. Due to the missing volatile, the compiler will now realize that the code reads several times from the same address, and may therefore optimize away the memory accesses. Consequently, the code starts to behave differently.

1
  • Another more relevant issue is code which is non-portable but correct when processed by implementations that, as a form of "conforming language extension", specify their behavior in more situations than mandated by the Standard.
    – supercat
    Mar 23, 2021 at 22:01
0

Rather than mandating that all implementations support the semantics necessary to accomplish all tasks, the Standard allows implementations intended to be suitable for various tasks to extend the language by defining semantics in corner cases beyond those mandated by the C Standard, in ways that would be useful for those tasks.

An extremely popular extension of this form is to specify that cross-module function calls will be processed in a fashion consistent with the platform's Application Binary Interface without regard for whether the C Standard would require such treatment.

Thus, if one makes a cross-module call to a function like:

uint32_t read_uint32_bits(void *p)
{
  return *(uint32_t*)p;
}

the generated code would read the bit pattern in a 32-bit chunk of storage at address p, and interpret it as a uint32_t value using the platform's native 32-bit integer format, without regard for how that chunk of storage came to hold that bit pattern. Likewise, if a compiler were given something like:

uint32_t read_uint32_bits(void *p);
uint32_t f1bits, f2bits;
void test(void)
{
  float f;
  f = 1.0f;
  f1bits = read_uint32_bits(&f);
  f = 2.0f;
  f2bits = read_uint32_bits(&f);
}

the compiler would reserve storage for f on the stack, store the bit pattern for 1.0f to that storage, call read_uint32_bits and store the returned value, store the bit pattern for 2.0f to that storage, call read_uint32_bits and store that returned value.

The Standard provides no syntax to indicate that the called function might read the storage whose address it receives using type uint32_t, nor to indicate that the pointer the function was given might have been written using type float, because implementations intended for low-level programming already extended the language to supported such semantics without using special syntax.

Unfortunately, adding in Link Time Optimization will break any code that relies upon that popular extension. Some people may view such code as broken, but if one recognizes the Spirit of C principle "Don't prevent programmers from doing what needs to be done", the Standard's failure to mandate support for a popular extension cannot be viewed as intending to deprecate its usage if the Standard fails to provide any reasonable alternative.

14
  • How is this relevant? Type punning is a C language feature completely unrelated to LTO.
    – user4945014
    Aug 4, 2021 at 19:09
  • @MattF.: In the absence of LTO, abstract and physical machine states will be synchronized whenever execution crosses compilation-unit boundaries. If code stores a value to a 64-bit unsigned long and passes its address as a void* to a function in a different compilation unit that casts it to a 64-bit unsigned long long* and dereferences it, then unless the implementation uses LTO behavior would be defined in terms of the platform ABI without regard for whether the called function accesses storage using the same type as the caller.
    – supercat
    Aug 4, 2021 at 19:17
  • @MattF.: Basically, my point is that the Committees saw no need for the Standard to let programmers demand that compilers do things that programmers might need them to do, but which they'd have no way of avoiding doing, but then compilers were changed so that compilers could avoid such things without regard for whether programmers might need them.
    – supercat
    Aug 4, 2021 at 19:20
  • would be defined in terms of the platform ABI without regard for whether the called function accesses storage using the same type as the caller. That's true regardless of LTO. By definition a pointer cast reinterprets the type regardless of its actual data.
    – user4945014
    Aug 4, 2021 at 21:03
  • @MattF.: If a compiler can see that a function only writes to pointers of type unsigned long long, and never dereferences any pointers of type unsigned long, it may refrain from synchronizing the abstract and physical values of objects of type unsigned long before/after calling the function, thus breaking any code that would rely upon the operations on type unsigned long being processed according to the platform ABI.
    – supercat
    Aug 4, 2021 at 21:14
0

LTO could also reveal edge-case bugs in code-signing algorithms. Consider a code-signing algorithm based on certain expectations about the TEXT portion of some object or module. Now LTO optimizes the TEXT portion away, or inlines stuff into it in a way the code-signing algorithm was not designed to handle. Worst case scenario, it only affects one particular distribution pipeline but not another, due to a subtle difference in which encryption algorithm was used on each pipeline. Good luck figuring out why the app won't launch when distributed from pipeline A but not B.

-1

LTO support is buggy and LTO related issues has lowest priority for compiler developers. For example: mingw-w64-x86_64-gcc-10.2.0-5 works fine with lto, mingw-w64-x86_64-gcc-10.2.0-6 segfauls with bogus address. We have just noticed that windows CI stopped working.

Please refer the following issue as an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.