Skip to content

8.1 Find the loops of a function and how they nest

You find which blocks of a control-flow graph form a loop, which block is the header of each loop, and which loop lies in which.

You want to know where the loops of a function are, because compilers and analyzers do much of their work per loop. The blocks that form a loop are its body. The block through which a loop is entered is its header. That is where the test of a for or while loop sits. You also want to know which loop lies in which, and how deep each block is nested. The source code shows the loops, but the control-flow graph is what the analysis has, for example after inlining, after other optimizations, or for bytecode without the source. You need this for:

  • moving a computation whose result does not change out of a loop, so that it runs once instead of on every pass;
  • unrolling small loops;
  • estimating how often a block runs, since a block in two nested loops usually runs far more often than one in none;
  • putting the effort where the program spends its time, for example by keeping the variables of inner loops in registers.

The method showshowshowShow prints the notes of a small notebook program, each note with its lines, in two nested loops:

void show(List<Note> notes) {
out.println(notes.size() + " notes"); // entry
for (Note note : notes) { // nextNote: another note?
List<String> lines = format(note).lines().toList(); // format
for (String line : lines) { // nextLine: another line?
out.println(" " + line); // print
}
}
out.flush(); // exit
}
fn show(notes: &[Note]) {
println!("{} notes", notes.len()); // entry
for note in notes { // nextNote: another note?
let text = format(note); // format
for line in text.lines() { // nextLine: another line?
println!(" {line}"); // print
}
}
let _ = io::stdout().flush(); // exit
}
function show(notes: Note[]): void {
out.write(`${notes.length} notes\n`); // entry
for (const note of notes) { // nextNote: another note?
const lines = format(note).split("\n"); // format
for (const line of lines) { // nextLine: another line?
out.write(` ${line}\n`); // print
}
}
out.end(); // exit
}
void Show(List<Note> notes)
{
output.WriteLine($"{notes.Count} notes"); // entry
foreach (Note note in notes) // nextNote: another note?
{
string[] lines = Format(note).Split('\n'); // format
foreach (string line in lines) // nextLine: another line?
{
output.WriteLine(" " + line); // print
}
}
output.Flush(); // exit
}

The graph cfg holds its control flow. This control-flow graph has a node for each basic block and an edge from each block to each block that can run right after it. The picture before shows it. Which blocks form loops, how do they nest, and which is the innermost loop of format and of print?

The picture after shows the two loops. Loop 0 runs over the notes. Its header is nextNote, and its body holds every block that can run again before the method returns. Loop 1 runs over the lines and is nested in loop 0. Its header is nextLine. The orange edges lie on cycles: execution can run through them again and again.

The control flow, its entry and the blocks asked about
Its loops and their headers
0: entry1: nextNote2: format3: nextLine4: print5: exit
0: entry1: nextNote2: format3: nextLine4: print5: exitloop 0loop 1
Input
  • Entry or block asked about
Context
  • Edge on a cycle
Output
  • Loop
  • Loop header

Loops.ofLoops::ofLoops.ofLoops.Of finds the loops from the entry block. It follows edges against their direction too, so it takes a BiAdjacentGraphBiAdjacentGraphBiAdjacentGraphBiAdjacentGraph, which BiAdjacentGraph.ofBiAdjacentGraph::ofBiAdjacentGraph.ofBiAdjacentGraph.Of builds from the control-flow graph. The result is a LoopsLoopsLoopsLoops, which answers the questions about each loop and each block:

// Find the loops of show, from its entry block.
Loops loops = Loops.of(BiAdjacentGraph.of(cfg), entry);
int loopCount = loops.loopCount(); // 2
// The innermost loop of format is the loop over the notes; that of print, over the
// lines.
int notesLoop = loops.innermostLoopOf(format); // 0
int linesLoop = loops.innermostLoopOf(print); // 1
int header = loops.headerOf(linesLoop); // 3 - nextLine
// [1, 2, 3, 4] - all but entry and exit
IntList body = loops.bodyOf(notesLoop);
// How the loops nest.
int parent = loops.parentOf(linesLoop); // 0 - the loop over the notes
int depth = loops.loopDepthOf(print); // 2 - print runs in both loops
Full example
// Find the loops of show, from its entry block.
let loops = Loops::of(&BiAdjacentGraph::of(&cfg), entry);
let loop_count = loops.loop_count(); // 2
// The innermost loop of format is the loop over the notes; that of print, over the
// lines. innermost_loop_of returns None for a block in no loop.
let notes_loop = loops.innermost_loop_of(format).unwrap(); // 0
let lines_loop = loops.innermost_loop_of(print).unwrap(); // 1
let header = loops.header_of(lines_loop); // 3 - nextLine
let body = loops.body_of(notes_loop); // [1, 2, 3, 4] - all but entry and exit
// How the loops nest.
let parent = loops.parent_of(lines_loop); // Some(0) - the loop over the notes
let depth = loops.loop_depth_of(print); // 2 - print runs in both loops
Full example
// Find the loops of show, from its entry block.
const loops = Loops.of(BiAdjacentGraph.of(cfg), entry);
const loopCount = loops.loopCount; // 2
// The innermost loop of format is the loop over the notes; that of print, over the
// lines.
const notesLoop = loops.innermostLoopOf(format); // 0
const linesLoop = loops.innermostLoopOf(print); // 1
const header = loops.headerOf(linesLoop); // 3 - nextLine
// [1, 2, 3, 4] - all but entry and exit
const body = loops.bodyOf(notesLoop);
// How the loops nest.
const parent = loops.parentOf(linesLoop); // 0 - the loop over the notes
const depth = loops.loopDepthOf(print); // 2 - print runs in both loops
Full example
// Find the loops of Show, from its entry block.
Loops loops = Loops.Of(BiAdjacentGraph.Of(cfg), entry);
int loopCount = loops.LoopCount; // 2
// The innermost loop of format is the loop over the notes; that of print, over
// the lines.
int notesLoop = loops.InnermostLoopOf(format); // 0
int linesLoop = loops.InnermostLoopOf(print); // 1
int header = loops.HeaderOf(linesLoop); // 3 - nextLine
// [1, 2, 3, 4] - all but entry and exit
ReadOnlySpan<int> body = loops.BodyOf(notesLoop);
// How the loops nest.
int parent = loops.ParentOf(linesLoop); // 0 - the loop over the notes
// 2 - print runs in both loops
int depth = loops.LoopDepthOf(print);
Full example

Loops have IDs from 0 to loopCount() - 1loop_count() - 1loopCount - 1LoopCount - 1. Loops.innermostLoopOfLoops::innermost_loop_ofLoops.innermostLoopOfLoops.InnermostLoopOf returns the innermost loop that contains a block. Loops.bodyOfLoops::body_ofLoops.bodyOfLoops.BodyOf returns the blocks of a loop: its header first, then its other blocks, then those of the loops nested in it. The body of the loop over the notes therefore contains the body of the loop over the lines. Loops.parentOfLoops::parent_ofLoops.parentOfLoops.ParentOf returns the loop that immediately encloses a loop, and -1None-1-1 for an outermost one. Loops.loopDepthOfLoops::loop_depth_ofLoops.loopDepthOfLoops.LoopDepthOf counts the loops that contain a block: 2 for print, 0 for entry and exit.