← Back to the labIllustrated lesson notes
Lesson 01 / 08One harmless variable
A loop that runs millions of times keeps reaching for the same few numbers, and the processor reaches numbers held inside itself many times faster than numbers kept in main memory. It has only a handful of those inside slots, so the compiler, the program that turns your code into machine instructions, works hard to keep the busiest loop numbers there.
One trip through your loop is a lap. Each lap makes two trips to memory. It reads a sample and writes a result. The machine has four fast places to hold numbers, called registers. You will predict the total trips per lap with one extra number.
At each line, some values will still be read later, so they must stay in place: values needed at the same moment, called live values. A busy moment is a line with the most live values. The loop has two. Each builds two values from sample and total, then reads the pair together. Read the four names each moment needs before any edit.
First sample total head mask → read head and mask
Later sample total tail step → read tail and step
Now keep one extra number, debug, so you can check it three times each lap. Reading debug costs nothing while it stays in a register. Pick your prediction in the lab before switching debugging on. Will the loop make two, four or six trips per lap?
Follow the two busy moments
On the first row, only one register is free for head and mask. Later, tail and step face the same choice. Debug still holds its place.
Turn on the extra value. A spill sends a value to memory to free a register. The allocator picks mask, then step; lesson 5 shows how it chooses. The lab counts one rule everywhere: each write of a spilled value is one store, and each read is one load, every time its line runs. Mask is written once and read once by read head and mask. Step is the same.
Check the count
Add the original read and write to the four extra trips. Six trips replace two. For ten laps the counter changes from 20 to 60. Turn debugging off and check which four trips per lap disappear.
A register allocator chooses which values get the machine’s registers. In the next lesson you will find out how it knows when a value still needs its place.
Open this experiment →
Lesson 02 / 08Which values must survive?
A block is a run of lines that always execute together. Its arrow lists the blocks that can run next. A loop block lists itself. This loop adds a fixed step to its running count. You will find what must already be in place when the addition begins.
Cover the text below. On the first lap, which names must the machine remember before it can run this line?
count = add count step
Walk backwards
The right side reads both names. The left side writes a new count. A value is live at a point if a later instruction can read it before another write replaces it. The old count and step are both live before this addition.
In the lab's Live values tab, USE lists reads and DEF lists writes. LIVE_OUT holds the names needed just after a line. LIVE_IN holds the names needed just before it. Build the second set from the first.
LIVE_IN = USE ∪ (LIVE_OUT − DEF)
The minus sign removes names. The cup joins sets, keeping each name once. Follow both exits from the addition. The return needs count. The next lap needs count and step. Join their LIVE_IN sets to get the addition’s LIVE_OUT set.
Check another pass
In the Live values tab, find step in both LIVE_IN and LIVE_OUT of the addition. Start with empty sets and repeat the backward walk. When a full pass changes nothing, you have reached a fixed point. Removing step at the end of the lap would lose a value the next lap reads.
Open this experiment →
Lesson 03 / 08Who can share a register?
Two inputs feed an addition. You will draw the conflicts that decide which names need different registers. Before and after the addition, circle the names the machine still needs.
Does sum need a separate register from both inputs?
sum = add left right
return sum
Draw one line
Just before the addition, the program needs both left and right. If their values differ, one register cannot carry both. Draw a dot for each name and join left to right. Each line is an edge. The drawing is an interference graph. An edge tells the allocator to give the two names different registers.
After reading the inputs, the addition can put sum in either register. Sum has no edge to either input in this program.
Make sharing unsafe
In the lab's Program tab, insert the line below just before the return.
use left
Now left must survive the write to sum. Find the new edge between left and sum. Right has its last read before the write. Find the pair that can still share. Restore the starting program when you finish.
Open this experiment →
Lesson 04 / 08Find a place on the way back
Each register has a color. A line joins two dots that need different colors. You will take a dot off a crowded graph, then test whether it actually needs memory when it returns.
With four register colors, does seeing four neighbors prove that all four colors are taken?
Take the graph apart
A dot’s degree is its number of remaining neighbors. Let K stand for the number of registers. A dot with degree below K is safe to remove. Even if each neighbor takes a different color, at least one color remains.
Each dot touches every other dot except one partner: a and x, b and y, c and z never touch. So each starts with degree four, and no dot is below K. The allocator must still remove one. It marks a as a possible spill and removes it. Step once to watch. Follow the next dot. How many neighbors did it lose?
Remove: a b c x y z
Restore: z y x c b a
Put the colors back
The stack is the pile of removed dots. Its top dot comes back first. The remove phase is called simplify. During select, each returning dot gets a color its neighbors have left free.
When a comes back, c and z share one color. The other two neighbors share another. Two colors remain free. This is optimistic coloring, the step Briggs added to Chaitin’s allocator. A possible spill still gets a chance to take a register. Here zero values spill.
Open this experiment →
Lesson 05 / 08Count trips where they happen
A receipt must survive a loop. The loop also needs four values of its own. You will decide which value costs less to move to memory.
Each value has four neighbors. Would you give up the register holding receipt or the one holding a?
Price the two choices
Receipt has one write and three reads in the whole program. Spilling it costs four trips. Value a has one write and one read per lap. Across ten laps that becomes 20 trips. The cheaper choice leaves the busy loop alone.
receipt 4 × 1 visit = 4
a 2 × 10 visits = 20
The loop depth counts how many loops enclose a line. In this model a line at depth zero runs once. At depth one it runs ten times. At depth two it runs 100 times. Those counts are estimates.
Change the cost rule
For each value, add its reads and writes, weighting each by ten raised to its depth. Divide by the remaining degree. That quotient is the value’s score: memory trips per conflict removed. When it cannot simplify any dot, the allocator marks the value with the lowest score.
Turn off Weight by loop depth. The score now counts each of a’s two instructions once, so a looks cheaper than receipt and spills. The counter still charges ten laps: 20 trips. Change the depth and compare the score with the trips.
Open this experiment →
Lesson 06 / 08Can one register do both jobs?
The program copies a value from seed to kept, and later from kept to final. You will decide whether putting both names in one register saves work. Start with the four values around those names.
If the two names join, which neighbors would the joined dot touch?
kept = mov seed
final = mov kept
The MOV instruction copies its source to its destination. Giving the two names one home can remove this instruction. This is coalescing. If a conflict edge already joins the two names, they must stay apart.
Test the proposed join
Here the four neighbors all conflict with each other. They need four different colors. Joining seed to kept would produce a dot that touches all four colors.
Call a neighbor crowded when its current degree is at least K, the register count. The Briggs check counts the crowded neighbors of the joined dot. Fewer than K makes the join safe. The George check passes when every crowded neighbor of one name already touches the other name. The lab tries seed against kept, then kept against seed.
Compare the bill
Set Coalesce copies to Guarded: the lab joins only when a check passes. It keeps the seed copy and removes the copy into final. Now choose Force join, which skips the checks. You save the remaining copy, but now a spills. Each of its two values is written once and read once: two stores and two loads make four trips. Saving a copy only pays when the rest of the allocation still fits.
Open this experiment →
Lesson 07 / 08What does a faster pass miss?
A program reads an old tag and later writes a new one with the same name. You will decide whether another value can use that register in between.
Look at the gap. Does the old tag have a future read there?
tag read a, b, c, d used tag replaced
Each name gets a span
The old tag has had its last read. The new tag has yet to be written. Look at the graph. Neither tag needs to compete with the four values in the gap.
A live interval records the first and last positions where a name needs storage. This version records one interval per name. A linear scan visits interval starts in order. It frees registers for intervals that already ended. With every register full, it evicts the interval that ends last: that value goes to memory.
Compare the results
Switch to linear scan. Its combined interval for tag covers all four middle values. It evicts tag. Each of the two tags is written once and read once: two stores and two loads make four trips. Graph coloring sees the gap and spends zero.
The gap comes from reusing one name. Many compilers first give every write a fresh name, as in tag1 and tag2. This is static single assignment (SSA) form. Then each interval is short, and the same scan spends zero.
A just-in-time compiler builds code while a program runs. Time spent choosing registers can delay the program. Scan can avoid building the conflict graph. This lab draws both views for study. Its traffic counter measures memory operations in the resulting program. A claim about compile speed needs a separate timing test.
Open this experiment →
Lesson 08 / 08Repair a loop you have not seen
A ticket must survive a mixing loop for a later check. Four colors need registers on every lap. You will predict the cost and choose where to move one value out of the way.
Amber spills: it loses its register. It has one write and one read per lap. Predict the total trips for ten laps before making a change.
Choose the two boundaries
The ticket is needed after the loop. Letting it disappear would lose the result. Which value could stay in memory for the whole loop without anyone reading it? Decide where to save it and where its first read will be after the loop.
gate → mix (10 laps) → leave → verify (100 visits) → done
Check your repair
After attempting the repair, follow the two ticket names in the table. At the end of gate, save ticket to one memory slot. At the start of leave, reload that slot into a fresh name that the later checks read. The ticket’s live range is the part of the program in which its value must survive. Lesson 7’s interval is its first and last position. This change splits the range in two, with memory in between.
There is now room for all four colors inside mix. Read the counter by block. One store at gate plus one load at leave costs two trips. The original amber spill cost 20. Putting the reload inside verify would repeat it 100 times.
Open this experiment →