Section 3.39

Compiler optimization

Definition

A compiler optimization is a transformation a compiler applies to make the generated code faster, smaller or otherwise cheaper while keeping the program’s observable behavior: the part of its behavior that the language standard requires every implementation to preserve. In C, observable behavior consists of accesses to volatile objects (objects marked as changeable from outside the program), the data written to files, and input and output on interactive devices. Everything else may change, including how many memory reads happen and in which order. This freedom is called the as-if rule.

The idea

A developer wants to check that the memory at address p can be read, so the developer adds the line int t = *p; and never uses t. In the optimized program the read is gone: the machine code contains no load from p. Read line by line, the source promised a read. The compiler read the source differently, and correctly: as a description of the results the program must produce, not as a list of steps the machine must take.

The language standard defines an abstract machine, an idealized computer that executes the source exactly as written. A real compiler must only produce code whose observable behavior is one that the abstract machine could have produced. A step that leaves no trace in the observable behavior is optional, and the optimizer removes it whenever removal makes the code cheaper.

A moving company works the same way: the customer checks only what arrives at the new house, so the movers choose the route and the order of loading. The analogy stops in two places. What counts as arriving is defined exactly by the standard, not by anyone’s wishes. And the compiler may assume that the program never performs an operation the standard leaves undefined, such as signed integer overflow §4.15; a mover has no such license.

How it works

An optimizing compiler translates the source into an intermediate representation §3.37 (IR), applies a sequence of passes to the IR, and then generates machine code. Each pass is a transformation that its authors justify for every execution that has no undefined behavior §4.12. Common passes are these.

Each pass relies on facts it can establish about the program, through data-flow analysis §3.15 and alias analysis §3.18, and on assumptions the language grants: that signed integer overflow never occurs, that every pointer that is read through points to a live object, and other consequences of the rule that no execution has undefined behavior.

Code that needs a particular access to happen must say so in a way the compiler respects.

Worked example

An unused read. Consider the function

int probe(int *p) { int t = *p; return 0; }

The read of *p produces a value that nothing uses. Reading an ordinary object is not observable behavior, so dead-code elimination removes the read. At their usual optimization level -O2, GCC and Clang compile probe for a 32-bit Arm processor to two instructions: one that places 0 in the return register and one that returns. If p is invalid, for example a null pointer §4.26, the read would be undefined behavior, so the compiler owes no fault either: the optimized probe returns 0 for every pointer, valid or not.

Changing the read to int t = *(volatile int *)p; makes it a volatile access. The optimized code now contains one load from p, and the function still returns 0. The value read is still discarded; only the access itself is guaranteed.

An optimization that relies on undefined behavior. Consider int scale(int x) { return (x * 4) / 4; } with a 32-bit int, whose largest value is 2,147,483,647. For x = 5 the abstract machine computes 5×4=205 \times 4 = 20 and 20/4=520 / 4 = 5. For every x at which x×4x \times 4 does not overflow, the result is x itself, so a compiler may compile scale to return x directly. For x = 1,000,000,000 the product 4,000,000,000 exceeds the largest int: a signed integer overflow, which is undefined. The optimized code returns 1,000,000,000. A reader who imagines 32-bit wrapping arithmetic expects 4,000,000,000−4,294,967,296=−294,967,2964{,}000{,}000{,}000 - 4{,}294{,}967{,}296 = -294{,}967{,}296, which divided by 4 gives −73,741,824-73{,}741{,}824. The standard requires neither result for this input, so the optimized code is correct.

With unsigned int the same function has a defined result for every input, because unsigned arithmetic wraps modulo 232=4,294,967,2962^{32} = 4{,}294{,}967{,}296. For x = 2,000,000,000, the product 2,000,000,000×4=8,000,000,0002{,}000{,}000{,}000 \times 4 = 8{,}000{,}000{,}000 wraps to 8,000,000,000−4,294,967,296=3,705,032,7048{,}000{,}000{,}000 - 4{,}294{,}967{,}296 = 3{,}705{,}032{,}704, and dividing by 4 gives 926,258,176. The compiler must keep that result, so it may not return x. It may instead keep only the low 30 bits of x: 2,000,000,000−230=2,000,000,000−1,073,741,824=926,258,1762{,}000{,}000{,}000 - 2^{30} = 2{,}000{,}000{,}000 - 1{,}073{,}741{,}824 = 926{,}258{,}176, the same value.

Stated precisely

For a program SS and an input II, let Obs(S,I)\mathrm{Obs}(S, I) be the set of observable behaviors that the language’s abstract machine allows for SS on II. One observable behavior consists of the volatile accesses in order, the interactive input and output in order, and the data in files when the program ends, together with whether the program ends. Obs(S,I)\mathrm{Obs}(S, I) is a set because the standard leaves some choices open, such as the order in which the arguments of a call are evaluated. An optimization that turns SS into S′S' is correct when, for every input II on which no execution of SS has undefined behavior, Obs(S′,I)⊆Obs(S,I).\mathrm{Obs}(S', I) \subseteq \mathrm{Obs}(S, I). For an input on which SS has undefined behavior, nothing is required.

Section 5.1.2.3 of C11 states the permission behind this rule: an implementation need not evaluate part of an expression if it can deduce that the value is not used and that no needed side effects are produced, including any caused by calling a function or by accessing a volatile object. Not part of Obs\mathrm{Obs}, and therefore free to change, are the number, width and order of ordinary memory accesses, intermediate values, execution time §9.32, code size and the addresses of instructions. A claim about any of these needs a separate mechanism, such as a volatile access, or an inspection of the produced code.

Limits and common mistakes

Optimization does not preserve timing. Code written to run in constant time, so that its duration reveals nothing about secret data, can acquire secret-dependent branches after optimization, because time is not observable behavior. A constant-time implementation §5.36 must be checked in the machine code.

Clearing a secret can be deleted. A call that overwrites a key buffer with zeros just before the buffer goes out of use writes values that nothing reads, so the compiler may remove the call as a dead store. Secret zeroization §5.37 needs a function made for the purpose, such as memset_s from the optional Annex K of C11, or explicit_bzero, which several C libraries provide.

A benchmark can end up measuring nothing. If the result of the measured computation is never used, the optimizer may delete the computation, and the benchmark reports an impossibly short time. A benchmark harness §14.36 must consume every result.

Volatile is neither an atomic operation nor a memory barrier. The volatile qualifier keeps the compiler from removing or reordering the volatile accesses themselves, and nothing more.

One build proves nothing about another. Without optimization (-O0), compilers typically perform every read as written; at -O2 the same source loses the read. A different compiler version, target or set of compiler flags §12.3 can change the result again.

A surprising result is usually not a compiler bug. Before blaming the optimizer, check the source for undefined behavior, for example with UndefinedBehaviorSanitizer §10.23, a compiler option that adds run-time checks for many kinds of undefined behavior. The guarantee that an optimizer keeps the observable behavior is the subject of the Compiler correctness §3.40 entry.

Questions answered

Can an apparently unused instrumentation §14.24 read be optimized away?

Yes. An ordinary memory read whose value is never used can be removed, because the read is not part of the program’s observable behavior. The C standard lets a compiler skip any part of an expression whose value is not used and that produces no needed side effect (section 5.1.2.3 of C11, the 2011 C standard; the freedom is known as the as-if rule), and dead-code elimination removes such reads at the usual optimization levels. Assigning the value to a local variable that is never used changes nothing. If the address is invalid, the read is undefined behavior, so the compiler need not preserve a fault either.

To keep the read, make it a volatile access, for example by reading through a pointer to a volatile-qualified type: the compiler must then perform the read exactly as written. A volatile access is not an atomic operation, does not order the surrounding ordinary accesses and emits no hardware barrier. Passing the value to a function in another file keeps the read only until link-time optimization sees that function. In every case, confirm that the load is present by disassembling the produced machine code.

Related entries: Memory barrier (§4.37), Intermediate representation (IR) (§3.37), Compiler correctness (§3.40), Volatile qualifier (§4.34), Dead-code elimination (§12.11), Secret zeroization (§5.37), Link-time optimization (LTO) (§12.10). Further reading: [78].