Print arguments of a function using Clang AST
Asked Answered
E

2

10

I want to get the arguments passed to a function. for example, if I have the call

printf("%d%d", i, j);

the output should be

%d%d
i
j

I am able to get to function calls using VisitCallExpr() in RecursiveASTVisitor. Also able to get the number of arguments and the argument types. But I don't know how to get the arguments.

bool MyRecursiveASTVisitor::VisitCallExpr (clang::CallExpr *E)  
{
    for(int i=0, j=E->getNumArgs(); i<j; i++)
    {
        llvm::errs() << "argType: " << E->getArg(i)->getType().getAsString() << "\n";
    }
    return true;
}

Output:

argType: char *
argType: int
argType: int

Please help me getting the arguments.

Erinerina answered 7/3, 2012 at 19:32 Comment(0)
D
10

You are calling E->getArg(i)->getType() - but that is type of argument. Use E->getArg(i) to get Expr* representing value of argument. Then use printPretty(...) method to pretty-print it to string, if you need string value.

Donn answered 7/3, 2012 at 20:58 Comment(1)
Hi martins, your answer was very helpful martins. I didn't know about printPretty(...) function. Now, I am able to print the arguments. Thank You.Erinerina
E
13

your answer was very helpful martins. I didn't know about printPretty(...) function. Now, I am able to print the arguments. below is my code to print the arguments.

bool MyRecursiveASTVisitor::VisitCallExpr (clang::CallExpr *E)
{
    clang::LangOptions LangOpts;
    LangOpts.CPlusPlus = true;
    clang::PrintingPolicy Policy(LangOpts);

    for(int i=0, j=E->getNumArgs(); i<j; i++)
    {
        std::string TypeS;
        llvm::raw_string_ostream s(TypeS);
        E->getArg(i)->printPretty(s, 0, Policy);
        llvm::errs() << "arg: " << s.str() << "\n";
    }
    return true;
}

and the output looks like this:

"%d%d"
i
j
Erinerina answered 9/3, 2012 at 18:36 Comment(0)
D
10

You are calling E->getArg(i)->getType() - but that is type of argument. Use E->getArg(i) to get Expr* representing value of argument. Then use printPretty(...) method to pretty-print it to string, if you need string value.

Donn answered 7/3, 2012 at 20:58 Comment(1)
Hi martins, your answer was very helpful martins. I didn't know about printPretty(...) function. Now, I am able to print the arguments. Thank You.Erinerina

© 2022 - 2024 — McMap. All rights reserved.