GetElementPtrInst question

Hi all,

How can I create an llvm::GetElementPtrInst in which the pointer and
the index are in registers previously loaded with llvm::LoadInst ? I
mean, the generated instruction will be like this:

  %1 = getelementptr i8* %myreg1, i32 %myreg2

here, %myreg1 and %myreg2 are previously created by load instructions

Please, let me know if there is an example of something similar.

Thanks for the help,


You'd use an IRBuilder, like you did to create your LoadInsts.

IRBuilder<> IRB(BB);
IRB.CreateGEP(myreg1, myreg2);

I assume because you asked this question, something went wrong when using the above method. What was it? :slight_smile:



Hi James,

Thanks for your quick reply.

I assume because you asked this question, something went wrong when using the above method. What was it? :slight_smile:

No, I am not using this method. I was trying to create a
llvm::GetElementPtrInst . I didn't create IRBuilder. I am writing a
ModulePass that insert new instruction to an existing Module.

Besides, how can you get a reference to myreg1 ? Looking at your
snippet this variable would be a llvm::Value* (I saw that in the
documentation of IRBuilder). All I have in my code is something like:

  llvm::LoadInst *inst2 = new llvm::LoadInst( oneGlobalVariable,
"myreg1", inst1);

Probably I can get a Value pointer to the output register from the
inst2 variable, but I don't know how (I couldn't figure out myself by
just reading the documentation).

Any help is very welcome,

Hi Eduardo,

"inst2" is a LoadInst, which inherits from Value. You can simply pass "inst2" to CreateGEP.

I'd recommend using an IRBuilder instead of manually new'ing the instructions anyway, because an IRBuilder will associate those instructions with a BasicBlock, and your code is currently not doing that (so you'll run into problems later).



Other than using the IR builder, you can create this instruction directly, using one of the "Create" functions, for example:

   static GetElementPtrInst *Create(Value *Ptr, ArrayRef<Value *> IdxList,
                                    const Twine &NameStr,
                                    Instruction *InsertBefore = 0) {
     GetElementPtrInst *GEP = Create(Ptr, IdxList, NameStr, InsertBefore);
     return GEP;

The "Ptr" would be your "myreg1", and you'll need to create an ArrayRef that holds a single element: "myreg2". Conveniently, ArrayRef has a constructor that creates a "singleton" array:

     /// Construct an ArrayRef from a single element.
     /*implicit*/ ArrayRef(const T &OneElt)
       : Data(&OneElt), Length(1) {}

Since it's not an explicit constructor, it may actually work if you do
   GEP = GetElementPtrInst::Create(myreg1, myreg2, "", where-to-insert);

Otherwise you'll need to create an ArrayRef that represents the arguments to the GetElemPtr instruction.