I'm taking a compiler class right now and we're at the point where we have to build a CFG in order to implement optimizations. One thing I can't figure out is how many CFGs are there for a program? Every example I ever see seems to be the CGF of a simple code segment. So, if you have a program that has say three functions. Do you have a separate CFG for each function or is there one big CFG for the entire program?
A Control Flow Graph (CFG) is the graphical representation of control flow or computation during the execution of programs or applications. Control flow graphs are mostly used in static analysis as well as compiler applications, as they can accurately represent the flow inside of a program unit.
Flow graph is a directed graph. It contains the flow of control information for the set of basic block. A control flow graph is used to depict that how the program control is being parsed among the blocks. It is useful in the loop optimization.
o The control flow graph is a graphical representation of a program's control structure. It uses the elements named process blocks, decisions, and junctions.
Per-function CFGs are connected by callsites. If one function calls another, e.g.:
0 void foo() { /* do stuff */ }
1 void bar() { /* do stuff */ }
2
3 void baz() {
4 foo(); // Callsite for foo. Control transfers to foo, then foo returns here.
5 bar(); // Callsite for bar. Control transfers to bar, then bar returns here.
6 }
then the control graph for baz
will include an edge that goes to the graph for foo
. Likewise, because foo
will eventually returns to baz
(and to wherever else it might've been called from), there will be an edge from the end of foo
's graph back to the statement after the call to foo
in baz
. Here, that next statement is the call to bar
on line 5. At that point, there's an edge from the bar
callsite to bar
's CFG, and lines from exit points in bar
back to the end of baz
.
Basically all you need to think about is "what code executes next". That tells you where the edges should go in your control graph. A function call transfers control until the function returns, which implies an edge from the callsite to the function CFG and back again.
Note that not all full-program CFGs are connected graphs. If there is unreachable code in the program you're analyzing, then that will be its own unconnected piece of the full CFG. e.g. if you took out the call to bar
in the above example, then bar
would have its own graph off to the side, while baz
and foo
would be connected by edges.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With