LLVM向另一个函数中插入函数调用

4

我正在尝试在主函数中插入函数调用,以便运行生成的二进制文件时函数会自动执行。由于我正在尝试“编译”的语言看起来像是一种“脚本”语言:

function foo () begin 3 end;
function boo () begin 4 end;

writeln (foo()+boo()) ;
writeln (8) ;
writeln (9) ;

writeln是默认可用的函数,执行二进制文件后,我期望看到7 8 9。有没有一种方法可以在主函数的return语句之前插入最后一个函数调用? 目前我的代码是

define i32 @main() {
entry:
  ret i32 0
}

我希望你能为我提供类似以下这样的内容:

define i32 @main() {
entry:
  %calltmp = call double @writeln(double 7.000000e+00)
  %calltmp = call double @writeln(double 8.000000e+00)
  %calltmp = call double @writeln(double 9.000000e+00)
  ret i32 0
}

手动编辑IR文件并编译成功了,但我想在代码生成部分自动完成这个过程。
编辑
目前我生成的是:
define double @__anon_expr() {
entry:
  %main = call double @writeln(double 3.000000e+00)
  ret double %main
}

define i32 @main() {
entry:
  ret i32 0
}

当我执行二进制文件时,什么都没有发生。


1
这与 c++ 有什么关系? - super
@super 我正在用C++编写LLVM的前端。 - John Galt
不太清楚你想做什么。如果你正在生成IR,那么你可以随心所欲地做任何事情。如果你想修改一些现有的IR——那可能不是你应该做的事情。如果你还是坚持要做,那就写一个函数传递并在opt中运行它。 - SK-logic
@SK-logic 我正在生成IR,但我不知道如何在主函数中添加函数调用。现在看起来像这样:define double @__anon_expr() { entry: %main = call double @writeln(double 3.000000e+00) ret double %main } define i32 @main() { entry: ret i32 0 }所以没有任何执行。 - John Galt
1个回答

6

随意从这里获取灵感

Type * returnType = Type::getInt32Ty(TheContext);
std::vector<Type *> argTypes;
FunctionType * functionType = FunctionType::get(returnType, argTypes, false);
Function * function = Function::Create(functionType, Function::ExternalLinkage, "main", TheModule.get());

    BasicBlock * BB = BasicBlock::Create(TheContext, "entry", function);
    Builder.SetInsertPoint(BB);
    vector<Value *> args;
    args.push_back(ConstantFP::get(TheContext, APFloat(4.0)));
    Builder.CreateCall(getFunction("writeln"), args, "call");
    Value * returnValue = Builder.getInt32(0);
    Builder.CreateRet(returnValue);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接