[LLVMdev] Instantiating modules from .bc files

Gordon Henriksen gordonhenriksen at mac.com
Wed Dec 26 15:33:16 PST 2007

Hi Danny,

On 2007-12-26, at 15:39, Danny wrote:

> I've noticed that the BitcodeReader appears to be an internal  
> module, but the BitstreamReader is public. Should I be using the  
> BitstreamReader? If so how.

The generic BitstreamReader class is public because it's used in other  
projects, including clang, to serialize data structures other than  
LLVM IR. The coding of the LLVM IR within the bitstream are private to  
the reader and writer modules. The functions exposed in ReaderWriter.h  
are the public interface to that functionality.

> I tried to get a module out of a file that I'd read in to it using  
> this code:
> MemoryBuffer* memBuf = MemoryBuffer::getFile(filename, sizeof
> filename, &errStr);
> printf("errStr: %s\n", errStr.c_str());
> BitcodeReader::BitcodeReader bcReader(memBuf);
> Module* Mod = bcReader.materializeModule(&errInfo);
> printf("errInfo: %s\n", errInfo.c_str());
> verifyModule(*Mod, PrintMessageAction);
> The errStr and the errInfo strings were empty, but I got a crash on  
> the verifyModule call.

Try this:

#include "llvm/Bitcode/ReaderWriter.h"


std::string &Message;
llvm::Module* Mod = llvm::ParseBitcodeFile(MemBuf, &Message);
if (!Mod) {
   // Message contains an error message.
   std::cerr << "error reading bitcode: " << Message << "\n";
   exit(1);  // Don't segfault!

// Okay, Mod is valid.

delete Mod;

Also note that the primary error indicator is not the string, but the  
return pointer, so you should always check that (not the error string)  
and stop if it's null in order to avoid segfaulting.

— Gordon

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20071226/0eb7bf1a/attachment.html>

More information about the llvm-dev mailing list