如何使用 AllocaInst 创建 LLVM 数组类型

How to create LLVM Array type using AllocaInst?

本文关键字:数组 类型 LLVM 创建 何使用 AllocaInst      更新时间:2023-10-16

我想在堆栈上创建LLVM ArrayType,所以我想使用AllocaInst (Type *Ty, Value *ArraySize=nullptr, const Twine &Name="", Instruction *InsertBefore=nullptr)。问题是我不明白这个界面。我猜Ty会像ArrayType::get(I.getType(), 4)一样,但我应该为ArraySize付出什么.此外,它需要Value*,所以它让我很困惑。

要么

我误解了 llvm 分配,要么我需要提供一个 llvm 常量作为数组大小的值。如果我必须给出常量,是不是有点多余,因为ArrayType包含 numElement 作为信息。

作为示例代码行,我尝试的方式:

AllocaInst* arr_alloc = new AllocaInst(ArrayType::get(I.getType(), num)
                                       /*, What is this parameter for?*/,
                                       "",
                                       funcEntry.getFirstInsertionPt());

I 是数组元素的类型,例如:

Type* I = IntegerType::getInt32Ty(module->getContext());

然后,您可以创建num元素的数组类型:

ArrayType* arrayType = ArrayType::get(I, num);

此类型可以在 AllocInstr 中使用,如下所示:

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.
);

此示例将生成以下 LLVM IR 指令:

%myarray = alloca [10 x i32]

编辑此外,似乎允许您将可变数组大小传递给 AllocInstr,如下所示:

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
);