Search code examples
c++clangllvmllvm-clang

Is there anyway to switch the functions using clang libtooling?


EDITED:

Me and my colleague are very new to clang and llvm .

I have three functions..

function 1{}
function 2{}
function 3{}

Is there anyway to swap the functions to

function 3{}
function 2{}
function 1{}

using clang libtooling / rewriter and print out the function name and also the parameter inside the function ?


Solution

  • You can parse the AST first using an ASTConsumer. You get one function's AST at a time, you might want to store it globally somewhere and then you can add them to the clang's REWRITTER API and finally dump the buffer back to a file.

    This is an example of editing some AST nodes and writing back to file. In your case, you won't edit the AST's but just rearrange the buffer push calls to rearrange the functions. In VisitFunctionDecl:

    bool VisitFunctionDecl(FunctionDecl *f) {
        // Only function definitions (with bodies), not declarations.
        if (f->hasBody()) {
             //store in a global array/vector
        }
    
        return true;
    }
    

    In main after ParseAST and before writing to file, you will do a rearrangeFunctionDecls.