LLVM 22.0.0git
BitcodeReader.h
Go to the documentation of this file.
1//===- llvm/Bitcode/BitcodeReader.h - Bitcode reader ------------*- C++ -*-===//
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//
9// This header defines interfaces to read LLVM bitcode files/streams.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_BITCODE_BITCODEREADER_H
14#define LLVM_BITCODE_BITCODEREADER_H
15
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/StringRef.h"
19#include "llvm/IR/GlobalValue.h"
21#include "llvm/Support/Endian.h"
22#include "llvm/Support/Error.h"
25#include <cstdint>
26#include <memory>
27#include <optional>
28#include <string>
29#include <system_error>
30#include <vector>
31namespace llvm {
32
33class LLVMContext;
34class Module;
35class MemoryBuffer;
36class Metadata;
37class ModuleSummaryIndex;
38class Type;
39class Value;
40
41// Callback to override the data layout string of an imported bitcode module.
42// The first argument is the target triple, the second argument the data layout
43// string from the input, or a default string. It will be used if the callback
44// returns std::nullopt.
45typedef std::function<std::optional<std::string>(StringRef, StringRef)>
47
48typedef std::function<Type *(unsigned)> GetTypeByIDTy;
49
50typedef std::function<unsigned(unsigned, unsigned)> GetContainedTypeIDTy;
51
52typedef std::function<void(Value *, unsigned, GetTypeByIDTy,
55
56typedef std::function<void(Metadata **, unsigned, GetTypeByIDTy,
59
60// These functions are for converting Expected/Error values to
61// ErrorOr/std::error_code for compatibility with legacy clients. FIXME:
62// Remove these functions once no longer needed by the C and libLTO APIs.
63
65 Error Err);
66
67template <typename T>
69 if (!Val)
71 return std::move(*Val);
72}
73
75 std::optional<DataLayoutCallbackFuncTy> DataLayout;
76 /// The ValueType callback is called for every function definition or
77 /// declaration and allows accessing the type information, also behind
78 /// pointers. This can be useful, when the opaque pointer upgrade cleans all
79 /// type information behind pointers.
80 /// The second argument to ValueTypeCallback is the type ID of the
81 /// function, the two passed functions can be used to extract type
82 /// information.
83 std::optional<ValueTypeCallbackTy> ValueType;
84 /// The MDType callback is called for every value in metadata.
85 std::optional<MDTypeCallbackTy> MDType;
86
87 ParserCallbacks() = default;
90};
91
92 struct BitcodeFileContents;
93
94 /// Basic information extracted from a bitcode module to be used for LTO.
100 };
101
102 /// Represents a module in a bitcode file.
104 // This covers the identification (if present) and module blocks.
105 ArrayRef<uint8_t> Buffer;
106 StringRef ModuleIdentifier;
107
108 // The string table used to interpret this module.
109 StringRef Strtab;
110
111 // The bitstream location of the IDENTIFICATION_BLOCK.
112 uint64_t IdentificationBit;
113
114 // The bitstream location of this module's MODULE_BLOCK.
115 uint64_t ModuleBit;
116
117 BitcodeModule(ArrayRef<uint8_t> Buffer, StringRef ModuleIdentifier,
118 uint64_t IdentificationBit, uint64_t ModuleBit)
119 : Buffer(Buffer), ModuleIdentifier(ModuleIdentifier),
120 IdentificationBit(IdentificationBit), ModuleBit(ModuleBit) {}
121
122 // Calls the ctor.
125
127 getModuleImpl(LLVMContext &Context, bool MaterializeAll,
128 bool ShouldLazyLoadMetadata, bool IsImporting,
129 ParserCallbacks Callbacks = {});
130
131 public:
133 return StringRef((const char *)Buffer.begin(), Buffer.size());
134 }
135
136 StringRef getStrtab() const { return Strtab; }
137
138 StringRef getModuleIdentifier() const { return ModuleIdentifier; }
139
140 /// Read the bitcode module and prepare for lazy deserialization of function
141 /// bodies. If ShouldLazyLoadMetadata is true, lazily load metadata as well.
142 /// If IsImporting is true, this module is being parsed for ThinLTO
143 /// importing into another module.
145 getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
146 bool IsImporting, ParserCallbacks Callbacks = {});
147
148 /// Read the entire bitcode module and return it.
149 LLVM_ABI Expected<std::unique_ptr<Module>>
150 parseModule(LLVMContext &Context, ParserCallbacks Callbacks = {});
151
152 /// Returns information about the module to be used for LTO: whether to
153 /// compile with ThinLTO, and whether it has a summary.
154 LLVM_ABI Expected<BitcodeLTOInfo> getLTOInfo();
155
156 /// Parse the specified bitcode buffer, returning the module summary index.
157 LLVM_ABI Expected<std::unique_ptr<ModuleSummaryIndex>> getSummary();
158
159 /// Parse the specified bitcode buffer and merge its module summary index
160 /// into CombinedIndex.
162 readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
163 std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr);
164 };
165
167 std::vector<BitcodeModule> Mods;
169 };
170
171 /// Returns the contents of a bitcode file. This includes the raw contents of
172 /// the symbol table embedded in the bitcode file. Clients which require a
173 /// symbol table should prefer to use irsymtab::read instead of this function
174 /// because it creates a reader for the irsymtab and handles upgrading bitcode
175 /// files without a symbol table or with an old symbol table.
178
179 /// Returns a list of modules in the specified bitcode buffer.
182
183 /// Read the header of the specified bitcode buffer and prepare for lazy
184 /// deserialization of function bodies. If ShouldLazyLoadMetadata is true,
185 /// lazily load metadata as well. If IsImporting is true, this module is
186 /// being parsed for ThinLTO importing into another module.
189 bool ShouldLazyLoadMetadata = false,
190 bool IsImporting = false,
191 ParserCallbacks Callbacks = {});
192
193 /// Like getLazyBitcodeModule, except that the module takes ownership of
194 /// the memory buffer if successful. If successful, this moves Buffer. On
195 /// error, this *does not* move Buffer. If IsImporting is true, this module is
196 /// being parsed for ThinLTO importing into another module.
197 LLVM_ABI Expected<std::unique_ptr<Module>> getOwningLazyBitcodeModule(
198 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
199 bool ShouldLazyLoadMetadata = false, bool IsImporting = false,
200 ParserCallbacks Callbacks = {});
201
202 /// Read the header of the specified bitcode buffer and extract just the
203 /// triple information. If successful, this returns a string. On error, this
204 /// returns "".
205 LLVM_ABI Expected<std::string> getBitcodeTargetTriple(MemoryBufferRef Buffer);
206
207 /// Return true if \p Buffer contains a bitcode file with ObjC code (category
208 /// or class) in it.
209 LLVM_ABI Expected<bool>
210 isBitcodeContainingObjCCategory(MemoryBufferRef Buffer);
211
212 /// Read the header of the specified bitcode buffer and extract just the
213 /// producer string information. If successful, this returns a string. On
214 /// error, this returns "".
215 LLVM_ABI Expected<std::string>
216 getBitcodeProducerString(MemoryBufferRef Buffer);
217
218 /// Read the specified bitcode file, returning the module.
219 LLVM_ABI Expected<std::unique_ptr<Module>>
220 parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
221 ParserCallbacks Callbacks = {});
222
223 /// Returns LTO information for the specified bitcode file.
224 LLVM_ABI Expected<BitcodeLTOInfo> getBitcodeLTOInfo(MemoryBufferRef Buffer);
225
226 /// Parse the specified bitcode buffer, returning the module summary index.
227 LLVM_ABI Expected<std::unique_ptr<ModuleSummaryIndex>>
228 getModuleSummaryIndex(MemoryBufferRef Buffer);
229
230 /// Parse the specified bitcode buffer and merge the index into CombinedIndex.
231 LLVM_ABI Error readModuleSummaryIndex(MemoryBufferRef Buffer,
232 ModuleSummaryIndex &CombinedIndex);
233
234 /// Parse the module summary index out of an IR file and return the module
235 /// summary index object if found, or an empty summary if not. If Path refers
236 /// to an empty file and IgnoreEmptyThinLTOIndexFile is true, then
237 /// this function will return nullptr.
238 LLVM_ABI Expected<std::unique_ptr<ModuleSummaryIndex>>
239 getModuleSummaryIndexForFile(StringRef Path,
240 bool IgnoreEmptyThinLTOIndexFile = false);
241
242 /// isBitcodeWrapper - Return true if the given bytes are the magic bytes
243 /// for an LLVM IR bitcode wrapper.
244 inline bool isBitcodeWrapper(const unsigned char *BufPtr,
245 const unsigned char *BufEnd) {
246 // See if you can find the hidden message in the magic bytes :-).
247 // (Hint: it's a little-endian encoding.)
248 return BufPtr != BufEnd &&
249 BufPtr[0] == 0xDE &&
250 BufPtr[1] == 0xC0 &&
251 BufPtr[2] == 0x17 &&
252 BufPtr[3] == 0x0B;
253 }
254
255 /// isRawBitcode - Return true if the given bytes are the magic bytes for
256 /// raw LLVM IR bitcode (without a wrapper).
257 inline bool isRawBitcode(const unsigned char *BufPtr,
258 const unsigned char *BufEnd) {
259 // These bytes sort of have a hidden message, but it's not in
260 // little-endian this time, and it's a little redundant.
261 return BufPtr != BufEnd &&
262 BufPtr[0] == 'B' &&
263 BufPtr[1] == 'C' &&
264 BufPtr[2] == 0xc0 &&
265 BufPtr[3] == 0xde;
266 }
267
268 /// isBitcode - Return true if the given bytes are the magic bytes for
269 /// LLVM IR bitcode, either with or without a wrapper.
270 inline bool isBitcode(const unsigned char *BufPtr,
271 const unsigned char *BufEnd) {
272 return isBitcodeWrapper(BufPtr, BufEnd) ||
273 isRawBitcode(BufPtr, BufEnd);
274 }
275
276 /// SkipBitcodeWrapperHeader - Some systems wrap bc files with a special
277 /// header for padding or other reasons. The format of this header is:
278 ///
279 /// struct bc_header {
280 /// uint32_t Magic; // 0x0B17C0DE
281 /// uint32_t Version; // Version, currently always 0.
282 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
283 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
284 /// ... potentially other gunk ...
285 /// };
286 ///
287 /// This function is called when we find a file with a matching magic number.
288 /// In this case, skip down to the subsection of the file that is actually a
289 /// BC file.
290 /// If 'VerifyBufferSize' is true, check that the buffer is large enough to
291 /// contain the whole bitcode file.
292 inline bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr,
293 const unsigned char *&BufEnd,
294 bool VerifyBufferSize) {
295 // Must contain the offset and size field!
296 if (unsigned(BufEnd - BufPtr) < BWH_SizeField + 4)
297 return true;
298
300 unsigned Size = support::endian::read32le(&BufPtr[BWH_SizeField]);
301 uint64_t BitcodeOffsetEnd = (uint64_t)Offset + (uint64_t)Size;
302
303 // Verify that Offset+Size fits in the file.
304 if (VerifyBufferSize && BitcodeOffsetEnd > uint64_t(BufEnd-BufPtr))
305 return true;
306 BufPtr += Offset;
307 BufEnd = BufPtr+Size;
308 return false;
309 }
310
311 LLVM_ABI APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits);
312
313 LLVM_ABI const std::error_category &BitcodeErrorCategory();
314 enum class BitcodeError { CorruptedBitcode = 1 };
315 inline std::error_code make_error_code(BitcodeError E) {
316 return std::error_code(static_cast<int>(E), BitcodeErrorCategory());
317 }
318
319} // end namespace llvm
320
321namespace std {
322
323template <> struct is_error_code_enum<llvm::BitcodeError> : std::true_type {};
324
325} // end namespace std
326
327#endif // LLVM_BITCODE_BITCODEREADER_H
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
RelocType Type
Definition: COFFYAML.cpp:410
#define LLVM_ABI
Definition: Compiler.h:213
dxil translate DXIL Translate Metadata
uint64_t Size
Provides ErrorOr<T> smart pointer.
Machine Check Debug Module
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:147
iterator begin() const
Definition: ArrayRef.h:135
Represents a module in a bitcode file.
LLVM_ABI friend Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
StringRef getModuleIdentifier() const
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
LLVM_ABI Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO,...
StringRef getBuffer() const
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(GlobalValue::GUID)> IsPrevailing=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
StringRef getStrtab() const
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
Represents either an error or a value T.
Definition: ErrorOr.h:56
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
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:577
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
Root of the metadata hierarchy.
Definition: Metadata.h:63
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:75
uint32_t read32le(const void *P)
Definition: Endian.h:429
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:477
LLVM_ABI const std::error_category & BitcodeErrorCategory()
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
std::error_code make_error_code(BitcodeError E)
std::function< Type *(unsigned)> GetTypeByIDTy
Definition: BitcodeReader.h:48
LLVM_ABI Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it.
std::function< unsigned(unsigned, unsigned)> GetContainedTypeIDTy
Definition: BitcodeReader.h:50
@ BWH_OffsetField
Definition: BitCodeEnums.h:29
@ BWH_SizeField
Definition: BitCodeEnums.h:30
LLVM_ABI Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
LLVM_ABI Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
ErrorOr< T > expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected< T > Val)
Definition: BitcodeReader.h:68
bool isRawBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isRawBitcode - Return true if the given bytes are the magic bytes for raw LLVM IR bitcode (without a ...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
LLVM_ABI Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
std::function< void(Metadata **, unsigned, GetTypeByIDTy, GetContainedTypeIDTy)> MDTypeCallbackTy
Definition: BitcodeReader.h:58
LLVM_ABI Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
LLVM_ABI Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize)
SkipBitcodeWrapperHeader - Some systems wrap bc files with a special header for padding or other reas...
bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcodeWrapper - Return true if the given bytes are the magic bytes for an LLVM IR bitcode wrapper.
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
std::function< void(Value *, unsigned, GetTypeByIDTy, GetContainedTypeIDTy)> ValueTypeCallbackTy
Definition: BitcodeReader.h:54
std::function< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackFuncTy
Definition: BitcodeReader.h:46
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 Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found,...
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::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
std::vector< BitcodeModule > Mods
Basic information extracted from a bitcode module to be used for LTO.
Definition: BitcodeReader.h:95
std::optional< ValueTypeCallbackTy > ValueType
The ValueType callback is called for every function definition or declaration and allows accessing th...
Definition: BitcodeReader.h:83
std::optional< DataLayoutCallbackFuncTy > DataLayout
Definition: BitcodeReader.h:75
ParserCallbacks(DataLayoutCallbackFuncTy DataLayout)
Definition: BitcodeReader.h:88
std::optional< MDTypeCallbackTy > MDType
The MDType callback is called for every value in metadata.
Definition: BitcodeReader.h:85