LLVM 20.0.0git
JITLinkMemoryManager.h
Go to the documentation of this file.
1//===-- JITLinkMemoryManager.h - JITLink mem manager 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// Contains the JITLinkMemoryManager interface.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_EXECUTIONENGINE_JITLINK_JITLINKMEMORYMANAGER_H
14#define LLVM_EXECUTIONENGINE_JITLINK_JITLINKMEMORYMANAGER_H
15
24#include "llvm/Support/Error.h"
26#include "llvm/Support/Memory.h"
28
29#include <cassert>
30#include <cstdint>
31#include <future>
32#include <mutex>
33
34namespace llvm {
35namespace jitlink {
36
37class Block;
38class LinkGraph;
39class Section;
40
41/// Manages allocations of JIT memory.
42///
43/// Instances of this class may be accessed concurrently from multiple threads
44/// and their implemetations should include any necessary synchronization.
46public:
47
48 /// Represents a finalized allocation.
49 ///
50 /// Finalized allocations must be passed to the
51 /// JITLinkMemoryManager:deallocate method prior to being destroyed.
52 ///
53 /// The interpretation of the Address associated with the finalized allocation
54 /// is up to the memory manager implementation. Common options are using the
55 /// base address of the allocation, or the address of a memory management
56 /// object that tracks the allocation.
59
60 static constexpr auto InvalidAddr = ~uint64_t(0);
61
62 public:
63 FinalizedAlloc() = default;
65 assert(A.getValue() != InvalidAddr &&
66 "Explicitly creating an invalid allocation?");
67 }
68 FinalizedAlloc(const FinalizedAlloc &) = delete;
70 Other.A.setValue(InvalidAddr);
71 }
74 assert(A.getValue() == InvalidAddr &&
75 "Cannot overwrite active finalized allocation");
76 std::swap(A, Other.A);
77 return *this;
78 }
80 assert(A.getValue() == InvalidAddr &&
81 "Finalized allocation was not deallocated");
82 }
83
84 /// FinalizedAllocs convert to false for default-constructed, and
85 /// true otherwise. Default-constructed allocs need not be deallocated.
86 explicit operator bool() const { return A.getValue() != InvalidAddr; }
87
88 /// Returns the address associated with this finalized allocation.
89 /// The allocation is unmodified.
90 orc::ExecutorAddr getAddress() const { return A; }
91
92 /// Returns the address associated with this finalized allocation and
93 /// resets this object to the default state.
94 /// This should only be used by allocators when deallocating memory.
96 orc::ExecutorAddr Tmp = A;
97 A.setValue(InvalidAddr);
98 return Tmp;
99 }
100
101 private:
102 orc::ExecutorAddr A{InvalidAddr};
103 };
104
105 /// Represents an allocation which has not been finalized yet.
106 ///
107 /// InFlightAllocs manage both executor memory allocations and working
108 /// memory allocations.
109 ///
110 /// On finalization, the InFlightAlloc should transfer the content of
111 /// working memory into executor memory, apply memory protections, and
112 /// run any finalization functions.
113 ///
114 /// Working memory should be kept alive at least until one of the following
115 /// happens: (1) the InFlightAlloc instance is destroyed, (2) the
116 /// InFlightAlloc is abandoned, (3) finalized target memory is destroyed.
117 ///
118 /// If abandon is called then working memory and executor memory should both
119 /// be freed.
121 public:
124
125 virtual ~InFlightAlloc();
126
127 /// Called prior to finalization if the allocation should be abandoned.
128 virtual void abandon(OnAbandonedFunction OnAbandoned) = 0;
129
130 /// Called to transfer working memory to the target and apply finalization.
131 virtual void finalize(OnFinalizedFunction OnFinalized) = 0;
132
133 /// Synchronous convenience version of finalize.
135 std::promise<MSVCPExpected<FinalizedAlloc>> FinalizeResultP;
136 auto FinalizeResultF = FinalizeResultP.get_future();
138 FinalizeResultP.set_value(std::move(Result));
139 });
140 return FinalizeResultF.get();
141 }
142 };
143
144 /// Typedef for the argument to be passed to OnAllocatedFunction.
146
147 /// Called when allocation has been completed.
149
150 /// Called when deallocation has completed.
152
154
155 /// Start the allocation process.
156 ///
157 /// If the initial allocation is successful then the OnAllocated function will
158 /// be called with a std::unique_ptr<InFlightAlloc> value. If the assocation
159 /// is unsuccessful then the OnAllocated function will be called with an
160 /// Error.
161 virtual void allocate(const JITLinkDylib *JD, LinkGraph &G,
162 OnAllocatedFunction OnAllocated) = 0;
163
164 /// Convenience function for blocking allocation.
166 std::promise<MSVCPExpected<std::unique_ptr<InFlightAlloc>>> AllocResultP;
167 auto AllocResultF = AllocResultP.get_future();
168 allocate(JD, G, [&](AllocResult Alloc) {
169 AllocResultP.set_value(std::move(Alloc));
170 });
171 return AllocResultF.get();
172 }
173
174 /// Deallocate a list of allocation objects.
175 ///
176 /// Dealloc actions will be run in reverse order (from the end of the vector
177 /// to the start).
178 virtual void deallocate(std::vector<FinalizedAlloc> Allocs,
179 OnDeallocatedFunction OnDeallocated) = 0;
180
181 /// Convenience function for deallocation of a single alloc.
183 std::vector<FinalizedAlloc> Allocs;
184 Allocs.push_back(std::move(Alloc));
185 deallocate(std::move(Allocs), std::move(OnDeallocated));
186 }
187
188 /// Convenience function for blocking deallocation.
189 Error deallocate(std::vector<FinalizedAlloc> Allocs) {
190 std::promise<MSVCPError> DeallocResultP;
191 auto DeallocResultF = DeallocResultP.get_future();
192 deallocate(std::move(Allocs),
193 [&](Error Err) { DeallocResultP.set_value(std::move(Err)); });
194 return DeallocResultF.get();
195 }
196
197 /// Convenience function for blocking deallocation of a single alloc.
199 std::vector<FinalizedAlloc> Allocs;
200 Allocs.push_back(std::move(Alloc));
201 return deallocate(std::move(Allocs));
202 }
203};
204
205/// BasicLayout simplifies the implementation of JITLinkMemoryManagers.
206///
207/// BasicLayout groups Sections into Segments based on their memory protection
208/// and deallocation policies. JITLinkMemoryManagers can construct a BasicLayout
209/// from a Graph, and then assign working memory and addresses to each of the
210/// Segments. These addreses will be mapped back onto the Graph blocks in
211/// the apply method.
213public:
214 /// The Alignment, ContentSize and ZeroFillSize of each segment will be
215 /// pre-filled from the Graph. Clients must set the Addr and WorkingMem fields
216 /// prior to calling apply.
217 //
218 // FIXME: The C++98 initializer is an attempt to work around compile failures
219 // due to http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1397.
220 // We should be able to switch this back to member initialization once that
221 // issue is fixed.
222 class Segment {
223 friend class BasicLayout;
224
225 public:
227 : ContentSize(0), ZeroFillSize(0), Addr(0), WorkingMem(nullptr),
228 NextWorkingMemOffset(0) {}
233 char *WorkingMem = nullptr;
234
235 private:
236 size_t NextWorkingMemOffset;
237 std::vector<Block *> ContentBlocks, ZeroFillBlocks;
238 };
239
240 /// A convenience class that further groups segments based on memory
241 /// deallocation policy. This allows clients to make two slab allocations:
242 /// one for all standard segments, and one for all finalize segments.
246
248 };
249
250private:
251 using SegmentMap = orc::AllocGroupSmallMap<Segment>;
252
253public:
255
256 /// Return a reference to the graph this allocation was created from.
257 LinkGraph &getGraph() { return G; }
258
259 /// Returns the total number of required to allocate all segments (with each
260 /// segment padded out to page size) for all standard segments, and all
261 /// finalize segments.
262 ///
263 /// This is a convenience function for the common case where the segments will
264 /// be allocated contiguously.
265 ///
266 /// This function will return an error if any segment has an alignment that
267 /// is higher than a page.
270
271 /// Returns an iterator over the segments of the layout.
273 return {Segments.begin(), Segments.end()};
274 }
275
276 /// Apply the layout to the graph.
277 Error apply();
278
279 /// Returns a reference to the AllocActions in the graph.
280 /// This convenience function saves callers from having to #include
281 /// LinkGraph.h if all they need are allocation actions.
283
284private:
285 LinkGraph &G;
286 SegmentMap Segments;
287};
288
289/// A utility class for making simple allocations using JITLinkMemoryManager.
290///
291/// SimpleSegementAlloc takes a mapping of AllocGroups to Segments and uses
292/// this to create a LinkGraph with one Section (containing one Block) per
293/// Segment. Clients can obtain a pointer to the working memory and executor
294/// address of that block using the Segment's AllocGroup. Once memory has been
295/// populated, clients can call finalize to finalize the memory.
296///
297/// Note: Segments with MemLifetime::NoAlloc are not permitted, since they would
298/// not be useful, and their presence is likely to indicate a bug.
300public:
301 /// Describes a segment to be allocated.
302 struct Segment {
303 Segment() = default;
306
307 size_t ContentSize = 0;
309 };
310
311 /// Describes the segment working memory and executor address.
312 struct SegmentInfo {
315 };
316
318
320
323
324 static void Create(JITLinkMemoryManager &MemMgr,
325 std::shared_ptr<orc::SymbolStringPool> SSP,
326 const JITLinkDylib *JD, SegmentMap Segments,
327 OnCreatedFunction OnCreated);
328
331 std::shared_ptr<orc::SymbolStringPool> SSP, const JITLinkDylib *JD,
332 SegmentMap Segments);
333
337
338 /// Returns the SegmentInfo for the given group.
340
341 /// Finalize all groups (async version).
342 void finalize(OnFinalizedFunction OnFinalized) {
343 Alloc->finalize(std::move(OnFinalized));
344 }
345
346 /// Finalize all groups.
348 return Alloc->finalize();
349 }
350
351private:
353 std::unique_ptr<LinkGraph> G,
355 std::unique_ptr<JITLinkMemoryManager::InFlightAlloc> Alloc);
356
357 std::unique_ptr<LinkGraph> G;
359 std::unique_ptr<JITLinkMemoryManager::InFlightAlloc> Alloc;
360};
361
362/// A JITLinkMemoryManager that allocates in-process memory.
364public:
365 class IPInFlightAlloc;
366
367 /// Attempts to auto-detect the host page size.
369
370 /// Create an instance using the given page size.
372 assert(isPowerOf2_64(PageSize) && "PageSize must be a power of 2");
373 }
374
375 void allocate(const JITLinkDylib *JD, LinkGraph &G,
376 OnAllocatedFunction OnAllocated) override;
377
378 // Use overloads from base class.
380
381 void deallocate(std::vector<FinalizedAlloc> Alloc,
382 OnDeallocatedFunction OnDeallocated) override;
383
384 // Use overloads from base class.
386
387private:
388 // FIXME: Use an in-place array instead of a vector for DeallocActions.
389 // There shouldn't need to be a heap alloc for this.
390 struct FinalizedAllocInfo {
391 sys::MemoryBlock StandardSegments;
392 std::vector<orc::shared::WrapperFunctionCall> DeallocActions;
393 };
394
395 FinalizedAlloc createFinalizedAlloc(
396 sys::MemoryBlock StandardSegments,
397 std::vector<orc::shared::WrapperFunctionCall> DeallocActions);
398
399 uint64_t PageSize;
400 std::mutex FinalizedAllocsMutex;
402};
403
404} // end namespace jitlink
405} // end namespace llvm
406
407#endif // LLVM_EXECUTIONENGINE_JITLINK_JITLINKMEMORYMANAGER_H
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file provides a collection of function (or more generally, callable) type erasure utilities supp...
static cl::opt< int > PageSize("imp-null-check-page-size", cl::desc("The page size of the target in bytes"), cl::init(4096), cl::Hidden)
#define G(x, y, z)
Definition: MD5.cpp:56
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
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
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:310
RecyclingAllocator - This class wraps an Allocator, adding the functionality of recycling deleted obj...
A range adaptor for a pair of iterators.
A specialized small-map for AllocGroups.
Definition: MemoryFlags.h:165
A pair of memory protections and allocation policies.
Definition: MemoryFlags.h:110
Represents an address in the executor process.
This class encapsulates the notion of a memory block which has an address and a size.
Definition: Memory.h:32
unique_function is a type-erasing functor similar to std::function.
std::vector< AllocActionCallPair > AllocActions
A vector of allocation actions to be run for this allocation.
NodeAddr< BlockNode * > Block
Definition: RDFGraph.h:392
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:296
@ Other
Any other memory.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39