Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get operand name of a LLVM getelementptr in

Tags:

arrays

c

llvm

I am trying to get the name of an array that a getelementptr instruction is referencing. This seems to work when the array is indexed into using an intermediate variable in the actual c code like so

int a = 0;
i[a] = 3; 

In this case, i get the following bitcode

%arrayidx = getelementptr inbounds [2 x i32], [2 x i32]* @i, i64 0, i64 %idxprom
store i32 3, i32* %arrayidx, align 4

In this case I can iterate over the operands of the getelementptr instruction and find the name of the array(i) through the getName() method on the first operand.

However, if in the source, the array is index directly as so,

i[0] = 3;

Then, the bitcode generated is as follows

store i32 3, i32* getelementptr inbounds ([2 x i32], [2 x i32]* @i, i64 0, i64 0), align 4

Here I am not sure of how to get the array name(i) from the bitcode. The type of the second operand of the store instruction is set to be PointerTy. And the contained type of the second operand is an int. Both of this is as expected since the operand is a i32*. But, I am not sure how to get a handle to the getelementptr instruction to iterate over its operands in this case.

Edit: I should mention that the array i is a global

like image 984
nave Avatar asked Nov 06 '15 19:11

nave


1 Answers

In the first example, the second operand of the store instruction is a getelementptr instruction, but in the second example, it's a getelementptr constant expression, because both the pointer and the indices are constants.

Thus, in the first case, if you get the pointer operand of the StoreInst, you'll get a GetElementPtrInst. In the second case, you'll get a ConstantExpr whose getOpcode() method returns Instruction::GetElementPtr.

You can handle both cases uniformly in your code by using GEPOperator. You can use dyn_cast<GEPOperator>(I) and it'll do the right thing for both instructions and constantexprs.

(Note -- Operator is not an LLVM IR concept -- it's just a C++ abstraction to help in cases like this where you might be dealing with an instruction or a constant expression (which might happen with casts, GEPs, or arithmetic operations) but you don't care about the distinction.)

like image 109
Ismail Badawi Avatar answered Oct 16 '22 18:10

Ismail Badawi