Cloning Clang Stmts, declarations and other AST objects


I would like to implement a set of transformations on Clang AST one after the other. Therefore I want to modify the AST by adding or removing nodes from it.
For example, I would like to do first loop-unrolling on the inner loop and add the unrolled copies in the AST and then make other transformations on the AST.

My question: is there a way to clone the stmts in the body of the loop and just go in and modify these copies and add them to the AST.

Best regards,

No, we don't have an easy way to do this. However, we will eventually need this functionality, so patches to implement AST cloning would be welcome!

  - Doug

Hi Doug,

Thanks. I have another question:

Assuming that somehow I implemented the cloning. What would be the proper way to add new nodes to the AST?

I think there are two ways for adding new nodes to the AST:
1.Appending children nodes
2.Inserting nodes in arbitrary order not necessary at the end

I took a look at how the parser builds the AST of compound statements specially and it seems that the parser pushes back the statements on a vector. Then it calls the acton method from Sema to create the objects.

Best regards,

Most expressions and statements are either allocated with new (ASTContext) or have static Create methods. Expressions and statements are generally meant to be immutable once created, so for your application you might want to implement some kind of recursive walk over the statements that builds the clone with the modifications in-place.

   - Doug