A Control-Flow-Graph is:

In computer science, a control-flow graph (CFG) is a representation, using graph notation, of all paths that might be traversed through a program during its execution.

The CFG is essential to many compiler optimizations and static-analysis tools.

I wanted to use them for code optimization and analysis such as dead code elimination and for ensuring valid code. My question is how can I implement a CFG? What data structures should I use and how can this be represented in code?


2 Answers 2


They say a good question contains half of the answer... So you have a good question! :)

As long as CFG is a graph, you can employ any graph representation. And there are a lot of libraries implementing graphs and graph algorithms for all popular programming languages.

Additionally I suggest taking a look at how they do it in existing compilers. Here's Cranelift for example. Cranelift is smaller and simpler than Clang/LLVM and GCC, easier to understand...


For control flow graphs, each basic block has a bunch of instructions which end in a jump/branch. This is really just a graph with some additional meta-information for vertices. So, you can represent this however you like and what fits best your implementation-language of choice. For example, in a functional language, you may choose to do something like:

type prim =
| Constant of int
| Plus of prim * prim
(* and more such primitives *)

type instru = 
| Assign of string * prim
(* load, store, ... *)
type basic_block = {
  instrus : instru list ;
  term : jump ;
and jump =
| Jmp of basic_block
| Branch of value * basic_block * basic_block
| Halt

Note that this is just one option out of many to represent your graph. Other options may be to store everything in an arena and reference to the nodes with indices or to embrace pointers and use them to represent the edges.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .