我试图在LLVM中使用函数的前向声明,但我做不到…这样做的原因是这个错误:
错误:对类型错误的函数'f'的前向引用无效!"
现在我正在尝试使用以下代码:
std::vector<Type *> args_type = f->get_args_type();
Module* mod = get_module();
std::string struct_name("struct.");
struct_name.append(f->get_name());
Type* StructTy = mod->getTypeByName(struct_name);
if (!StructTy) {
StructTy = Type::getVoidTy(getGlobalContext());
}
FunctionType *ftype = FunctionType::get(StructTy, args_type, false);
//Function *func = Function::Create(ftype, GlobalValue::InternalLinkage, f->get_name(), get_module());
Constant* c = mod->getOrInsertFunction(f->get_name(), ftype);
Function *func = cast<Function>(c);
但当我生成代码时,它不会显示在IR中。当我再次使用上面显示的相同代码创建函数时,它就工作了。我想知道这是否是因为我在开始在函数中插入东西之后立即插入了BasicBlock。
现在我的红外就是这样
define internal void @main() {
entry:
...
}
define internal %struct.f @f(i32* %x) {
entry:
...
}
我相信在@main函数之前放一个declare %struct.f @f(i32*)
会解决这个问题,但我不知道如何做到…
摘要:我只想在文件顶部创建一个declare
,这样我就可以稍后使用define
,并开始插入函数
好吧,LLVM似乎是"自动"完成的。
当我再次运行代码时,我刚刚意识到函数改变了它们的顺序。因此,如果您之前创建了一个函数,即使您没有插入任何代码(主体),它也会创建原型并等待对主体的任何进一步声明,只要您使用Module类的getOrInsert()
方法引用该函数即可。
我不知道这是正确的答案还是清楚的答案,但它解决了我的问题。。。