Search code examples
c++llvmllvm-clang

How do I replace an instruction with a value?


I'm writing in C++. Say I have

define void @ha(i32) #0 {
  %2 = add nsw i32 %0, 1
  %3 = sub nsw i32 %2, 1
  ret void
}

I'd like to replace

%3 = sub nsw i32 %2, 1

with

%3 = %0

I've tried

inst_iter->replaceAllUsesWith(val);
inst_iter->eraseFromParent();

and ReplaceInstWithValue(inst_iter->getParent()->getInstList(), inst_iter, val);

The first understandably does not work, as it does not have another reference; for the second one, it just deletes the instruction. I couldn't find an appropriate function either (and I haven't included IRBuilder). Any help is appreciated, thank you!


Solution

  • The function you want is replaceAllUsesWith(). Find your sub and replace all uses of that instruction with. Done.