blob: 0bf42b80994b3ca26f139371063dd99691cbac2a [file] [log] [blame]
Chris Lattner8907b4b2007-12-05 23:39:57 +00001//===-- JITMemoryManager.cpp - Memory Allocator for JIT'd code ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner8907b4b2007-12-05 23:39:57 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the DefaultJITMemoryManager class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ExecutionEngine/JITMemoryManager.h"
15#include "llvm/Support/Compiler.h"
16#include "llvm/System/Memory.h"
17#include <map>
18#include <vector>
Chuck Rose III3012ac62007-12-06 02:03:01 +000019#include <cassert>
Chris Lattner8907b4b2007-12-05 23:39:57 +000020using namespace llvm;
21
22
23JITMemoryManager::~JITMemoryManager() {}
24
25//===----------------------------------------------------------------------===//
26// Memory Block Implementation.
27//===----------------------------------------------------------------------===//
28
29namespace {
30 /// MemoryRangeHeader - For a range of memory, this is the header that we put
31 /// on the block of memory. It is carefully crafted to be one word of memory.
32 /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
33 /// which starts with this.
34 struct FreeRangeHeader;
35 struct MemoryRangeHeader {
36 /// ThisAllocated - This is true if this block is currently allocated. If
37 /// not, this can be converted to a FreeRangeHeader.
38 unsigned ThisAllocated : 1;
39
40 /// PrevAllocated - Keep track of whether the block immediately before us is
41 /// allocated. If not, the word immediately before this header is the size
42 /// of the previous block.
43 unsigned PrevAllocated : 1;
44
45 /// BlockSize - This is the size in bytes of this memory block,
46 /// including this header.
47 uintptr_t BlockSize : (sizeof(intptr_t)*8 - 2);
48
49
50 /// getBlockAfter - Return the memory block immediately after this one.
51 ///
52 MemoryRangeHeader &getBlockAfter() const {
53 return *(MemoryRangeHeader*)((char*)this+BlockSize);
54 }
55
56 /// getFreeBlockBefore - If the block before this one is free, return it,
57 /// otherwise return null.
58 FreeRangeHeader *getFreeBlockBefore() const {
59 if (PrevAllocated) return 0;
60 intptr_t PrevSize = ((intptr_t *)this)[-1];
61 return (FreeRangeHeader*)((char*)this-PrevSize);
62 }
63
64 /// FreeBlock - Turn an allocated block into a free block, adjusting
65 /// bits in the object headers, and adding an end of region memory block.
66 FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
67
68 /// TrimAllocationToSize - If this allocated block is significantly larger
69 /// than NewSize, split it into two pieces (where the former is NewSize
70 /// bytes, including the header), and add the new block to the free list.
71 FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
72 uint64_t NewSize);
73 };
74
75 /// FreeRangeHeader - For a memory block that isn't already allocated, this
76 /// keeps track of the current block and has a pointer to the next free block.
77 /// Free blocks are kept on a circularly linked list.
78 struct FreeRangeHeader : public MemoryRangeHeader {
79 FreeRangeHeader *Prev;
80 FreeRangeHeader *Next;
81
82 /// getMinBlockSize - Get the minimum size for a memory block. Blocks
83 /// smaller than this size cannot be created.
84 static unsigned getMinBlockSize() {
85 return sizeof(FreeRangeHeader)+sizeof(intptr_t);
86 }
87
88 /// SetEndOfBlockSizeMarker - The word at the end of every free block is
89 /// known to be the size of the free block. Set it for this block.
90 void SetEndOfBlockSizeMarker() {
91 void *EndOfBlock = (char*)this + BlockSize;
92 ((intptr_t *)EndOfBlock)[-1] = BlockSize;
93 }
94
95 FreeRangeHeader *RemoveFromFreeList() {
96 assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
97 Next->Prev = Prev;
98 return Prev->Next = Next;
99 }
100
101 void AddToFreeList(FreeRangeHeader *FreeList) {
102 Next = FreeList;
103 Prev = FreeList->Prev;
104 Prev->Next = this;
105 Next->Prev = this;
106 }
107
108 /// GrowBlock - The block after this block just got deallocated. Merge it
109 /// into the current block.
110 void GrowBlock(uintptr_t NewSize);
111
112 /// AllocateBlock - Mark this entire block allocated, updating freelists
113 /// etc. This returns a pointer to the circular free-list.
114 FreeRangeHeader *AllocateBlock();
115 };
116}
117
118
119/// AllocateBlock - Mark this entire block allocated, updating freelists
120/// etc. This returns a pointer to the circular free-list.
121FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
122 assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
123 "Cannot allocate an allocated block!");
124 // Mark this block allocated.
125 ThisAllocated = 1;
126 getBlockAfter().PrevAllocated = 1;
127
128 // Remove it from the free list.
129 return RemoveFromFreeList();
130}
131
132/// FreeBlock - Turn an allocated block into a free block, adjusting
133/// bits in the object headers, and adding an end of region memory block.
134/// If possible, coalesce this block with neighboring blocks. Return the
135/// FreeRangeHeader to allocate from.
136FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
137 MemoryRangeHeader *FollowingBlock = &getBlockAfter();
138 assert(ThisAllocated && "This block is already allocated!");
139 assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
140
141 FreeRangeHeader *FreeListToReturn = FreeList;
142
143 // If the block after this one is free, merge it into this block.
144 if (!FollowingBlock->ThisAllocated) {
145 FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
146 // "FreeList" always needs to be a valid free block. If we're about to
147 // coalesce with it, update our notion of what the free list is.
148 if (&FollowingFreeBlock == FreeList) {
149 FreeList = FollowingFreeBlock.Next;
150 FreeListToReturn = 0;
151 assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
152 }
153 FollowingFreeBlock.RemoveFromFreeList();
154
155 // Include the following block into this one.
156 BlockSize += FollowingFreeBlock.BlockSize;
157 FollowingBlock = &FollowingFreeBlock.getBlockAfter();
158
159 // Tell the block after the block we are coalescing that this block is
160 // allocated.
161 FollowingBlock->PrevAllocated = 1;
162 }
163
164 assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
165
166 if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
167 PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
168 return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
169 }
170
171 // Otherwise, mark this block free.
172 FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
173 FollowingBlock->PrevAllocated = 0;
174 FreeBlock.ThisAllocated = 0;
175
176 // Link this into the linked list of free blocks.
177 FreeBlock.AddToFreeList(FreeList);
178
179 // Add a marker at the end of the block, indicating the size of this free
180 // block.
181 FreeBlock.SetEndOfBlockSizeMarker();
182 return FreeListToReturn ? FreeListToReturn : &FreeBlock;
183}
184
185/// GrowBlock - The block after this block just got deallocated. Merge it
186/// into the current block.
187void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
188 assert(NewSize > BlockSize && "Not growing block?");
189 BlockSize = NewSize;
190 SetEndOfBlockSizeMarker();
191 getBlockAfter().PrevAllocated = 0;
192}
193
194/// TrimAllocationToSize - If this allocated block is significantly larger
195/// than NewSize, split it into two pieces (where the former is NewSize
196/// bytes, including the header), and add the new block to the free list.
197FreeRangeHeader *MemoryRangeHeader::
198TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
199 assert(ThisAllocated && getBlockAfter().PrevAllocated &&
200 "Cannot deallocate part of an allocated block!");
201
202 // Round up size for alignment of header.
203 unsigned HeaderAlign = __alignof(FreeRangeHeader);
204 NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
205
206 // Size is now the size of the block we will remove from the start of the
207 // current block.
208 assert(NewSize <= BlockSize &&
209 "Allocating more space from this block than exists!");
210
211 // If splitting this block will cause the remainder to be too small, do not
212 // split the block.
213 if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
214 return FreeList;
215
216 // Otherwise, we splice the required number of bytes out of this block, form
217 // a new block immediately after it, then mark this block allocated.
218 MemoryRangeHeader &FormerNextBlock = getBlockAfter();
219
220 // Change the size of this block.
221 BlockSize = NewSize;
222
223 // Get the new block we just sliced out and turn it into a free block.
224 FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
225 NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
226 NewNextBlock.ThisAllocated = 0;
227 NewNextBlock.PrevAllocated = 1;
228 NewNextBlock.SetEndOfBlockSizeMarker();
229 FormerNextBlock.PrevAllocated = 0;
230 NewNextBlock.AddToFreeList(FreeList);
231 return &NewNextBlock;
232}
233
234//===----------------------------------------------------------------------===//
235// Memory Block Implementation.
236//===----------------------------------------------------------------------===//
237
238namespace {
239 /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
240 /// This splits a large block of MAP_NORESERVE'd memory into two
241 /// sections, one for function stubs, one for the functions themselves. We
242 /// have to do this because we may need to emit a function stub while in the
243 /// middle of emitting a function, and we don't know how large the function we
244 /// are emitting is.
245 class VISIBILITY_HIDDEN DefaultJITMemoryManager : public JITMemoryManager {
246 std::vector<sys::MemoryBlock> Blocks; // Memory blocks allocated by the JIT
247 FreeRangeHeader *FreeMemoryList; // Circular list of free blocks.
248
249 // When emitting code into a memory block, this is the block.
250 MemoryRangeHeader *CurBlock;
251
252 unsigned char *CurStubPtr, *StubBase;
253 unsigned char *GOTBase; // Target Specific reserved memory
254
255 // Centralize memory block allocation.
256 sys::MemoryBlock getNewMemoryBlock(unsigned size);
257
258 std::map<const Function*, MemoryRangeHeader*> FunctionBlocks;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000259 std::map<const Function*, MemoryRangeHeader*> TableBlocks;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000260 public:
261 DefaultJITMemoryManager();
262 ~DefaultJITMemoryManager();
263
264 void AllocateGOT();
265
266 unsigned char *allocateStub(unsigned StubSize, unsigned Alignment);
267
268 /// startFunctionBody - When a function starts, allocate a block of free
269 /// executable memory, returning a pointer to it and its actual size.
270 unsigned char *startFunctionBody(const Function *F, uintptr_t &ActualSize) {
271 CurBlock = FreeMemoryList;
272
273 // Allocate the entire memory block.
274 FreeMemoryList = FreeMemoryList->AllocateBlock();
275 ActualSize = CurBlock->BlockSize-sizeof(MemoryRangeHeader);
276 return (unsigned char *)(CurBlock+1);
277 }
278
279 /// endFunctionBody - The function F is now allocated, and takes the memory
280 /// in the range [FunctionStart,FunctionEnd).
281 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
282 unsigned char *FunctionEnd) {
283 assert(FunctionEnd > FunctionStart);
284 assert(FunctionStart == (unsigned char *)(CurBlock+1) &&
285 "Mismatched function start/end!");
286
287 uintptr_t BlockSize = FunctionEnd - (unsigned char *)CurBlock;
288 FunctionBlocks[F] = CurBlock;
289
290 // Release the memory at the end of this block that isn't needed.
291 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
292 }
293
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000294 /// startExceptionTable - Use startFunctionBody to allocate memory for the
295 /// function's exception table.
296 unsigned char* startExceptionTable(const Function* F, uintptr_t &ActualSize) {
297 return startFunctionBody(F, ActualSize);
298 }
299
300 /// endExceptionTable - The exception table of F is now allocated,
301 /// and takes the memory in the range [TableStart,TableEnd).
302 void endExceptionTable(const Function *F, unsigned char *TableStart,
303 unsigned char *TableEnd,
304 unsigned char* FrameRegister) {
305 assert(TableEnd > TableStart);
306 assert(TableStart == (unsigned char *)(CurBlock+1) &&
307 "Mismatched table start/end!");
308
309 uintptr_t BlockSize = TableEnd - (unsigned char *)CurBlock;
310 TableBlocks[F] = CurBlock;
311
312 // Release the memory at the end of this block that isn't needed.
313 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
314 }
315
Chris Lattner8907b4b2007-12-05 23:39:57 +0000316 unsigned char *getGOTBase() const {
317 return GOTBase;
318 }
319
320 /// deallocateMemForFunction - Deallocate all memory for the specified
321 /// function body.
322 void deallocateMemForFunction(const Function *F) {
323 std::map<const Function*, MemoryRangeHeader*>::iterator
324 I = FunctionBlocks.find(F);
325 if (I == FunctionBlocks.end()) return;
326
327 // Find the block that is allocated for this function.
328 MemoryRangeHeader *MemRange = I->second;
329 assert(MemRange->ThisAllocated && "Block isn't allocated!");
330
331 // Fill the buffer with garbage!
332#ifndef NDEBUG
333 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
334#endif
335
336 // Free the memory.
337 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
338
339 // Finally, remove this entry from FunctionBlocks.
340 FunctionBlocks.erase(I);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000341
342 I = TableBlocks.find(F);
343 if (I == TableBlocks.end()) return;
344
345 // Find the block that is allocated for this function.
346 MemRange = I->second;
347 assert(MemRange->ThisAllocated && "Block isn't allocated!");
348
349 // Fill the buffer with garbage!
350#ifndef NDEBUG
351 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
352#endif
353
354 // Free the memory.
355 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
356
357 // Finally, remove this entry from TableBlocks.
358 TableBlocks.erase(I);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000359 }
360 };
361}
362
363DefaultJITMemoryManager::DefaultJITMemoryManager() {
364 // Allocate a 16M block of memory for functions.
365 sys::MemoryBlock MemBlock = getNewMemoryBlock(16 << 20);
366
367 unsigned char *MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
368
369 // Allocate stubs backwards from the base, allocate functions forward
370 // from the base.
371 StubBase = MemBase;
372 CurStubPtr = MemBase + 512*1024; // Use 512k for stubs, working backwards.
373
374 // We set up the memory chunk with 4 mem regions, like this:
375 // [ START
376 // [ Free #0 ] -> Large space to allocate functions from.
377 // [ Allocated #1 ] -> Tiny space to separate regions.
378 // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
379 // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
380 // END ]
381 //
382 // The last three blocks are never deallocated or touched.
383
384 // Add MemoryRangeHeader to the end of the memory region, indicating that
385 // the space after the block of memory is allocated. This is block #3.
386 MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
387 Mem3->ThisAllocated = 1;
388 Mem3->PrevAllocated = 0;
389 Mem3->BlockSize = 0;
390
391 /// Add a tiny free region so that the free list always has one entry.
392 FreeRangeHeader *Mem2 =
393 (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
394 Mem2->ThisAllocated = 0;
395 Mem2->PrevAllocated = 1;
396 Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
397 Mem2->SetEndOfBlockSizeMarker();
398 Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
399 Mem2->Next = Mem2;
400
401 /// Add a tiny allocated region so that Mem2 is never coalesced away.
402 MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
403 Mem1->ThisAllocated = 1;
404 Mem1->PrevAllocated = 0;
405 Mem1->BlockSize = (char*)Mem2 - (char*)Mem1;
406
407 // Add a FreeRangeHeader to the start of the function body region, indicating
408 // that the space is free. Mark the previous block allocated so we never look
409 // at it.
410 FreeRangeHeader *Mem0 = (FreeRangeHeader*)CurStubPtr;
411 Mem0->ThisAllocated = 0;
412 Mem0->PrevAllocated = 1;
413 Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
414 Mem0->SetEndOfBlockSizeMarker();
415 Mem0->AddToFreeList(Mem2);
416
417 // Start out with the freelist pointing to Mem0.
418 FreeMemoryList = Mem0;
419
420 GOTBase = NULL;
421}
422
423void DefaultJITMemoryManager::AllocateGOT() {
424 assert(GOTBase == 0 && "Cannot allocate the got multiple times");
425 GOTBase = new unsigned char[sizeof(void*) * 8192];
426 HasGOT = true;
427}
428
429
430DefaultJITMemoryManager::~DefaultJITMemoryManager() {
431 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
432 sys::Memory::ReleaseRWX(Blocks[i]);
433
434 delete[] GOTBase;
435 Blocks.clear();
436}
437
438unsigned char *DefaultJITMemoryManager::allocateStub(unsigned StubSize,
439 unsigned Alignment) {
440 CurStubPtr -= StubSize;
441 CurStubPtr = (unsigned char*)(((intptr_t)CurStubPtr) &
442 ~(intptr_t)(Alignment-1));
443 if (CurStubPtr < StubBase) {
444 // FIXME: allocate a new block
445 fprintf(stderr, "JIT ran out of memory for function stubs!\n");
446 abort();
447 }
448 return CurStubPtr;
449}
450
451sys::MemoryBlock DefaultJITMemoryManager::getNewMemoryBlock(unsigned size) {
452 // Allocate a new block close to the last one.
453 const sys::MemoryBlock *BOld = Blocks.empty() ? 0 : &Blocks.front();
454 std::string ErrMsg;
455 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld, &ErrMsg);
456 if (B.base() == 0) {
457 fprintf(stderr,
458 "Allocation failed when allocating new memory in the JIT\n%s\n",
459 ErrMsg.c_str());
460 abort();
461 }
462 Blocks.push_back(B);
463 return B;
464}
465
466
467JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
468 return new DefaultJITMemoryManager();
469}