Fee
Fee

Reputation: 851

LLVM get possible store instructions for a load instruction

I'am writing a LLVM pass and I need to find every instruction that could have defined the memory read by a load instruction. E.g.:

%x = alloca i32, align 4
store i32 123, i32* %x, align 4
%0 = load i32, i32* %x, align 4

In this example I want to get from the load instruction to every instruction that could have initialized/altered %x. In this case just the previous store instruction. I tried to use the use-def chain, but this gives me the instruction for the definition of the memory, which is the alloca instruction.

bool runOnModule(Module &M) override {
        for(Function &fun : M) {
            for(BasicBlock &bb : fun) {
                for(Instruction &instr : bb) {

                    if(isa<LoadInst>(instr)){
                        for (Use &U : instr.operands()) {
                          if (Instruction *Inst = dyn_cast<Instruction>(U)) {
                            errs() << *Inst << "\n";
                          }
                        }
                    }

                }
            }
        }
        return false;
    }
};

How can I get every possible store instructions that could have defined the memory read by a load instruction?

Upvotes: 3

Views: 3078

Answers (1)

Chirag Patel
Chirag Patel

Reputation: 1161

you can cast the AllocaInst to Value and then check its uses, if they are loads or stores.

Just for side note: Value is superclass Value <-- User <-- Instruction <-- UnaryInst <-- AllocaInst, you can also look at the Inheritance diagram at http://llvm.org/docs/doxygen/html/classllvm_1_1Value.html#details

Value* val = cast<Value>(alloca_x);
Value::use_iterator sUse = val->use_begin();
Value::use_iterator sEnd = val->use_end();
for (; sUse != sEnd; ++sUse) {
    if(isa<LoadInst>(sUse)) // load inst
    else if(isa<StoreInst>(sUse)) // store inst
}

There is also memory dependency analysis pass which in turns uses alias analysis, you can query store instruction and it will return the instructions which loads from or store to that memory. see http://llvm.org/docs/doxygen/html/classllvm_1_1MemoryDependenceAnalysis.html for more information.

Upvotes: 6

Related Questions