blob: 5908e434516ada4473a87793fa4ee7596ba54708 [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>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000020#include <cstdlib>
21#include <cstring>
Chris Lattner8907b4b2007-12-05 23:39:57 +000022using namespace llvm;
23
24
25JITMemoryManager::~JITMemoryManager() {}
26
27//===----------------------------------------------------------------------===//
28// Memory Block Implementation.
29//===----------------------------------------------------------------------===//
30
31namespace {
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;
41
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;
46
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);
50
51
52 /// getBlockAfter - Return the memory block immediately after this one.
53 ///
54 MemoryRangeHeader &getBlockAfter() const {
55 return *(MemoryRangeHeader*)((char*)this+BlockSize);
56 }
57
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);
64 }
65
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);
69
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,
74 uint64_t NewSize);
75 };
76
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;
83
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);
88 }
89
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;
95 }
96
97 FreeRangeHeader *RemoveFromFreeList() {
98 assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
99 Next->Prev = Prev;
100 return Prev->Next = Next;
101 }
102
103 void AddToFreeList(FreeRangeHeader *FreeList) {
104 Next = FreeList;
105 Prev = FreeList->Prev;
106 Prev->Next = this;
107 Next->Prev = this;
108 }
109
110 /// GrowBlock - The block after this block just got deallocated. Merge it
111 /// into the current block.
112 void GrowBlock(uintptr_t NewSize);
113
114 /// AllocateBlock - Mark this entire block allocated, updating freelists
115 /// etc. This returns a pointer to the circular free-list.
116 FreeRangeHeader *AllocateBlock();
117 };
118}
119
120
121/// AllocateBlock - Mark this entire block allocated, updating freelists
122/// etc. This returns a pointer to the circular free-list.
123FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
124 assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
125 "Cannot allocate an allocated block!");
126 // Mark this block allocated.
127 ThisAllocated = 1;
128 getBlockAfter().PrevAllocated = 1;
129
130 // Remove it from the free list.
131 return RemoveFromFreeList();
132}
133
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.
138FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
139 MemoryRangeHeader *FollowingBlock = &getBlockAfter();
140 assert(ThisAllocated && "This block is already allocated!");
141 assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
142
143 FreeRangeHeader *FreeListToReturn = FreeList;
144
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?");
154 }
155 FollowingFreeBlock.RemoveFromFreeList();
156
157 // Include the following block into this one.
158 BlockSize += FollowingFreeBlock.BlockSize;
159 FollowingBlock = &FollowingFreeBlock.getBlockAfter();
160
161 // Tell the block after the block we are coalescing that this block is
162 // allocated.
163 FollowingBlock->PrevAllocated = 1;
164 }
165
166 assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
167
168 if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
169 PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
170 return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
171 }
172
173 // Otherwise, mark this block free.
174 FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
175 FollowingBlock->PrevAllocated = 0;
176 FreeBlock.ThisAllocated = 0;
177
178 // Link this into the linked list of free blocks.
179 FreeBlock.AddToFreeList(FreeList);
180
181 // Add a marker at the end of the block, indicating the size of this free
182 // block.
183 FreeBlock.SetEndOfBlockSizeMarker();
184 return FreeListToReturn ? FreeListToReturn : &FreeBlock;
185}
186
187/// GrowBlock - The block after this block just got deallocated. Merge it
188/// into the current block.
189void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
190 assert(NewSize > BlockSize && "Not growing block?");
191 BlockSize = NewSize;
192 SetEndOfBlockSizeMarker();
193 getBlockAfter().PrevAllocated = 0;
194}
195
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.
199FreeRangeHeader *MemoryRangeHeader::
200TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
201 assert(ThisAllocated && getBlockAfter().PrevAllocated &&
202 "Cannot deallocate part of an allocated block!");
203
204 // Round up size for alignment of header.
205 unsigned HeaderAlign = __alignof(FreeRangeHeader);
206 NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
207
208 // Size is now the size of the block we will remove from the start of the
209 // current block.
210 assert(NewSize <= BlockSize &&
211 "Allocating more space from this block than exists!");
212
213 // If splitting this block will cause the remainder to be too small, do not
214 // split the block.
215 if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
216 return FreeList;
217
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();
221
222 // Change the size of this block.
223 BlockSize = NewSize;
224
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;
234}
235
236//===----------------------------------------------------------------------===//
237// Memory Block Implementation.
238//===----------------------------------------------------------------------===//
239
240namespace {
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
246 /// are emitting is.
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.
250
251 // When emitting code into a memory block, this is the block.
252 MemoryRangeHeader *CurBlock;
253
254 unsigned char *CurStubPtr, *StubBase;
255 unsigned char *GOTBase; // Target Specific reserved memory
256
257 // Centralize memory block allocation.
258 sys::MemoryBlock getNewMemoryBlock(unsigned size);
259
260 std::map<const Function*, MemoryRangeHeader*> FunctionBlocks;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000261 std::map<const Function*, MemoryRangeHeader*> TableBlocks;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000262 public:
263 DefaultJITMemoryManager();
264 ~DefaultJITMemoryManager();
265
266 void AllocateGOT();
267
268 unsigned char *allocateStub(unsigned StubSize, unsigned Alignment);
269
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;
274
275 // Allocate the entire memory block.
276 FreeMemoryList = FreeMemoryList->AllocateBlock();
277 ActualSize = CurBlock->BlockSize-sizeof(MemoryRangeHeader);
278 return (unsigned char *)(CurBlock+1);
279 }
280
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!");
288
289 uintptr_t BlockSize = FunctionEnd - (unsigned char *)CurBlock;
290 FunctionBlocks[F] = CurBlock;
291
292 // Release the memory at the end of this block that isn't needed.
293 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
294 }
295
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000296 /// startExceptionTable - Use startFunctionBody to allocate memory for the
297 /// function's exception table.
Chris Lattner0fdaa0b2008-03-07 20:05:43 +0000298 unsigned char* startExceptionTable(const Function* F,
299 uintptr_t &ActualSize) {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000300 return startFunctionBody(F, ActualSize);
301 }
302
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!");
311
312 uintptr_t BlockSize = TableEnd - (unsigned char *)CurBlock;
313 TableBlocks[F] = CurBlock;
314
315 // Release the memory at the end of this block that isn't needed.
316 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
317 }
318
Chris Lattner8907b4b2007-12-05 23:39:57 +0000319 unsigned char *getGOTBase() const {
320 return GOTBase;
321 }
322
323 /// deallocateMemForFunction - Deallocate all memory for the specified
324 /// function body.
325 void deallocateMemForFunction(const Function *F) {
326 std::map<const Function*, MemoryRangeHeader*>::iterator
327 I = FunctionBlocks.find(F);
328 if (I == FunctionBlocks.end()) return;
329
330 // Find the block that is allocated for this function.
331 MemoryRangeHeader *MemRange = I->second;
332 assert(MemRange->ThisAllocated && "Block isn't allocated!");
333
334 // Fill the buffer with garbage!
335#ifndef NDEBUG
336 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
337#endif
338
339 // Free the memory.
340 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
341
342 // Finally, remove this entry from FunctionBlocks.
343 FunctionBlocks.erase(I);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000344
345 I = TableBlocks.find(F);
346 if (I == TableBlocks.end()) return;
347
348 // Find the block that is allocated for this function.
349 MemRange = I->second;
350 assert(MemRange->ThisAllocated && "Block isn't allocated!");
351
352 // Fill the buffer with garbage!
353#ifndef NDEBUG
354 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
355#endif
356
357 // Free the memory.
358 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
359
360 // Finally, remove this entry from TableBlocks.
361 TableBlocks.erase(I);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000362 }
363 };
364}
365
366DefaultJITMemoryManager::DefaultJITMemoryManager() {
367 // Allocate a 16M block of memory for functions.
368 sys::MemoryBlock MemBlock = getNewMemoryBlock(16 << 20);
369
370 unsigned char *MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
371
372 // Allocate stubs backwards from the base, allocate functions forward
373 // from the base.
374 StubBase = MemBase;
375 CurStubPtr = MemBase + 512*1024; // Use 512k for stubs, working backwards.
376
377 // We set up the memory chunk with 4 mem regions, like this:
378 // [ START
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.
383 // END ]
384 //
385 // The last three blocks are never deallocated or touched.
386
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;
392 Mem3->BlockSize = 0;
393
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.
402 Mem2->Next = Mem2;
403
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;
409
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
412 // at it.
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);
419
420 // Start out with the freelist pointing to Mem0.
421 FreeMemoryList = Mem0;
422
423 GOTBase = NULL;
424}
425
426void DefaultJITMemoryManager::AllocateGOT() {
427 assert(GOTBase == 0 && "Cannot allocate the got multiple times");
428 GOTBase = new unsigned char[sizeof(void*) * 8192];
429 HasGOT = true;
430}
431
432
433DefaultJITMemoryManager::~DefaultJITMemoryManager() {
434 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
435 sys::Memory::ReleaseRWX(Blocks[i]);
436
437 delete[] GOTBase;
438 Blocks.clear();
439}
440
441unsigned 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");
449 abort();
450 }
451 return CurStubPtr;
452}
453
454sys::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();
457 std::string ErrMsg;
458 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld, &ErrMsg);
459 if (B.base() == 0) {
460 fprintf(stderr,
461 "Allocation failed when allocating new memory in the JIT\n%s\n",
462 ErrMsg.c_str());
463 abort();
464 }
465 Blocks.push_back(B);
466 return B;
467}
468
469
470JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
471 return new DefaultJITMemoryManager();
472}