LLVM 20.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"
13#include "llvm/IR/LLVMContext.h"
14#include "llvm/IR/Module.h"
17#include "llvm/Support/Timer.h"
19#include <optional>
20#include <system_error>
21
22using namespace llvm;
23
24namespace llvm {
25 extern bool TimePassesIsEnabled;
26}
27
28const char TimeIRParsingGroupName[] = "irparse";
29const char TimeIRParsingGroupDescription[] = "LLVM IR Parsing";
30const char TimeIRParsingName[] = "parse";
31const char TimeIRParsingDescription[] = "Parse IR";
32
33std::unique_ptr<Module>
34llvm::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
53std::unique_ptr<Module> llvm::getLazyIRFileModule(StringRef Filename,
54 SMDiagnostic &Err,
55 LLVMContext &Context,
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
69std::unique_ptr<Module> llvm::parseIR(MemoryBufferRef Buffer, SMDiagnostic &Err,
70 LLVMContext &Context,
71 ParserCallbacks Callbacks) {
75 if (isBitcode((const unsigned char *)Buffer.getBufferStart(),
76 (const unsigned char *)Buffer.getBufferEnd())) {
78 parseBitcodeFile(Buffer, Context, Callbacks);
79 if (Error E = ModuleOrErr.takeError()) {
80 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
82 EIB.message());
83 });
84 return nullptr;
85 }
86 return std::move(ModuleOrErr.get());
87 }
88
89 return parseAssembly(Buffer, Err, Context, nullptr,
90 Callbacks.DataLayout.value_or(
91 [](StringRef, StringRef) { return std::nullopt; }));
92}
93
94std::unique_ptr<Module> llvm::parseIRFile(StringRef Filename, SMDiagnostic &Err,
95 LLVMContext &Context,
96 ParserCallbacks Callbacks) {
98 MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
99 if (std::error_code EC = FileOrErr.getError()) {
100 Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
101 "Could not open input file: " + EC.message());
102 return nullptr;
103 }
104
105 return parseIR(FileOrErr.get()->getMemBufferRef(), Err, Context, Callbacks);
106}
107
108//===----------------------------------------------------------------------===//
109// C API.
110//===----------------------------------------------------------------------===//
111
114 char **OutMessage) {
115 SMDiagnostic Diag;
116
117 std::unique_ptr<MemoryBuffer> MB(unwrap(MemBuf));
118 *OutM =
119 wrap(parseIR(MB->getMemBufferRef(), Diag, *unwrap(ContextRef)).release());
120
121 if(!*OutM) {
122 if (OutMessage) {
123 std::string buf;
124 raw_string_ostream os(buf);
125
126 Diag.print(nullptr, os, false);
127
128 *OutMessage = strdup(buf.c_str());
129 }
130 return 1;
131 }
132
133 return 0;
134}
const char TimeIRParsingDescription[]
Definition: IRReader.cpp:31
const char TimeIRParsingGroupDescription[]
Definition: IRReader.cpp:29
const char TimeIRParsingName[]
Definition: IRReader.cpp:30
const char TimeIRParsingGroupName[]
Definition: IRReader.cpp:28
Module.h This file contains the declarations for the Module class.
Base class for error info classes.
Definition: Error.h:45
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:53
Represents either an error or a value T.
Definition: ErrorOr.h:56
reference get()
Definition: ErrorOr.h:149
std::error_code getError() const
Definition: ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
reference get()
Returns a reference to the stored T value.
Definition: Error.h:578
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
StringRef getBufferIdentifier() const
const char * getBufferStart() const
const char * getBufferEnd() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:281
void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true, bool ShowLocation=true) const
Definition: SourceMgr.cpp:484
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
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:112
int LLVMBool
Definition: Types.h:28
struct LLVMOpaqueMemoryBuffer * LLVMMemoryBufferRef
LLVM uses a polymorphic type hierarchy which C cannot represent, therefore parameters must be passed ...
Definition: Types.h:48
struct LLVMOpaqueContext * LLVMContextRef
The top-level container for all LLVM global data.
Definition: Types.h:53
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition: Types.h:61
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::unique_ptr< Module > parseIRFile(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, ParserCallbacks Callbacks={})
If the given file holds a bitcode image, return a Module for it.
Definition: IRReader.cpp:94
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
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:977
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
std::unique_ptr< Module > parseIR(MemoryBufferRef Buffer, SMDiagnostic &Err, LLVMContext &Context, ParserCallbacks Callbacks={})
If the given MemoryBuffer holds a bitcode image, return a Module for it.
Definition: IRReader.cpp:69
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:332
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
std::unique_ptr< Module > parseAssembly(MemoryBufferRef F, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots=nullptr, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
parseAssemblyFile and parseAssemblyString are wrappers around this function.
Definition: Parser.cpp:47
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:327
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,...
Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful.
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:34
This class is basically a combination of TimeRegion and Timer.
Definition: Timer.h:163
std::optional< DataLayoutCallbackFuncTy > DataLayout
Definition: BitcodeReader.h:73