Section 12.17

GCC and Clang

Full name: GNU Compiler Collection (GCC), where GNU stands for GNU’s Not Unix; Clang is a name, not an abbreviation.

Definition

GCC and Clang are the two major open-source compilers for C and C++: programs that translate source code into machine instructions. GCC, the GNU Compiler Collection, belongs to the GNU free-software project and was first released in 1987. Clang, begun at Apple and published as open source in 2007, is the C-family front end of the LLVM §12.18 compiler project (LLVM began as Low Level Virtual Machine). Both accept largely the same command-line options. Being independent implementations, they usually produce different machine code from the same source file and options.

The idea

A team compiles one C file with both compilers, at the same optimization level -O2 and for the same processor. The two programs give the same results, yet the instructions differ, the code sizes differ, and a function that exists on its own in one program has been merged into its caller in the other. None of this is a bug. The C standard describes what a program does on an abstract machine, an idealized computer, and requires a compiler to reproduce only the program’s observable behavior [78]: its input and output, the data it writes to files, and its accesses to objects marked volatile, which may change outside the program’s control. Which instructions, registers, loops and function calls produce that behavior is the compiler’s choice. This freedom is called the as-if rule.

Two independent compilers use that freedom differently. Each has its own internal forms of the program, its own sequence of optimization passes, and its own estimates of what is cheap on each processor. Two translators of one contract are a fair picture: the obligations must come out the same, the sentences will not. The picture fails where the contract is vague: where the C standard leaves a choice open, or says nothing at all, the two translations can differ in substance.

How it works

GCC works in stages. The driver program gcc runs the compiler proper, cc1. It parses C into a tree form called GENERIC, lowers that into GIMPLE, a simplified form with at most three operands per statement, and runs most optimizations on GIMPLE in static single assignment §3.38 (SSA) form, in which every value is assigned exactly once. It then lowers the program into RTL (Register Transfer Language), a form close to machine instructions, in which registers are allocated, and writes assembly text. The GNU assembler as encodes that text into an object file. One GCC installation produces code for one processor family: a cross-compiler §12.1 such as arm-none-eabi-gcc is a separate build of GCC.

Clang parses C into an abstract syntax tree (AST), a tree that mirrors the structure of the source, and translates the tree into LLVM’s intermediate representation §3.37 (IR), the form in which LLVM holds a program between source and machine code. LLVM’s optimizer transforms the IR through a list of passes, LLVM’s code generator selects instructions and allocates registers, and LLVM’s built-in assembler writes the object file directly. One Clang program can produce code for every processor family that its LLVM was built with; the option --target chooses, for example --target=thumbv7em-none-eabi for an Arm Cortex-M4 §6.3.

The differences in output come from these sources.

The two compilers are built to work together. Both follow the platform’s ABI §12.47 (application binary interface), the rules for passing arguments, laying out structures and naming symbols, so object files from GCC and Clang can be linked into one program as long as options that change the ABI, such as the floating-point calling convention, match. Clang accepts most GCC options and language extensions. It defines the predefined macro __GNUC__, with the value 4, so that code written for GCC compiles; code that must know which compiler it is under tests __clang__ first.

Worked example

The function unsigned sum(unsigned n) { unsigned s = 0; for (unsigned i = 0; i < n; i++) s += i; return s; } adds 0+1+…+(n−1)0 + 1 + \dots + (n - 1). It was compiled for an Arm Cortex-M4 with GCC 13.2.1 (arm-none-eabi-gcc -O2 -mcpu=cortex-m4 -mthumb) and with Clang 18.1.8 (clang -O2 --target=thumbv7em-none-eabi -mcpu=cortex-m4). On this processor the argument nn arrives in register r0, and the result is returned in r0. Write ss for the running total and ii for the counter.

GCC keeps the loop: 10 instructions, all 2 bytes long, so 10×2=2010 \times 2 = 20 bytes.

sum: mov r2, r0 copy nn into r2
cbz r0, .L4 if n=0n = 0, go to .L4
movs r3, #0 i←0i \leftarrow 0, kept in r3
mov r0, r3 s←0s \leftarrow 0, kept in r0
.L3: add r0, r0, r3 s←s+is \leftarrow s + i
adds r3, r3, #1 i←i+1i \leftarrow i + 1
cmp r2, r3 compare nn with ii
bne .L3 if i≠ni \ne n, repeat from .L3
bx lr return ss
.L4: bx lr return 0, already in r0

Clang removes the loop and evaluates the formula (n−1)(n−2)/2+(n−1)(n-1)(n-2)/2 + (n-1), which equals (n−1)((n−2)/2+1)=n(n−1)/2(n-1)\bigl((n-2)/2 + 1\bigr) = n(n-1)/2: 12 instructions, 8 of them 2 bytes long and 4 of them 4 bytes long, so 8×2+4×4=328 \times 2 + 4 \times 4 = 32 bytes. The instruction itt opens an If-Then (IT) block, which makes the following instructions conditional.

sum: cmp r0, #0 compare nn with 0
itt eq the next two run only if n=0n = 0
moveq r0, #0 result 0
bxeq lr return
subs r1, r0, #1 r1 ←n−1\leftarrow n - 1
subs r0, #2 r0 ←n−2\leftarrow n - 2
umull r0, r2, r1, r0 64-bit product (n−1)(n−2)(n-1)(n-2):
low half in r0, high half in r2
and r2, r2, #1 keep bit 32 of the product
lsrs.w r2, r2, #1 move that bit into the carry flag §4.42
rrx r0, r0 shift r0 right by one, carry
entering at bit 31
add r0, r1 add n−1n - 1
bx lr return

Check with n=4n = 4. GCC’s loop adds 0,1,2,30, 1, 2, 3 and returns 66. It runs 4 set-up instructions, 4×4=164 \times 4 = 16 loop instructions and 1 return, 4+16+1=214 + 16 + 1 = 21 instructions in all. Clang computes (3×2)/2+3=3+3=6(3 \times 2)/2 + 3 = 3 + 3 = 6 with 12 instructions. For n=100,000n = 100{,}000 GCC runs 4+4×100,000+1=400,0054 + 4 \times 100{,}000 + 1 = 400{,}005 instructions, and Clang still 12. The exact sum is 100,000×99,999/2=4,999,950,000100{,}000 \times 99{,}999 / 2 = 4{,}999{,}950{,}000, larger than the largest 32-bit value 232−1=4,294,967,2952^{32} - 1 = 4{,}294{,}967{,}295. C’s unsigned arithmetic wraps around modulo 2322^{32}, so the function must return 4,999,950,000−4,294,967,296=704,982,7044{,}999{,}950{,}000 - 4{,}294{,}967{,}296 = 704{,}982{,}704. Both programs do. Clang’s formula gets this right because umull forms the full 64-bit product before the halving.

Both translations are correct. The C standard requires only the returned value. The loop, the instruction count, the size (20 bytes against 32) and the running time are not part of the program’s observable behavior.

Stated precisely

The C standard (ISO/IEC 9899, clause 5.1.2.3, Program execution) states the least requirements on a conforming implementation: accesses to volatile objects follow the rules of the abstract machine exactly; at program termination, the data written to files equal what the abstract machine would have written; and input and output on interactive devices take place as the standard describes. Everything else, including the instructions, their number and order, the code size and the running time, is left to the compiler.

Let PP be a program, xx an input, and Obs(P,x)\mathrm{Obs}(P, x) the set of observable behaviors that the standard allows for PP on xx. The set has one member when the behavior of PP on xx is fully specified. It has several members when PP has unspecified behavior, where the standard allows several outcomes and does not require the choice to be documented. It is unrestricted when PP has undefined behavior on xx. A compiler TT translates PP correctly when, for every input xx, the observable behavior of the compiled program T(P)T(P) on xx lies in Obs(P,x)\mathrm{Obs}(P, x). Two correct compilers GG and KK may therefore produce different machine code, G(P)≠K(P)G(P) \ne K(P), for any program, but different observable behavior only on inputs where Obs(P,x)\mathrm{Obs}(P, x) has more than one member.

Implementation-defined behavior §4.13, such as the width of int, is a choice that each implementation must document. On one platform both compilers follow the same ABI, and the ABI fixes most of these choices, so GCC and Clang agree on them there.

Limits and common mistakes

The same option is not the same optimization. -O2 in GCC and -O2 in Clang run different passes, and two versions of one compiler differ too.

Compare behavior, not bytes. Code size, timing, stack use, which functions exist as separate symbols, and the order of accesses to non-volatile memory are all outside the standard. Anything that relies on them, such as a probe placed at a function’s entry, a worst-case timing bound, a stack-size limit or a constant-time cryptographic implementation §5.36 (code whose running time must not depend on secret data), must be checked in each compiler’s output.

Unspecified behavior differs in practice. C leaves the order in which a function’s arguments are evaluated unspecified. In printf("%d %d\n", f(), g()), where f prints the letter f and returns 1 and g prints the letter g and returns 2, GCC 13.3 on 64-bit x86 Linux calls g first and Clang 18.1.8 calls f first. Both programs then print 1 2, but the lines printed by f and g appear in opposite orders. Both compilers conform.

A program with undefined behavior, such as signed integer overflow §4.15, may behave differently under each compiler and each option, and agreement between the two compilers does not show that the program is free of it. Differential testing §10.6, which runs both builds on the same inputs and compares the results, finds many such programs, and the sanitizers §10.21 of both compilers, checks compiled into the program, detect many cases while it runs.

Compilers have bugs. Yang, Chen, Eide and Regehr, at the 2011 conference on Programming Language Design and Implementation (PLDI), generated random valid C programs with their tool Csmith, compiled each with several compilers and compared the results. They reported more than 325 previously unknown bugs, in GCC, LLVM and other compilers, and every compiler they tested both crashed and silently produced wrong code on some valid inputs.

Questions answered

Why can both compile valid source into structurally different machine code?

Both can, because the C standard fixes only a program’s observable behavior, meaning its input and output, the data it writes to files and its accesses to volatile objects, and not the instructions that produce it, and GCC and Clang are independent compilers that choose different instructions within that freedom. Each has its own internal forms of the program, its own list of optimization passes, its own cost estimates for inlining, loop transformations and instruction choice, its own register allocator, and its own meaning for options such as -O2. Both results are correct if every observable behavior is one that the standard allows.

For example, for a C loop that sums 00 to n−1n - 1, GCC 13.2 keeps a four-instruction loop for an Arm Cortex-M4, while Clang 18.1.8 replaces the loop by the formula n(n−1)/2n(n-1)/2; both return 6 for n=4n = 4. Where the source leaves choices open (unspecified behavior) or breaks a language rule (undefined behavior), even the observable behavior may differ. Compare the two programs by their observable behavior, and check separately every property outside the standard that something relies on, such as code size, timing, stack use or the presence of a function.

Related entries: Compiler flag (§12.3), Link-time optimization (LTO) (§12.10), Differential testing (§10.6), Undefined behavior (UB) (§4.12), Compiler optimization (§3.39), Compiler correctness (§3.40), Unspecified behavior (§4.14), LLVM (§12.18), Native application binary interface (ABI) (§12.47). Further reading: [78, 231].