Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding -fdump-tree output gcc with GraphViz

I've created a tree dump how described here: How can I dump an abstract syntax tree generated by gcc into a .dot file? for this dummy script:

int fact(int n) {
    if (n<=1) {
        return 1;
    }
    return n * fact(n-1);
}

int main(void) {
    int a = 4;
    int res = fact(a);
    return res;
}

And the image what I've got:

Graph generated via GraphViz

As I know gcc is not the best way to learn AST representation. But anyway it would be nice to understand what image's content means.

Especially what % sign here means and a FREQ:0 statement?

like image 846
funnydman Avatar asked Jan 12 '19 19:01

funnydman


1 Answers

The answer you link shows how to obtain the Control Flow Graph from GCC debugging dumps. So your image does not actually show a syntax tree.

The GCC C front end does not have an abstract syntax tree in the classical sense. A lot of syntactic constructs are lowered during parsing, often to a bunch of gotos. For example, c_finish_loop has this:

  /* If we have an exit condition, then we build an IF with gotos either
     out of the loop, or to the top of it.  If there's no exit condition,
     then we just build a jump back to the top.  */
  exit = build_and_jump (&LABEL_EXPR_LABEL (top));

if statements are turned into COND_EXPR nodes. You can see that in the .original dump (where the COND_EXPR node is printed like a C if statement). But there's no .dot file generated from that pass. Once the compilation process enters the middle end, it's GIMPLE, and GIMPLE (as an SSA variant) does not represent control flow using high-level language constructs such as for and if statements at all.

Clang has a more traditional AST, printed by clang -Xclang -ast-dump. It's still not suitable input for Graphviz, but at least the data is there. If your goal is to understand GCC, have a look at the C++ front end, which preserves a richer structure in the parser.

like image 141
Florian Weimer Avatar answered Nov 14 '22 12:11

Florian Weimer