blob: fb87cbd8bf878045ddf764f01c063fe4d76de65f [file] [log] [blame]
Chandler Carruth7fc162f2013-03-26 02:25:37 +00001//===---- IRReader.cpp - Reader for LLVM IR files -------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/IRReader/IRReader.h"
11#include "llvm/ADT/OwningPtr.h"
12#include "llvm/Assembly/Parser.h"
13#include "llvm/Bitcode/ReaderWriter.h"
14#include "llvm/Support/MemoryBuffer.h"
15#include "llvm/Support/SourceMgr.h"
16#include "llvm/Support/system_error.h"
17
18using namespace llvm;
19
20Module *llvm::getLazyIRModule(MemoryBuffer *Buffer, SMDiagnostic &Err,
Eli Bendersky19801a62013-04-01 19:47:56 +000021 LLVMContext &Context) {
Chandler Carruth7fc162f2013-03-26 02:25:37 +000022 if (isBitcode((const unsigned char *)Buffer->getBufferStart(),
23 (const unsigned char *)Buffer->getBufferEnd())) {
24 std::string ErrMsg;
25 Module *M = getLazyBitcodeModule(Buffer, Context, &ErrMsg);
26 if (M == 0) {
27 Err = SMDiagnostic(Buffer->getBufferIdentifier(), SourceMgr::DK_Error,
28 ErrMsg);
29 // ParseBitcodeFile does not take ownership of the Buffer in the
30 // case of an error.
31 delete Buffer;
32 }
33 return M;
34 }
35
36 return ParseAssembly(Buffer, 0, Err, Context);
37}
38
39Module *llvm::getLazyIRFileModule(const std::string &Filename, SMDiagnostic &Err,
Eli Bendersky19801a62013-04-01 19:47:56 +000040 LLVMContext &Context) {
Chandler Carruth7fc162f2013-03-26 02:25:37 +000041 OwningPtr<MemoryBuffer> File;
42 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename.c_str(), File)) {
43 Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
44 "Could not open input file: " + ec.message());
45 return 0;
46 }
47
48 return getLazyIRModule(File.take(), Err, Context);
49}
50
51Module *llvm::ParseIR(MemoryBuffer *Buffer, SMDiagnostic &Err,
52 LLVMContext &Context) {
53 if (isBitcode((const unsigned char *)Buffer->getBufferStart(),
54 (const unsigned char *)Buffer->getBufferEnd())) {
55 std::string ErrMsg;
56 Module *M = ParseBitcodeFile(Buffer, Context, &ErrMsg);
57 if (M == 0)
58 Err = SMDiagnostic(Buffer->getBufferIdentifier(), SourceMgr::DK_Error,
59 ErrMsg);
60 // ParseBitcodeFile does not take ownership of the Buffer.
61 delete Buffer;
62 return M;
63 }
64
65 return ParseAssembly(Buffer, 0, Err, Context);
66}
67
68Module *llvm::ParseIRFile(const std::string &Filename, SMDiagnostic &Err,
69 LLVMContext &Context) {
70 OwningPtr<MemoryBuffer> File;
71 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename.c_str(), File)) {
72 Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
73 "Could not open input file: " + ec.message());
74 return 0;
75 }
76
77 return ParseIR(File.take(), Err, Context);
78}