在LLVM传递中添加简单的printf

时间:2018-03-29 14:14:25

标签: llvm llvm-clang

我试图通过LLVM传递将printf调用插入程序。 printf函数应该只打印" test"。我使用了getOrInsertFunction来获取printf函数。之后我尝试用CreateCall创建方法。可悲的是,我遇到了分段错误。任何人都可以为我指出错误吗?

// Declaring some variables 
static LLVMContext context;
Module* module = F.getParent();
IRBuilder<> builder(call_inst);
Type *intType = Type::getInt32Ty(context);


// Declare C standard library printf 
std::vector<Type *> printfArgsTypes({Type::getInt8PtrTy(context)});
FunctionType *printfType = FunctionType::get(intType, printfArgsTypes, true);
Constant *printfFunc = module->getOrInsertFunction("printf", printfType);


// The format string for the printf function, declared as a global literal
Value *str = builder.CreateGlobalStringPtr("test\n", "str");

std::vector<Value *> argsV({str});
builder.CreateCall(printfFunc, argsV, "calltmp");

LLVM调用的部分错误消息:

void llvm::CallInst::init(llvm::FunctionType*, llvm::Value*, llvm::ArrayRef<llvm::Value*>, llvm::ArrayRef<llvm::OperandBundleDefT<llvm::Value*> >, const llvm::Twine&): Assertion `(i >= FTy->getNumParams() || FTy->getParamType(i) == Args[i]->getType()) && "Calling a function with a bad signature!"' failed. 

1 个答案:

答案 0 :(得分:1)

基于Ismail Badawi对问题的评论,以下代码对我有用:

Module* module = F.getParent();
LLVMContext & context = module->getContext();
IRBuilder<> builder(call_inst);
// The rest is unchanged

请注意从模块获取上下文的方式(而不是声明为静态)