Using TreeTransform for AST Transformations


I am working on a project which involves reading in a C source file,
doing some analysis (mainly on loops), reordering the code and then
generating transformed C code at the end. I have been using Clang to
do the analysis part and thus far it has worked out well (I'm
following the usual path of deriving from ASTConsumer).

For the transform part, however, I am not clear on how to proceed.
After reading up on the threads related to source-to-source transforms
and about AST transformations, it seems I have two options: (1) Use
the Rewriter or (2) Modify the AST itself and then pretty-print it. I
would like to do the latter and from what I've seen, using Sema's
TreeTransform class seems to be the most elegant solution. I have been
playing around with the code and trying to use TreeTransform in some
useful way, but I would be glad if somebody briefly explained how it
is supposed to be used with the ASTConsumer that I already have (for
example, how do I replace a loop node in the AST with a new,
transformed loop node such that it doesn't break any semantics?). I'm
relatively new to Clang and any help would be greatly appreciated.