[LLVMdev] allocating an array
Bill Wendling
isanbard at gmail.com
Wed Jul 16 11:19:30 PDT 2008
On Wed, Jul 16, 2008 at 11:07 AM, HyperQuantum <hyperquantum at gmail.com> wrote:
> How can I allocate an array with a size that is not known at compile time?
>
> The language reference says that the array size must be a constant
> integer value. It also says that variable sized arrays are represented
> by using zero as the number of elements. Obviously I cannot use zero
> in the array type when it is allocated. llvm-gcc seems to use a
> pointer type instead of an array type, so compiling a simple C program
> that uses an array with a runtime size and looking at the resulting
> bitcode didn't provide an answer to my question.
>
Do you mean a variable length array (as in C99) or something else?
LLVM will convert VLAs into an "alloca":
int foo(int X) {
int a[X];
...
}
define i32 @foo(i32 %X) nounwind {
entry:
%tmp23 = alloca i32, i32 %X ; <i32*> [#uses=2]
...
}
If you are doing the zero-sized array hack, then you'll have to call
malloc on it anyway. Something like:
struct a {
char c;
int d[0];
};
And then in your program do something like this:
void bar(int z) {
struct a *fnord = malloc(sizeof(struct a) + z * sizeof(int));
...
}
LLVM will generate the obvious code for that.
-bw
More information about the llvm-dev
mailing list