blob: 3796624621474c449c3c527e1b4c342a43c9b6a4 [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
Reid Kleckner10b4fc52009-07-23 21:46:56 +000014#define DEBUG_TYPE "jit"
Reid Kleckner4bf37062009-07-23 01:40:54 +000015#include "llvm/ExecutionEngine/JITMemoryManager.h"
Reid Kleckner10b4fc52009-07-23 21:46:56 +000016#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/Statistic.h"
18#include "llvm/GlobalValue.h"
19#include "llvm/Support/Allocator.h"
Chris Lattner8907b4b2007-12-05 23:39:57 +000020#include "llvm/Support/Compiler.h"
Reid Kleckner10b4fc52009-07-23 21:46:56 +000021#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000022#include "llvm/Support/ErrorHandling.h"
Reid Kleckner10b4fc52009-07-23 21:46:56 +000023#include "llvm/Support/raw_ostream.h"
Chris Lattner8907b4b2007-12-05 23:39:57 +000024#include "llvm/System/Memory.h"
25#include <map>
26#include <vector>
Chuck Rose III3012ac62007-12-06 02:03:01 +000027#include <cassert>
Dan Gohmande551f92009-04-01 18:45:54 +000028#include <climits>
Duncan Sands4520dd22008-10-08 07:23:46 +000029#include <cstdio>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000030#include <cstdlib>
31#include <cstring>
Chris Lattner8907b4b2007-12-05 23:39:57 +000032using namespace llvm;
33
Reid Kleckner10b4fc52009-07-23 21:46:56 +000034STATISTIC(NumSlabs, "Number of slabs of memory allocated by the JIT");
Chris Lattner8907b4b2007-12-05 23:39:57 +000035
36JITMemoryManager::~JITMemoryManager() {}
37
38//===----------------------------------------------------------------------===//
39// Memory Block Implementation.
40//===----------------------------------------------------------------------===//
41
42namespace {
43 /// MemoryRangeHeader - For a range of memory, this is the header that we put
44 /// on the block of memory. It is carefully crafted to be one word of memory.
45 /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
46 /// which starts with this.
47 struct FreeRangeHeader;
48 struct MemoryRangeHeader {
49 /// ThisAllocated - This is true if this block is currently allocated. If
50 /// not, this can be converted to a FreeRangeHeader.
51 unsigned ThisAllocated : 1;
52
53 /// PrevAllocated - Keep track of whether the block immediately before us is
54 /// allocated. If not, the word immediately before this header is the size
55 /// of the previous block.
56 unsigned PrevAllocated : 1;
57
58 /// BlockSize - This is the size in bytes of this memory block,
59 /// including this header.
Dan Gohmande551f92009-04-01 18:45:54 +000060 uintptr_t BlockSize : (sizeof(intptr_t)*CHAR_BIT - 2);
Chris Lattner8907b4b2007-12-05 23:39:57 +000061
62
63 /// getBlockAfter - Return the memory block immediately after this one.
64 ///
65 MemoryRangeHeader &getBlockAfter() const {
66 return *(MemoryRangeHeader*)((char*)this+BlockSize);
67 }
68
69 /// getFreeBlockBefore - If the block before this one is free, return it,
70 /// otherwise return null.
71 FreeRangeHeader *getFreeBlockBefore() const {
72 if (PrevAllocated) return 0;
73 intptr_t PrevSize = ((intptr_t *)this)[-1];
74 return (FreeRangeHeader*)((char*)this-PrevSize);
75 }
76
77 /// FreeBlock - Turn an allocated block into a free block, adjusting
78 /// bits in the object headers, and adding an end of region memory block.
79 FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
80
81 /// TrimAllocationToSize - If this allocated block is significantly larger
82 /// than NewSize, split it into two pieces (where the former is NewSize
83 /// bytes, including the header), and add the new block to the free list.
84 FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
85 uint64_t NewSize);
86 };
87
88 /// FreeRangeHeader - For a memory block that isn't already allocated, this
89 /// keeps track of the current block and has a pointer to the next free block.
90 /// Free blocks are kept on a circularly linked list.
91 struct FreeRangeHeader : public MemoryRangeHeader {
92 FreeRangeHeader *Prev;
93 FreeRangeHeader *Next;
94
95 /// getMinBlockSize - Get the minimum size for a memory block. Blocks
96 /// smaller than this size cannot be created.
97 static unsigned getMinBlockSize() {
98 return sizeof(FreeRangeHeader)+sizeof(intptr_t);
99 }
100
101 /// SetEndOfBlockSizeMarker - The word at the end of every free block is
102 /// known to be the size of the free block. Set it for this block.
103 void SetEndOfBlockSizeMarker() {
104 void *EndOfBlock = (char*)this + BlockSize;
105 ((intptr_t *)EndOfBlock)[-1] = BlockSize;
106 }
107
108 FreeRangeHeader *RemoveFromFreeList() {
109 assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
110 Next->Prev = Prev;
111 return Prev->Next = Next;
112 }
113
114 void AddToFreeList(FreeRangeHeader *FreeList) {
115 Next = FreeList;
116 Prev = FreeList->Prev;
117 Prev->Next = this;
118 Next->Prev = this;
119 }
120
121 /// GrowBlock - The block after this block just got deallocated. Merge it
122 /// into the current block.
123 void GrowBlock(uintptr_t NewSize);
124
125 /// AllocateBlock - Mark this entire block allocated, updating freelists
126 /// etc. This returns a pointer to the circular free-list.
127 FreeRangeHeader *AllocateBlock();
128 };
129}
130
131
132/// AllocateBlock - Mark this entire block allocated, updating freelists
133/// etc. This returns a pointer to the circular free-list.
134FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
135 assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
136 "Cannot allocate an allocated block!");
137 // Mark this block allocated.
138 ThisAllocated = 1;
139 getBlockAfter().PrevAllocated = 1;
140
141 // Remove it from the free list.
142 return RemoveFromFreeList();
143}
144
145/// FreeBlock - Turn an allocated block into a free block, adjusting
146/// bits in the object headers, and adding an end of region memory block.
147/// If possible, coalesce this block with neighboring blocks. Return the
148/// FreeRangeHeader to allocate from.
149FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
150 MemoryRangeHeader *FollowingBlock = &getBlockAfter();
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000151 assert(ThisAllocated && "This block is already free!");
Chris Lattner8907b4b2007-12-05 23:39:57 +0000152 assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
153
154 FreeRangeHeader *FreeListToReturn = FreeList;
155
156 // If the block after this one is free, merge it into this block.
157 if (!FollowingBlock->ThisAllocated) {
158 FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
159 // "FreeList" always needs to be a valid free block. If we're about to
160 // coalesce with it, update our notion of what the free list is.
161 if (&FollowingFreeBlock == FreeList) {
162 FreeList = FollowingFreeBlock.Next;
163 FreeListToReturn = 0;
164 assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
165 }
166 FollowingFreeBlock.RemoveFromFreeList();
167
168 // Include the following block into this one.
169 BlockSize += FollowingFreeBlock.BlockSize;
170 FollowingBlock = &FollowingFreeBlock.getBlockAfter();
171
172 // Tell the block after the block we are coalescing that this block is
173 // allocated.
174 FollowingBlock->PrevAllocated = 1;
175 }
176
177 assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
178
179 if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
180 PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
181 return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
182 }
183
184 // Otherwise, mark this block free.
185 FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
186 FollowingBlock->PrevAllocated = 0;
187 FreeBlock.ThisAllocated = 0;
188
189 // Link this into the linked list of free blocks.
190 FreeBlock.AddToFreeList(FreeList);
191
192 // Add a marker at the end of the block, indicating the size of this free
193 // block.
194 FreeBlock.SetEndOfBlockSizeMarker();
195 return FreeListToReturn ? FreeListToReturn : &FreeBlock;
196}
197
198/// GrowBlock - The block after this block just got deallocated. Merge it
199/// into the current block.
200void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
201 assert(NewSize > BlockSize && "Not growing block?");
202 BlockSize = NewSize;
203 SetEndOfBlockSizeMarker();
204 getBlockAfter().PrevAllocated = 0;
205}
206
207/// TrimAllocationToSize - If this allocated block is significantly larger
208/// than NewSize, split it into two pieces (where the former is NewSize
209/// bytes, including the header), and add the new block to the free list.
210FreeRangeHeader *MemoryRangeHeader::
211TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
212 assert(ThisAllocated && getBlockAfter().PrevAllocated &&
213 "Cannot deallocate part of an allocated block!");
214
Evan Cheng60b75f42008-07-29 07:38:32 +0000215 // Don't allow blocks to be trimmed below minimum required size
216 NewSize = std::max<uint64_t>(FreeRangeHeader::getMinBlockSize(), NewSize);
217
Chris Lattner8907b4b2007-12-05 23:39:57 +0000218 // Round up size for alignment of header.
219 unsigned HeaderAlign = __alignof(FreeRangeHeader);
220 NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
221
222 // Size is now the size of the block we will remove from the start of the
223 // current block.
224 assert(NewSize <= BlockSize &&
225 "Allocating more space from this block than exists!");
226
227 // If splitting this block will cause the remainder to be too small, do not
228 // split the block.
229 if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
230 return FreeList;
231
232 // Otherwise, we splice the required number of bytes out of this block, form
233 // a new block immediately after it, then mark this block allocated.
234 MemoryRangeHeader &FormerNextBlock = getBlockAfter();
235
236 // Change the size of this block.
237 BlockSize = NewSize;
238
239 // Get the new block we just sliced out and turn it into a free block.
240 FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
241 NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
242 NewNextBlock.ThisAllocated = 0;
243 NewNextBlock.PrevAllocated = 1;
244 NewNextBlock.SetEndOfBlockSizeMarker();
245 FormerNextBlock.PrevAllocated = 0;
246 NewNextBlock.AddToFreeList(FreeList);
247 return &NewNextBlock;
248}
249
250//===----------------------------------------------------------------------===//
251// Memory Block Implementation.
252//===----------------------------------------------------------------------===//
253
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000254namespace {
255
256 class DefaultJITMemoryManager;
257
258 class JITSlabAllocator : public SlabAllocator {
259 DefaultJITMemoryManager &JMM;
260 public:
261 JITSlabAllocator(DefaultJITMemoryManager &jmm) : JMM(jmm) { }
262 virtual ~JITSlabAllocator() { }
263 virtual MemSlab *Allocate(size_t Size);
264 virtual void Deallocate(MemSlab *Slab);
265 };
266
Chris Lattner8907b4b2007-12-05 23:39:57 +0000267 /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
268 /// This splits a large block of MAP_NORESERVE'd memory into two
269 /// sections, one for function stubs, one for the functions themselves. We
270 /// have to do this because we may need to emit a function stub while in the
271 /// middle of emitting a function, and we don't know how large the function we
272 /// are emitting is.
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000273 class DefaultJITMemoryManager : public JITMemoryManager {
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000274
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000275 // Whether to poison freed memory.
276 bool PoisonMemory;
277
278 /// LastSlab - This points to the last slab allocated and is used as the
279 /// NearBlock parameter to AllocateRWX so that we can attempt to lay out all
280 /// stubs, data, and code contiguously in memory. In general, however, this
281 /// is not possible because the NearBlock parameter is ignored on Windows
282 /// platforms and even on Unix it works on a best-effort pasis.
283 sys::MemoryBlock LastSlab;
284
285 // Memory slabs allocated by the JIT. We refer to them as slabs so we don't
286 // confuse them with the blocks of memory descibed above.
287 std::vector<sys::MemoryBlock> CodeSlabs;
288 JITSlabAllocator BumpSlabAllocator;
289 BumpPtrAllocator StubAllocator;
290 BumpPtrAllocator DataAllocator;
291
292 // Circular list of free blocks.
293 FreeRangeHeader *FreeMemoryList;
294
Chris Lattner8907b4b2007-12-05 23:39:57 +0000295 // When emitting code into a memory block, this is the block.
296 MemoryRangeHeader *CurBlock;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000297
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000298 uint8_t *GOTBase; // Target Specific reserved memory
299 void *DlsymTable; // Stub external symbol information
Chris Lattner8907b4b2007-12-05 23:39:57 +0000300 public:
301 DefaultJITMemoryManager();
302 ~DefaultJITMemoryManager();
303
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000304 /// allocateNewSlab - Allocates a new MemoryBlock and remembers it as the
305 /// last slab it allocated, so that subsequent allocations follow it.
306 sys::MemoryBlock allocateNewSlab(size_t size);
307
308 /// DefaultCodeSlabSize - When we have to go map more memory, we allocate at
309 /// least this much unless more is requested.
310 static const size_t DefaultCodeSlabSize;
311
312 /// DefaultSlabSize - Allocate data into slabs of this size unless we get
313 /// an allocation above SizeThreshold.
314 static const size_t DefaultSlabSize;
315
316 /// DefaultSizeThreshold - For any allocation larger than this threshold, we
317 /// should allocate a separate slab.
318 static const size_t DefaultSizeThreshold;
319
Chris Lattner8907b4b2007-12-05 23:39:57 +0000320 void AllocateGOT();
Nate Begemand6b7a242009-02-18 08:31:02 +0000321 void SetDlsymTable(void *);
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000322
323 // Testing methods.
324 virtual bool CheckInvariants(std::string &ErrorStr);
325 size_t GetDefaultCodeSlabSize() { return DefaultCodeSlabSize; }
326 size_t GetDefaultDataSlabSize() { return DefaultSlabSize; }
327 size_t GetDefaultStubSlabSize() { return DefaultSlabSize; }
328 unsigned GetNumCodeSlabs() { return CodeSlabs.size(); }
329 unsigned GetNumDataSlabs() { return DataAllocator.GetNumSlabs(); }
330 unsigned GetNumStubSlabs() { return StubAllocator.GetNumSlabs(); }
331
Chris Lattner8907b4b2007-12-05 23:39:57 +0000332 /// startFunctionBody - When a function starts, allocate a block of free
333 /// executable memory, returning a pointer to it and its actual size.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000334 uint8_t *startFunctionBody(const Function *F, uintptr_t &ActualSize) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000335
Chris Lattner96c96b42009-03-09 21:34:10 +0000336 FreeRangeHeader* candidateBlock = FreeMemoryList;
337 FreeRangeHeader* head = FreeMemoryList;
338 FreeRangeHeader* iter = head->Next;
339
340 uintptr_t largest = candidateBlock->BlockSize;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000341
Chris Lattner96c96b42009-03-09 21:34:10 +0000342 // Search for the largest free block
343 while (iter != head) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000344 if (iter->BlockSize > largest) {
345 largest = iter->BlockSize;
346 candidateBlock = iter;
347 }
348 iter = iter->Next;
Chris Lattner96c96b42009-03-09 21:34:10 +0000349 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000350
Nicolas Geoffray1b10d792009-07-29 22:55:02 +0000351 largest = largest - sizeof(MemoryRangeHeader);
352
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000353 // If this block isn't big enough for the allocation desired, allocate
354 // another block of memory and add it to the free list.
Nicolas Geoffray1b10d792009-07-29 22:55:02 +0000355 if (largest < ActualSize ||
356 largest <= FreeRangeHeader::getMinBlockSize()) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000357 DEBUG(errs() << "JIT: Allocating another slab of memory for function.");
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000358 candidateBlock = allocateNewCodeSlab((size_t)ActualSize);
359 }
360
Chris Lattner96c96b42009-03-09 21:34:10 +0000361 // Select this candidate block for allocation
362 CurBlock = candidateBlock;
363
Chris Lattner8907b4b2007-12-05 23:39:57 +0000364 // Allocate the entire memory block.
Chris Lattner96c96b42009-03-09 21:34:10 +0000365 FreeMemoryList = candidateBlock->AllocateBlock();
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000366 ActualSize = CurBlock->BlockSize - sizeof(MemoryRangeHeader);
367 return (uint8_t *)(CurBlock + 1);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000368 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000369
370 /// allocateNewCodeSlab - Helper method to allocate a new slab of code
371 /// memory from the OS and add it to the free list. Returns the new
372 /// FreeRangeHeader at the base of the slab.
373 FreeRangeHeader *allocateNewCodeSlab(size_t MinSize) {
374 // If the user needs at least MinSize free memory, then we account for
375 // two MemoryRangeHeaders: the one in the user's block, and the one at the
376 // end of the slab.
377 size_t PaddedMin = MinSize + 2 * sizeof(MemoryRangeHeader);
378 size_t SlabSize = std::max(DefaultCodeSlabSize, PaddedMin);
379 sys::MemoryBlock B = allocateNewSlab(SlabSize);
380 CodeSlabs.push_back(B);
381 char *MemBase = (char*)(B.base());
382
383 // Put a tiny allocated block at the end of the memory chunk, so when
384 // FreeBlock calls getBlockAfter it doesn't fall off the end.
385 MemoryRangeHeader *EndBlock =
386 (MemoryRangeHeader*)(MemBase + B.size()) - 1;
387 EndBlock->ThisAllocated = 1;
388 EndBlock->PrevAllocated = 0;
389 EndBlock->BlockSize = sizeof(MemoryRangeHeader);
390
391 // Start out with a vast new block of free memory.
392 FreeRangeHeader *NewBlock = (FreeRangeHeader*)MemBase;
393 NewBlock->ThisAllocated = 0;
394 // Make sure getFreeBlockBefore doesn't look into unmapped memory.
395 NewBlock->PrevAllocated = 1;
396 NewBlock->BlockSize = (uintptr_t)EndBlock - (uintptr_t)NewBlock;
397 NewBlock->SetEndOfBlockSizeMarker();
398 NewBlock->AddToFreeList(FreeMemoryList);
399
400 assert(NewBlock->BlockSize - sizeof(MemoryRangeHeader) >= MinSize &&
401 "The block was too small!");
402 return NewBlock;
403 }
404
Chris Lattner8907b4b2007-12-05 23:39:57 +0000405 /// endFunctionBody - The function F is now allocated, and takes the memory
406 /// in the range [FunctionStart,FunctionEnd).
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000407 void endFunctionBody(const Function *F, uint8_t *FunctionStart,
408 uint8_t *FunctionEnd) {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000409 assert(FunctionEnd > FunctionStart);
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000410 assert(FunctionStart == (uint8_t *)(CurBlock+1) &&
Chris Lattner8907b4b2007-12-05 23:39:57 +0000411 "Mismatched function start/end!");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000412
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000413 uintptr_t BlockSize = FunctionEnd - (uint8_t *)CurBlock;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000414
415 // Release the memory at the end of this block that isn't needed.
416 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
417 }
Nuno Lopescef75272008-10-21 11:42:16 +0000418
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000419 /// allocateSpace - Allocate a memory block of the given size. This method
420 /// cannot be called between calls to startFunctionBody and endFunctionBody.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000421 uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +0000422 CurBlock = FreeMemoryList;
423 FreeMemoryList = FreeMemoryList->AllocateBlock();
424
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000425 uint8_t *result = (uint8_t *)(CurBlock + 1);
Nuno Lopescef75272008-10-21 11:42:16 +0000426
427 if (Alignment == 0) Alignment = 1;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000428 result = (uint8_t*)(((intptr_t)result+Alignment-1) &
Nuno Lopescef75272008-10-21 11:42:16 +0000429 ~(intptr_t)(Alignment-1));
430
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000431 uintptr_t BlockSize = result + Size - (uint8_t *)CurBlock;
Nuno Lopescef75272008-10-21 11:42:16 +0000432 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
433
434 return result;
435 }
436
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000437 /// allocateStub - Allocate memory for a function stub.
438 uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
439 unsigned Alignment) {
440 return (uint8_t*)StubAllocator.Allocate(StubSize, Alignment);
441 }
442
443 /// allocateGlobal - Allocate memory for a global.
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000444 uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000445 return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000446 }
447
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000448 /// startExceptionTable - Use startFunctionBody to allocate memory for the
449 /// function's exception table.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000450 uint8_t* startExceptionTable(const Function* F, uintptr_t &ActualSize) {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000451 return startFunctionBody(F, ActualSize);
452 }
453
454 /// endExceptionTable - The exception table of F is now allocated,
455 /// and takes the memory in the range [TableStart,TableEnd).
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000456 void endExceptionTable(const Function *F, uint8_t *TableStart,
457 uint8_t *TableEnd, uint8_t* FrameRegister) {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000458 assert(TableEnd > TableStart);
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000459 assert(TableStart == (uint8_t *)(CurBlock+1) &&
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000460 "Mismatched table start/end!");
461
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000462 uintptr_t BlockSize = TableEnd - (uint8_t *)CurBlock;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000463
464 // Release the memory at the end of this block that isn't needed.
465 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
466 }
467
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000468 uint8_t *getGOTBase() const {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000469 return GOTBase;
470 }
471
Nate Begemand6b7a242009-02-18 08:31:02 +0000472 void *getDlsymTable() const {
473 return DlsymTable;
474 }
475
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000476 void deallocateBlock(void *Block) {
477 // Find the block that is allocated for this function.
478 MemoryRangeHeader *MemRange = static_cast<MemoryRangeHeader*>(Block) - 1;
479 assert(MemRange->ThisAllocated && "Block isn't allocated!");
480
481 // Fill the buffer with garbage!
482 if (PoisonMemory) {
483 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
484 }
485
486 // Free the memory.
487 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
488 }
489
490 /// deallocateFunctionBody - Deallocate all memory for the specified
Chris Lattner8907b4b2007-12-05 23:39:57 +0000491 /// function body.
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000492 void deallocateFunctionBody(void *Body) {
Nicolas Geoffray71e0b7c2009-10-22 14:35:57 +0000493 if (Body) deallocateBlock(Body);
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000494 }
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000495
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000496 /// deallocateExceptionTable - Deallocate memory for the specified
497 /// exception table.
498 void deallocateExceptionTable(void *ET) {
Nicolas Geoffray71e0b7c2009-10-22 14:35:57 +0000499 if (ET) deallocateBlock(ET);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000500 }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000501
502 /// setMemoryWritable - When code generation is in progress,
503 /// the code pages may need permissions changed.
Dan Gohmana9ad0412009-08-12 22:10:57 +0000504 void setMemoryWritable()
Jim Grosbachcce6c292008-10-03 16:17:20 +0000505 {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000506 for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
507 sys::Memory::setWritable(CodeSlabs[i]);
Jim Grosbachcce6c292008-10-03 16:17:20 +0000508 }
509 /// setMemoryExecutable - When code generation is done and we're ready to
510 /// start execution, the code pages may need permissions changed.
Dan Gohmana9ad0412009-08-12 22:10:57 +0000511 void setMemoryExecutable()
Jim Grosbachcce6c292008-10-03 16:17:20 +0000512 {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000513 for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
514 sys::Memory::setExecutable(CodeSlabs[i]);
Jim Grosbachcce6c292008-10-03 16:17:20 +0000515 }
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000516
517 /// setPoisonMemory - Controls whether we write garbage over freed memory.
518 ///
519 void setPoisonMemory(bool poison) {
520 PoisonMemory = poison;
521 }
Chris Lattner8907b4b2007-12-05 23:39:57 +0000522 };
523}
524
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000525MemSlab *JITSlabAllocator::Allocate(size_t Size) {
526 sys::MemoryBlock B = JMM.allocateNewSlab(Size);
527 MemSlab *Slab = (MemSlab*)B.base();
528 Slab->Size = B.size();
529 Slab->NextPtr = 0;
530 return Slab;
531}
532
533void JITSlabAllocator::Deallocate(MemSlab *Slab) {
534 sys::MemoryBlock B(Slab, Slab->Size);
535 sys::Memory::ReleaseRWX(B);
536}
537
538DefaultJITMemoryManager::DefaultJITMemoryManager()
Dan Gohman5b78d502009-08-27 01:25:57 +0000539 :
540#ifdef NDEBUG
541 PoisonMemory(false),
542#else
543 PoisonMemory(true),
544#endif
545 LastSlab(0, 0),
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000546 BumpSlabAllocator(*this),
547 StubAllocator(DefaultSlabSize, DefaultSizeThreshold, BumpSlabAllocator),
548 DataAllocator(DefaultSlabSize, DefaultSizeThreshold, BumpSlabAllocator) {
549
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000550 // Allocate space for code.
551 sys::MemoryBlock MemBlock = allocateNewSlab(DefaultCodeSlabSize);
552 CodeSlabs.push_back(MemBlock);
553 uint8_t *MemBase = (uint8_t*)MemBlock.base();
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000554
Chris Lattner8907b4b2007-12-05 23:39:57 +0000555 // We set up the memory chunk with 4 mem regions, like this:
556 // [ START
557 // [ Free #0 ] -> Large space to allocate functions from.
558 // [ Allocated #1 ] -> Tiny space to separate regions.
559 // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
560 // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
561 // END ]
562 //
563 // The last three blocks are never deallocated or touched.
564
565 // Add MemoryRangeHeader to the end of the memory region, indicating that
566 // the space after the block of memory is allocated. This is block #3.
567 MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
568 Mem3->ThisAllocated = 1;
569 Mem3->PrevAllocated = 0;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000570 Mem3->BlockSize = sizeof(MemoryRangeHeader);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000571
572 /// Add a tiny free region so that the free list always has one entry.
573 FreeRangeHeader *Mem2 =
574 (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
575 Mem2->ThisAllocated = 0;
576 Mem2->PrevAllocated = 1;
577 Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
578 Mem2->SetEndOfBlockSizeMarker();
579 Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
580 Mem2->Next = Mem2;
581
582 /// Add a tiny allocated region so that Mem2 is never coalesced away.
583 MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
584 Mem1->ThisAllocated = 1;
585 Mem1->PrevAllocated = 0;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000586 Mem1->BlockSize = sizeof(MemoryRangeHeader);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000587
588 // Add a FreeRangeHeader to the start of the function body region, indicating
589 // that the space is free. Mark the previous block allocated so we never look
590 // at it.
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000591 FreeRangeHeader *Mem0 = (FreeRangeHeader*)MemBase;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000592 Mem0->ThisAllocated = 0;
593 Mem0->PrevAllocated = 1;
594 Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
595 Mem0->SetEndOfBlockSizeMarker();
596 Mem0->AddToFreeList(Mem2);
597
598 // Start out with the freelist pointing to Mem0.
599 FreeMemoryList = Mem0;
600
601 GOTBase = NULL;
Nate Begemand6b7a242009-02-18 08:31:02 +0000602 DlsymTable = NULL;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000603}
604
605void DefaultJITMemoryManager::AllocateGOT() {
606 assert(GOTBase == 0 && "Cannot allocate the got multiple times");
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000607 GOTBase = new uint8_t[sizeof(void*) * 8192];
Chris Lattner8907b4b2007-12-05 23:39:57 +0000608 HasGOT = true;
609}
610
Nate Begemand6b7a242009-02-18 08:31:02 +0000611void DefaultJITMemoryManager::SetDlsymTable(void *ptr) {
612 DlsymTable = ptr;
613}
Chris Lattner8907b4b2007-12-05 23:39:57 +0000614
615DefaultJITMemoryManager::~DefaultJITMemoryManager() {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000616 for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
617 sys::Memory::ReleaseRWX(CodeSlabs[i]);
618
Chris Lattner8907b4b2007-12-05 23:39:57 +0000619 delete[] GOTBase;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000620}
621
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000622sys::MemoryBlock DefaultJITMemoryManager::allocateNewSlab(size_t size) {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000623 // Allocate a new block close to the last one.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000624 std::string ErrMsg;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000625 sys::MemoryBlock *LastSlabPtr = LastSlab.base() ? &LastSlab : 0;
626 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, LastSlabPtr, &ErrMsg);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000627 if (B.base() == 0) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000628 llvm_report_error("Allocation failed when allocating new memory in the"
629 " JIT\n" + ErrMsg);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000630 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000631 LastSlab = B;
632 ++NumSlabs;
Reid Kleckner01248e62009-08-21 21:03:57 +0000633 // Initialize the slab to garbage when debugging.
634 if (PoisonMemory) {
635 memset(B.base(), 0xCD, B.size());
636 }
Chris Lattner8907b4b2007-12-05 23:39:57 +0000637 return B;
638}
639
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000640/// CheckInvariants - For testing only. Return "" if all internal invariants
641/// are preserved, and a helpful error message otherwise. For free and
642/// allocated blocks, make sure that adding BlockSize gives a valid block.
643/// For free blocks, make sure they're in the free list and that their end of
644/// block size marker is correct. This function should return an error before
645/// accessing bad memory. This function is defined here instead of in
646/// JITMemoryManagerTest.cpp so that we don't have to expose all of the
647/// implementation details of DefaultJITMemoryManager.
648bool DefaultJITMemoryManager::CheckInvariants(std::string &ErrorStr) {
649 raw_string_ostream Err(ErrorStr);
650
651 // Construct a the set of FreeRangeHeader pointers so we can query it
652 // efficiently.
653 llvm::SmallPtrSet<MemoryRangeHeader*, 16> FreeHdrSet;
654 FreeRangeHeader* FreeHead = FreeMemoryList;
655 FreeRangeHeader* FreeRange = FreeHead;
656
657 do {
658 // Check that the free range pointer is in the blocks we've allocated.
659 bool Found = false;
660 for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
661 E = CodeSlabs.end(); I != E && !Found; ++I) {
662 char *Start = (char*)I->base();
663 char *End = Start + I->size();
664 Found = (Start <= (char*)FreeRange && (char*)FreeRange < End);
665 }
666 if (!Found) {
667 Err << "Corrupt free list; points to " << FreeRange;
668 return false;
669 }
670
671 if (FreeRange->Next->Prev != FreeRange) {
672 Err << "Next and Prev pointers do not match.";
673 return false;
674 }
675
676 // Otherwise, add it to the set.
677 FreeHdrSet.insert(FreeRange);
678 FreeRange = FreeRange->Next;
679 } while (FreeRange != FreeHead);
680
681 // Go over each block, and look at each MemoryRangeHeader.
682 for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
683 E = CodeSlabs.end(); I != E; ++I) {
684 char *Start = (char*)I->base();
685 char *End = Start + I->size();
686
687 // Check each memory range.
688 for (MemoryRangeHeader *Hdr = (MemoryRangeHeader*)Start, *LastHdr = NULL;
689 Start <= (char*)Hdr && (char*)Hdr < End;
690 Hdr = &Hdr->getBlockAfter()) {
691 if (Hdr->ThisAllocated == 0) {
692 // Check that this range is in the free list.
693 if (!FreeHdrSet.count(Hdr)) {
694 Err << "Found free header at " << Hdr << " that is not in free list.";
695 return false;
696 }
697
698 // Now make sure the size marker at the end of the block is correct.
699 uintptr_t *Marker = ((uintptr_t*)&Hdr->getBlockAfter()) - 1;
700 if (!(Start <= (char*)Marker && (char*)Marker < End)) {
701 Err << "Block size in header points out of current MemoryBlock.";
702 return false;
703 }
704 if (Hdr->BlockSize != *Marker) {
705 Err << "End of block size marker (" << *Marker << ") "
706 << "and BlockSize (" << Hdr->BlockSize << ") don't match.";
707 return false;
708 }
709 }
710
711 if (LastHdr && LastHdr->ThisAllocated != Hdr->PrevAllocated) {
712 Err << "Hdr->PrevAllocated (" << Hdr->PrevAllocated << ") != "
713 << "LastHdr->ThisAllocated (" << LastHdr->ThisAllocated << ")";
714 return false;
715 } else if (!LastHdr && !Hdr->PrevAllocated) {
716 Err << "The first header should have PrevAllocated true.";
717 return false;
718 }
719
720 // Remember the last header.
721 LastHdr = Hdr;
722 }
723 }
724
725 // All invariants are preserved.
726 return true;
727}
Chris Lattner8907b4b2007-12-05 23:39:57 +0000728
729JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
730 return new DefaultJITMemoryManager();
731}
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000732
733// Allocate memory for code in 512K slabs.
734const size_t DefaultJITMemoryManager::DefaultCodeSlabSize = 512 * 1024;
735
736// Allocate globals and stubs in slabs of 64K. (probably 16 pages)
737const size_t DefaultJITMemoryManager::DefaultSlabSize = 64 * 1024;
738
739// Waste at most 16K at the end of each bump slab. (probably 4 pages)
740const size_t DefaultJITMemoryManager::DefaultSizeThreshold = 16 * 1024;