I am wondering how to insert a GetElementPointer instruction in LLVM IR through LLVM Pass, say suppose I have an array
%arr4 = alloca [100000 x i32], align 4
and Want to insert a gep like
%arrayidx = getelementptr inbounds [100000 x i32]* %arr, i32 0, i32 %some value
the what will be the sequence of instructions to write as in IRBuilder Class there are so many instructions to create getelementpointer. Which One to use and what will be its parameters. can anyone explain it with example Any help would be appreciated.
Let's start with the documentation for GetElementPtrInst, since the IRBuilder is providing a wrapper to its constructors. If we want to add this instruction, I usually go direct and call create.
GetElementPtrInst::Create(ptr, IdxList, name, insertpoint)
Putting these pieces together, we have the following code sequence:
Value* arr = ...; // This is the instruction producing %arr
Value* someValue = ...; // This is the instruction producing %some value
// We need an array of index values
// Note - we need a type for constants, so use someValue's type
Value* indexList[2] = {ConstantInt::get(someValue->getType(), 0), someValue};
GetElementPtrInst* gepInst = GetElementPtrInst::Create(arr, ArrayRef<Value*>(indexList, 2), "arrayIdx", <some location to insert>);
Now, you asked about using IRBuilder, which has a very similar function:
IRBuilder::CreateGEP(ptr, idxList, name)
If you want to use the IRBuilder, then you can replace the last line of the code snippet with the similar IRBuilder's call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With