I'm trying to write a LLVM pass to analyse the following IR:
%d = alloca i32, align 4
store i32 0, i32* %d, align 4
%1 = load i32* %d, align 4
%2 = add nsw i32 %1, 2
store i32 %2, i32* %d, align 4
What I need to do is to figure out the final value of d.
For the store i32 0, i32* %d, align 4
I used ConstantInt casting for the operand 0 and found the assigned value for d (which is 0). But I'm struggling with how to find the value for the d in last store instruction:
store i32 %2, i32* %d, align 4
As I know, %2 is a pointer to the result of the instruction %2 = add nsw i32 %1, 2
and similar thing to the %1.
Do I need to backtrack for %2 to find the value of %2 or is there a simpler method for this?
EDIT:
Following is the code I used so far:
void analyse(BasicBlock* BB)
{
for (auto &I: *BB)
{
if (isa<StoreInst>(I))
{
Value *v = I.getOperand(0);
Instruction *i = dyn_cast<Instruction>(I.getOperand(1));
if (isa<ConstantInt>(v))
{
llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(v);
int value = CI->getZExtValue();
std::string ope = i->getName().str().c_str();
std::cout << "ope " << value << " \n";
}
}
}
}
Way to solve this is to back track. In this case:
store i32 %2, i32* %d, align 4
%2 = add nsw i32 %1, 2
%1 = load i32* %d, align 4
so it's checking the operand is an instruction, and if so, check the type of the instruction (i.e: isa(v), isa(v) or isa(v) etc), and then find the value.