如果你的目标是运行 LLVM IR, 则不建议写入文件, 因为 LLVM 提供了 JIT 的方式直接从 C++ 运行. 后续会有相关文章链接放在此处.

首先, 我们必须有一个 LLVM Module 作为基础, 也就是生成 LLVM IR 的时候使用的 Module, 此处使用 theModule 作为例子.

查找 llvm/IR/Module.h 文件, 了解到 print 函数接受如下参数:
image.png

使用如下参数, 可以将结果输出到命令行, 即 stdout 或者 stderr.

/* llvm ir -> stdout */
theModule->print(llvm::outs(), nullptr);
/* llvm ir -> stderr */
// theModule -> print(llvm::errs(), nullptr);

使用如下代码, 可以将结果输出到文件 output.ll 中:

std::error_code EC;
llvm::raw_fd_ostream output_stream(
  "output.ll", /* file name */
  EC,
  llvm::sys::fs::OpenFlags::OF_None
);
if (EC) {
  std::cerr << "Can't open file output.ll; " << EC.message() << std::endl;
}

/* write to current_work_directory/output.ll */
theModule->print(output_stream, nullptr);

输出的文件打开后为人类可读代码, 可以使用 lli 工具执行, 在此我们使用 C++ 的 system 函数:

int lli_result = std::system("lli output.ll");

执行结果 0 代表 成功运行, 1 代表 运行错误.


unka_malloc
7 声望3 粉丝