LLVM  10.0.0svn
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 static const char *const TimeIRParsingGroupName = "irparse";
28 static const char *const TimeIRParsingGroupDescription = "LLVM IR Parsing";
29 static const char *const TimeIRParsingName = "parse";
30 static const char *const 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()) {
40  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
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  bool UpgradeDebugInfo,
71  StringRef DataLayoutString) {
72  NamedRegionTimer T(TimeIRParsingName, TimeIRParsingDescription,
73  TimeIRParsingGroupName, TimeIRParsingGroupDescription,
75  if (isBitcode((const unsigned char *)Buffer.getBufferStart(),
76  (const unsigned char *)Buffer.getBufferEnd())) {
78  parseBitcodeFile(Buffer, Context);
79  if (Error E = ModuleOrErr.takeError()) {
80  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
82  EIB.message());
83  });
84  return nullptr;
85  }
86  if (!DataLayoutString.empty())
87  ModuleOrErr.get()->setDataLayout(DataLayoutString);
88  return std::move(ModuleOrErr.get());
89  }
90 
91  return parseAssembly(Buffer, Err, Context, nullptr, UpgradeDebugInfo,
92  DataLayoutString);
93 }
94 
95 std::unique_ptr<Module> llvm::parseIRFile(StringRef Filename, SMDiagnostic &Err,
97  bool UpgradeDebugInfo,
98  StringRef DataLayoutString) {
101  if (std::error_code EC = FileOrErr.getError()) {
102  Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
103  "Could not open input file: " + EC.message());
104  return nullptr;
105  }
106 
107  return parseIR(FileOrErr.get()->getMemBufferRef(), Err, Context,
108  UpgradeDebugInfo, DataLayoutString);
109 }
110 
111 //===----------------------------------------------------------------------===//
112 // C API.
113 //===----------------------------------------------------------------------===//
114 
116  LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM,
117  char **OutMessage) {
118  SMDiagnostic Diag;
119 
120  std::unique_ptr<MemoryBuffer> MB(unwrap(MemBuf));
121  *OutM =
122  wrap(parseIR(MB->getMemBufferRef(), Diag, *unwrap(ContextRef)).release());
123 
124  if(!*OutM) {
125  if (OutMessage) {
126  std::string buf;
127  raw_string_ostream os(buf);
128 
129  Diag.print(nullptr, os, false);
130  os.flush();
131 
132  *OutMessage = strdup(buf.c_str());
133  }
134  return 1;
135  }
136 
137  return 0;
138 }
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:68
static const char *const TimeIRParsingGroupDescription
Definition: IRReader.cpp:28
Represents either an error or a value T.
Definition: ErrorOr.h:56
LLVMContext & Context
This class represents lattice values for constants.
Definition: AllocatorList.h:23
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:277
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:56
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
Error takeError()
Take ownership of the stored error.
Definition: Error.h:552
Base class for error info classes.
Definition: Error.h:48
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:204
This class is basically a combination of TimeRegion and Timer.
Definition: Timer.h:160
Tagged union holding either a T or a Error.
Definition: yaml2obj.h:21
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:140
struct LLVMOpaqueContext * LLVMContextRef
The top-level container for all LLVM global data.
Definition: Types.h:54
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:41
static const char *const TimeIRParsingName
Definition: IRReader.cpp:29
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::error_code getError() const
Definition: ErrorOr.h:159
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:52
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:904
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:115
reference get()
Returns a reference to the stored T value.
Definition: Error.h:532
StringRef getBufferIdentifier() const
Definition: MemoryBuffer.h:274
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:199
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:95
static const char *const TimeIRParsingGroupName
Definition: IRReader.cpp:27
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:276
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:503
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
Definition: Pass.h:356
static const char *const TimeIRParsingDescription
Definition: IRReader.cpp:30
reference get()
Definition: ErrorOr.h:156
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:261