ArticleslgStudy

science

Control-flow graph

Control-flow graph is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Control-flow graph rather than just read about it. In short: In computer science, a control-flow graph (CFG) is a representation, using graph notation, of all paths that might be traversed through a function during its execution, or control flow. The control-flow graph was conceived by Frances E.

Control-flow graph — main illustration
Control-flow graph — illustration

Key takeaways

  • Control-flow graph belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Control-flow graph to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Control-flow graph from memory before moving on to harder problems.

Reference excerpt

In computer science, a control-flow graph (CFG) is a representation, using graph notation, of all paths that might be traversed through a function during its execution, or control flow. The control-flow graph was conceived by Frances E. Allen, who noted that Reese T. Prosser used boolean connectivity matrices for flow analysis before. The CFG is essential to many compiler optimizations and static-analysis tools.

Definition A control flow graph is the directed graph of the basic blocks of the function (the nodes of the graph) and the control flow between them (the edges of the graph). The exact details vary between representations. Typically, a basic block consists of a straight-line sequence of instructions or statements. Only the last instruction or statement in each block can perform control flow, and control flow can only be directed to the first instruction or statement in a block. In most CFG representations, there are two specially designated blocks: the entry block, through which control enters into the function, and the exit block, through which all control exits the function (typically by returning). Some representations permit multiple exit blocks, especially if there are different kinds of exit, or permit the exit block to be omitted if it is not reachable (see below). If there is a control-flow edge from block A to block B, then A is called a predecessor of B, and B is called a successor of A.

Examples As a simple example, consider the following C function definition:

This function has three basic blocks:

Block 1 is the entry block. It runs from the start of the function until the end of the expression p != NULL. It ends with the if control flow, either entering block 2 if the condition is true or skipping ahead to block 3 if the condition is false. Block 2 is the body of the if statement. It ends by unconditionally falling into block 3. Block 3 is the exit block. It runs from the end of the if statement to the implicit return at the end of the function body. The nested structure of the source program makes it a little hard to see the basic blocks. As an alternative representation that makes the blocks more obvious, we can flatten that structure into a sequence of labeled blocks. To make the control flow explicit, we will require each block to end in either goto, an if/else of gotos, or return (only in the exit block).

This is a source-level representation of the CFG. The basic blocks consist of sequences of C statements taken directly from the source program. Only the structured control flow has been eliminated. Now consider a more complex example which includes a loop:

This function has six basic blocks, which can be clearly seen in our source-level representation of the CFG:

This style of statement-level CFG representation is not commonly used, and it is shown here only for illustrative purposes. Not all programs can be easily represented this way, even in C. Notice how the local variable declaration has been raised to the top of function, and its initialization in block1 has been turned into an assignment. This would cause difficulties for scope-driven features such as shadowing and variable-length arrays. Statements would also need to be significantly rewritten to deal with expression-level control flow, such as is introduced by the &&, ||, and ? : operators. Most practical CFG representations use something other than complete source statements as the components of their basic blocks. For example, compiler frameworks such as LLVM use a CFG in which basic blocks consist of abstract static single-assignment instructions as their primary IR. Here is the above function translated into LLVM IR:

Notice how the block structure is the same in the source-level and the LLVM CFGs. In both representations, the functions have the same basic semantics, performing the same sequence of operations and control flow. Only the representation of the individual operations is different.

Construction A very explicit control flow graph can be obtained from a source function by placing each statement into its own basic block. If the statement is not a control-flow statement, a "fall-through" jump to the block for the next statement is added to the block. Unfortunately, this tends to create a large number of unnecessary basic blocks and fall-through jumps, which makes subsequent analysis more cumbersome and expensive. It is usually desirable that successive statements be placed in the same basic block whenever possible. Another way to say this is that, across the entire CFG, every edge A→B should have the property that:

outdegree(A) > 1 or indegree(B) > 1 (or both). Such a graph can be derived from the one-statement-per-block CFG by performing an edge contraction for every edge that falsifies the predicate above, which is to say, by merging two blocks whenever the source block always jumps to the destination block and the destination block can only be jumped to by the source block. However, this contraction-based algorithm is of little practical importance except as a visualization aid for understanding CFG construction because of the expense of building the initial form. In typical implementations, the CFG is built directly from the program in a way that minimizes unnecessary blocks by construction, such as by scanning the program for necessary boundaries between basic blocks.

Reachability

Reachability is a graph property useful in optimization. If a block cannot be reached by any path from the entry block, then it cannot possibly be executed, in which case it is called unreachable code. Unreachable code can usually be removed from the control flow graph without any negative consequences. If the exit block cannot be reached by any path from the entry block, then control flow cannot leave the graph normally. This indicates the presence of either an infinite loop or, in representations that directly support these features, an abnormal exit or termination of the program. The exit block being reachable by some path does not mean that the program will necessarily reach it, and it is impossible to prove that it will be reached in a general graph; see Halting problem. Optimization can reveal unreachable code and infinite loops that were not apparent in the original program. For example, consider the following LLVM function:

… excerpt ends here. Continue reading the full article.

Illustrations

Control-flow graph: Some CFG examples:(a) an if-then-else(b) a while loop(c) a natural loop with two exits, e.g. while with an if...break in the middle; non-structured but reducible(d) an irreducible CFG: a loop with two entry points, e.g. goto into a while or for loop
Some CFG examples:(a) an if-then-else(b) a while loop(c) a natural loop with two exits, e.g. while with an if...break in the middle; non-structured but reducible(d) an irreducible CFG: a loop with two entry points, e.g. goto into a while or for loop
Control-flow graph: A control-flow graph used by the Rust compiler to perform codegen.
A control-flow graph used by the Rust compiler to perform codegen.

Worked examples

Example 1 — a first encounter with Control-flow graph

Start with the simplest possible case. Write down what Control-flow graph claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Control-flow graph before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Control-flow graph ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Control-flow graph

In research
Control-flow graph appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Control-flow graph in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Control-flow graph is common in secondary-school and first-year university syllabi. It links to neighbouring topics Application-specific graphs, Compiler construction, Control-flow analysis, so understanding it makes those chapters shorter.
In everyday life
Look for Control-flow graph outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Control-flow graph” →

How to study Control-flow graph in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Control-flow graph means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Control-flow graph out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Control-flow graph in simple terms?

In computer science, a control-flow graph (CFG) is a representation, using graph notation, of all paths that might be traversed through a function during its execution, or control flow. The control-flow graph was conceived by Frances E.

Why does Control-flow graph matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Control-flow graph?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Control-flow graph.

Tags

  • Application-specific graphs
  • Compiler construction
  • Control-flow analysis
  • Modeling languages

Keep exploring