gpt4 book ai didi

c++ - LLVM 将函数调用插入另一个函数

转载 作者:行者123 更新时间:2023-11-30 03:16:41 24 4
gpt4 key购买 nike

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

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
}

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

最佳答案

随时从这里获取灵感

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

关于c++ - LLVM 将函数调用插入另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com