Varun Hegde
Varun Hegde

Reputation: 349

How to get the source Variable Declaration of an caller argument in Clang?

I am very new to clang. So please excuse me if this question sounds very silly.

I am trying to write a simple Clang checker.

I have a simple program.

void function(int a)
{
   printf("%d", a);
}

main()
{      
       static int A = 0; 
       //some computation
       //How to get the source of the variable declaration of A here? 
       func(A);    
}

My Attempt

void MyChecker::checkPreCall(const CallEvent &Call,
                                       CheckerContext &C) const {

   ParamVarDecl *VD = Call.parameters()[0];
   //this dumps the declaration of the callee function, i.e dest
   Call.parameters()[0]->dump();
   if(Call.parameters()[0]->isStaticLocal()){
        std::cout << "Static variable";
    }

}

I am trying to get the Variable Declaration of the of A at the time of calling func. However it gets the variable declaration of the callee argument; i.e the dest. How do I get the variable declaration of the source?

Upvotes: 0

Views: 188

Answers (1)

Valeriy Savchenko
Valeriy Savchenko

Reputation: 1614

Parameters are part of the function's declaration, while arguments are part of the call expression. You can read more about it in this question. Clang's documentation also underlines this difference for parameters method:

Return call's formal parameters.

Remember that the number of formal parameters may not match the number of arguments for all calls. However, the first parameter will always correspond with the argument value returned by getArgSVal(0).

You need to use getArgExpr instead. Additionally I want to note that any expression can be used as call arguments, so in order to get the variable declaration, you first need to check argument expression is indeed referring to a named declaration (i.e. DeclRefExpr), and then go to the actual declaration.

I hope this information is helpful. Happy hacking with Clang!

Upvotes: 1

Related Questions