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.
Problem
Section titled “Problem”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.
Example
Section titled “Example”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.
- Entry or block asked about
- Edge on a cycle
- Loop
- Loop header
Solution
Section titled “Solution”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); // 0int linesLoop = loops.innermostLoopOf(print); // 1int header = loops.headerOf(linesLoop); // 3 - nextLine// [1, 2, 3, 4] - all but entry and exitIntList body = loops.bodyOf(notesLoop);
// How the loops nest.int parent = loops.parentOf(linesLoop); // 0 - the loop over the notesint depth = loops.loopDepthOf(print); // 2 - print runs in both loops// 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(); // 0let lines_loop = loops.innermost_loop_of(print).unwrap(); // 1let header = loops.header_of(lines_loop); // 3 - nextLinelet 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 noteslet depth = loops.loop_depth_of(print); // 2 - print runs in both loops// 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); // 0const linesLoop = loops.innermostLoopOf(print); // 1const header = loops.headerOf(linesLoop); // 3 - nextLine// [1, 2, 3, 4] - all but entry and exitconst body = loops.bodyOf(notesLoop);
// How the loops nest.const parent = loops.parentOf(linesLoop); // 0 - the loop over the notesconst depth = loops.loopDepthOf(print); // 2 - print runs in both loops// 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); // 0int linesLoop = loops.InnermostLoopOf(print); // 1int header = loops.HeaderOf(linesLoop); // 3 - nextLine// [1, 2, 3, 4] - all but entry and exitReadOnlySpan<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 loopsint depth = loops.LoopDepthOf(print);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.
Good to know
Section titled “Good to know”- Outer loops have smaller IDs. A loop has a smaller ID than the loops nested in it. So going
through the IDs from
loopCount() - 1loop_count() - 1loopCount - 1LoopCount - 1down to 0 visits every loop after the loops inside it. An optimizer usually works in that order. - Is a block in a loop?
Loops.isInLoopLoops::is_in_loopLoops.isInLoopLoops.IsInLoopanswers it for a block and a loop, also when the block lies in a loop nested in it. - Loops with several entries. A loop written with
fororwhileis entered only through its header. A loop built withgoto, in bytecode or in a generated state machine can have several entries. An entry is a block at which execution can enter the loop from outside it. A loop with several entries is irreducible. Graphity finds it as one loop, andLoops.entriesOfLoops::entries_ofLoops.entriesOfLoops.EntriesOfreturns all its entries.Loops.isReducibleLoops::is_reducibleLoops.isReducibleLoops.IsReducibletells whether the graph has no irreducible loop among the blocks that the entry reaches. See Find loops that can be entered in more than one place. - Several entries of the function.
Loops.ofLoops::of_entriesLoops.ofLoops.Oftakes a list of entry blocks, for example when exception handlers are blocks that no edge leads to. Blocks that no entry reaches are in no loop.
API used
Section titled “API used”BiAdjacentGraph.of(Graph)BiAdjacentGraph::ofBiAdjacentGraph.ofBiAdjacentGraph.OfLoops.of(BiAdjacentGraph, int)Loops::ofLoops.of(graph: BiAdjacentGraph, entry: number)Loops.Of(BiAdjacentGraph, int)Loops.of(BiAdjacentGraph, IntList)Loops::of_entriesLoops.of(graph: BiAdjacentGraph, entries: IntList)Loops.Of(BiAdjacentGraph, ReadOnlySpan<int>)Loops.loopCount()Loops::loop_countLoops.loopCountLoops.LoopCountLoops.innermostLoopOf(int)Loops::innermost_loop_ofLoops.innermostLoopOfLoops.InnermostLoopOfLoops.headerOf(int)Loops::header_ofLoops.headerOfLoops.HeaderOfLoops.bodyOf(int)Loops::body_ofLoops.bodyOfLoops.BodyOfLoops.parentOf(int)Loops::parent_ofLoops.parentOfLoops.ParentOfLoops.loopDepthOf(int)Loops::loop_depth_ofLoops.loopDepthOfLoops.LoopDepthOfLoops.isInLoop(int, int)Loops::is_in_loopLoops.isInLoopLoops.IsInLoopLoops.isReducible()Loops::is_reducibleLoops.isReducibleLoops.IsReducibleLoops.entriesOf(int)Loops::entries_ofLoops.entriesOfLoops.EntriesOf