LLVM 23.0.0git
MemoryBuffer.h
Go to the documentation of this file.
1//===--- MemoryBuffer.h - Memory Buffer Interface ---------------*- 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 file defines the MemoryBuffer interface.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_MEMORYBUFFER_H
14#define LLVM_SUPPORT_MEMORYBUFFER_H
15
16#include "llvm-c/Types.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Twine.h"
25#include <cstddef>
26#include <cstdint>
27#include <memory>
28
29namespace llvm {
30namespace sys {
31namespace fs {
32// Duplicated from FileSystem.h to avoid a dependency.
33#if defined(_WIN32)
34// A Win32 HANDLE is a typedef of void*
35using file_t = void *;
36#else
37using file_t = int;
38#endif
39} // namespace fs
40} // namespace sys
41
42/// This interface provides simple read-only access to a block of memory, and
43/// provides simple methods for reading files and standard input into a memory
44/// buffer. In addition to basic access to the characters in the file, this
45/// interface guarantees you can read one character past the end of the file,
46/// and that this character will read as '\0'.
47///
48/// The '\0' guarantee is needed to support an optimization -- it's intended to
49/// be more efficient for clients which are reading all the data to stop
50/// reading when they encounter a '\0' than to continually check the file
51/// position to see if it has reached the end of the file.
53 const char *BufferStart; // Start of the buffer.
54 const char *BufferEnd; // End of the buffer.
55
56protected:
57 MemoryBuffer() = default;
58
59 void init(const char *BufStart, const char *BufEnd,
60 bool RequiresNullTerminator);
61
62public:
63 MemoryBuffer(const MemoryBuffer &) = delete;
65 virtual ~MemoryBuffer();
66
67 const char *getBufferStart() const { return BufferStart; }
68 const char *getBufferEnd() const { return BufferEnd; }
69 size_t getBufferSize() const { return BufferEnd-BufferStart; }
70
72 return StringRef(BufferStart, getBufferSize());
73 }
74
75 /// Return an identifier for this buffer, typically the filename it was read
76 /// from.
77 virtual StringRef getBufferIdentifier() const { return "Unknown buffer"; }
78
79 /// For read-only MemoryBuffer_MMap, mark the buffer as unused in the near
80 /// future and the kernel can free resources associated with it. Further
81 /// access is supported but may be expensive. This calls
82 /// madvise(MADV_DONTNEED) on read-only file mappings on *NIX systems. This
83 /// function should not be called on a writable buffer.
84 virtual void dontNeedIfMmap() {}
85
86 /// Mark the buffer as to-be-used in a near future. This shall trigger OS
87 /// prefetching from the storage device and into memory, if possible.
88 /// This should be use purely as an read optimization.
89 virtual void willNeedIfMmap() {}
90
91 /// For read-only MemoryBuffer_MMap, advise the kernel that accesses will be
92 /// random, disabling readahead. This calls madvise(MADV_RANDOM) on *NIX.
93 /// This function should not be called on a writable buffer.
94 virtual void randomAccessIfMmap() {}
95
96 /// Open the specified file as a MemoryBuffer, returning a new MemoryBuffer
97 /// if successful, otherwise returning null.
98 ///
99 /// \param IsText Set to true to indicate that the file should be read in
100 /// text mode.
101 ///
102 /// \param IsVolatile Set to true to indicate that the contents of the file
103 /// can change outside the user's control, e.g. when libclang tries to parse
104 /// while the user is editing/updating the file or if the file is on an NFS.
105 ///
106 /// \param Alignment Set to indicate that the buffer should be aligned to at
107 /// least the specified alignment.
109 getFile(const Twine &Filename, bool IsText = false,
110 bool RequiresNullTerminator = true, bool IsVolatile = false,
111 std::optional<Align> Alignment = std::nullopt);
112
113 /// Read all of the specified file into a MemoryBuffer as a stream
114 /// (i.e. until EOF reached). This is useful for special files that
115 /// look like a regular file but have 0 size (e.g. /proc/cpuinfo on Linux).
117 getFileAsStream(const Twine &Filename);
118
119 /// Given an already-open file descriptor, map some slice of it into a
120 /// MemoryBuffer. The slice is specified by an \p Offset and \p MapSize.
121 /// Since this is in the middle of a file, the buffer is not null terminated.
123 getOpenFileSlice(sys::fs::file_t FD, const Twine &Filename, uint64_t MapSize,
124 int64_t Offset, bool IsVolatile = false,
125 std::optional<Align> Alignment = std::nullopt);
126
127 /// Given an already-open file descriptor, read the file and return a
128 /// MemoryBuffer.
129 ///
130 /// \param IsVolatile Set to true to indicate that the contents of the file
131 /// can change outside the user's control, e.g. when libclang tries to parse
132 /// while the user is editing/updating the file or if the file is on an NFS.
133 ///
134 /// \param Alignment Set to indicate that the buffer should be aligned to at
135 /// least the specified alignment.
137 getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize,
138 bool RequiresNullTerminator = true, bool IsVolatile = false,
139 std::optional<Align> Alignment = std::nullopt);
140
141 /// Open the specified memory range as a MemoryBuffer. Note that InputData
142 /// must be null terminated if RequiresNullTerminator is true.
143 static std::unique_ptr<MemoryBuffer>
144 getMemBuffer(StringRef InputData, StringRef BufferName = "",
145 bool RequiresNullTerminator = true);
146
147 static std::unique_ptr<MemoryBuffer>
148 getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator = true);
149
150 /// Open the specified memory range as a MemoryBuffer, copying the contents
151 /// and taking ownership of it. InputData does not have to be null terminated.
152 static std::unique_ptr<MemoryBuffer>
153 getMemBufferCopy(StringRef InputData, const Twine &BufferName = "");
154
155 /// Read all of stdin into a file buffer, and return it.
156 static ErrorOr<std::unique_ptr<MemoryBuffer>> getSTDIN();
157
158 /// Open the specified file as a MemoryBuffer, or open stdin if the Filename
159 /// is "-".
161 getFileOrSTDIN(const Twine &Filename, bool IsText = false,
162 bool RequiresNullTerminator = true,
163 std::optional<Align> Alignment = std::nullopt);
164
165 /// Map a subrange of the specified file as a MemoryBuffer.
167 getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset,
168 bool IsVolatile = false,
169 std::optional<Align> Alignment = std::nullopt);
170
171 //===--------------------------------------------------------------------===//
172 // Provided for performance analysis.
173 //===--------------------------------------------------------------------===//
174
175 /// The kind of memory backing used to support the MemoryBuffer.
180
181 /// Return information on the memory mechanism used to support the
182 /// MemoryBuffer.
183 virtual BufferKind getBufferKind() const = 0;
184
186};
187
188/// This class is an extension of MemoryBuffer, which allows copy-on-write
189/// access to the underlying contents. It only supports creation methods that
190/// are guaranteed to produce a writable buffer. For example, mapping a file
191/// read-only is not supported.
193protected:
195
196public:
200
201 // const_cast is well-defined here, because the underlying buffer is
202 // guaranteed to have been initialized with a mutable buffer.
204 return const_cast<char *>(MemoryBuffer::getBufferStart());
205 }
206 char *getBufferEnd() {
207 return const_cast<char *>(MemoryBuffer::getBufferEnd());
208 }
212
214 getFile(const Twine &Filename, bool IsVolatile = false,
215 std::optional<Align> Alignment = std::nullopt);
216
217 /// Map a subrange of the specified file as a WritableMemoryBuffer.
220 bool IsVolatile = false,
221 std::optional<Align> Alignment = std::nullopt);
222
223 /// Allocate a new MemoryBuffer of the specified size that is not initialized.
224 /// Note that the caller should initialize the memory allocated by this
225 /// method. The memory is owned by the MemoryBuffer object.
226 ///
227 /// \param Alignment Set to indicate that the buffer should be aligned to at
228 /// least the specified alignment.
229 LLVM_ABI static std::unique_ptr<WritableMemoryBuffer>
230 getNewUninitMemBuffer(size_t Size, const Twine &BufferName = "",
231 std::optional<Align> Alignment = std::nullopt);
232
233 /// Allocate a new zero-initialized MemoryBuffer of the specified size. Note
234 /// that the caller need not initialize the memory allocated by this method.
235 /// The memory is owned by the MemoryBuffer object.
236 LLVM_ABI static std::unique_ptr<WritableMemoryBuffer>
237 getNewMemBuffer(size_t Size, const Twine &BufferName = "");
238
239private:
240 // Hide these base class factory function so one can't write
241 // WritableMemoryBuffer::getXXX()
242 // and be surprised that he got a read-only Buffer.
250};
251
252/// This class is an extension of MemoryBuffer, which allows write access to
253/// the underlying contents and committing those changes to the original source.
254/// It only supports creation methods that are guaranteed to produce a writable
255/// buffer. For example, mapping a file read-only is not supported.
257protected:
259
260public:
264
265 // const_cast is well-defined here, because the underlying buffer is
266 // guaranteed to have been initialized with a mutable buffer.
268 return const_cast<char *>(MemoryBuffer::getBufferStart());
269 }
270 char *getBufferEnd() {
271 return const_cast<char *>(MemoryBuffer::getBufferEnd());
272 }
276
278 getFile(const Twine &Filename, int64_t FileSize = -1);
279
280 /// Map a subrange of the specified file as a ReadWriteMemoryBuffer.
283
284private:
285 // Hide these base class factory function so one can't write
286 // WritableMemoryBuffer::getXXX()
287 // and be surprised that he got a read-only Buffer.
295};
296
297// Create wrappers for C Binding types (see CBindingWrapping.h).
299
300} // end namespace llvm
301
302#endif // LLVM_SUPPORT_MEMORYBUFFER_H
#define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref)
#define LLVM_ABI
Definition Compiler.h:213
Provides ErrorOr<T> smart pointer.
static constexpr StringLiteral Filename
Represents either an error or a value T.
Definition ErrorOr.h:56
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Given an already-open file descriptor, read the file and return a MemoryBuffer.
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
BufferKind
The kind of memory backing used to support the MemoryBuffer.
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
size_t getBufferSize() const
static std::unique_ptr< MemoryBuffer > getMemBufferCopy(StringRef InputData, const Twine &BufferName="")
Open the specified memory range as a MemoryBuffer, copying the contents and taking ownership of it.
MemoryBuffer(const MemoryBuffer &)=delete
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFileSlice(sys::fs::file_t FD, const Twine &Filename, uint64_t MapSize, int64_t Offset, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Given an already-open file descriptor, map some slice of it into a MemoryBuffer.
virtual BufferKind getBufferKind() const =0
Return information on the memory mechanism used to support the MemoryBuffer.
void init(const char *BufStart, const char *BufEnd, bool RequiresNullTerminator)
init - Initialize this MemoryBuffer as a reference to externally allocated memory,...
StringRef getBuffer() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileAsStream(const Twine &Filename)
Read all of the specified file into a MemoryBuffer as a stream (i.e.
virtual void dontNeedIfMmap()
For read-only MemoryBuffer_MMap, mark the buffer as unused in the near future and the kernel can free...
virtual void randomAccessIfMmap()
For read-only MemoryBuffer_MMap, advise the kernel that accesses will be random, disabling readahead.
MemoryBufferRef getMemBufferRef() const
virtual void willNeedIfMmap()
Mark the buffer as to-be-used in a near future.
virtual ~MemoryBuffer()
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 "-".
MemoryBuffer & operator=(const MemoryBuffer &)=delete
MemoryBuffer()=default
const char * getBufferEnd() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getSTDIN()
Read all of stdin into a file buffer, and return it.
const char * getBufferStart() const
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
MutableArrayRef< char > getBuffer()
static LLVM_ABI std::unique_ptr< WritableMemoryBuffer > getNewMemBuffer(size_t Size, const Twine &BufferName="")
Allocate a new zero-initialized MemoryBuffer of the specified size.
static LLVM_ABI ErrorOr< std::unique_ptr< WritableMemoryBuffer > > getFile(const Twine &Filename, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
static LLVM_ABI std::unique_ptr< WritableMemoryBuffer > getNewUninitMemBuffer(size_t Size, const Twine &BufferName="", std::optional< Align > Alignment=std::nullopt)
Allocate a new MemoryBuffer of the specified size that is not initialized.
static LLVM_ABI ErrorOr< std::unique_ptr< WritableMemoryBuffer > > getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Map a subrange of the specified file as a WritableMemoryBuffer.
MutableArrayRef< char > getBuffer()
static LLVM_ABI ErrorOr< std::unique_ptr< WriteThroughMemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1)
static LLVM_ABI ErrorOr< std::unique_ptr< WriteThroughMemoryBuffer > > getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset)
Map a subrange of the specified file as a ReadWriteMemoryBuffer.
struct LLVMOpaqueMemoryBuffer * LLVMMemoryBufferRef
LLVM uses a polymorphic type hierarchy which C cannot represent, therefore parameters must be passed ...
Definition Types.h:48
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32