blob: 9820493828cf8e9c88b49cfa36f40a2ee355fbc7 [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
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +000014#include "llvm/GlobalValue.h"
Chris Lattner8907b4b2007-12-05 23:39:57 +000015#include "llvm/ExecutionEngine/JITMemoryManager.h"
16#include "llvm/Support/Compiler.h"
17#include "llvm/System/Memory.h"
18#include <map>
19#include <vector>
Chuck Rose III3012ac62007-12-06 02:03:01 +000020#include <cassert>
Dan Gohmande551f92009-04-01 18:45:54 +000021#include <climits>
Duncan Sands4520dd22008-10-08 07:23:46 +000022#include <cstdio>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000023#include <cstdlib>
24#include <cstring>
Chris Lattner8907b4b2007-12-05 23:39:57 +000025using namespace llvm;
26
27
28JITMemoryManager::~JITMemoryManager() {}
29
30//===----------------------------------------------------------------------===//
31// Memory Block Implementation.
32//===----------------------------------------------------------------------===//
33
34namespace {
35 /// MemoryRangeHeader - For a range of memory, this is the header that we put
36 /// on the block of memory. It is carefully crafted to be one word of memory.
37 /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
38 /// which starts with this.
39 struct FreeRangeHeader;
40 struct MemoryRangeHeader {
41 /// ThisAllocated - This is true if this block is currently allocated. If
42 /// not, this can be converted to a FreeRangeHeader.
43 unsigned ThisAllocated : 1;
44
45 /// PrevAllocated - Keep track of whether the block immediately before us is
46 /// allocated. If not, the word immediately before this header is the size
47 /// of the previous block.
48 unsigned PrevAllocated : 1;
49
50 /// BlockSize - This is the size in bytes of this memory block,
51 /// including this header.
Dan Gohmande551f92009-04-01 18:45:54 +000052 uintptr_t BlockSize : (sizeof(intptr_t)*CHAR_BIT - 2);
Chris Lattner8907b4b2007-12-05 23:39:57 +000053
54
55 /// getBlockAfter - Return the memory block immediately after this one.
56 ///
57 MemoryRangeHeader &getBlockAfter() const {
58 return *(MemoryRangeHeader*)((char*)this+BlockSize);
59 }
60
61 /// getFreeBlockBefore - If the block before this one is free, return it,
62 /// otherwise return null.
63 FreeRangeHeader *getFreeBlockBefore() const {
64 if (PrevAllocated) return 0;
65 intptr_t PrevSize = ((intptr_t *)this)[-1];
66 return (FreeRangeHeader*)((char*)this-PrevSize);
67 }
68
69 /// FreeBlock - Turn an allocated block into a free block, adjusting
70 /// bits in the object headers, and adding an end of region memory block.
71 FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
72
73 /// TrimAllocationToSize - If this allocated block is significantly larger
74 /// than NewSize, split it into two pieces (where the former is NewSize
75 /// bytes, including the header), and add the new block to the free list.
76 FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
77 uint64_t NewSize);
78 };
79
80 /// FreeRangeHeader - For a memory block that isn't already allocated, this
81 /// keeps track of the current block and has a pointer to the next free block.
82 /// Free blocks are kept on a circularly linked list.
83 struct FreeRangeHeader : public MemoryRangeHeader {
84 FreeRangeHeader *Prev;
85 FreeRangeHeader *Next;
86
87 /// getMinBlockSize - Get the minimum size for a memory block. Blocks
88 /// smaller than this size cannot be created.
89 static unsigned getMinBlockSize() {
90 return sizeof(FreeRangeHeader)+sizeof(intptr_t);
91 }
92
93 /// SetEndOfBlockSizeMarker - The word at the end of every free block is
94 /// known to be the size of the free block. Set it for this block.
95 void SetEndOfBlockSizeMarker() {
96 void *EndOfBlock = (char*)this + BlockSize;
97 ((intptr_t *)EndOfBlock)[-1] = BlockSize;
98 }
99
100 FreeRangeHeader *RemoveFromFreeList() {
101 assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
102 Next->Prev = Prev;
103 return Prev->Next = Next;
104 }
105
106 void AddToFreeList(FreeRangeHeader *FreeList) {
107 Next = FreeList;
108 Prev = FreeList->Prev;
109 Prev->Next = this;
110 Next->Prev = this;
111 }
112
113 /// GrowBlock - The block after this block just got deallocated. Merge it
114 /// into the current block.
115 void GrowBlock(uintptr_t NewSize);
116
117 /// AllocateBlock - Mark this entire block allocated, updating freelists
118 /// etc. This returns a pointer to the circular free-list.
119 FreeRangeHeader *AllocateBlock();
120 };
121}
122
123
124/// AllocateBlock - Mark this entire block allocated, updating freelists
125/// etc. This returns a pointer to the circular free-list.
126FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
127 assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
128 "Cannot allocate an allocated block!");
129 // Mark this block allocated.
130 ThisAllocated = 1;
131 getBlockAfter().PrevAllocated = 1;
132
133 // Remove it from the free list.
134 return RemoveFromFreeList();
135}
136
137/// FreeBlock - Turn an allocated block into a free block, adjusting
138/// bits in the object headers, and adding an end of region memory block.
139/// If possible, coalesce this block with neighboring blocks. Return the
140/// FreeRangeHeader to allocate from.
141FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
142 MemoryRangeHeader *FollowingBlock = &getBlockAfter();
143 assert(ThisAllocated && "This block is already allocated!");
144 assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
145
146 FreeRangeHeader *FreeListToReturn = FreeList;
147
148 // If the block after this one is free, merge it into this block.
149 if (!FollowingBlock->ThisAllocated) {
150 FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
151 // "FreeList" always needs to be a valid free block. If we're about to
152 // coalesce with it, update our notion of what the free list is.
153 if (&FollowingFreeBlock == FreeList) {
154 FreeList = FollowingFreeBlock.Next;
155 FreeListToReturn = 0;
156 assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
157 }
158 FollowingFreeBlock.RemoveFromFreeList();
159
160 // Include the following block into this one.
161 BlockSize += FollowingFreeBlock.BlockSize;
162 FollowingBlock = &FollowingFreeBlock.getBlockAfter();
163
164 // Tell the block after the block we are coalescing that this block is
165 // allocated.
166 FollowingBlock->PrevAllocated = 1;
167 }
168
169 assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
170
171 if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
172 PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
173 return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
174 }
175
176 // Otherwise, mark this block free.
177 FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
178 FollowingBlock->PrevAllocated = 0;
179 FreeBlock.ThisAllocated = 0;
180
181 // Link this into the linked list of free blocks.
182 FreeBlock.AddToFreeList(FreeList);
183
184 // Add a marker at the end of the block, indicating the size of this free
185 // block.
186 FreeBlock.SetEndOfBlockSizeMarker();
187 return FreeListToReturn ? FreeListToReturn : &FreeBlock;
188}
189
190/// GrowBlock - The block after this block just got deallocated. Merge it
191/// into the current block.
192void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
193 assert(NewSize > BlockSize && "Not growing block?");
194 BlockSize = NewSize;
195 SetEndOfBlockSizeMarker();
196 getBlockAfter().PrevAllocated = 0;
197}
198
199/// TrimAllocationToSize - If this allocated block is significantly larger
200/// than NewSize, split it into two pieces (where the former is NewSize
201/// bytes, including the header), and add the new block to the free list.
202FreeRangeHeader *MemoryRangeHeader::
203TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
204 assert(ThisAllocated && getBlockAfter().PrevAllocated &&
205 "Cannot deallocate part of an allocated block!");
206
Evan Cheng60b75f42008-07-29 07:38:32 +0000207 // Don't allow blocks to be trimmed below minimum required size
208 NewSize = std::max<uint64_t>(FreeRangeHeader::getMinBlockSize(), NewSize);
209
Chris Lattner8907b4b2007-12-05 23:39:57 +0000210 // Round up size for alignment of header.
211 unsigned HeaderAlign = __alignof(FreeRangeHeader);
212 NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
213
214 // Size is now the size of the block we will remove from the start of the
215 // current block.
216 assert(NewSize <= BlockSize &&
217 "Allocating more space from this block than exists!");
218
219 // If splitting this block will cause the remainder to be too small, do not
220 // split the block.
221 if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
222 return FreeList;
223
224 // Otherwise, we splice the required number of bytes out of this block, form
225 // a new block immediately after it, then mark this block allocated.
226 MemoryRangeHeader &FormerNextBlock = getBlockAfter();
227
228 // Change the size of this block.
229 BlockSize = NewSize;
230
231 // Get the new block we just sliced out and turn it into a free block.
232 FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
233 NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
234 NewNextBlock.ThisAllocated = 0;
235 NewNextBlock.PrevAllocated = 1;
236 NewNextBlock.SetEndOfBlockSizeMarker();
237 FormerNextBlock.PrevAllocated = 0;
238 NewNextBlock.AddToFreeList(FreeList);
239 return &NewNextBlock;
240}
241
242//===----------------------------------------------------------------------===//
243// Memory Block Implementation.
244//===----------------------------------------------------------------------===//
245
246namespace {
247 /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
248 /// This splits a large block of MAP_NORESERVE'd memory into two
249 /// sections, one for function stubs, one for the functions themselves. We
250 /// have to do this because we may need to emit a function stub while in the
251 /// middle of emitting a function, and we don't know how large the function we
252 /// are emitting is.
253 class VISIBILITY_HIDDEN DefaultJITMemoryManager : public JITMemoryManager {
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000254 bool PoisonMemory; // Whether to poison freed memory.
255
Chris Lattner8907b4b2007-12-05 23:39:57 +0000256 std::vector<sys::MemoryBlock> Blocks; // Memory blocks allocated by the JIT
257 FreeRangeHeader *FreeMemoryList; // Circular list of free blocks.
258
259 // When emitting code into a memory block, this is the block.
260 MemoryRangeHeader *CurBlock;
261
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000262 uint8_t *CurStubPtr, *StubBase;
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000263 uint8_t *CurGlobalPtr, *GlobalEnd;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000264 uint8_t *GOTBase; // Target Specific reserved memory
265 void *DlsymTable; // Stub external symbol information
Chris Lattner8907b4b2007-12-05 23:39:57 +0000266
267 // Centralize memory block allocation.
268 sys::MemoryBlock getNewMemoryBlock(unsigned size);
269
270 std::map<const Function*, MemoryRangeHeader*> FunctionBlocks;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000271 std::map<const Function*, MemoryRangeHeader*> TableBlocks;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000272 public:
273 DefaultJITMemoryManager();
274 ~DefaultJITMemoryManager();
275
276 void AllocateGOT();
Nate Begemand6b7a242009-02-18 08:31:02 +0000277 void SetDlsymTable(void *);
278
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000279 uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
280 unsigned Alignment);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000281
282 /// startFunctionBody - When a function starts, allocate a block of free
283 /// executable memory, returning a pointer to it and its actual size.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000284 uint8_t *startFunctionBody(const Function *F, uintptr_t &ActualSize) {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000285
Chris Lattner96c96b42009-03-09 21:34:10 +0000286 FreeRangeHeader* candidateBlock = FreeMemoryList;
287 FreeRangeHeader* head = FreeMemoryList;
288 FreeRangeHeader* iter = head->Next;
289
290 uintptr_t largest = candidateBlock->BlockSize;
291
292 // Search for the largest free block
293 while (iter != head) {
294 if (iter->BlockSize > largest) {
295 largest = iter->BlockSize;
296 candidateBlock = iter;
297 }
298 iter = iter->Next;
299 }
300
301 // Select this candidate block for allocation
302 CurBlock = candidateBlock;
303
Chris Lattner8907b4b2007-12-05 23:39:57 +0000304 // Allocate the entire memory block.
Chris Lattner96c96b42009-03-09 21:34:10 +0000305 FreeMemoryList = candidateBlock->AllocateBlock();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000306 ActualSize = CurBlock->BlockSize-sizeof(MemoryRangeHeader);
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000307 return (uint8_t *)(CurBlock+1);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000308 }
309
310 /// endFunctionBody - The function F is now allocated, and takes the memory
311 /// in the range [FunctionStart,FunctionEnd).
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000312 void endFunctionBody(const Function *F, uint8_t *FunctionStart,
313 uint8_t *FunctionEnd) {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000314 assert(FunctionEnd > FunctionStart);
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000315 assert(FunctionStart == (uint8_t *)(CurBlock+1) &&
Chris Lattner8907b4b2007-12-05 23:39:57 +0000316 "Mismatched function start/end!");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000317
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000318 uintptr_t BlockSize = FunctionEnd - (uint8_t *)CurBlock;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000319 FunctionBlocks[F] = CurBlock;
320
321 // Release the memory at the end of this block that isn't needed.
322 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
323 }
Nuno Lopescef75272008-10-21 11:42:16 +0000324
325 /// allocateSpace - Allocate a memory block of the given size.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000326 uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +0000327 CurBlock = FreeMemoryList;
328 FreeMemoryList = FreeMemoryList->AllocateBlock();
329
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000330 uint8_t *result = (uint8_t *)(CurBlock + 1);
Nuno Lopescef75272008-10-21 11:42:16 +0000331
332 if (Alignment == 0) Alignment = 1;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000333 result = (uint8_t*)(((intptr_t)result+Alignment-1) &
Nuno Lopescef75272008-10-21 11:42:16 +0000334 ~(intptr_t)(Alignment-1));
335
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000336 uintptr_t BlockSize = result + Size - (uint8_t *)CurBlock;
Nuno Lopescef75272008-10-21 11:42:16 +0000337 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
338
339 return result;
340 }
341
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000342 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
343 /// this method does not touch the current block and can be called at any
344 /// time.
345 uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
346 uint8_t *Result = CurGlobalPtr;
347
348 // Align the pointer.
349 if (Alignment == 0) Alignment = 1;
350 Result = (uint8_t*)(((uintptr_t)Result + Alignment-1) &
351 ~(uintptr_t)(Alignment-1));
352
353 // Move the current global pointer forward.
354 CurGlobalPtr += Result - CurGlobalPtr + Size;
355
356 // Check for overflow.
357 if (CurGlobalPtr > GlobalEnd) {
358 // FIXME: Allocate more memory.
359 fprintf(stderr, "JIT ran out of memory for globals!\n");
360 abort();
361 }
362
363 return Result;
364 }
365
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000366 /// startExceptionTable - Use startFunctionBody to allocate memory for the
367 /// function's exception table.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000368 uint8_t* startExceptionTable(const Function* F, uintptr_t &ActualSize) {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000369 return startFunctionBody(F, ActualSize);
370 }
371
372 /// endExceptionTable - The exception table of F is now allocated,
373 /// and takes the memory in the range [TableStart,TableEnd).
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000374 void endExceptionTable(const Function *F, uint8_t *TableStart,
375 uint8_t *TableEnd, uint8_t* FrameRegister) {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000376 assert(TableEnd > TableStart);
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000377 assert(TableStart == (uint8_t *)(CurBlock+1) &&
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000378 "Mismatched table start/end!");
379
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000380 uintptr_t BlockSize = TableEnd - (uint8_t *)CurBlock;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000381 TableBlocks[F] = CurBlock;
382
383 // Release the memory at the end of this block that isn't needed.
384 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
385 }
386
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000387 uint8_t *getGOTBase() const {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000388 return GOTBase;
389 }
390
Nate Begemand6b7a242009-02-18 08:31:02 +0000391 void *getDlsymTable() const {
392 return DlsymTable;
393 }
394
Chris Lattner8907b4b2007-12-05 23:39:57 +0000395 /// deallocateMemForFunction - Deallocate all memory for the specified
396 /// function body.
397 void deallocateMemForFunction(const Function *F) {
398 std::map<const Function*, MemoryRangeHeader*>::iterator
399 I = FunctionBlocks.find(F);
400 if (I == FunctionBlocks.end()) return;
401
402 // Find the block that is allocated for this function.
403 MemoryRangeHeader *MemRange = I->second;
404 assert(MemRange->ThisAllocated && "Block isn't allocated!");
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000405
Chris Lattner8907b4b2007-12-05 23:39:57 +0000406 // Fill the buffer with garbage!
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000407 if (PoisonMemory) {
408 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
409 }
410
Chris Lattner8907b4b2007-12-05 23:39:57 +0000411 // Free the memory.
412 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
413
414 // Finally, remove this entry from FunctionBlocks.
415 FunctionBlocks.erase(I);
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000416
417 I = TableBlocks.find(F);
418 if (I == TableBlocks.end()) return;
419
420 // Find the block that is allocated for this function.
421 MemRange = I->second;
422 assert(MemRange->ThisAllocated && "Block isn't allocated!");
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000423
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000424 // Fill the buffer with garbage!
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000425 if (PoisonMemory) {
426 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
427 }
428
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000429 // Free the memory.
430 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
431
432 // Finally, remove this entry from TableBlocks.
433 TableBlocks.erase(I);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000434 }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000435
436 /// setMemoryWritable - When code generation is in progress,
437 /// the code pages may need permissions changed.
438 void setMemoryWritable(void)
439 {
440 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
441 sys::Memory::setWritable(Blocks[i]);
442 }
443 /// setMemoryExecutable - When code generation is done and we're ready to
444 /// start execution, the code pages may need permissions changed.
445 void setMemoryExecutable(void)
446 {
447 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
448 sys::Memory::setExecutable(Blocks[i]);
449 }
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000450
451 /// setPoisonMemory - Controls whether we write garbage over freed memory.
452 ///
453 void setPoisonMemory(bool poison) {
454 PoisonMemory = poison;
455 }
Chris Lattner8907b4b2007-12-05 23:39:57 +0000456 };
457}
458
459DefaultJITMemoryManager::DefaultJITMemoryManager() {
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000460#ifdef NDEBUG
461 PoisonMemory = true;
462#else
463 PoisonMemory = false;
464#endif
465
Chris Lattner8907b4b2007-12-05 23:39:57 +0000466 // Allocate a 16M block of memory for functions.
Evan Chengbc4707a2008-09-18 07:54:21 +0000467#if defined(__APPLE__) && defined(__arm__)
468 sys::MemoryBlock MemBlock = getNewMemoryBlock(4 << 20);
469#else
Chris Lattner8907b4b2007-12-05 23:39:57 +0000470 sys::MemoryBlock MemBlock = getNewMemoryBlock(16 << 20);
Evan Chengbc4707a2008-09-18 07:54:21 +0000471#endif
Chris Lattner8907b4b2007-12-05 23:39:57 +0000472
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000473 uint8_t *MemBase = static_cast<uint8_t*>(MemBlock.base());
Chris Lattner8907b4b2007-12-05 23:39:57 +0000474
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000475 // Allocate stubs backwards to the base, globals forward from the stubs, and
476 // functions forward after globals.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000477 StubBase = MemBase;
478 CurStubPtr = MemBase + 512*1024; // Use 512k for stubs, working backwards.
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000479 CurGlobalPtr = CurStubPtr; // Use 2M for globals, working forwards.
480 GlobalEnd = CurGlobalPtr + 2*1024*1024;
481
Chris Lattner8907b4b2007-12-05 23:39:57 +0000482 // We set up the memory chunk with 4 mem regions, like this:
483 // [ START
484 // [ Free #0 ] -> Large space to allocate functions from.
485 // [ Allocated #1 ] -> Tiny space to separate regions.
486 // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
487 // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
488 // END ]
489 //
490 // The last three blocks are never deallocated or touched.
491
492 // Add MemoryRangeHeader to the end of the memory region, indicating that
493 // the space after the block of memory is allocated. This is block #3.
494 MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
495 Mem3->ThisAllocated = 1;
496 Mem3->PrevAllocated = 0;
497 Mem3->BlockSize = 0;
498
499 /// Add a tiny free region so that the free list always has one entry.
500 FreeRangeHeader *Mem2 =
501 (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
502 Mem2->ThisAllocated = 0;
503 Mem2->PrevAllocated = 1;
504 Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
505 Mem2->SetEndOfBlockSizeMarker();
506 Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
507 Mem2->Next = Mem2;
508
509 /// Add a tiny allocated region so that Mem2 is never coalesced away.
510 MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
511 Mem1->ThisAllocated = 1;
512 Mem1->PrevAllocated = 0;
513 Mem1->BlockSize = (char*)Mem2 - (char*)Mem1;
514
515 // Add a FreeRangeHeader to the start of the function body region, indicating
516 // that the space is free. Mark the previous block allocated so we never look
517 // at it.
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000518 FreeRangeHeader *Mem0 = (FreeRangeHeader*)GlobalEnd;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000519 Mem0->ThisAllocated = 0;
520 Mem0->PrevAllocated = 1;
521 Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
522 Mem0->SetEndOfBlockSizeMarker();
523 Mem0->AddToFreeList(Mem2);
524
525 // Start out with the freelist pointing to Mem0.
526 FreeMemoryList = Mem0;
527
528 GOTBase = NULL;
Nate Begemand6b7a242009-02-18 08:31:02 +0000529 DlsymTable = NULL;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000530}
531
532void DefaultJITMemoryManager::AllocateGOT() {
533 assert(GOTBase == 0 && "Cannot allocate the got multiple times");
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000534 GOTBase = new uint8_t[sizeof(void*) * 8192];
Chris Lattner8907b4b2007-12-05 23:39:57 +0000535 HasGOT = true;
536}
537
Nate Begemand6b7a242009-02-18 08:31:02 +0000538void DefaultJITMemoryManager::SetDlsymTable(void *ptr) {
539 DlsymTable = ptr;
540}
Chris Lattner8907b4b2007-12-05 23:39:57 +0000541
542DefaultJITMemoryManager::~DefaultJITMemoryManager() {
543 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
544 sys::Memory::ReleaseRWX(Blocks[i]);
545
546 delete[] GOTBase;
547 Blocks.clear();
548}
549
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000550uint8_t *DefaultJITMemoryManager::allocateStub(const GlobalValue* F,
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000551 unsigned StubSize,
Chris Lattner8907b4b2007-12-05 23:39:57 +0000552 unsigned Alignment) {
553 CurStubPtr -= StubSize;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000554 CurStubPtr = (uint8_t*)(((intptr_t)CurStubPtr) &
555 ~(intptr_t)(Alignment-1));
Chris Lattner8907b4b2007-12-05 23:39:57 +0000556 if (CurStubPtr < StubBase) {
557 // FIXME: allocate a new block
558 fprintf(stderr, "JIT ran out of memory for function stubs!\n");
559 abort();
560 }
561 return CurStubPtr;
562}
563
564sys::MemoryBlock DefaultJITMemoryManager::getNewMemoryBlock(unsigned size) {
565 // Allocate a new block close to the last one.
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000566 const sys::MemoryBlock *BOld = Blocks.empty() ? 0 : &Blocks.back();
Chris Lattner8907b4b2007-12-05 23:39:57 +0000567 std::string ErrMsg;
568 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld, &ErrMsg);
569 if (B.base() == 0) {
570 fprintf(stderr,
571 "Allocation failed when allocating new memory in the JIT\n%s\n",
572 ErrMsg.c_str());
573 abort();
574 }
575 Blocks.push_back(B);
576 return B;
577}
578
579
580JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
581 return new DefaultJITMemoryManager();
582}