LLVM  14.0.0git
IRReader.cpp
Go to the documentation of this file.
1 //===---- IRReader.cpp - Reader for LLVM IR files -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
10 #include "llvm-c/IRReader.h"
11 #include "llvm/AsmParser/Parser.h"
13 #include "llvm/IR/LLVMContext.h"
14 #include "llvm/IR/Module.h"
16 #include "llvm/Support/SourceMgr.h"
17 #include "llvm/Support/Timer.h"
19 #include <system_error>
20 
21 using namespace llvm;
22 
23 namespace llvm {
24  extern bool TimePassesIsEnabled;
25 }
26 
27 const char TimeIRParsingGroupName[] = "irparse";
28 const char TimeIRParsingGroupDescription[] = "LLVM IR Parsing";
29 const char TimeIRParsingName[] = "parse";
30 const char TimeIRParsingDescription[] = "Parse IR";
31 
32 std::unique_ptr<Module>
33 llvm::getLazyIRModule(std::unique_ptr<MemoryBuffer> Buffer, SMDiagnostic &Err,
34  LLVMContext &Context, bool ShouldLazyLoadMetadata) {
35  if (isBitcode((const unsigned char *)Buffer->getBufferStart(),
36  (const unsigned char *)Buffer->getBufferEnd())) {
38  std::move(Buffer), Context, ShouldLazyLoadMetadata);
39  if (Error E = ModuleOrErr.takeError()) {
41  Err = SMDiagnostic(Buffer->getBufferIdentifier(), SourceMgr::DK_Error,
42  EIB.message());
43  });
44  return nullptr;
45  }
46  return std::move(ModuleOrErr.get());
47  }
48 
49  return parseAssembly(Buffer->getMemBufferRef(), Err, Context);
50 }
51 
52 std::unique_ptr<Module> llvm::getLazyIRFileModule(StringRef Filename,
53  SMDiagnostic &Err,
55  bool ShouldLazyLoadMetadata) {
58  if (std::error_code EC = FileOrErr.getError()) {
59  Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
60  "Could not open input file: " + EC.message());
61  return nullptr;
62  }
63 
64  return getLazyIRModule(std::move(FileOrErr.get()), Err, Context,
65  ShouldLazyLoadMetadata);
66 }
67 
68 std::unique_ptr<Module> llvm::parseIR(MemoryBufferRef Buffer, SMDiagnostic &Err,
70  DataLayoutCallbackTy DataLayoutCallback) {
74  if (isBitcode((const unsigned char *)Buffer.getBufferStart(),
75  (const unsigned char *)Buffer.getBufferEnd())) {
77  parseBitcodeFile(Buffer, Context, DataLayoutCallback);
78  if (Error E = ModuleOrErr.takeError()) {
81  EIB.message());
82  });
83  return nullptr;
84  }
85  return std::move(ModuleOrErr.get());
86  }
87 
88  return parseAssembly(Buffer, Err, Context, nullptr, DataLayoutCallback);
89 }
90 
91 std::unique_ptr<Module>
93  DataLayoutCallbackTy DataLayoutCallback) {
95  MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
96  if (std::error_code EC = FileOrErr.getError()) {
97  Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
98  "Could not open input file: " + EC.message());
99  return nullptr;
100  }
101 
102  return parseIR(FileOrErr.get()->getMemBufferRef(), Err, Context,
103  DataLayoutCallback);
104 }
105 
106 //===----------------------------------------------------------------------===//
107 // C API.
108 //===----------------------------------------------------------------------===//
109 
111  LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM,
112  char **OutMessage) {
113  SMDiagnostic Diag;
114 
115  std::unique_ptr<MemoryBuffer> MB(unwrap(MemBuf));
116  *OutM =
117  wrap(parseIR(MB->getMemBufferRef(), Diag, *unwrap(ContextRef)).release());
118 
119  if(!*OutM) {
120  if (OutMessage) {
121  std::string buf;
122  raw_string_ostream os(buf);
123 
124  Diag.print(nullptr, os, false);
125  os.flush();
126 
127  *OutMessage = strdup(buf.c_str());
128  }
129  return 1;
130  }
131 
132  return 0;
133 }
llvm::getOwningLazyBitcodeModule
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.
Definition: BitcodeReader.cpp:6992
MemoryBuffer.h
llvm::parseIR
std::unique_ptr< Module > parseIR(MemoryBufferRef Buffer, SMDiagnostic &Err, LLVMContext &Context, DataLayoutCallbackTy DataLayoutCallback=[](StringRef) { return None;})
If the given MemoryBuffer holds a bitcode image, return a Module for it.
Definition: IRReader.cpp:68
llvm::MemoryBufferRef::getBufferStart
const char * getBufferStart() const
Definition: MemoryBufferRef.h:35
llvm
---------------------— PointerInfo ------------------------------------—
Definition: AllocatorList.h:23
LLVMContextRef
struct LLVMOpaqueContext * LLVMContextRef
The top-level container for all LLVM global data.
Definition: Types.h:53
TimeIRParsingGroupDescription
const char TimeIRParsingGroupDescription[]
Definition: IRReader.cpp:28
Parser.h
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:625
llvm::AtomicOrderingCABI::release
@ release
llvm::TimePassesIsEnabled
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
Definition: PassTimingInfo.cpp:37
Module.h
TimeIRParsingGroupName
const char TimeIRParsingGroupName[]
Definition: IRReader.cpp:27
T
#define T
Definition: Mips16ISelLowering.cpp:341
llvm::parseAssembly
std::unique_ptr< Module > parseAssembly(MemoryBufferRef F, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots=nullptr, DataLayoutCallbackTy DataLayoutCallback=[](StringRef) { return None;})
parseAssemblyFile and parseAssemblyString are wrappers around this function.
Definition: Parser.cpp:48
llvm::Expected
Tagged union holding either a T or a Error.
Definition: APFloat.h:42
llvm::MemoryBufferRef
Definition: MemoryBufferRef.h:22
Context
LLVMContext & Context
Definition: NVVMIntrRange.cpp:66
IRReader.h
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::SMDiagnostic
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:251
llvm::ErrorOr::getError
std::error_code getError() const
Definition: ErrorOr.h:153
llvm::getLazyIRFileModule
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:52
TimeIRParsingDescription
const char TimeIRParsingDescription[]
Definition: IRReader.cpp:30
llvm::unwrap
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:256
llvm::raw_ostream::flush
void flush()
Definition: raw_ostream.h:186
llvm::isBitcode
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,...
Definition: BitcodeReader.h:225
llvm::ErrorInfoBase
Base class for error info classes.
Definition: Error.h:48
SourceMgr.h
llvm::ErrorInfoBase::message
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:56
llvm::function_ref
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:168
Timer.h
llvm::SMDiagnostic::print
void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true) const
Definition: SourceMgr.cpp:473
llvm::MemoryBufferRef::getBufferEnd
const char * getBufferEnd() const
Definition: MemoryBufferRef.h:36
llvm::parseBitcodeFile
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, DataLayoutCallbackTy DataLayoutCallback=[](StringRef) { return None;})
Read the specified bitcode file, returning the module.
Definition: BitcodeReader.cpp:7011
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::LLVMContext
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
llvm::MemoryBuffer::getFileOrSTDIN
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
Definition: MemoryBuffer.cpp:144
llvm::wrap
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:251
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
llvm::Expected::get
reference get()
Returns a reference to the stored T value.
Definition: Error.h:569
LLVMBool
int LLVMBool
Definition: Types.h:28
llvm::parseIRFile
std::unique_ptr< Module > parseIRFile(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, DataLayoutCallbackTy DataLayoutCallback=[](StringRef) { return None;})
If the given file holds a bitcode image, return a Module for it.
Definition: IRReader.cpp:92
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
llvm::NamedRegionTimer
This class is basically a combination of TimeRegion and Timer.
Definition: Timer.h:166
llvm::SourceMgr::DK_Error
@ DK_Error
Definition: SourceMgr.h:34
llvm::Expected::takeError
Error takeError()
Take ownership of the stored error.
Definition: Error.h:589
llvm::ErrorOr::get
reference get()
Definition: ErrorOr.h:150
llvm::ErrorOr
Represents either an error or a value T.
Definition: ErrorOr.h:56
IRReader.h
llvm::MemoryBufferRef::getBufferIdentifier
StringRef getBufferIdentifier() const
Definition: MemoryBufferRef.h:33
LLVMMemoryBufferRef
struct LLVMOpaqueMemoryBuffer * LLVMMemoryBufferRef
LLVM uses a polymorphic type hierarchy which C cannot represent, therefore parameters must be passed ...
Definition: Types.h:48
LLVMParseIRInContext
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:110
LLVMContext.h
llvm::getLazyIRModule
std::unique_ptr< Module > getLazyIRModule(std::unique_ptr< MemoryBuffer > Buffer, SMDiagnostic &Err, LLVMContext &Context, bool ShouldLazyLoadMetadata=false)
If the given MemoryBuffer holds a bitcode image, return a Module for it which does lazy deserializati...
Definition: IRReader.cpp:33
BitcodeReader.h
raw_ostream.h
llvm::handleAllErrors
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:958
TimeIRParsingName
const char TimeIRParsingName[]
Definition: IRReader.cpp:29
LLVMModuleRef
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition: Types.h:61