Stack Exchange
How to put Load Instructions into InsertElement Instructions through LLVM pass?
I would like to auto-generate Load and InsertElement Instruction through llvm pass.
My problem is how to put Load Instructions such as %4, %6, %8, %10 into InsertElement Instructions, like my goal of LLVM-IR code:
%4 = load i32, i32* %1, align 4
%5 = insertelement <4 x i32> undef, i32 %4, i32 0
%6 = load i32, i32* %1, align 4
%7 = insertelement <4 x i32> %5, i32 %6, i32 1
%8 = load i32, i32* %1, align 4
%9 = insertelement <4 x i32> %7, i32 %8, i32 2
%10 = load i32, i32* %1, align 4
%11 = insertelement <4 x i32> %9, i32 %10, i32 3

and my pass:
if (auto *op = dyn_cast<LoadInst>(&I)) {
            ...
            Value* loadinst_ptr=op->getPointerOperand();
            Type* load_ty= loadinst_ptr->getType();
            Value* val = UndefValue::get(VectorType::get(load_ty, 4));
            for (unsigned i = 0; i < 4; i++)//for 4 copies
            {
                LoadInst* load_val=builder.CreateLoad(loadinst_ptr);
                load_val->setAlignment(4);
                //my problem is here, parameter load_val is invalid on CreateInsertElement.
                val = builder.CreateInsertElement(val,load_val, builder.getInt32(i));

            }
        }

here is error message:
opt: /home/shun/llvm-proj/llvm/lib/IR/Instructions.cpp:1748: 
llvm::InsertElementInst::InsertElementInst(llvm::Value*, llvm::Value*, llvm::Value*, const llvm::Twine&, llvm::Instruction*): 
Assertion `isValidOperands(Vec, Elt, Index) && "Invalid insertelement instruction operands!"' failed.


How are loadinst_ptr and val declared & initialized?

I added them in my question.

Try calling ->dump() on both val and load_val just before the call, to verify they are what you expect them to be.

I tried to print load_val before val = builder.CreateInsertElement(), and I got this instruction %4 = load i32, i32* %1, align 4, which I expect. but I still can't insert it, or how to put %4 into CreateInsertElement() using another way?

If I use the parameter loadinst_ptr into CreateInsertElement(), it work, but I got %1, the IR instruction became %5 = insertelement <4 x i32> undef, i32 %1, i32 0, which is not my expect; My expect is %5 = insertelement <4 x i32> undef, i32 %4, i32 0

The code must be different than what you're showing us. loadinst_ptr should be an i32*, but you're saying it shows up as i32 %1.

Value* loadinst_ptr=op->getPointerOperand();
Type* load_ty= loadinst_ptr->getType();
Value* val = UndefValue::get(VectorType::get(load_ty, 4)); instead can you try Type* load_ty= op->getType();
Value* val = UndefValue::get(VectorType::get(load_ty, 4));

@IsmailBadawi I got it, thank you!

@lazyCoder It's work, I know the problem is the type, thank you for your help!
