Home:ALL Converter>Insert instructions in LLVM

Insert instructions in LLVM

Ask Time:2020-11-23T16:24:19         Author:localacct

Json Formatter

If I am trying to create an instruction and insert at the start of a function, will this be the right way as I could not see the instruction inserted when I used opt to load the .so file and process the .ll file.

if (auto* op = dyn_cast<Instruction>(&I))
{
    if(prepend_first == false)
    {
        llvm::LLVMContext& context = I.getContext();
        Value* lhs = ConstantInt::get(Type::getInt32Ty(context), 4);
        Value* rhs = ConstantInt::get(Type::getInt32Ty(context), 6);

        IRBuilder<> builder(op);
        builder.CreateMul(lhs, rhs);
        builder.SetInsertPoint(&I);

        prepend_first = true;
    }
}

EDIT (27 Nov 2020) This is the entire pass, which is based on other articles as well.

using namespace llvm;

namespace
{
    struct customllvm : public PassInfoMixin<customllvm>
    {
        llvm:PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
        {
            for(BasicBlock &BB : F)
            {
                bool prepend_first = false;

                for(Instruction &I : BB)
                {
                    if(auto *op = dyn_cast<Instruction>(&I))
                    {
                        if(prepend_first != true)
                        {
                            llvm::LLVMContext& context = I.getContext();
                            Value* lhs = ConstantInt::get(Type::getInt32Ty(context), 4);
                            Value* rhs = ConstantInt::get(Type::getInt32Ty(context), 6);

                            IRBuilder<> builder(op);
                            builder.CreateMul(lhs, rhs);
                            builder.SetInsertPoint(&I);

                            prepend_first = true;
                        }
                    }
                }
            }
        }
    }
}

Author:localacct,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/64964810/insert-instructions-in-llvm
Anton Korobeynikov :

You need to set the insertion point first. And only then create instruction.",
2020-11-24T05:54:41
yy