Using Clang for CFG creation

Hi everyone!

I'm currently working on a project for which i need a way to parse c/c++ source code and convert it into a CFG.

I happened upon Clang just a few days ago, and have been trying to figure out how to use it to create my CFG, but i failed. All i can use Clang for at the moment is using

clang -cc1 -analyze -analyzer-checker=debug.DumpCFG test.cpp

But this only yields a textual representation. Worst case i could write a parser for the output. I would much prefer to find a way to extract the CFG as it is used within Clang to my application.

The best would be if i could just call a function in Clang from my application and get the CFG returned.

Thanks for your time and answers. It is much appreciated.


I was looking for exactly the same kind of tool. :slight_smile:
You may be interested by
clang -cc1 -analyze -analyzer-checker=debug.ViewCFG test.cpp

It generates a ps file in /tmp/ from a dot file which I cannot reach at the moment.


Both DumpCFG and ViewCFG are meant as debug tools for working on the Clang static analyzer; in particular, the way the CFG is built for the analyzer may not match your needs.

If you are willing to write your own tool based on Clang’s C++ interface, you can get a parsed AST and then ask for the CFG of any particular function using CFG::buildCFG. Note, though that the C++ API is not stable from release to release.


Hi Jordan,

thanks for your advice. It took me a while to get through the LibTooling. By mostly copying the code from your link, i wrote up a few lines of code. However since i am just setting up for testing, I have not gotten around to test this yet.

However i have a few questions: buildCFG takes four parameters:
- a Decl
- a Stmt
- an ASTContext
- buildOptions

To be honest i am not exactly clear on what is what here.

I called it like this:

myCFG = CFG::buildCFG(inFile, getBody(), *Context, cfgBuildOptions);

which i mostly copied from

I will append my current code. You will notice that i am fairly novice in terms of coding. Please excuse any blatant mistakes.

Best regards,

FindCFGFrontendTool.cpp (856 Bytes)

Hi, Viktor. Fair question; it’s not the most well-documented part of Clang. You got the context and the build options right, but the decl is supposed to be the function you’re creating the CFG for. The statement is indeed the body of the function.

(Why do you pass both of them? Well, you can actually omit the decl and pass any arbitrary statement, so that you can get a CFG for just part of a program, or for the initializer of a global variable, or something like that. A better interface would probably be to allow you to pass a statement or a decl, because passing any statement other than the decl’s immediate body may cause some problems.)

Hope that helps,