c++ - 使用 c++ api 将 c++ 回调函数转换为 llvm

标签 c++ callback llvm llvm-c++-api

我想使用 C++ API 将 C 回调函数转换为 llvm 函数。 我的示例 C++ 函数如下所示。

extern "C" void bindMe(int(*compare)(const int a))
{

    llvm::LLVMContext& context = llvm::getGlobalContext();
    llvm::Module *module = new llvm::Module("top", context);
    llvm::IRBuilder<> builder(context);

    //I want to create the corresponding llvm function here which is called compareLLVM

    llvm::BasicBlock *entry = llvm::BasicBlock::Create(context, "entrypoint", compareLLVM);
    builder.SetInsertPoint(entry);

    module->dump();

}

基本上我想将bindMe函数的参数(一个c回调函数)转换为相应的llvm函数。使用 API 可以实现类似的功能吗?

我将非常感谢任何想法。

谢谢

最佳答案

compare 是指向函数编译代码所在位置的指针。那里没有源代码 - 事实上,它甚至可能不是从 C 语言编译的 - 因此 LLVM 无法用它做太多事情,并且您无法将其转换为 LLVM Function 对象。

可以做的是插入对该函数的调用:从该compare指针创建一个LLVM Value,并将其转换为适当的值类型,然后使用该强制转换指针作为函数创建一个调用指令。使用 API 插入这样的调用将类似于:

Type* longType = Type::getInt64Ty(context);
Type* intType = Type::getInt32Ty(context);
Type* funcType = FunctionType::get(intType, intType, false);

// Insert the 'compare' value:
Constant* ptrInt = ConstantInt::get(longType, (long long)compare); 

// Convert it to the correct type:
Value* ptr = ConstantExpr::getIntToPtr(ptrInt, funcType->getPointerTo());

// Insert function call, assuming 'num' is an int32-typed
// value you have already created:
CallInst* call = builder.CreateCall(ptr, num);

关于c++ - 使用 c++ api 将 c++ 回调函数转换为 llvm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17540649/

相关文章:

c++ - 使用(模板化的)删除函数重载来防止通常的算术转换

用于lib和可执行文件的c++ CMake项目结构

javascript - Javascript 中的 .bind(this) 与 var context = this - 最好的风格是什么?

llvm - 在 xvcg 中显示来自 llvm 的 CFG

c++ - boost Asio : waiting until thread_group has processed all posted tasks?

c++ - 您可以从 MS SQL Server 调用 C++ 应用程序吗?

javascript - 如何将回调代码转换为 ES6 中的 promise

php - array_map - "Argument passed must be of the type array, string given"错误

javascript - 如何将 LLVM IR br 转换回 while 循环

c++ - 如何使用 clang::TreeTransform?