Search code examples
llvmllvm-irllvm-c++-api

How to make a new LLVM instruction?


I am trying to make the instruction

%a = i32 add %b, %c

into

%a = i32 mul %b, %c

I have been searching for hours but the answers I have discovered so far are answers that are related to creating new instructions defined in Instructions.h (ex AllocaInst) not mul, sdiv, div, instructions. I have also read the https://llvm.org/docs/ProgrammersManual.html#creating-and-inserting-new-instructions but I couldn't get the example "auto *newInst = new Instruction(...);" to work because I didn't know what the parameters of the should be even after looking at https://llvm.org/doxygen/classllvm_1_1Instruction.html#a2b30181f228bc6318130557d7ffca945

EDIT: I think I have successfully created the instruction itself, but not I'm having trouble replacing it in the right way.

Instruction *ni = BinaryOperator::CreateMul(inst.getOperand(0), newvalue);
ReplaceInstWithInst(*i, ni);

where *i is from iterating over a basic block (ex for (auto &i : bb))


Solution

  • Solved!

    Instruction *ni = BinaryOperator::CreateMul(inst.getOperand(0), newvalue);
    bb.getInstList().insert(inst.getIterator(), ni);