Reputation: 404
I want to create LLVM ArrayType on stack so I wanted to use AllocaInst (Type *Ty, Value *ArraySize=nullptr, const Twine &Name="", Instruction *InsertBefore=nullptr)
. The problem is I don't understand this interface. I guessed that Ty
will be something like ArrayType::get(I.getType(), 4)
, but what should I give for ArraySize
. Furthermore, it requires Value*
, so it confused me a lot.
Either I misunderstood llvm alloc or I need to provide a llvm constant as a value for array size. If I have to give the constant, isn't it little bit redundant since ArrayType
contains the numElement as an information.
As an example line of code, the way I am trying to:
AllocaInst* arr_alloc = new AllocaInst(ArrayType::get(I.getType(), num)
/*, What is this parameter for?*/,
"",
funcEntry.getFirstInsertionPt());
Upvotes: 6
Views: 8950
Reputation: 1573
I is the type of the array elements such as:
Type* I = IntegerType::getInt32Ty(module->getContext());
Then you can create an ArrayType of num
elements:
ArrayType* arrayType = ArrayType::get(I, num);
This type can be used in an AllocInstr as following:
AllocaInst* arr_alloc = new AllocaInst(
arrayType, "myarray" , funcEntry
// ~~~~~~~~~
// -> custom variable name in the LLVM IR which can be omitted,
// LLVM will create a random name then such as %2.
);
This example will yield the following LLVM IR instruction:
%myarray = alloca [10 x i32]
EDIT Also it seems like you are allowed to pass a variable array size to the AllocInstr as following:
Type* I = IntegerType::getInt32Ty(module->getContext());
auto num = 10;
auto funcEntry = label_entry;
ArrayType* arrayType = ArrayType::get(I, num);
AllocaInst* variable = new AllocaInst(
I, "array_size", funcEntry
);
new StoreInst(ConstantInt::get(I, APInt(32, 10)), variable, funcEntry);
auto load = new LoadInst(variable, "loader", funcEntry);
AllocaInst* arr_alloc = new AllocaInst(
I, load, "my_array", funcEntry
);
Upvotes: 6