LLVM 24.0.0git
JITLinkMemoryManager.cpp
Go to the documentation of this file.
1//===--- JITLinkMemoryManager.cpp - JITLinkMemoryManager implementation ---===//
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
13
14#define DEBUG_TYPE "jitlink"
15
16using namespace llvm;
17
18namespace llvm {
19namespace jitlink {
20
23
25
26 for (auto &Sec : G.sections()) {
27 // Skip empty sections, and sections with NoAlloc lifetime policies.
28 if (Sec.blocks().empty() ||
29 Sec.getMemLifetime() == orc::MemLifetime::NoAlloc)
30 continue;
31
32 auto &Seg = Segments[{Sec.getMemProt(), Sec.getMemLifetime()}];
33 for (auto *B : Sec.blocks())
34 if (LLVM_LIKELY(!B->isZeroFill()))
35 Seg.ContentBlocks.push_back(B);
36 else
37 Seg.ZeroFillBlocks.push_back(B);
38 }
39
40 // Build Segments map.
41 auto CompareBlocks = [](const Block *LHS, const Block *RHS) {
42 // Sort by section, address and size
43 if (LHS->getSection().getOrdinal() != RHS->getSection().getOrdinal())
44 return LHS->getSection().getOrdinal() < RHS->getSection().getOrdinal();
45 if (LHS->getAddress() != RHS->getAddress())
46 return LHS->getAddress() < RHS->getAddress();
47 return LHS->getSize() < RHS->getSize();
48 };
49
50 LLVM_DEBUG(dbgs() << "Generated BasicLayout for " << G.getName() << ":\n");
51 for (auto &KV : Segments) {
52 auto &Seg = KV.second;
53
54 llvm::sort(Seg.ContentBlocks, CompareBlocks);
55 llvm::sort(Seg.ZeroFillBlocks, CompareBlocks);
56
57 for (auto *B : Seg.ContentBlocks) {
58 Seg.ContentSize = alignToBlock(Seg.ContentSize, *B);
59 Seg.ContentSize += B->getSize();
60 Seg.Alignment = std::max(Seg.Alignment, Align(B->getAlignment()));
61 }
62
63 uint64_t SegEndOffset = Seg.ContentSize;
64 for (auto *B : Seg.ZeroFillBlocks) {
65 SegEndOffset = alignToBlock(SegEndOffset, *B);
66 SegEndOffset += B->getSize();
67 Seg.Alignment = std::max(Seg.Alignment, Align(B->getAlignment()));
68 }
69 Seg.ZeroFillSize = SegEndOffset - Seg.ContentSize;
70
72 dbgs() << " Seg " << KV.first
73 << ": content-size=" << formatv("{0:x}", Seg.ContentSize)
74 << ", zero-fill-size=" << formatv("{0:x}", Seg.ZeroFillSize)
75 << ", align=" << formatv("{0:x}", Seg.Alignment.value()) << "\n";
76 });
77 }
78}
79
83
84 for (auto &KV : segments()) {
85 auto &AG = KV.first;
86 auto &Seg = KV.second;
87
88 if (Seg.Alignment > PageSize)
89 return make_error<StringError>("Segment alignment greater than page size",
91
92 uint64_t SegSize = alignTo(Seg.ContentSize + Seg.ZeroFillSize, PageSize);
93 if (AG.getMemLifetime() == orc::MemLifetime::Standard)
94 SegsSizes.StandardSegs += SegSize;
95 else
96 SegsSizes.FinalizeSegs += SegSize;
97 }
98
99 return SegsSizes;
100}
101
103 for (auto &KV : Segments) {
104 auto &Seg = KV.second;
105
106 assert(!(Seg.ContentBlocks.empty() && Seg.ZeroFillBlocks.empty()) &&
107 "Empty section recorded?");
108
109 for (auto *B : Seg.ContentBlocks) {
110 // Align addr and working-mem-offset.
111 Seg.Addr = alignToBlock(Seg.Addr, *B);
112 Seg.NextWorkingMemOffset = alignToBlock(Seg.NextWorkingMemOffset, *B);
113
114 // Update block addr.
115 B->setAddress(Seg.Addr);
116 Seg.Addr += B->getSize();
117
118 // Copy content to working memory, then update content to point at working
119 // memory.
120 memcpy(Seg.WorkingMem + Seg.NextWorkingMemOffset, B->getContent().data(),
121 B->getSize());
122 B->setMutableContent(
123 {Seg.WorkingMem + Seg.NextWorkingMemOffset, B->getSize()});
124 Seg.NextWorkingMemOffset += B->getSize();
125 }
126
127 for (auto *B : Seg.ZeroFillBlocks) {
128 // Align addr.
129 Seg.Addr = alignToBlock(Seg.Addr, *B);
130 // Update block addr.
131 B->setAddress(Seg.Addr);
132 Seg.Addr += B->getSize();
133 }
134
135 Seg.ContentBlocks.clear();
136 Seg.ZeroFillBlocks.clear();
137 }
138
139 return Error::success();
140}
141
143 return G.allocActions();
144}
145
147 std::shared_ptr<orc::SymbolStringPool> SSP,
148 Triple TT, const JITLinkDylib *JD,
149 SegmentMap Segments,
150 OnCreatedFunction OnCreated) {
151
152 static_assert(orc::AllocGroup::NumGroups == 32,
153 "AllocGroup has changed. Section names below must be updated");
154 StringRef AGSectionNames[] = {
155 "__---.standard", "__R--.standard", "__-W-.standard", "__RW-.standard",
156 "__--X.standard", "__R-X.standard", "__-WX.standard", "__RWX.standard",
157 "__---.finalize", "__R--.finalize", "__-W-.finalize", "__RW-.finalize",
158 "__--X.finalize", "__R-X.finalize", "__-WX.finalize", "__RWX.finalize"};
159
160 unsigned PointerSize = TT.getArchPointerBitWidth() / 8;
161 auto G = std::make_unique<LinkGraph>("", std::move(SSP), std::move(TT),
162 PointerSize, SubtargetFeatures(),
165
166 orc::ExecutorAddr NextAddr(0x100000);
167 for (auto &KV : Segments) {
168 auto &AG = KV.first;
169 auto &Seg = KV.second;
170
171 assert(AG.getMemLifetime() != orc::MemLifetime::NoAlloc &&
172 "NoAlloc segments are not supported by SimpleSegmentAlloc");
173
174 auto AGSectionName =
175 AGSectionNames[static_cast<unsigned>(AG.getMemProt()) |
176 static_cast<bool>(AG.getMemLifetime()) << 3];
177
178 auto &Sec = G->createSection(AGSectionName, AG.getMemProt());
179 Sec.setMemLifetime(AG.getMemLifetime());
180
181 if (Seg.ContentSize != 0) {
182 NextAddr =
183 orc::ExecutorAddr(alignTo(NextAddr.getValue(), Seg.ContentAlign));
184 auto &B =
185 G->createMutableContentBlock(Sec, G->allocateBuffer(Seg.ContentSize),
186 NextAddr, Seg.ContentAlign.value(), 0);
187 ContentBlocks[AG] = &B;
188 NextAddr += Seg.ContentSize;
189 }
190 }
191
192 // GRef declared separately since order-of-argument-eval isn't specified.
193 auto &GRef = *G;
194 MemMgr.allocate(JD, GRef,
195 [G = std::move(G), ContentBlocks = std::move(ContentBlocks),
196 OnCreated = std::move(OnCreated)](
197 JITLinkMemoryManager::AllocResult Alloc) mutable {
198 if (!Alloc)
199 OnCreated(Alloc.takeError());
200 else
201 OnCreated(SimpleSegmentAlloc(std::move(G),
202 std::move(ContentBlocks),
203 std::move(*Alloc)));
204 });
205}
206
208 JITLinkMemoryManager &MemMgr, std::shared_ptr<orc::SymbolStringPool> SSP,
209 Triple TT, const JITLinkDylib *JD, SegmentMap Segments) {
210 std::promise<MSVCPExpected<SimpleSegmentAlloc>> AllocP;
211 auto AllocF = AllocP.get_future();
212 Create(MemMgr, std::move(SSP), std::move(TT), JD, std::move(Segments),
213 [&](Expected<SimpleSegmentAlloc> Result) {
214 AllocP.set_value(std::move(Result));
215 });
216 return AllocF.get();
217}
218
223
226 auto I = ContentBlocks.find(AG);
227 if (I != ContentBlocks.end()) {
228 auto &B = *I->second;
229 return {B.getAddress(), B.getAlreadyMutableContent()};
230 }
231 return {};
232}
233
235 std::unique_ptr<LinkGraph> G,
237 std::unique_ptr<JITLinkMemoryManager::InFlightAlloc> Alloc)
238 : G(std::move(G)), ContentBlocks(std::move(ContentBlocks)),
239 Alloc(std::move(Alloc)) {}
240
243public:
245 sys::MemoryBlock StandardSegments,
246 sys::MemoryBlock FinalizationSegments)
247 : MemMgr(MemMgr), G(&G), BL(std::move(BL)),
248 StandardSegments(std::move(StandardSegments)),
249 FinalizationSegments(std::move(FinalizationSegments)) {}
250
251 ~IPInFlightAlloc() override {
252 assert(!G && "InFlight alloc neither abandoned nor finalized");
253 }
254
255 void finalize(OnFinalizedFunction OnFinalized) override {
256
257 // Apply memory protections to all segments.
258 if (auto Err = applyProtections()) {
259 OnFinalized(std::move(Err));
260 return;
261 }
262
263 // Run finalization actions.
264 auto DeallocActions = runFinalizeActions(G->allocActions());
265 if (!DeallocActions) {
266 OnFinalized(DeallocActions.takeError());
267 return;
268 }
269
270 // Release the finalize segments slab.
271 if (auto EC = sys::Memory::releaseMappedMemory(FinalizationSegments)) {
272 OnFinalized(errorCodeToError(EC));
273 return;
274 }
275
276#ifndef NDEBUG
277 // Set 'G' to null to flag that we've been successfully finalized.
278 // This allows us to assert at destruction time that a call has been made
279 // to either finalize or abandon.
280 G = nullptr;
281#endif
282
283 // Continue with finalized allocation.
284 OnFinalized(MemMgr.createFinalizedAlloc(std::move(StandardSegments),
285 std::move(*DeallocActions)));
286 }
287
288 void abandon(OnAbandonedFunction OnAbandoned) override {
289 Error Err = Error::success();
290 if (auto EC = sys::Memory::releaseMappedMemory(FinalizationSegments))
291 Err = joinErrors(std::move(Err), errorCodeToError(EC));
292 if (auto EC = sys::Memory::releaseMappedMemory(StandardSegments))
293 Err = joinErrors(std::move(Err), errorCodeToError(EC));
294
295#ifndef NDEBUG
296 // Set 'G' to null to flag that we've been successfully finalized.
297 // This allows us to assert at destruction time that a call has been made
298 // to either finalize or abandon.
299 G = nullptr;
300#endif
301
302 OnAbandoned(std::move(Err));
303 }
304
305private:
306 Error applyProtections() {
307 for (auto &KV : BL.segments()) {
308 const auto &AG = KV.first;
309 auto &Seg = KV.second;
310
311 auto Prot = toSysMemoryProtectionFlags(AG.getMemProt());
312
313 uint64_t SegSize =
314 alignTo(Seg.ContentSize + Seg.ZeroFillSize, MemMgr.PageSize);
315 sys::MemoryBlock MB(Seg.WorkingMem, SegSize);
316 if (auto EC = sys::Memory::protectMappedMemory(MB, Prot))
317 return errorCodeToError(EC);
318 if (Prot & sys::Memory::MF_EXEC)
319 sys::Memory::InvalidateInstructionCache(MB.base(), MB.allocatedSize());
320 }
321 return Error::success();
322 }
323
325 LinkGraph *G;
326 BasicLayout BL;
327 sys::MemoryBlock StandardSegments;
328 sys::MemoryBlock FinalizationSegments;
329};
330
333 if (auto PageSize = sys::Process::getPageSize()) {
334 // FIXME: Just check this once on startup.
335 if (!isPowerOf2_64((uint64_t)*PageSize))
337 "Could not create InProcessMemoryManager: Page size " +
338 Twine(*PageSize) + " is not a power of 2",
340
341 return std::make_unique<InProcessMemoryManager>(*PageSize);
342 } else
343 return PageSize.takeError();
344}
345
347 OnAllocatedFunction OnAllocated) {
348 BasicLayout BL(G);
349
350 /// Scan the request and calculate the group and total sizes.
351 /// Check that segment size is no larger than a page.
352 auto SegsSizes = BL.getContiguousPageBasedLayoutSizes(PageSize);
353 if (!SegsSizes) {
354 OnAllocated(SegsSizes.takeError());
355 return;
356 }
357
358 /// Check that the total size requested (including zero fill) is not larger
359 /// than a size_t.
360 if (SegsSizes->total() > std::numeric_limits<size_t>::max()) {
361 OnAllocated(make_error<JITLinkError>(
362 "Total requested size " + formatv("{0:x}", SegsSizes->total()) +
363 " for graph " + G.getName() + " exceeds address space"));
364 return;
365 }
366
367 // Allocate one slab for the whole thing (to make sure everything is
368 // in-range), then partition into standard and finalization blocks.
369 //
370 // FIXME: Make two separate allocations in the future to reduce
371 // fragmentation: finalization segments will usually be a single page, and
372 // standard segments are likely to be more than one page. Where multiple
373 // allocations are in-flight at once (likely) the current approach will leave
374 // a lot of single-page holes.
375 sys::MemoryBlock Slab;
376 sys::MemoryBlock StandardSegsMem;
377 sys::MemoryBlock FinalizeSegsMem;
378 {
382
383 std::error_code EC;
384 Slab = sys::Memory::allocateMappedMemory(SegsSizes->total(), nullptr,
385 ReadWrite, EC);
386
387 if (EC) {
388 OnAllocated(errorCodeToError(EC));
389 return;
390 }
391
392 // Zero-fill the whole slab up-front.
393 memset(Slab.base(), 0, Slab.allocatedSize());
394
395 StandardSegsMem = {Slab.base(),
396 static_cast<size_t>(SegsSizes->StandardSegs)};
397 FinalizeSegsMem = {(void *)((char *)Slab.base() + SegsSizes->StandardSegs),
398 static_cast<size_t>(SegsSizes->FinalizeSegs)};
399 }
400
401 auto NextStandardSegAddr = orc::ExecutorAddr::fromPtr(StandardSegsMem.base());
402 auto NextFinalizeSegAddr = orc::ExecutorAddr::fromPtr(FinalizeSegsMem.base());
403
404 LLVM_DEBUG({
405 dbgs() << "InProcessMemoryManager allocated:\n";
406 if (SegsSizes->StandardSegs)
407 dbgs() << formatv(" [ {0:x16} -- {1:x16} ]", NextStandardSegAddr,
408 NextStandardSegAddr + StandardSegsMem.allocatedSize())
409 << " to stardard segs\n";
410 else
411 dbgs() << " no standard segs\n";
412 if (SegsSizes->FinalizeSegs)
413 dbgs() << formatv(" [ {0:x16} -- {1:x16} ]", NextFinalizeSegAddr,
414 NextFinalizeSegAddr + FinalizeSegsMem.allocatedSize())
415 << " to finalize segs\n";
416 else
417 dbgs() << " no finalize segs\n";
418 });
419
420 // Build ProtMap, assign addresses.
421 for (auto &KV : BL.segments()) {
422 auto &AG = KV.first;
423 auto &Seg = KV.second;
424
425 auto &SegAddr = (AG.getMemLifetime() == orc::MemLifetime::Standard)
426 ? NextStandardSegAddr
427 : NextFinalizeSegAddr;
428
429 Seg.WorkingMem = SegAddr.toPtr<char *>();
430 Seg.Addr = SegAddr;
431
432 SegAddr += alignTo(Seg.ContentSize + Seg.ZeroFillSize, PageSize);
433 }
434
435 if (auto Err = BL.apply()) {
436 OnAllocated(std::move(Err));
437 return;
438 }
439
440 OnAllocated(std::make_unique<IPInFlightAlloc>(*this, G, std::move(BL),
441 std::move(StandardSegsMem),
442 std::move(FinalizeSegsMem)));
443}
444
445void InProcessMemoryManager::deallocate(std::vector<FinalizedAlloc> Allocs,
446 OnDeallocatedFunction OnDeallocated) {
447 std::vector<sys::MemoryBlock> StandardSegmentsList;
448 std::vector<std::vector<orc::shared::WrapperFunctionCall>> DeallocActionsList;
449
450 {
451 std::lock_guard<std::mutex> Lock(FinalizedAllocsMutex);
452 for (auto &Alloc : Allocs) {
453 auto *FA = Alloc.release().toPtr<FinalizedAllocInfo *>();
454 StandardSegmentsList.push_back(std::move(FA->StandardSegments));
455 DeallocActionsList.push_back(std::move(FA->DeallocActions));
456 FA->~FinalizedAllocInfo();
457 FinalizedAllocInfos.Deallocate(FA);
458 }
459 }
460
461 Error DeallocErr = Error::success();
462
463 while (!DeallocActionsList.empty()) {
464 auto &DeallocActions = DeallocActionsList.back();
465 auto &StandardSegments = StandardSegmentsList.back();
466
467 /// Run any deallocate calls.
468 while (!DeallocActions.empty()) {
469 if (auto Err = DeallocActions.back().runWithSPSRetErrorMerged())
470 DeallocErr = joinErrors(std::move(DeallocErr), std::move(Err));
471 DeallocActions.pop_back();
472 }
473
474 /// Release the standard segments slab.
475 if (auto EC = sys::Memory::releaseMappedMemory(StandardSegments))
476 DeallocErr = joinErrors(std::move(DeallocErr), errorCodeToError(EC));
477
478 DeallocActionsList.pop_back();
479 StandardSegmentsList.pop_back();
480 }
481
482 OnDeallocated(std::move(DeallocErr));
483}
484
486InProcessMemoryManager::createFinalizedAlloc(
487 sys::MemoryBlock StandardSegments,
488 std::vector<orc::shared::WrapperFunctionCall> DeallocActions) {
489 std::lock_guard<std::mutex> Lock(FinalizedAllocsMutex);
490 auto *FA = FinalizedAllocInfos.Allocate<FinalizedAllocInfo>();
491 new (FA) FinalizedAllocInfo(
492 {std::move(StandardSegments), std::move(DeallocActions)});
493 return FinalizedAlloc(orc::ExecutorAddr::fromPtr(FA));
494}
495
496} // end namespace jitlink
497} // end namespace llvm
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:351
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 I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
if(PassOpts->AAPipeline)
Provides a library for accessing information about this process and other processes on the operating ...
#define LLVM_DEBUG(...)
Definition Debug.h:119
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
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
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Manages the enabling and disabling of subtarget specific features.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
A specialized small-map for AllocGroups.
A pair of memory protections and allocation policies.
static constexpr unsigned NumGroups
Represents an address in the executor process.
uint64_t getValue() const
static ExecutorAddr fromPtr(T *Ptr, UnwrapFn &&Unwrap=UnwrapFn())
Create an ExecutorAddr from the given pointer.
This class encapsulates the notion of a memory block which has an address and a size.
Definition Memory.h:33
void * base() const
Definition Memory.h:38
size_t allocatedSize() const
The size as it was allocated.
Definition Memory.h:41
static LLVM_ABI std::error_code protectMappedMemory(const MemoryBlock &Block, unsigned Flags)
This method sets the protection flags for a block of memory to the state specified by /p Flags.
static LLVM_ABI std::error_code releaseMappedMemory(MemoryBlock &Block)
This method releases a block of memory that was allocated with the allocateMappedMemory method.
static LLVM_ABI void InvalidateInstructionCache(const void *Addr, size_t Len)
InvalidateInstructionCache - Before the JIT can run a block of code that has been emitted it must inv...
static LLVM_ABI MemoryBlock allocateMappedMemory(size_t NumBytes, const MemoryBlock *const NearBlock, unsigned Flags, std::error_code &EC)
This method allocates a block of memory that is suitable for loading dynamically generated code (e....
static LLVM_ABI Expected< unsigned > getPageSize()
Get the process's page size.
std::vector< AllocActionCallPair > AllocActions
A vector of allocation actions to be run for this allocation.
@ NoAlloc
NoAlloc memory should not be allocated by the JITLinkMemoryManager at all.
Definition MemoryFlags.h:88
@ Standard
Standard memory should be allocated by the allocator and then deallocated when the deallocate method ...
Definition MemoryFlags.h:78
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39