1 //===-- JITMemoryManager.cpp - Memory Allocator for JIT'd code ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the DefaultJITMemoryManager class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ExecutionEngine/JITMemoryManager.h"
15 #include "llvm/Support/Compiler.h"
16 #include "llvm/System/Memory.h"
25 JITMemoryManager::~JITMemoryManager() {}
27 //===----------------------------------------------------------------------===//
28 // Memory Block Implementation.
29 //===----------------------------------------------------------------------===//
32 /// MemoryRangeHeader - For a range of memory, this is the header that we put
33 /// on the block of memory. It is carefully crafted to be one word of memory.
34 /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
35 /// which starts with this.
36 struct FreeRangeHeader;
37 struct MemoryRangeHeader {
38 /// ThisAllocated - This is true if this block is currently allocated. If
39 /// not, this can be converted to a FreeRangeHeader.
40 unsigned ThisAllocated : 1;
42 /// PrevAllocated - Keep track of whether the block immediately before us is
43 /// allocated. If not, the word immediately before this header is the size
44 /// of the previous block.
45 unsigned PrevAllocated : 1;
47 /// BlockSize - This is the size in bytes of this memory block,
48 /// including this header.
49 uintptr_t BlockSize : (sizeof(intptr_t)*8 - 2);
52 /// getBlockAfter - Return the memory block immediately after this one.
54 MemoryRangeHeader &getBlockAfter() const {
55 return *(MemoryRangeHeader*)((char*)this+BlockSize);
58 /// getFreeBlockBefore - If the block before this one is free, return it,
59 /// otherwise return null.
60 FreeRangeHeader *getFreeBlockBefore() const {
61 if (PrevAllocated) return 0;
62 intptr_t PrevSize = ((intptr_t *)this)[-1];
63 return (FreeRangeHeader*)((char*)this-PrevSize);
66 /// FreeBlock - Turn an allocated block into a free block, adjusting
67 /// bits in the object headers, and adding an end of region memory block.
68 FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
70 /// TrimAllocationToSize - If this allocated block is significantly larger
71 /// than NewSize, split it into two pieces (where the former is NewSize
72 /// bytes, including the header), and add the new block to the free list.
73 FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
77 /// FreeRangeHeader - For a memory block that isn't already allocated, this
78 /// keeps track of the current block and has a pointer to the next free block.
79 /// Free blocks are kept on a circularly linked list.
80 struct FreeRangeHeader : public MemoryRangeHeader {
81 FreeRangeHeader *Prev;
82 FreeRangeHeader *Next;
84 /// getMinBlockSize - Get the minimum size for a memory block. Blocks
85 /// smaller than this size cannot be created.
86 static unsigned getMinBlockSize() {
87 return sizeof(FreeRangeHeader)+sizeof(intptr_t);
90 /// SetEndOfBlockSizeMarker - The word at the end of every free block is
91 /// known to be the size of the free block. Set it for this block.
92 void SetEndOfBlockSizeMarker() {
93 void *EndOfBlock = (char*)this + BlockSize;
94 ((intptr_t *)EndOfBlock)[-1] = BlockSize;
97 FreeRangeHeader *RemoveFromFreeList() {
98 assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
100 return Prev->Next = Next;
103 void AddToFreeList(FreeRangeHeader *FreeList) {
105 Prev = FreeList->Prev;
110 /// GrowBlock - The block after this block just got deallocated. Merge it
111 /// into the current block.
112 void GrowBlock(uintptr_t NewSize);
114 /// AllocateBlock - Mark this entire block allocated, updating freelists
115 /// etc. This returns a pointer to the circular free-list.
116 FreeRangeHeader *AllocateBlock();
121 /// AllocateBlock - Mark this entire block allocated, updating freelists
122 /// etc. This returns a pointer to the circular free-list.
123 FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
124 assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
125 "Cannot allocate an allocated block!");
126 // Mark this block allocated.
128 getBlockAfter().PrevAllocated = 1;
130 // Remove it from the free list.
131 return RemoveFromFreeList();
134 /// FreeBlock - Turn an allocated block into a free block, adjusting
135 /// bits in the object headers, and adding an end of region memory block.
136 /// If possible, coalesce this block with neighboring blocks. Return the
137 /// FreeRangeHeader to allocate from.
138 FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
139 MemoryRangeHeader *FollowingBlock = &getBlockAfter();
140 assert(ThisAllocated && "This block is already allocated!");
141 assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
143 FreeRangeHeader *FreeListToReturn = FreeList;
145 // If the block after this one is free, merge it into this block.
146 if (!FollowingBlock->ThisAllocated) {
147 FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
148 // "FreeList" always needs to be a valid free block. If we're about to
149 // coalesce with it, update our notion of what the free list is.
150 if (&FollowingFreeBlock == FreeList) {
151 FreeList = FollowingFreeBlock.Next;
152 FreeListToReturn = 0;
153 assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
155 FollowingFreeBlock.RemoveFromFreeList();
157 // Include the following block into this one.
158 BlockSize += FollowingFreeBlock.BlockSize;
159 FollowingBlock = &FollowingFreeBlock.getBlockAfter();
161 // Tell the block after the block we are coalescing that this block is
163 FollowingBlock->PrevAllocated = 1;
166 assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
168 if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
169 PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
170 return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
173 // Otherwise, mark this block free.
174 FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
175 FollowingBlock->PrevAllocated = 0;
176 FreeBlock.ThisAllocated = 0;
178 // Link this into the linked list of free blocks.
179 FreeBlock.AddToFreeList(FreeList);
181 // Add a marker at the end of the block, indicating the size of this free
183 FreeBlock.SetEndOfBlockSizeMarker();
184 return FreeListToReturn ? FreeListToReturn : &FreeBlock;
187 /// GrowBlock - The block after this block just got deallocated. Merge it
188 /// into the current block.
189 void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
190 assert(NewSize > BlockSize && "Not growing block?");
192 SetEndOfBlockSizeMarker();
193 getBlockAfter().PrevAllocated = 0;
196 /// TrimAllocationToSize - If this allocated block is significantly larger
197 /// than NewSize, split it into two pieces (where the former is NewSize
198 /// bytes, including the header), and add the new block to the free list.
199 FreeRangeHeader *MemoryRangeHeader::
200 TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
201 assert(ThisAllocated && getBlockAfter().PrevAllocated &&
202 "Cannot deallocate part of an allocated block!");
204 // Round up size for alignment of header.
205 unsigned HeaderAlign = __alignof(FreeRangeHeader);
206 NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
208 // Size is now the size of the block we will remove from the start of the
210 assert(NewSize <= BlockSize &&
211 "Allocating more space from this block than exists!");
213 // If splitting this block will cause the remainder to be too small, do not
215 if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
218 // Otherwise, we splice the required number of bytes out of this block, form
219 // a new block immediately after it, then mark this block allocated.
220 MemoryRangeHeader &FormerNextBlock = getBlockAfter();
222 // Change the size of this block.
225 // Get the new block we just sliced out and turn it into a free block.
226 FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
227 NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
228 NewNextBlock.ThisAllocated = 0;
229 NewNextBlock.PrevAllocated = 1;
230 NewNextBlock.SetEndOfBlockSizeMarker();
231 FormerNextBlock.PrevAllocated = 0;
232 NewNextBlock.AddToFreeList(FreeList);
233 return &NewNextBlock;
236 //===----------------------------------------------------------------------===//
237 // Memory Block Implementation.
238 //===----------------------------------------------------------------------===//
241 /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
242 /// This splits a large block of MAP_NORESERVE'd memory into two
243 /// sections, one for function stubs, one for the functions themselves. We
244 /// have to do this because we may need to emit a function stub while in the
245 /// middle of emitting a function, and we don't know how large the function we
247 class VISIBILITY_HIDDEN DefaultJITMemoryManager : public JITMemoryManager {
248 std::vector<sys::MemoryBlock> Blocks; // Memory blocks allocated by the JIT
249 FreeRangeHeader *FreeMemoryList; // Circular list of free blocks.
251 // When emitting code into a memory block, this is the block.
252 MemoryRangeHeader *CurBlock;
254 unsigned char *CurStubPtr, *StubBase;
255 unsigned char *GOTBase; // Target Specific reserved memory
257 // Centralize memory block allocation.
258 sys::MemoryBlock getNewMemoryBlock(unsigned size);
260 std::map<const Function*, MemoryRangeHeader*> FunctionBlocks;
261 std::map<const Function*, MemoryRangeHeader*> TableBlocks;
263 DefaultJITMemoryManager();
264 ~DefaultJITMemoryManager();
268 unsigned char *allocateStub(unsigned StubSize, unsigned Alignment);
270 /// startFunctionBody - When a function starts, allocate a block of free
271 /// executable memory, returning a pointer to it and its actual size.
272 unsigned char *startFunctionBody(const Function *F, uintptr_t &ActualSize) {
273 CurBlock = FreeMemoryList;
275 // Allocate the entire memory block.
276 FreeMemoryList = FreeMemoryList->AllocateBlock();
277 ActualSize = CurBlock->BlockSize-sizeof(MemoryRangeHeader);
278 return (unsigned char *)(CurBlock+1);
281 /// endFunctionBody - The function F is now allocated, and takes the memory
282 /// in the range [FunctionStart,FunctionEnd).
283 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
284 unsigned char *FunctionEnd) {
285 assert(FunctionEnd > FunctionStart);
286 assert(FunctionStart == (unsigned char *)(CurBlock+1) &&
287 "Mismatched function start/end!");
289 uintptr_t BlockSize = FunctionEnd - (unsigned char *)CurBlock;
290 FunctionBlocks[F] = CurBlock;
292 // Release the memory at the end of this block that isn't needed.
293 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
296 /// startExceptionTable - Use startFunctionBody to allocate memory for the
297 /// function's exception table.
298 unsigned char* startExceptionTable(const Function* F,
299 uintptr_t &ActualSize) {
300 return startFunctionBody(F, ActualSize);
303 /// endExceptionTable - The exception table of F is now allocated,
304 /// and takes the memory in the range [TableStart,TableEnd).
305 void endExceptionTable(const Function *F, unsigned char *TableStart,
306 unsigned char *TableEnd,
307 unsigned char* FrameRegister) {
308 assert(TableEnd > TableStart);
309 assert(TableStart == (unsigned char *)(CurBlock+1) &&
310 "Mismatched table start/end!");
312 uintptr_t BlockSize = TableEnd - (unsigned char *)CurBlock;
313 TableBlocks[F] = CurBlock;
315 // Release the memory at the end of this block that isn't needed.
316 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
319 unsigned char *getGOTBase() const {
323 /// deallocateMemForFunction - Deallocate all memory for the specified
325 void deallocateMemForFunction(const Function *F) {
326 std::map<const Function*, MemoryRangeHeader*>::iterator
327 I = FunctionBlocks.find(F);
328 if (I == FunctionBlocks.end()) return;
330 // Find the block that is allocated for this function.
331 MemoryRangeHeader *MemRange = I->second;
332 assert(MemRange->ThisAllocated && "Block isn't allocated!");
334 // Fill the buffer with garbage!
336 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
340 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
342 // Finally, remove this entry from FunctionBlocks.
343 FunctionBlocks.erase(I);
345 I = TableBlocks.find(F);
346 if (I == TableBlocks.end()) return;
348 // Find the block that is allocated for this function.
349 MemRange = I->second;
350 assert(MemRange->ThisAllocated && "Block isn't allocated!");
352 // Fill the buffer with garbage!
354 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
358 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
360 // Finally, remove this entry from TableBlocks.
361 TableBlocks.erase(I);
366 DefaultJITMemoryManager::DefaultJITMemoryManager() {
367 // Allocate a 16M block of memory for functions.
368 sys::MemoryBlock MemBlock = getNewMemoryBlock(16 << 20);
370 unsigned char *MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
372 // Allocate stubs backwards from the base, allocate functions forward
375 CurStubPtr = MemBase + 512*1024; // Use 512k for stubs, working backwards.
377 // We set up the memory chunk with 4 mem regions, like this:
379 // [ Free #0 ] -> Large space to allocate functions from.
380 // [ Allocated #1 ] -> Tiny space to separate regions.
381 // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
382 // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
385 // The last three blocks are never deallocated or touched.
387 // Add MemoryRangeHeader to the end of the memory region, indicating that
388 // the space after the block of memory is allocated. This is block #3.
389 MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
390 Mem3->ThisAllocated = 1;
391 Mem3->PrevAllocated = 0;
394 /// Add a tiny free region so that the free list always has one entry.
395 FreeRangeHeader *Mem2 =
396 (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
397 Mem2->ThisAllocated = 0;
398 Mem2->PrevAllocated = 1;
399 Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
400 Mem2->SetEndOfBlockSizeMarker();
401 Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
404 /// Add a tiny allocated region so that Mem2 is never coalesced away.
405 MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
406 Mem1->ThisAllocated = 1;
407 Mem1->PrevAllocated = 0;
408 Mem1->BlockSize = (char*)Mem2 - (char*)Mem1;
410 // Add a FreeRangeHeader to the start of the function body region, indicating
411 // that the space is free. Mark the previous block allocated so we never look
413 FreeRangeHeader *Mem0 = (FreeRangeHeader*)CurStubPtr;
414 Mem0->ThisAllocated = 0;
415 Mem0->PrevAllocated = 1;
416 Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
417 Mem0->SetEndOfBlockSizeMarker();
418 Mem0->AddToFreeList(Mem2);
420 // Start out with the freelist pointing to Mem0.
421 FreeMemoryList = Mem0;
426 void DefaultJITMemoryManager::AllocateGOT() {
427 assert(GOTBase == 0 && "Cannot allocate the got multiple times");
428 GOTBase = new unsigned char[sizeof(void*) * 8192];
433 DefaultJITMemoryManager::~DefaultJITMemoryManager() {
434 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
435 sys::Memory::ReleaseRWX(Blocks[i]);
441 unsigned char *DefaultJITMemoryManager::allocateStub(unsigned StubSize,
442 unsigned Alignment) {
443 CurStubPtr -= StubSize;
444 CurStubPtr = (unsigned char*)(((intptr_t)CurStubPtr) &
445 ~(intptr_t)(Alignment-1));
446 if (CurStubPtr < StubBase) {
447 // FIXME: allocate a new block
448 fprintf(stderr, "JIT ran out of memory for function stubs!\n");
454 sys::MemoryBlock DefaultJITMemoryManager::getNewMemoryBlock(unsigned size) {
455 // Allocate a new block close to the last one.
456 const sys::MemoryBlock *BOld = Blocks.empty() ? 0 : &Blocks.front();
458 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld, &ErrMsg);
461 "Allocation failed when allocating new memory in the JIT\n%s\n",
470 JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
471 return new DefaultJITMemoryManager();