LLVM  7.0.0svn
IRReader.cpp
Go to the documentation of this file.
1 //===---- 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-c/IRReader.h"
12 #include "llvm/AsmParser/Parser.h"
14 #include "llvm/IR/LLVMContext.h"
15 #include "llvm/IR/Module.h"
17 #include "llvm/Support/SourceMgr.h"
18 #include "llvm/Support/Timer.h"
20 #include <system_error>
21 
22 using namespace llvm;
23 
24 namespace llvm {
25  extern bool TimePassesIsEnabled;
26 }
27 
28 static const char *const TimeIRParsingGroupName = "irparse";
29 static const char *const TimeIRParsingGroupDescription = "LLVM IR Parsing";
30 static const char *const TimeIRParsingName = "parse";
31 static const char *const TimeIRParsingDescription = "Parse IR";
32 
33 static std::unique_ptr<Module>
34 getLazyIRModule(std::unique_ptr<MemoryBuffer> Buffer, SMDiagnostic &Err,
35  LLVMContext &Context, bool ShouldLazyLoadMetadata) {
36  if (isBitcode((const unsigned char *)Buffer->getBufferStart(),
37  (const unsigned char *)Buffer->getBufferEnd())) {
39  std::move(Buffer), Context, ShouldLazyLoadMetadata);
40  if (Error E = ModuleOrErr.takeError()) {
41  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
42  Err = SMDiagnostic(Buffer->getBufferIdentifier(), SourceMgr::DK_Error,
43  EIB.message());
44  });
45  return nullptr;
46  }
47  return std::move(ModuleOrErr.get());
48  }
49 
50  return parseAssembly(Buffer->getMemBufferRef(), Err, Context);
51 }
52 
53 std::unique_ptr<Module> llvm::getLazyIRFileModule(StringRef Filename,
54  SMDiagnostic &Err,
56  bool ShouldLazyLoadMetadata) {
59  if (std::error_code EC = FileOrErr.getError()) {
60  Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
61  "Could not open input file: " + EC.message());
62  return nullptr;
63  }
64 
65  return getLazyIRModule(std::move(FileOrErr.get()), Err, Context,
66  ShouldLazyLoadMetadata);
67 }
68 
69 std::unique_ptr<Module> llvm::parseIR(MemoryBufferRef Buffer, SMDiagnostic &Err,
71  bool UpgradeDebugInfo,
72  StringRef DataLayoutString) {
73  NamedRegionTimer T(TimeIRParsingName, TimeIRParsingDescription,
74  TimeIRParsingGroupName, TimeIRParsingGroupDescription,
76  if (isBitcode((const unsigned char *)Buffer.getBufferStart(),
77  (const unsigned char *)Buffer.getBufferEnd())) {
79  parseBitcodeFile(Buffer, Context);
80  if (Error E = ModuleOrErr.takeError()) {
81  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
83  EIB.message());
84  });
85  return nullptr;
86  }
87  if (!DataLayoutString.empty())
88  ModuleOrErr.get()->setDataLayout(DataLayoutString);
89  return std::move(ModuleOrErr.get());
90  }
91 
92  return parseAssembly(Buffer, Err, Context, nullptr, UpgradeDebugInfo,
93  DataLayoutString);
94 }
95 
96 std::unique_ptr<Module> llvm::parseIRFile(StringRef Filename, SMDiagnostic &Err,
98  bool UpgradeDebugInfo,
99  StringRef DataLayoutString) {
102  if (std::error_code EC = FileOrErr.getError()) {
103  Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
104  "Could not open input file: " + EC.message());
105  return nullptr;
106  }
107 
108  return parseIR(FileOrErr.get()->getMemBufferRef(), Err, Context,
109  UpgradeDebugInfo, DataLayoutString);
110 }
111 
112 //===----------------------------------------------------------------------===//
113 // C API.
114 //===----------------------------------------------------------------------===//
115 
117  LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM,
118  char **OutMessage) {
119  SMDiagnostic Diag;
120 
121  std::unique_ptr<MemoryBuffer> MB(unwrap(MemBuf));
122  *OutM =
123  wrap(parseIR(MB->getMemBufferRef(), Diag, *unwrap(ContextRef)).release());
124 
125  if(!*OutM) {
126  if (OutMessage) {
127  std::string buf;
128  raw_string_ostream os(buf);
129 
130  Diag.print(nullptr, os, false);
131  os.flush();
132 
133  *OutMessage = strdup(buf.c_str());
134  }
135  return 1;
136  }
137 
138  return 0;
139 }
std::unique_ptr< Module > parseIR(MemoryBufferRef Buffer, SMDiagnostic &Err, LLVMContext &Context, bool UpgradeDebugInfo=true, StringRef DataLayoutString="")
If the given MemoryBuffer holds a bitcode image, return a Module for it.
Definition: IRReader.cpp:69
static const char *const TimeIRParsingGroupDescription
Definition: IRReader.cpp:29
Represents either an error or a value T.
Definition: ErrorOr.h:69
LLVMContext & Context
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition: Types.h:62
void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true) const
Definition: SourceMgr.cpp:368
const char * getBufferEnd() const
Definition: MemoryBuffer.h:282
struct LLVMOpaqueMemoryBuffer * LLVMMemoryBufferRef
LLVM uses a polymorphic type hierarchy which C cannot represent, therefore parameters must be passed ...
Definition: Types.h:49
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:55
Error takeError()
Take ownership of the stored error.
Definition: Error.h:537
Base class for error info classes.
Definition: Error.h:47
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:194
This class is basically a combination of TimeRegion and Timer.
Definition: Timer.h:160
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
#define T
struct LLVMOpaqueContext * LLVMContextRef
The top-level container for all LLVM global data.
Definition: Types.h:54
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
std::unique_ptr< Module > parseAssembly(MemoryBufferRef F, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots=nullptr, bool UpgradeDebugInfo=true, StringRef DataLayoutString="")
parseAssemblyFile and parseAssemblyString are wrappers around this function.
Definition: Parser.cpp:38
static const char *const TimeIRParsingName
Definition: IRReader.cpp:30
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::error_code getError() const
Definition: ErrorOr.h:172
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
int LLVMBool
Definition: Types.h:29
std::unique_ptr< Module > getLazyIRFileModule(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, bool ShouldLazyLoadMetadata=false)
If the given file holds a bitcode image, return a Module for it which does lazy deserialization of fu...
Definition: IRReader.cpp:53
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:889
Module.h This file contains the declarations for the Module class.
bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcode - Return true if the given bytes are the magic bytes for LLVM IR bitcode, either with or without a wrapper.
LLVMBool LLVMParseIRInContext(LLVMContextRef ContextRef, LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM, char **OutMessage)
Read LLVM IR from a memory buffer and convert it into an in-memory Module object. ...
Definition: IRReader.cpp:116
reference get()
Returns a reference to the stored T value.
Definition: Error.h:517
StringRef getBufferIdentifier() const
Definition: MemoryBuffer.h:279
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:189
std::unique_ptr< Module > parseIRFile(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, bool UpgradeDebugInfo=true, StringRef DataLayoutString="")
If the given file holds a bitcode image, return a Module for it.
Definition: IRReader.cpp:96
static const char *const TimeIRParsingGroupName
Definition: IRReader.cpp:28
Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful...
const char * getBufferStart() const
Definition: MemoryBuffer.h:281
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:467
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
Definition: IRReader.cpp:25
static const char *const TimeIRParsingDescription
Definition: IRReader.cpp:31
static std::unique_ptr< Module > getLazyIRModule(std::unique_ptr< MemoryBuffer > Buffer, SMDiagnostic &Err, LLVMContext &Context, bool ShouldLazyLoadMetadata)
Definition: IRReader.cpp:34
reference get()
Definition: ErrorOr.h:169
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:260