Search code examples
llvmllvm-clangllvm-irdataflow

LLVM - given a register, get where it was last used in the IR representation


I am trying to keep track of data flow in my source code. For that, I'm looking at instructions of type load and obtaining which register they're loading the value from with the use of

*(LI->getPointerOperand())

LI being the instruction of type LoadInst. Now I need to know where this register was last accessed so that I can point that check the data flow from that instruction to this one. Any suggestions will be highly appreciated.


Solution

  • Initially, simplify the problem by excluding loops and functions with multiple exits, so that you have a function CFG as a single entry and single exit graph.

    One (probably simplistic) way would be to first find all its users by doing something like:

    llvm::Instruction i = [the register for that LoadInst];
    auto users = i->users();
    

    Then using the PostDominatorTree and the getLevel method of the DomTreeNodeBase (I think this was introduced with LLVM 5.0.0, if not available in your version you could use getChildren and perform a BFS traversal), you could filter through those with the highest level number.

    I'm not sure what you want to do with loops, but if nothing special, the above should suffice. For dealing with multiple exits from functions you could make use of the mergereturn pass prior to any processing.