1 //===-- BitReader.cpp -----------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm-c/BitReader.h"
11 #include "llvm-c/Core.h"
12 #include "llvm/Bitcode/ReaderWriter.h"
13 #include "llvm/IR/DiagnosticPrinter.h"
14 #include "llvm/IR/LLVMContext.h"
15 #include "llvm/IR/Module.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/Support/raw_ostream.h"
23 /* Builds a module from the bitcode in the specified memory buffer, returning a
24 reference to the module via the OutModule parameter. Returns 0 on success.
25 Optionally returns a human-readable error message via OutMessage. */
26 LLVMBool LLVMParseBitcode(LLVMMemoryBufferRef MemBuf,
27 LLVMModuleRef *OutModule, char **OutMessage) {
28 return LLVMParseBitcodeInContext(wrap(&getGlobalContext()), MemBuf, OutModule,
32 static void diagnosticHandler(const DiagnosticInfo &DI, void *C) {
33 auto *Message = reinterpret_cast<std::string *>(C);
34 raw_string_ostream Stream(*Message);
35 DiagnosticPrinterRawOStream DP(Stream);
39 LLVMBool LLVMParseBitcodeInContext(LLVMContextRef ContextRef,
40 LLVMMemoryBufferRef MemBuf,
41 LLVMModuleRef *OutModule,
43 MemoryBufferRef Buf = unwrap(MemBuf)->getMemBufferRef();
44 LLVMContext &Ctx = *unwrap(ContextRef);
46 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
47 Ctx.getDiagnosticHandler();
48 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
50 Ctx.setDiagnosticHandler(diagnosticHandler, &Message, true);
52 ErrorOr<std::unique_ptr<Module>> ModuleOrErr = parseBitcodeFile(Buf, Ctx);
54 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext, true);
56 if (ModuleOrErr.getError()) {
58 *OutMessage = strdup(Message.c_str());
59 *OutModule = wrap((Module*)nullptr);
63 *OutModule = wrap(ModuleOrErr.get().release());
67 /* Reads a module from the specified path, returning via the OutModule parameter
68 a module provider which performs lazy deserialization. Returns 0 on success.
69 Optionally returns a human-readable error message via OutMessage. */
70 LLVMBool LLVMGetBitcodeModuleInContext(LLVMContextRef ContextRef,
71 LLVMMemoryBufferRef MemBuf,
75 std::unique_ptr<MemoryBuffer> Owner(unwrap(MemBuf));
77 ErrorOr<std::unique_ptr<Module>> ModuleOrErr =
78 getLazyBitcodeModule(std::move(Owner), *unwrap(ContextRef));
81 if (std::error_code EC = ModuleOrErr.getError()) {
82 *OutM = wrap((Module *)nullptr);
84 *OutMessage = strdup(EC.message().c_str());
88 *OutM = wrap(ModuleOrErr.get().release());
94 LLVMBool LLVMGetBitcodeModule(LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM,
96 return LLVMGetBitcodeModuleInContext(LLVMGetGlobalContext(), MemBuf, OutM,