[LLVMdev] newbie question on getelementptr

Óscar Fuentes ofv at wanadoo.es
Wed Sep 19 04:02:13 PDT 2012


Jay Gelisah <jay.gelisah at gmail.com> writes:

> I'm creating a GlobalVariable that contains a StructType that contains a
> Function. The function returns i32 and takes two i32's.
>
> Here is my code:
> GlobalVariable* retrieved = module->getGlobalVariable("myGV");
> ...
> Constant* result = ConstantExpr::getGetElementPtr(retrieved, indices);
>
> How do I get my Function back from the Constant* result?

You already have a pointer to the function pointer stored in `result'.

> I'd like to be able to run the function.

Use CallInst::Create for creating a CallInst. CallInst will gladly
accept a Value* or one of its derivatives as its argument, as far as it
has the correct type (see below). No need to cast.

> result->dump() shows the following:
> i32 (i32, i32)** getelementptr inbounds (%myStruct* @myGV, i32 0, i32 0)

Please note that you need to pass the result of the getelementptr
through a LoadInst because, as shown, getelementptr returns a pointer to
the data inside the struct or array.

Value *v = new LoadInst(result, "", theBasicBlock);
Function *myfn = cast<Function>(v);
<check that `myfn' is not null>

In general, for learning the C++ API it is a good idea to create a
sample of C/C++ code that does what your generated code should do and
pass it through Clang/llc to see the C++ API code. The online demo
available at http://llvm.org/demo/index.cgi is handy for that. In your
specific case, put there the code below, check the C++ radiobutton,
select the C++ API target and push the Compile button.

struct Foo {
  int dummy;
  double anotherDummy;
  int (*fn)(int, int);
};

int callIt(Foo foo) {
  return (*foo.fn)(1, 2);
}



More information about the llvm-dev mailing list