LLVM 22.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"
18#include "llvm/Support/Timer.h"
20#include <optional>
21#include <system_error>
22
23using namespace llvm;
24
25namespace llvm {
26 extern bool TimePassesIsEnabled;
27}
28
29const char TimeIRParsingGroupName[] = "irparse";
30const char TimeIRParsingGroupDescription[] = "LLVM IR Parsing";
31const char TimeIRParsingName[] = "parse";
32const char TimeIRParsingDescription[] = "Parse IR";
33
34std::unique_ptr<Module>
35llvm::getLazyIRModule(std::unique_ptr<MemoryBuffer> Buffer, SMDiagnostic &Err,
36 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
37 if (isBitcode((const unsigned char *)Buffer->getBufferStart(),
38 (const unsigned char *)Buffer->getBufferEnd())) {
40 std::move(Buffer), Context, ShouldLazyLoadMetadata);
41 if (Error E = ModuleOrErr.takeError()) {
42 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
43 Err = SMDiagnostic(Buffer->getBufferIdentifier(), SourceMgr::DK_Error,
44 EIB.message());
45 });
46 return nullptr;
47 }
48 return std::move(ModuleOrErr.get());
49 }
50
51 return parseAssembly(Buffer->getMemBufferRef(), Err, Context);
52}
53
54std::unique_ptr<Module> llvm::getLazyIRFileModule(StringRef Filename,
55 SMDiagnostic &Err,
56 LLVMContext &Context,
57 bool ShouldLazyLoadMetadata) {
60 if (std::error_code EC = FileOrErr.getError()) {
61 Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
62 "Could not open input file: " + EC.message());
63 return nullptr;
64 }
65
66 return getLazyIRModule(std::move(FileOrErr.get()), Err, Context,
67 ShouldLazyLoadMetadata);
68}
69
70std::unique_ptr<Module> llvm::parseIR(MemoryBufferRef Buffer, SMDiagnostic &Err,
71 LLVMContext &Context,
72 ParserCallbacks Callbacks,
73 llvm::AsmParserContext *ParserContext) {
77 if (isBitcode((const unsigned char *)Buffer.getBufferStart(),
78 (const unsigned char *)Buffer.getBufferEnd())) {
80 parseBitcodeFile(Buffer, Context, Callbacks);
81 if (Error E = ModuleOrErr.takeError()) {
82 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
84 EIB.message());
85 });
86 return nullptr;
87 }
88 return std::move(ModuleOrErr.get());
89 }
90
91 return parseAssembly(Buffer, Err, Context, nullptr,
92 Callbacks.DataLayout.value_or(
93 [](StringRef, StringRef) { return std::nullopt; }),
94 ParserContext);
95}
96
97std::unique_ptr<Module> llvm::parseIRFile(StringRef Filename, SMDiagnostic &Err,
98 LLVMContext &Context,
99 ParserCallbacks Callbacks,
100 AsmParserContext *ParserContext) {
102 MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
103 if (std::error_code EC = FileOrErr.getError()) {
104 Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
105 "Could not open input file: " + EC.message());
106 return nullptr;
107 }
108
109 return parseIR(FileOrErr.get()->getMemBufferRef(), Err, Context, Callbacks,
110 ParserContext);
111}
112
113//===----------------------------------------------------------------------===//
114// C API.
115//===----------------------------------------------------------------------===//
116
119 char **OutMessage) {
120 SMDiagnostic Diag;
121
122 std::unique_ptr<MemoryBuffer> MB(unwrap(MemBuf));
123 *OutM =
124 wrap(parseIR(MB->getMemBufferRef(), Diag, *unwrap(ContextRef)).release());
125
126 if(!*OutM) {
127 if (OutMessage) {
128 std::string buf;
129 raw_string_ostream os(buf);
130
131 Diag.print(nullptr, os, false);
132
133 *OutMessage = strdup(buf.c_str());
134 }
135 return 1;
136 }
137
138 return 0;
139}
const char TimeIRParsingDescription[]
Definition IRReader.cpp:32
const char TimeIRParsingGroupDescription[]
Definition IRReader.cpp:30
const char TimeIRParsingName[]
Definition IRReader.cpp:31
const char TimeIRParsingGroupName[]
Definition IRReader.cpp:29
Module.h This file contains the declarations for the Module class.
#define T
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 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:117
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:990
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:70
Attribute unwrap(LLVMAttributeRef Attr)
Definition Attributes.h:351
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:54
LLVMAttributeRef wrap(Attribute Attr)
Definition Attributes.h:346
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:97
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:35
This class is basically a combination of TimeRegion and Timer.
Definition Timer.h:176
std::optional< DataLayoutCallbackFuncTy > DataLayout