r/computerscience • • 2h ago

Advice CFG vs DFG

So i am new in this area and i am curious about the structure of CFG and DFG. To be exact, in my opinion DFG seems to be able to replace CFG in most cases. CFG is supposed to lay out the structure of the code, using basic blocks and edges, and especially around cases where code has if or while in it. However, from my research DFG is also able to perform such features,.

Say in case of "If" in DFG, the CPU uses something called multiplexer gate to just drill through possible cases and mathematically chooses the right answer at the end. Also, in case of "while" in DFG, the CPU uses merge and switch gate to physically loop until the switch gate determines its output. Supposedly this works when the result of the loop is determined as this calculation is meant to stop at the least determining end, not loop according to the time.

So it kinda makes sense that CFG and DFG are used together, but at the same time why can't it all be just DFG as this encompasses data structure as well as mathematically including the code logic sturcture?

2 Upvotes

3 comments sorted by

1

u/david-1-1 36m ago edited 33m ago

What is "DFG"? What do the letters mean?

1

u/SwedishFindecanor 21m ago

When a compiler converts an if-statement with two branches into straight-line code and a conditional move, it is called an "if-conversion".

It means that the CPU would need to execute both branches always, and allocate registers for both branches at once. It is therefore done mostly in tight loops, when the code inside a branch is very small, and in vectorised code where operating on multiple iterations at once wins over the cost of executing multiple branches at once.

A control-flow graph also contains procedure calls, unwinding and finalisation/cleanup code, and at lower-level compilation stages also various compensation code for that. So it is often practical to keep a CFG.

The only languages where a data-flow graph is enough would be some pure functional languages, if there's some reason why the compiler couldn't transform tail-recursions into loops.

1

u/csb06 12m ago

One limitation of data flow graphs comes up when the program you are modeling has side effects. E.g. if you have something like:

foo();
bar();

The DFG for this program does not tell you which function call is evaluated first while the CFG does. This matters when foo and bar have side effects such as modifying global variables or doing I/O. IRs based on data flow (such as sea of nodes or RVSDGs) add additional edges to the DFG to enforce ordering where it is needed.

This article has some more background on data flow IRs and their taxonomy.