Skip to content

IR 08 ssa phi

Mugundan edited this page Nov 27, 2026 · 1 revision

SSA and Phi

Relevant source files

The following files were used as context for generating this wiki page:

SSA (static single assignment) form means every value is assigned exactly once in the program text. A C variable that is assigned in several places becomes several IR values. Where control paths join and different paths carry different values, a phi instruction picks the right one. This page explains why LLVM uses SSA, how phi works, and how the mem2reg pass builds SSA from the simpler code Clang emits.

Purpose and Scope

This page covers the SSA rule, the phi instruction and its placement rules, and the mem2reg pass with a before/after example. Dominance, which decides where phis are needed, is explained in depth on Dominance.

The SSA Rule

In this C code x is assigned twice:

int x = a;
x = x + 1;
return x * 2;

In SSA each assignment creates a new name (illustrative):

%x1 = add i32 %a, 1
%x2 = mul i32 %x1, 2
ret i32 %x2

Because every value has one definition:

  • "Which definition reaches this use?" has one answer: the operand pointer itself.
  • A value can be replaced everywhere with replaceAllUsesWith, with no need to check for other assignments.
  • Many analyses (constant propagation, dead code, value numbering) become simple walks over def-use chains.

A second rule goes with it: a definition must dominate all its uses. Every path from the entry block to a use must pass through the definition, so the value always exists when it is used. The verifier checks this.

Why phi Is Needed

Straight-line code is easy. The problem is a join point:

int x;
if (c) x = 1; else x = 2;
return x;

After the if, x is 1 or 2 depending on which branch ran. Neither definition dominates the return. A phi creates a new value that is selected by the edge control arrived on (illustrative):

define i32 @pick(i1 %c) {
entry:
  br i1 %c, label %then, label %else
then:
  br label %join
else:
  br label %join
join:
  %x = phi i32 [ 1, %then ], [ 2, %else ]
  ret i32 %x
}

phi i32 [ 1, %then ], [ 2, %else ] means "1 if we came from %then, 2 if we came from %else".

flowchart TD
    E["entry: br %c"] --> T["then"]
    E --> F["else"]
    T -->|"x = 1"| J["join: %x = phi [1,%then],[2,%else]"]
    F -->|"x = 2"| J
Loading

Sources: llvm/include/llvm/IR/Instructions.h:2727

phi Rules

Rule Reason
phis must be at the top of a block, before any other instruction They conceptually run "on the edge", all at once, as control enters
One incoming entry per predecessor edge Each way in must say what value it brings
Every incoming value has the same type as the phi Same as any other instruction
An incoming value only needs to be available at the end of its predecessor, not in the phi's block The value travels along the edge

All phis at the top of a block are evaluated together, so in a loop this swap is correct (illustrative):

loop:
  %a = phi i32 [ 0, %entry ], [ %b, %loop ]
  %b = phi i32 [ 1, %entry ], [ %a, %loop ]

phi is not a real machine instruction. Before register allocation the back end replaces each phi with copies at the end of the predecessor blocks; see the Register Allocation wiki.

In C++, PHINode has getNumIncomingValues(), getIncomingValue(i), getIncomingBlock(i) and addIncoming(V, BB). BasicBlock::phis() iterates over the phis at the top of a block.

Clang Does Not Emit SSA for Variables

Building SSA directly is fiddly, so Clang does something simpler. At -O0, and as the first step at higher levels, every local variable gets an alloca, every read is a load, and every write is a store. Memory is not subject to the single-assignment rule, so this is valid IR. Then the mem2reg pass (or the more general sroa) promotes those stack slots to SSA values and inserts the phis.

Before mem2reg

int pick(int c) { int x; if (c) x = 1; else x = 2; return x; }

(illustrative, shaped like clang -O0 -Xclang -disable-O0-optnone -S -emit-llvm)

define i32 @pick(i32 %c) {
entry:
  %c.addr = alloca i32, align 4
  %x = alloca i32, align 4
  store i32 %c, ptr %c.addr, align 4
  %0 = load i32, ptr %c.addr, align 4
  %tobool = icmp ne i32 %0, 0
  br i1 %tobool, label %if.then, label %if.else

if.then:
  store i32 1, ptr %x, align 4
  br label %if.end

if.else:
  store i32 2, ptr %x, align 4
  br label %if.end

if.end:
  %1 = load i32, ptr %x, align 4
  ret i32 %1
}

After opt -S -passes=mem2reg

(illustrative)

define i32 @pick(i32 %c) {
entry:
  %tobool = icmp ne i32 %c, 0
  br i1 %tobool, label %if.then, label %if.else

if.then:
  br label %if.end

if.else:
  br label %if.end

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

The allocas, loads and stores are gone. The load of %c.addr was replaced by %c directly, because only one store reached it. The load of %x became a phi, because two different stores reached it. simplifycfg would then turn the empty diamond into a select, see Common Passes.

mem2reg is registered in PassRegistry.def as FUNCTION_PASS("mem2reg", PromotePass()).

Sources: llvm/lib/Passes/PassRegistry.def:491

How mem2reg Works

PromoteMemoryToRegister.cpp implements the classic algorithm (Cytron et al., 1991) in four steps:

  1. Pick promotable allocas. isAllocaPromotable accepts an alloca only if it is used just by simple loads and stores (and a few harmless intrinsics). If its address escapes, for example by being passed to a call, it must stay in memory.
  2. Find where the variable is live. ComputeLiveInBlocks finds the blocks where the variable's value is needed on entry. A phi in a block where it is not live would be dead, so these blocks restrict placement.
  3. Place phis at the iterated dominance frontier. The blocks containing stores are the definition blocks. A phi is needed exactly where two different definitions first meet, which is the dominance frontier of the definition blocks, and repeated because each new phi is itself a definition. ForwardIDFCalculator computes this set, and QueuePhiNode inserts an empty phi in each block.
  4. Rename. A walk over the CFG in dominator-tree order keeps the "current value" of each variable. A store updates it, a load is replaced by it, and on each edge the current value is added as an incoming value of the successor's phis. Finally the allocas and stores are deleted.
flowchart LR
    A["Promotable allocas<br/>isAllocaPromotable"] --> L["Live-in blocks<br/>ComputeLiveInBlocks"]
    L --> P["Insert phis at IDF<br/>ForwardIDFCalculator, QueuePhiNode"]
    P --> R["Rename loads/stores<br/>along dominator tree"]
    R --> D["Delete allocas"]
Loading

The public entry point used by passes is PromoteMemToReg(Allocas, DT, ...), which needs a dominator tree.

Sources: llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:66, llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:809, llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:879-895, llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:1039, llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:1108, llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:1259, llvm/include/llvm/Analysis/IteratedDominanceFrontier.h:39-55

A Loop Example

A loop always needs a phi in its header, because the header is reached both from before the loop and from the end of the previous iteration (illustrative, after mem2reg):

int sum(int n) { int s = 0; for (int i = 0; i < n; i++) s += i; return s; }
define i32 @sum(i32 %n) {
entry:
  br label %for.cond

for.cond:
  %s.0 = phi i32 [ 0, %entry ], [ %add, %for.body ]
  %i.0 = phi i32 [ 0, %entry ], [ %inc, %for.body ]
  %cmp = icmp slt i32 %i.0, %n
  br i1 %cmp, label %for.body, label %for.end

for.body:
  %add = add nsw i32 %s.0, %i.0
  %inc = add nsw i32 %i.0, 1
  br label %for.cond

for.end:
  ret i32 %s.0
}

Here %add is used by a phi in %for.cond even though %for.body comes "later" in the text. That is allowed: the use is on the edge from %for.body, and %add dominates the end of %for.body.

Key Points

  • SSA: one definition per value, and the definition dominates every use.
  • phi picks a value by incoming edge; phis sit at the top of a block.
  • Clang emits alloca/load/store; mem2reg inserts phis at the iterated dominance frontier and renames.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally