LLVM 23.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"
14#include "llvm/IR/LLVMContext.h"
15#include "llvm/IR/Module.h"
19#include "llvm/Support/Timer.h"
21#include <cstring>
22#include <optional>
23#include <system_error>
24
25using namespace llvm;
26
27const char TimeIRParsingGroupName[] = "irparse";
28const char TimeIRParsingGroupDescription[] = "LLVM IR Parsing";
29const char TimeIRParsingName[] = "parse";
30const char TimeIRParsingDescription[] = "Parse IR";
31
32std::unique_ptr<Module>
33llvm::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
53 SMDiagnostic &Err,
54 LLVMContext &Context,
55 bool ShouldLazyLoadMetadata) {
58 if (std::error_code EC = FileOrErr.getError()) {
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
68std::unique_ptr<Module> llvm::parseIR(MemoryBufferRef Buffer, SMDiagnostic &Err,
69 LLVMContext &Context,
70 ParserCallbacks Callbacks,
71 llvm::AsmParserContext *ParserContext) {
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 ParserContext);
93}
94
95std::unique_ptr<Module> llvm::parseIRFile(StringRef Filename, SMDiagnostic &Err,
96 LLVMContext &Context,
97 ParserCallbacks Callbacks,
98 AsmParserContext *ParserContext) {
100 MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
101 if (std::error_code EC = FileOrErr.getError()) {
103 "Could not open input file: " + EC.message());
104 return nullptr;
105 }
106
107 return parseIR(FileOrErr.get()->getMemBufferRef(), Err, Context, Callbacks,
108 ParserContext);
109}
110
111//===----------------------------------------------------------------------===//
112// C API.
113//===----------------------------------------------------------------------===//
114
117 char **OutMessage) {
118 std::unique_ptr<MemoryBuffer> MB(unwrap(MemBuf));
119 return LLVMParseIRInContext2(ContextRef, wrap(MB.get()), OutM, OutMessage);
120}
121
124 char **OutMessage) {
125 SMDiagnostic Diag;
126
127 *OutM = wrap(parseIR(*unwrap(MemBuf), Diag, *unwrap(ContextRef)).release());
128
129 if (*OutM)
130 return 0;
131
132 if (OutMessage) {
133 std::string Buf;
134 raw_string_ostream OS(Buf);
135 Diag.print(nullptr, OS, /*ShowColors=*/false);
136 *OutMessage = strdup(Buf.c_str());
137 }
138
139 return 1;
140}
const char TimeIRParsingDescription[]
Definition IRReader.cpp:30
const char TimeIRParsingGroupDescription[]
Definition IRReader.cpp:28
const char TimeIRParsingName[]
Definition IRReader.cpp:29
const char TimeIRParsingGroupName[]
Definition IRReader.cpp:27
Module.h This file contains the declarations for the Module class.
#define T
static constexpr StringLiteral Filename
This header defines classes/functions to handle pass execution timing information with interfaces for...
Registry of file location information for LLVM IR constructs.
Base class for error info classes.
Definition Error.h:44
virtual std::string message() const
Return the error message as a string.
Definition Error.h:52
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:159
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
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:297
LLVM_ABI void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true, bool ShowLocation=true) const
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
A raw_ostream that writes to an std::string.
LLVMBool LLVMParseIRInContext2(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:122
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
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.
LLVM_ABI 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:1013
LLVM_ABI std::unique_ptr< Module > parseAssembly(MemoryBufferRef F, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots=nullptr, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;}, AsmParserContext *ParserContext=nullptr)
parseAssemblyFile and parseAssemblyString are wrappers around this function.
Definition Parser.cpp:51
LLVM_ABI bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
LLVM_ABI std::unique_ptr< Module > parseIR(MemoryBufferRef Buffer, SMDiagnostic &Err, LLVMContext &Context, ParserCallbacks Callbacks={}, AsmParserContext *ParserContext=nullptr)
If the given MemoryBuffer holds a bitcode image, return a Module for it.
Definition IRReader.cpp:68
Attribute unwrap(LLVMAttributeRef Attr)
Definition Attributes.h:397
LLVM_ABI 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
LLVMAttributeRef wrap(Attribute Attr)
Definition Attributes.h:392
LLVM_ABI std::unique_ptr< Module > parseIRFile(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, ParserCallbacks Callbacks={}, AsmParserContext *ParserContext=nullptr)
If the given file holds a bitcode image, return a Module for it.
Definition IRReader.cpp:95
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,...
LLVM_ABI 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.
LLVM_ABI 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
This class is basically a combination of TimeRegion and Timer.
Definition Timer.h:175
std::optional< DataLayoutCallbackFuncTy > DataLayout