Search code examples
compiler-constructionllvmcompiler-optimizationllvm-clangllvm-ir

Creating a new Store Instruction LLVM


I am working with LLVM IR code. I want to create a new store instruction ( Eg: store i32 %add, i32* %temp1, align 4) and I need to insert it after a particular instruction, say after an add instruction. My intention is, the result of an addition operation (some pointer) is stored in %add, I need to keep a copy of the same in a temperory variable say %temp1.

For that, I created a variable named temp1 first (%temp1 = alloca i32, align 4). Now I want to store the result of addition instruction (%add = add nsw i32 %0, %1) i.e., %add to temp1. Then the final store instruction will be something like this: store i32 %add, i32* %temp1, align 4. How to do this?

Any help with some examples?


Solution

  • For creating %temp1 = alloca i32, align 4 instruction, I used the following statement:

    AllocaInst* pa = new AllocaInst(llvm::Type::getInt32Ty(getGlobalContext()), 0, 4,"temp1");
    

    For creating and inserting a new store instruction:

    StoreInst *str = new StoreInst(i, pa); // i -> current instruction pointer which represents %add ( source of store instruction ), pa -> destination. i.e., temp1
    BB->getInstList().insert(ib, str); // ib -> instruction address before which you want to insert this store instruction