Getting the location or scope of variable from a DeclRefExpr

Hi,

I have a Stmt that belongs in a CFG that I built and in that Stmt is a DeclRefExpr that points to a variable, I was wondering what’s the advisable and most appropriate way to get to the location where this variable is defined (source location, scope) starting from the DeclRefExpr.

In my case, this variable is in a Stmt, that’s in a CFGBlock, that belongs to a CFG that I created, I’ve looked at the code and I could come up with a couple of ideas, I’m not sure these are the correct ways though:

  1. Visit the CFG using a visitor that notes the source locations of variable definitions, variable names and types then use the LiveVariables (not sure of the exact name of the class) to run on the different CFGBlocks in the CFG and manually interrogate the class for the liveness of every variable at the end of a CFGBlock, taking into account the correct path and reachability through the CFG starting from the entry block.

  2. Possibly create an AnalysisContext and from there possibly find a way to get the Scopes.

As per my limited experience with Clang and just looking at the code, it seems that 1 is quite tedious but probably more straightforward, and I’m sure that it is already being done in Clang/LLVM to resolve the variable references to the proper variables already, it’s just that I haven’t figured out where is it being done to reuse it without having to reimplement it again.

2 seemed to be way more complicated, involving creating the AnalysisContextManager and a whole lot more support objects.

I was wondering which of the 2 is more appropriate and if there’s yet another way to do it that’s simpler than these two potential solutions.

Regards,
Ahmed

Hi Ahmed,

I'm not 100% certain what you are trying to do. By "defined", are you talking about finding the locations where a variable 'x' is one of the following?

  Declared with initialization, e.g.: int x = ...
  
  Assigned, e.g.: x = ...

  Increments/Decrements, e.g.: ++x

  Address-taken, e.g.: &x

The last case, while not a definition of 'x', might be considered a "value-kill" by a conservative analysis that doesn't want to reason about aliases.

If you are looking for these, probably the easiest solution is to just do a recursive walk of the AST, and look for these expressions where the DeclRefExpr refers to the VarDecl 'x'. Once you find the expressions that define the variable, you can just query their SourceLocations.

Is this what you are looking for?

Ted