从ExecutionEngine调用C/C ++函数 [英] Call C/C++ functions from the ExecutionEngine

查看:73
本文介绍了从ExecutionEngine调用C/C ++函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习llvm,并想对我的想法做一个概念证明.

I am learning llvm and wanted to do a proof of concept of an idea I have.

基本上,我想拆分我的编译器和运行时.编译器将提供一个.bc,运行时将通过ParseBitcodeFile加载它,并使用ExecutionEngine来运行它.这部分正在工作.

Basically, I want to split my compiler and my runtime. The compiler would give a .bc and the runtime would load it via ParseBitcodeFile and use the ExecutionEngine to run it. This part is working.

现在,为了轻松进行系统调用,我希望能够在我的运行时C/C ++函数中实现所有系统调用(文件io,stdout打印等).我的问题是,如何从我的玩具编译器的代码中调用这些函数,该玩具编译器由llvm在不同的步骤中进行编译,并允许它们在执行时使用.

Now, to make system calls easily, I want to be able to implement in my runtime C/C++ functions which do all the system calls (file io, stdout printing, etc). My question is, how could I call these functions from the code from my toy compiler, which is compiled in a different step by llvm, and allow it to be used when executed.

推荐答案

好消息:使用JIT ExecutionEngine时,这将正常工作.当JIT-er找到IR本身未找到的IR使用的外部符号时,它会在JIT-ing过程本身中查找,因此可以调用宿主程序中可见的任何符号.

Good news: when using the JIT ExecutionEngine, this will just work. When the JIT-er finds an external symbol used by the IR which is not found in the IR itself, it looks in the JIT-ing process itself, so any symbols visible from your host program can be called.

在LLVM教程的第4部分第4部分中直接对此进行了解释:

This is explained directly in part 4 of the LLVM tutorial:

哇,准时制如何知道罪恶和cos?答案是 出奇的简单:在此示例中,JIT开始执行 函数并转到函数调用.它意识到该功能是 尚未JIT编译并调用了标准的例程集以 解决功能.在这种情况下,没有为 函数,因此JIT最终在 万花筒过程本身.由于罪"是在JIT的内部定义的 地址空间,它只是修补模块中的调用以调用 libm版本的sin直接.

Whoa, how does the JIT know about sin and cos? The answer is surprisingly simple: in this example, the JIT started execution of a function and got to a function call. It realized that the function was not yet JIT compiled and invoked the standard set of routines to resolve the function. In this case, there is no body defined for the function, so the JIT ended up calling "dlsym("sin")" on the Kaleidoscope process itself. Since "sin" is defined within the JIT’s address space, it simply patches up calls in the module to call the libm version of sin directly.

有关gory的详细信息,请参见lib/ExecutionEngine/JIT/JIT.cpp-特别是DynamicLibrary的用法.

For the gory details look at lib/ExecutionEngine/JIT/JIT.cpp - in particular its usage of DynamicLibrary.

这篇关于从ExecutionEngine调用C/C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆