Skip to content
systemcoding.dev
Toolchains

Emit and Read LLVM IR With clang -emit-llvm -S

Write LLVM IR from C with clang -S -emit-llvm, then read types, basic blocks, loads, stores, phi nodes and calls well enough to check what the compiler did.

7 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the LLVM, GNU and C logos.

LLVM IR is the language between Clang and the machine code. You do not need to write it, but reading it is a useful skill: it shows what the optimizer did to your function in a form that is much easier to follow than assembly, and it is the same for every CPU. This post shows how to produce IR from C, explains the handful of constructs you will see in nearly every function, compares the output at -O0 and -O2, and lists the flags that make it readable. The examples use Clang 18, and the exact attribute numbers and metadata will vary between versions, so read the structure and not the fine print.

Produce IR

Two flags together do the job. -S means "stop after generating assembly-like text", and -emit-llvm changes that output to LLVM IR instead of machine assembly. Without -S, -emit-llvm writes bitcode, the binary form:

Shell
clang -S -emit-llvm file.c -o file.ll     ## textual IR
clang -c -emit-llvm file.c -o file.bc     ## bitcode
llvm-dis file.bc -o file.ll                ## bitcode back to text

Two more flags make the text far easier to read. -fno-discard-value-names keeps your parameter and variable names, where by default Clang numbers every value as %0, %1, and so on. And -g0, the default, avoids debug metadata that would bury the code under !dbg annotations. If you add -g the IR gets many call void @llvm.dbg.declare lines and a block of metadata at the end; useful for debugging, noisy for reading.

A first function

add.cc
int add3(int a, int b, int c)
{
    return a + b + c;
}
Shell
clang -O0 -S -emit-llvm -fno-discard-value-names add.c -o add.ll

The file starts with a module header describing the target, then the function. The header lines look like this, and you can skip them for now:

Text
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
target triple = "x86_64-pc-linux-gnu"

The target triple and datalayout record what the front end assumed about the machine: pointer sizes, alignments and endianness. The function itself, at -O0:

Text
define dso_local i32 @add3(i32 noundef %a, i32 noundef %b, i32 noundef %c) #0 {
entry:
  %a.addr = alloca i32, align 4
  %b.addr = alloca i32, align 4
  %c.addr = alloca i32, align 4
  store i32 %a, ptr %a.addr, align 4
  store i32 %b, ptr %b.addr, align 4
  store i32 %c, ptr %c.addr, align 4
  %0 = load i32, ptr %a.addr, align 4
  %1 = load i32, ptr %b.addr, align 4
  %add = add nsw i32 %0, %1
  %2 = load i32, ptr %c.addr, align 4
  %add1 = add nsw i32 %add, %2
  ret i32 %add1
}

Reading the pieces

The signature. define dso_local i32 @add3(i32 noundef %a, ...) defines a function named add3 returning a 32-bit integer. A name with @ is global, and % is local to the function. dso_local says the symbol resolves within the same module and linking unit, and noundef says the argument is never an uninitialized value. #0 refers to an attribute group listed at the bottom of the file.

Types. i32 is a 32-bit integer with no signedness: IR has only bit widths, and signedness lives in the instructions (sdiv is signed, udiv unsigned). ptr is an opaque pointer, which since LLVM 15 has no pointee type; older IR wrote i32*. float, double, <4 x i32> (a vector) and [8 x i8] (an array) appear too.

Basic blocks. The label entry: names the first block. A basic block is straight-line code that ends in one terminator, a ret, br or switch. Control only enters at the top. This is why loops and if statements show up as several labeled blocks.

Stack slots. At -O0 every local variable and parameter has an alloca, which reserves stack memory, a store that writes the incoming value into it and loads to read it. This makes the IR a direct translation of the C and also makes it long.

Arithmetic and flags. %add = add nsw i32 %0, %1 adds two values. nsw means "no signed wrap": signed overflow is undefined behavior in C, and the flag records that promise, which later passes use. Unsigned arithmetic would have no flag. Names such as %add and %add1 come from the operation; without -fno-discard-value-names they would be %4 and %5.

Return. ret i32 %add1 ends the function.

The same function after optimization

Shell
clang -O2 -S -emit-llvm -fno-discard-value-names add.c -o add_opt.ll
Text
define dso_local i32 @add3(i32 noundef %a, i32 noundef %b, i32 noundef %c) local_unnamed_addr #0 {
entry:
  %add = add nsw i32 %b, %a
  %add1 = add nsw i32 %add, %c
  ret i32 %add1
}

All the memory traffic is gone. A pass called mem2reg replaced the alloca/store/load triples with direct use of the SSA values. Another pass reordered the first addition to %b, %a, which is harmless for addition. The attribute local_unnamed_addr says the function's address is not significant, which lets it be merged with an identical function. Comparing -O0 and -O2 IR for the same function is the fastest way to learn what the optimizer does.

Control flow: branches and phi nodes

A conditional shows the two constructs that make IR look strange the first time.

clamp.cc
int clamp_pos(int x)
{
    int r;
    if (x < 0)
        r = 0;
    else
        r = x;
    return r;
}

At -O1, with names kept, Clang produces a version that has no memory use but still a branch pattern, or, more likely, the select instruction. Compile at -O0 and then run the mem2reg pass to see the intermediate form, which uses a phi:

Shell
clang -O0 -Xclang -disable-O0-optnone -S -emit-llvm -fno-discard-value-names clamp.c -o clamp.ll
opt -passes=mem2reg -S clamp.ll -o clamp_ssa.ll
Text
define dso_local i32 @clamp_pos(i32 noundef %x) #0 {
entry:
  %cmp = icmp slt i32 %x, 0
  br i1 %cmp, label %if.then, label %if.else

if.then:
  br label %if.end

if.else:
  br label %if.end

if.end:
  %r.0 = phi i32 [ 0, %if.then ], [ %x, %if.else ]
  ret i32 %r.0
}

icmp slt compares two integers as signed values and yields an i1, a one-bit boolean. br i1 %cmp, label %if.then, label %if.else branches on it. The phi reads "if we came from if.then, the value is 0; if we came from if.else, it is %x." SSA requires that each name is assigned once, so a variable that has different values on different paths needs a phi where the paths join. The next optimization pass, simplifycfg, would turn the diamond into a select instruction, and instcombine into a smax intrinsic. The -Xclang -disable-O0-optnone flag matters here: without it, Clang marks -O0 functions optnone, and opt refuses to touch them.

Calls, globals and strings

call.cc
#include <stdio.h>

int main(void)
{
    puts("hi");
    return 0;
}
Text
@.str = private unnamed_addr constant [3 x i8] c"hi\00", align 1

define dso_local i32 @main() #0 {
entry:
  %call = call i32 @puts(ptr noundef @.str)
  ret i32 0
}

declare i32 @puts(ptr noundef) #1

A string literal becomes a global constant @.str, an array of three bytes, h, i and the terminating null written \00. private means no other module can see it, and unnamed_addr allows the linker to merge it with identical strings. The call is call i32 @puts(ptr noundef @.str), and a declare line says puts exists elsewhere with this signature. At -O2 Clang uses the same call, since puts is the right function for a string without format specifiers.

Reading structs, loops and GEP

Two more constructs appear as soon as your code uses arrays or structs. A loop becomes blocks connected by backward branches, with a phi for the induction variable. Access to an array element or a struct field uses getelementptr, often written GEP, which computes an address but does not load anything:

Text
%arrayidx = getelementptr inbounds i32, ptr %p, i64 %idx
%val = load i32, ptr %arrayidx, align 4

The first line computes p + idx * 4 for a pointer to i32; the second loads from the result. inbounds records a promise that the address stays within the object. When a GEP confuses you, read it as pointer arithmetic with a type, and remember that the first index steps over whole objects of the given type, with later indexes stepping into fields.

Practical uses of reading IR

Reading IR answers questions that assembly does not answer clearly. Did the compiler remove my bounds check? Look for the icmp and br in the IR. Did it inline this function? There is no call left. Did it vectorize the loop? Look for types like <4 x float>. Why is this variable reloaded each iteration? There is a load in the loop body that the optimizer could not hoist, typically because of possible aliasing. Because IR is target-independent, the answer is the same on x86-64, AArch64 or RISC-V, and the differences in speed then come from the back end.

For a quick look without saving files, clang -S -emit-llvm -O2 file.c -o - writes the IR to standard output. The Compiler Explorer site shows IR beside source for many Clang versions, and its output matches what you get locally if the versions match.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.