3.4 Check whether every node reaches every other
You check whether a graph is strongly connected, and use that to check a control-flow graph for blocks that never run or never reach the exit.
Problem
Section titled “Problem”You want to be sure that from every node of a graph you can get to every other node. A graph with this property is called strongly connected. It forms a single SCC. You need this for:
- a network of one-way streets, in which every place must be reachable from every other;
- the states of a protocol or of a user interface: each state must be reachable from the start, and the start must be reachable again from each state;
- a control-flow graph, in which every block should be reachable from the entry and reach the exit. With an extra edge from the exit to the entry, this is the same check.
Example
Section titled “Example”The method loadloadloadLoad of a small program reads the
lines of a file and parses each line that is not blank into a note:
List<Note> load(Path file) { List<String> lines = read(file); // entry List<Note> notes = new ArrayList<>(); for (int i = 0; i < lines.size(); i++) { // header: i < lines.size() String line = lines.get(i); // body if (!line.isBlank()) { notes.add(parse(line)); // then } } // next: i++ return notes; // exit}fn load(file: &Path) -> Vec<Note> { let lines = read(file); // entry let mut notes = Vec::new(); let mut i = 0; while i < lines.len() { // header: i < lines.len() let line = &lines[i]; // body if !line.trim().is_empty() { notes.push(parse(line)); // then } i += 1; // next } notes // exit}function load(file: string): Note[] { const lines = read(file); // entry const notes: Note[] = []; for (let i = 0; i < lines.length; i++) { // header: i < lines.length const line = lines[i]; // body if (line.trim() !== "") { notes.push(parse(line)); // then } } // next: i++ return notes; // exit}List<Note> Load(string file){ string[] lines = Read(file); // entry var notes = new List<Note>(); for (int i = 0; i < lines.Length; i++) // header: i < lines.Length { string line = lines[i]; // body if (!string.IsNullOrWhiteSpace(line)) { notes.Add(Parse(line)); // then } } // next: i++ return notes; // exit}The graph cfg holds its control flow. This control-flow graph has a node for each
basic block, from its entry entry to its exit exit. Is every
block reachable from entry, and does every block reach exit? If so, every block can run, and
from every block the method can return. With an extra edge from exit back to entry, this is the
same as asking whether the graph is strongly connected. In the picture before, only the orange edges
of the loop lie on a cycle. The picture after adds
the edge exit -> entry. Now every edge lies on a cycle, and all blocks form one SCC, which is the
gray frame.
- End of the extra edge
- SCC
- Edge on a cycle
Solution
Section titled “Solution”Graphs.isStronglyConnectedgraphs::is_strongly_connectedGraphs.isStronglyConnectedGraphs.IsStronglyConnected checks the control-flow graph as it is. Then it
checks the graph with the extra edge, which a GraphBuilderGraphBuilderGraphBuilderGraphBuilder adds to a copy of it:
// No edge leads to entry, so no other block reaches it.boolean cfgStronglyConnected = Graphs.isStronglyConnected(cfg); // false
// With an edge from exit back to entry, the graph is strongly connected exactly when// every block can be reached from entry and can reach exit.var builder = new GraphBuilder();builder.addGraph(cfg);builder.addEdge(exit, entry);boolean loadWellFormed = Graphs.isStronglyConnected(builder.build()); // true// No edge leads to entry, so no other block reaches it.let cfg_strongly_connected = graphs::is_strongly_connected(&cfg); // false
// With an edge from exit back to entry, the graph is strongly connected exactly when// every block can be reached from entry and can reach exit.let mut builder = GraphBuilder::new();builder.add_graph(&cfg);builder.add_edge(exit, entry);let load_well_formed = graphs::is_strongly_connected(&builder.build()); // true// No edge leads to entry, so no other block reaches it.const cfgStronglyConnected = Graphs.isStronglyConnected(cfg); // false
// With an edge from exit back to entry, the graph is strongly connected exactly when// every block can be reached from entry and can reach exit.const builder = new GraphBuilder();builder.addGraph(cfg);builder.addEdge(exit, entry);const loadWellFormed = Graphs.isStronglyConnected(builder.build()); // true// No edge leads to entry, so no other block reaches it.bool cfgStronglyConnected = Graphs.IsStronglyConnected(cfg); // false
// With an edge from exit back to entry, the graph is strongly connected exactly// when every block can be reached from entry and can reach exit.var builder = new GraphBuilder();builder.AddGraph(cfg);builder.AddEdge(exit, entry);bool loadWellFormed = Graphs.IsStronglyConnected(builder.Build()); // trueThe control flow of loadloadloadLoad alone is not strongly
connected: no edge leads to entry, so no other block reaches it. With the extra edge it is
strongly connected: every block lies on a cycle through entry and exit, as the picture after
shows.
Good to know
Section titled “Good to know”- Why the trick works. With the edge
exit -> entry, a block thatentryreaches and that reachesexitlies on a cycle through both, so any two such blocks reach each other. A block thatentrydoes not reach, or that does not reachexit, has no such cycle, and the check fails. - Several exits. A method that returns in several places has several exits: add an edge from each of them to the entry. The graph is then strongly connected exactly when every block is reachable from the entry and reaches one of the exits.
- Which blocks fail the check?
Graphs.reachableFromgraphs::reachable_fromGraphs.reachableFromGraphs.ReachableFromgives the blocks thatentryreaches. A block missing from them never runs. See Find everything a node reaches. A search against the direction of the edges gives the blocks that reachexit. From a block missing from them, the method never returns. See Find everything that reaches a node. See Find the groups of nodes that reach each other for the SCCs of any graph that fails the check. - Which edges and blocks keep it so.
Components.strongConnectivityOfcomponents::strong_connectivity_ofComponents.strongConnectivityOfComponents.StrongConnectivityOffinds the edges and blocks without which the graph is no longer strongly connected. See Find the edges and nodes whose removal splits a strongly connected component. - The empty graph counts as strongly connected, and so does a graph of a single node.
API used
Section titled “API used”Graphs.isStronglyConnected(Graph)graphs::is_strongly_connectedGraphs.isStronglyConnectedGraphs.IsStronglyConnectedGraphBuilder()GraphBuilder::newnew GraphBuildernew GraphBuilderGraphBuilder.addGraph(Graph)GraphBuilder::add_graphGraphBuilder.addGraphGraphBuilder.AddGraphGraphBuilder.addEdge(int, int)GraphBuilder::add_edgeGraphBuilder.addEdgeGraphBuilder.AddEdgeGraphBuilder.build()GraphBuilder::buildGraphBuilder.buildGraphBuilder.BuildSccs.isStronglyConnected()Sccs::is_strongly_connectedSccs.isStronglyConnectedSccs.IsStronglyConnected