How to get argument names from clang::CallExpr?

Hi!

How can I retrieve the argument names from a clang::CallExpr? I was trying something along the following lines, but the dyn_cast returns null.

const auto *dr = clang::dyn_castclang::DeclRefExpr(expr->getArg(0));

auto name = dr->getDecl()->getName().str();

Thanks,

Kenth

What if you don't try to cast it to a `DeclRefExpr`, but you cast it to a `Expr` and `->dump()` it?

Note that some args are not represented by `DeclRefExpr` if they are literals such as IntegerLiteral or StringLiteral.

Also - are you sure you want argument names? In the code below, clang calls a1 and a2 arguments and p1 and p2 parameters:

void foo(int p1, int p2);

void bar()
{
    int a1 = 5;
    int a2 = 7;
    foo(a1, a2);
}

if you want parameters, you need to get the FunctionDecl from the callExpr and query its parameters to get their names.

Thanks,

Stephen.

What if you don't try to cast it to a `DeclRefExpr`, but you cast it
to
a `Expr` and `->dump()` it?

If I dump the CallExpr, I can see the following;

CallExpr 0x5640de2c08c8 'char *'

-ImplicitCastExpr 0x5640de2c08b0 'char *(*)(char *, const char *)' <FunctionToPointerDecay>
`-DeclRefExpr 0x5640de2c07f0 'char *(char *, const char *)' Function 0x5640de2916a8 'strcpy' 'char *(char *, const char *)'
-ImplicitCastExpr 0x5640de2c08f8 'char *' <LValueToRValue>
`-UnaryOperator 0x5640de2c0848 'char *' lvalue prefix '*' cannot overflow
  `-ImplicitCastExpr 0x5640de2c0830 'char **' <LValueToRValue>
    `-DeclRefExpr 0x5640de2c0810 'char **' lvalue ParmVar 0x5640de366998 'valueString' 'char **'

`-ImplicitCastExpr 0x5640de2c0928 'const char *' <NoOp>
  `-ImplicitCastExpr 0x5640de2c0910 'char *' <LValueToRValue>
    `-DeclRefExpr 0x5640de2c0860 'char *' lvalue Var 0x5640de366d88 'ptr1' 'char *'

I want to get the name of the first argument supplied to the call of
strcpy.

Note that some args are not represented by `DeclRefExpr` if they are

Can you show use the code corresponding to the CallExpr?

Also, when you say the “name of the first argument supplied…” that presumes that the first argument is always a variable. That’s not generally the case – any (well typed) argument will work. For example, your first argument in the dumped CallExpr above is pointer-dereference (I think *valueString?). So, you would, at the least, want your code to be

if (const auto *dr = clang::dyn_castclang::DeclRefExpr(expr->getArg(0))) {

auto name = dr->getDecl()->getName().str();

}

That said, you probably want expr->IgnoringImplicit(), since lvalues (e.g. variable names) are always implicitly cast to rvalues.

*valueString = (char*)malloc(len+1);
strcpy(*valueString, ptr1);