如何从ifstream加载LLVM比特代码文件

How to load LLVM bitcode file from an ifstream?

本文关键字:代码 文件 LLVM 加载 ifstream      更新时间:2023-10-16

我正在尝试加载运行时.bc文件中定义的LLVM模块,但遇到了snag。

hello.cpp生成了感兴趣的比特码:

// hello.cpp
// build with:
// clang-3.4 -c -emit-llvm hello.cpp -o hello.bc
#include <iostream>
void hello()
{
  std::cout << "Hello, world!" << std::endl;
}

当下面的程序尝试在运行时加载它时,它会在llvm::BitstreamCursor::Read()内崩溃:

// main.cpp
// build with:
// g++ main.cpp `llvm-config-3.4 --cppflags --ldflags --libs` -ldl -lpthread -lcurses
#include <llvm/IR/Module.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/raw_ostream.h>
#include <fstream>
#include <iostream>
llvm::Module *load_module(std::ifstream &stream)
{
  if(!stream)
  {
    std::cerr << "error after open stream" << std::endl;
    return 0;
  }
  // load bitcode
  std::string ir((std::istreambuf_iterator<char>(stream)), (std::istreambuf_iterator<char>()));
  // parse it
  using namespace llvm;
  LLVMContext context;
  SMDiagnostic error;
  Module *module = ParseIR(MemoryBuffer::getMemBuffer(StringRef(ir.c_str())), error, context);
  if(!module)
  {
    std::string what;
    llvm::raw_string_ostream os(what);
    error.print("error after ParseIR()", os);
    std::cerr << what;
  } // end if
  return module;
}
int main()
{
  std::ifstream stream("hello.bc", std::ios_base::binary);
  llvm::Module *m = load_module(stream);
  if(m)
  {
    m->dump();
  }
  return 0;
}

我使用评论中提到的命令行反对LLVM v3.4。

知道我做错了什么?

有两个问题:

  1. LLVMContext的寿命需要超过Module的寿命。否则Module将参考不再存在的LLVMContext
  2. StringRef指的是IR,应从包含IR的std::string构建,而不是零端的字符串。否则ParseIR将无法正确找到IR的末端。

这是load_module的更正版本:

llvm::Module *load_module(std::ifstream &stream, llvm::LLVMContext &context)
{
  if(!stream)
  {
    std::cerr << "error after open stream" << std::endl;
    return 0;
  }
  // load bitcode
  std::string ir((std::istreambuf_iterator<char>(stream)), (std::istreambuf_iterator<char>()));
  // parse it
  using namespace llvm;
  SMDiagnostic error;
  Module *module = ParseIR(MemoryBuffer::getMemBuffer(StringRef(ir)), error, context);
  if(!module)
  {
    std::string what;
    llvm::raw_string_ostream os(what);
    error.print("error after ParseIR()", os);
    std::cerr << what;
  } // end if
  return module;
}

一种可能的解决方案是用

替换ParseIR()调用

ParseIRFile("hello.bc", error, getGlobalContext())

这样做也使代码变得更加简单,因为您可以跳过手动加载比特码的部分。

以下内容足以获得模块的转储(您应该添加一些错误处理)

#include <llvm/IR/Module.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/Support/SourceMgr.h>
using namespace llvm;
int main()
{
  LLVMContext context;
  SMDiagnostic error;
  Module *m = ParseIRFile("hello.bc", error, context);
  if(m)
  {
    m->dump();
  } 
  return 0;
}