在 LLVM 中创建一个包含指向自身的指针的结构

Tho*_*ski 3 llvm llvm-c++-api

我目前正在使用 LLVM 构建 JIT。structs我希望能够在我的 JIT IR 中使用一些 C 语言。其中之一具有以下布局:

struct myStruct {
    int depth;
    myStruct* parent;
}
Run Code Online (Sandbox Code Playgroud)

当使用 进行编译clang和使用时-S -emit-llvm,我得到以下结果,这似乎绝对合理:

type myStruct = { i32, myStruct* } 
Run Code Online (Sandbox Code Playgroud)

好吧。现在,如果我想使用 LLVM API 执行相同的操作,我不太确定应该如何执行。以下(预期)不起作用:

auto intType = IntegerType::get(context, 32); // 32 bits integer
Type* myStructPtrType = nullptr; // Pointer to myStruct

// The following crashes because myStructPtrType is null: 
auto myStructType = StructType::create(context, { intType, myStructPtrType }, "myStruct"); // myStruct

myStructPtrType = PointerType::get(myStructType, 0); // Initialise the pointer type now
Run Code Online (Sandbox Code Playgroud)

我真的不知道如何继续这里。欢迎任何建议。

Tho*_*ski 5

感谢@arnt 的评论,我能够回答这个问题。如果有人有相同的目标/问题。这个想法是首先创建一个不透明类型,然后获取该不透明类型的指针类型,然后使用 .set 聚合体(这是解决方案的关键)setBody

这是一些代码:

auto intType = IntegerType::get(context, 32); // 32 bits integer
auto myStructType = StructType::create(context, "myStruct"); // Create opaque type
auto myStructPtrType = PointerType::get(myStructType, 0); // Initialise the pointer type now
myStructType->setBody({ intType, myStructPtrType }, /* packed */ false); // Set the body of the aggregate
Run Code Online (Sandbox Code Playgroud)