【问题标题】:LLVM Insert function call into another functionLLVM 将函数调用插入另一个函数
【发布时间】:2019-05-12 11:59:41
【问题描述】:

我试图在主函数中插入函数调用,所以当我运行生成的二进制文件时,函数将自动执行。由于我试图“编译”的语言看起来像“脚本”语言:

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

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

其中 writeln 是默认可用的函数,在执行二进制文件后,我希望看到 7 8 9。有没有办法在 main 函数的 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 文件并在之后编译它是可行的,但我想在我的代码的 codegen 部分中进行。

编辑

我现在生成的是

define double @__anon_expr() {
entry:
  %main = call double @writeln(double 3.000000e+00)
  ret double %main
}

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

所以当我执行二进制时 - 什么都没有发生

【问题讨论】:

  • 这和c++有什么关系?
  • @super 我正在用 C++ 编写 llvm 的前端
  • 不太清楚您要做什么。如果它是你生成的 IR,你可以做任何你喜欢的事情。如果您想修改一些现有的 IR - 这可能不是您应该做的。如果您仍然坚持,那么只需编写一个函数传递并使用opt 运行它。
  • @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 } ``` 所以什么都不执行

标签: c++ llvm


【解决方案1】:

随时从这里获取您的灵感

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多