我现在正在学习编译器课程,我们必须构建 CFG 才能实现优化。我不明白的一件事是一个程序有多少个 CFG?我见过的每个例子似乎都是一个简单代码段的 CGF。因此,如果您有一个具有三个功能的程序。您是否为每个函数都有一个单独的 CFG,或者是否为整个程序有一个大的 CFG?
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?
发布评论
评论(2)
每个功能的 CFG 通过调用点连接。如果一个函数调用另一个函数,例如:
那么 baz 的控制图将包含一条通向 foo 的图的边。同样,由于
foo
最终将返回到baz
(以及可能从其调用的其他任何地方),因此从foo 的末尾将有一条边
的图表返回到在baz
中调用foo
后的语句。在这里,下一个语句是第 5 行对bar
的调用。此时,从bar
调用站点到bar
的CFG,以及从bar
中的出口点到baz
末尾的线。基本上您需要考虑的是“接下来执行什么代码”。这告诉您边缘应该在控制图中的位置。函数调用会传输控制权,直到函数返回,这意味着从调用点到函数 CFG 并再次返回的边缘。
请注意,并非所有完整程序 CFG 都是连通图。如果您正在分析的程序中有无法访问的代码,那么这将是它自己的未连接完整 CFG 的一部分。例如,如果您在上面的示例中取出对
bar
的调用,那么bar
将在侧面拥有自己的图形,而baz
和foo
将通过边连接。Per-function CFGs are connected by callsites. If one function calls another, e.g.:
then the control graph for
baz
will include an edge that goes to the graph forfoo
. Likewise, becausefoo
will eventually returns tobaz
(and to wherever else it might've been called from), there will be an edge from the end offoo
's graph back to the statement after the call tofoo
inbaz
. Here, that next statement is the call tobar
on line 5. At that point, there's an edge from thebar
callsite tobar
's CFG, and lines from exit points inbar
back to the end ofbaz
.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, thenbar
would have its own graph off to the side, whilebaz
andfoo
would be connected by edges.好吧,您可以为每个功能构建一个 CFG,然后(如果您需要的话)将它们组合成一个完整的功能。然而,整个程序 CFG 可能非常大,因此它们通常不能很好地作为示例。
Well, you can construct a CFG for each function and then - if desirable for what you want to do - combine them into a complete one. Whole program CFGs can be pretty big, however, so they usually don't work well as examples.