如何从ifstream加载LLVM bitcode文件?

Jar*_*ock 5 c++ iostream llvm

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

感兴趣的bitcode来自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;
}
Run Code Online (Sandbox Code Playgroud)

当下面的程序试图在运行时加载它时,它崩溃在里面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;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用注释中提到的命令行来构建LLVM v3.4.

知道我做错了什么吗?

Jar*_*ock 6

有两个问题:

  1. 需要的生命周期LLVMContext比 的生命周期更长久Module。否则,Module将引用LLVMContext不再存在的 a。
  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;
}
Run Code Online (Sandbox Code Playgroud)


vPr*_*tor 5

一种可能的解决方案是将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;
}
Run Code Online (Sandbox Code Playgroud)