rgaillard
rgaillard

Reputation: 87

Size of types in LLVM

We are currently building a compiler in Java that uses LLVM as intermediate code representation. We use several types and we need to allocate memory for them, using malloc for instance.

I would like to know how to compute the size that elements will need in memory: pointers, structures, ...

I know that we can use DataLayout if we use the LLVM API, but unfortunately we don't use it and we generate LLVM code "by hand" (mainly because we were not able to find a decent and easy to use Java binding).

So we are trying to determine how to compute the size of (complex) types, depending on the architecture the compiler will be executed on.

Right now, we just check if we are on a 64-bit architecture or not, to determine the size of the pointers (4 or 8 bytes). We guess the size of structures by simply adding the sizes of their elements, but it seems that it is not correct (alignment should be taken into account, I guess).

Could you help me to find a way to solve this problem?

Thank you!

Upvotes: 0

Views: 586

Answers (1)

Colin LeMahieu
Colin LeMahieu

Reputation: 618

A way I've done this is by making a pointer to the type you're trying to size. Then use getelementpointer to get a pointer to element 1 and element 0. Subtract the pointer to element 0 from the pointer to element 1 and this will be the size. When this gets lowered to the padded sizes by the backend it should get constant folded and optimized to a single constant.

Upvotes: 1

Related Questions