blob: 353bebf84ab97e0d5555bf34727417227304a594 [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"
Benjamin Kramer1bd73352010-04-08 10:44:28 +000018#include "llvm/ADT/Twine.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000019#include "llvm/Config/config.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000020#include "llvm/IR/GlobalValue.h"
Reid Kleckner10b4fc52009-07-23 21:46:56 +000021#include "llvm/Support/Allocator.h"
Chris Lattner8907b4b2007-12-05 23:39:57 +000022#include "llvm/Support/Compiler.h"
Reid Kleckner10b4fc52009-07-23 21:46:56 +000023#include "llvm/Support/Debug.h"
Danil Malyshev30b9e322012-03-28 21:46:36 +000024#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000025#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000026#include "llvm/Support/Memory.h"
27#include "llvm/Support/raw_ostream.h"
Chuck Rose III3012ac62007-12-06 02:03:01 +000028#include <cassert>
Dan Gohmande551f92009-04-01 18:45:54 +000029#include <climits>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000030#include <cstring>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000031#include <vector>
Danil Malyshev30b9e322012-03-28 21:46:36 +000032
33#if defined(__linux__)
34#if defined(HAVE_SYS_STAT_H)
35#include <sys/stat.h>
36#endif
37#include <fcntl.h>
38#include <unistd.h>
39#endif
40
Chris Lattner8907b4b2007-12-05 23:39:57 +000041using namespace llvm;
42
Reid Kleckner10b4fc52009-07-23 21:46:56 +000043STATISTIC(NumSlabs, "Number of slabs of memory allocated by the JIT");
Chris Lattner8907b4b2007-12-05 23:39:57 +000044
45JITMemoryManager::~JITMemoryManager() {}
46
47//===----------------------------------------------------------------------===//
48// Memory Block Implementation.
49//===----------------------------------------------------------------------===//
50
51namespace {
52 /// MemoryRangeHeader - For a range of memory, this is the header that we put
53 /// on the block of memory. It is carefully crafted to be one word of memory.
54 /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
55 /// which starts with this.
56 struct FreeRangeHeader;
57 struct MemoryRangeHeader {
58 /// ThisAllocated - This is true if this block is currently allocated. If
59 /// not, this can be converted to a FreeRangeHeader.
60 unsigned ThisAllocated : 1;
Eric Christopher5cf0aed2009-11-12 01:06:08 +000061
Chris Lattner8907b4b2007-12-05 23:39:57 +000062 /// PrevAllocated - Keep track of whether the block immediately before us is
63 /// allocated. If not, the word immediately before this header is the size
64 /// of the previous block.
65 unsigned PrevAllocated : 1;
Eric Christopher5cf0aed2009-11-12 01:06:08 +000066
Chris Lattner8907b4b2007-12-05 23:39:57 +000067 /// BlockSize - This is the size in bytes of this memory block,
68 /// including this header.
Dan Gohmande551f92009-04-01 18:45:54 +000069 uintptr_t BlockSize : (sizeof(intptr_t)*CHAR_BIT - 2);
Eric Christopher5cf0aed2009-11-12 01:06:08 +000070
Chris Lattner8907b4b2007-12-05 23:39:57 +000071
72 /// getBlockAfter - Return the memory block immediately after this one.
73 ///
74 MemoryRangeHeader &getBlockAfter() const {
75 return *(MemoryRangeHeader*)((char*)this+BlockSize);
76 }
Eric Christopher5cf0aed2009-11-12 01:06:08 +000077
Chris Lattner8907b4b2007-12-05 23:39:57 +000078 /// getFreeBlockBefore - If the block before this one is free, return it,
79 /// otherwise return null.
80 FreeRangeHeader *getFreeBlockBefore() const {
81 if (PrevAllocated) return 0;
82 intptr_t PrevSize = ((intptr_t *)this)[-1];
83 return (FreeRangeHeader*)((char*)this-PrevSize);
84 }
Eric Christopher5cf0aed2009-11-12 01:06:08 +000085
Chris Lattner8907b4b2007-12-05 23:39:57 +000086 /// FreeBlock - Turn an allocated block into a free block, adjusting
87 /// bits in the object headers, and adding an end of region memory block.
88 FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
Eric Christopher5cf0aed2009-11-12 01:06:08 +000089
Chris Lattner8907b4b2007-12-05 23:39:57 +000090 /// TrimAllocationToSize - If this allocated block is significantly larger
91 /// than NewSize, split it into two pieces (where the former is NewSize
92 /// bytes, including the header), and add the new block to the free list.
Eric Christopher5cf0aed2009-11-12 01:06:08 +000093 FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
Chris Lattner8907b4b2007-12-05 23:39:57 +000094 uint64_t NewSize);
95 };
96
97 /// FreeRangeHeader - For a memory block that isn't already allocated, this
98 /// keeps track of the current block and has a pointer to the next free block.
99 /// Free blocks are kept on a circularly linked list.
100 struct FreeRangeHeader : public MemoryRangeHeader {
101 FreeRangeHeader *Prev;
102 FreeRangeHeader *Next;
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000103
Chris Lattner8907b4b2007-12-05 23:39:57 +0000104 /// getMinBlockSize - Get the minimum size for a memory block. Blocks
105 /// smaller than this size cannot be created.
106 static unsigned getMinBlockSize() {
107 return sizeof(FreeRangeHeader)+sizeof(intptr_t);
108 }
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000109
Chris Lattner8907b4b2007-12-05 23:39:57 +0000110 /// SetEndOfBlockSizeMarker - The word at the end of every free block is
111 /// known to be the size of the free block. Set it for this block.
112 void SetEndOfBlockSizeMarker() {
113 void *EndOfBlock = (char*)this + BlockSize;
114 ((intptr_t *)EndOfBlock)[-1] = BlockSize;
115 }
116
117 FreeRangeHeader *RemoveFromFreeList() {
118 assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
119 Next->Prev = Prev;
120 return Prev->Next = Next;
121 }
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000122
Chris Lattner8907b4b2007-12-05 23:39:57 +0000123 void AddToFreeList(FreeRangeHeader *FreeList) {
124 Next = FreeList;
125 Prev = FreeList->Prev;
126 Prev->Next = this;
127 Next->Prev = this;
128 }
129
130 /// GrowBlock - The block after this block just got deallocated. Merge it
131 /// into the current block.
132 void GrowBlock(uintptr_t NewSize);
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000133
Chris Lattner8907b4b2007-12-05 23:39:57 +0000134 /// AllocateBlock - Mark this entire block allocated, updating freelists
135 /// etc. This returns a pointer to the circular free-list.
136 FreeRangeHeader *AllocateBlock();
137 };
138}
139
140
141/// AllocateBlock - Mark this entire block allocated, updating freelists
142/// etc. This returns a pointer to the circular free-list.
143FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
144 assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
145 "Cannot allocate an allocated block!");
146 // Mark this block allocated.
147 ThisAllocated = 1;
148 getBlockAfter().PrevAllocated = 1;
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000149
Chris Lattner8907b4b2007-12-05 23:39:57 +0000150 // Remove it from the free list.
151 return RemoveFromFreeList();
152}
153
154/// FreeBlock - Turn an allocated block into a free block, adjusting
155/// bits in the object headers, and adding an end of region memory block.
156/// If possible, coalesce this block with neighboring blocks. Return the
157/// FreeRangeHeader to allocate from.
158FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
159 MemoryRangeHeader *FollowingBlock = &getBlockAfter();
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000160 assert(ThisAllocated && "This block is already free!");
Chris Lattner8907b4b2007-12-05 23:39:57 +0000161 assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000162
Chris Lattner8907b4b2007-12-05 23:39:57 +0000163 FreeRangeHeader *FreeListToReturn = FreeList;
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000164
Chris Lattner8907b4b2007-12-05 23:39:57 +0000165 // If the block after this one is free, merge it into this block.
166 if (!FollowingBlock->ThisAllocated) {
167 FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
168 // "FreeList" always needs to be a valid free block. If we're about to
169 // coalesce with it, update our notion of what the free list is.
170 if (&FollowingFreeBlock == FreeList) {
171 FreeList = FollowingFreeBlock.Next;
172 FreeListToReturn = 0;
173 assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
174 }
175 FollowingFreeBlock.RemoveFromFreeList();
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000176
Chris Lattner8907b4b2007-12-05 23:39:57 +0000177 // Include the following block into this one.
178 BlockSize += FollowingFreeBlock.BlockSize;
179 FollowingBlock = &FollowingFreeBlock.getBlockAfter();
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000180
Chris Lattner8907b4b2007-12-05 23:39:57 +0000181 // Tell the block after the block we are coalescing that this block is
182 // allocated.
183 FollowingBlock->PrevAllocated = 1;
184 }
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000185
Chris Lattner8907b4b2007-12-05 23:39:57 +0000186 assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000187
Chris Lattner8907b4b2007-12-05 23:39:57 +0000188 if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
189 PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
190 return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
191 }
192
193 // Otherwise, mark this block free.
194 FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
195 FollowingBlock->PrevAllocated = 0;
196 FreeBlock.ThisAllocated = 0;
197
198 // Link this into the linked list of free blocks.
199 FreeBlock.AddToFreeList(FreeList);
200
201 // Add a marker at the end of the block, indicating the size of this free
202 // block.
203 FreeBlock.SetEndOfBlockSizeMarker();
204 return FreeListToReturn ? FreeListToReturn : &FreeBlock;
205}
206
207/// GrowBlock - The block after this block just got deallocated. Merge it
208/// into the current block.
209void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
210 assert(NewSize > BlockSize && "Not growing block?");
211 BlockSize = NewSize;
212 SetEndOfBlockSizeMarker();
213 getBlockAfter().PrevAllocated = 0;
214}
215
216/// TrimAllocationToSize - If this allocated block is significantly larger
217/// than NewSize, split it into two pieces (where the former is NewSize
218/// bytes, including the header), and add the new block to the free list.
219FreeRangeHeader *MemoryRangeHeader::
220TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
221 assert(ThisAllocated && getBlockAfter().PrevAllocated &&
222 "Cannot deallocate part of an allocated block!");
223
Evan Cheng60b75f42008-07-29 07:38:32 +0000224 // Don't allow blocks to be trimmed below minimum required size
225 NewSize = std::max<uint64_t>(FreeRangeHeader::getMinBlockSize(), NewSize);
226
Chris Lattner8907b4b2007-12-05 23:39:57 +0000227 // Round up size for alignment of header.
228 unsigned HeaderAlign = __alignof(FreeRangeHeader);
229 NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000230
Chris Lattner8907b4b2007-12-05 23:39:57 +0000231 // Size is now the size of the block we will remove from the start of the
232 // current block.
233 assert(NewSize <= BlockSize &&
234 "Allocating more space from this block than exists!");
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000235
Chris Lattner8907b4b2007-12-05 23:39:57 +0000236 // If splitting this block will cause the remainder to be too small, do not
237 // split the block.
238 if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
239 return FreeList;
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000240
Chris Lattner8907b4b2007-12-05 23:39:57 +0000241 // Otherwise, we splice the required number of bytes out of this block, form
242 // a new block immediately after it, then mark this block allocated.
243 MemoryRangeHeader &FormerNextBlock = getBlockAfter();
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000244
Chris Lattner8907b4b2007-12-05 23:39:57 +0000245 // Change the size of this block.
246 BlockSize = NewSize;
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000247
Chris Lattner8907b4b2007-12-05 23:39:57 +0000248 // Get the new block we just sliced out and turn it into a free block.
249 FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
250 NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
251 NewNextBlock.ThisAllocated = 0;
252 NewNextBlock.PrevAllocated = 1;
253 NewNextBlock.SetEndOfBlockSizeMarker();
254 FormerNextBlock.PrevAllocated = 0;
255 NewNextBlock.AddToFreeList(FreeList);
256 return &NewNextBlock;
257}
258
259//===----------------------------------------------------------------------===//
260// Memory Block Implementation.
261//===----------------------------------------------------------------------===//
262
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000263namespace {
264
265 class DefaultJITMemoryManager;
266
267 class JITSlabAllocator : public SlabAllocator {
268 DefaultJITMemoryManager &JMM;
269 public:
270 JITSlabAllocator(DefaultJITMemoryManager &jmm) : JMM(jmm) { }
271 virtual ~JITSlabAllocator() { }
272 virtual MemSlab *Allocate(size_t Size);
273 virtual void Deallocate(MemSlab *Slab);
274 };
275
Chris Lattner8907b4b2007-12-05 23:39:57 +0000276 /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
277 /// This splits a large block of MAP_NORESERVE'd memory into two
278 /// sections, one for function stubs, one for the functions themselves. We
279 /// have to do this because we may need to emit a function stub while in the
280 /// middle of emitting a function, and we don't know how large the function we
281 /// are emitting is.
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000282 class DefaultJITMemoryManager : public JITMemoryManager {
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000283
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000284 // Whether to poison freed memory.
285 bool PoisonMemory;
286
287 /// LastSlab - This points to the last slab allocated and is used as the
288 /// NearBlock parameter to AllocateRWX so that we can attempt to lay out all
289 /// stubs, data, and code contiguously in memory. In general, however, this
290 /// is not possible because the NearBlock parameter is ignored on Windows
291 /// platforms and even on Unix it works on a best-effort pasis.
292 sys::MemoryBlock LastSlab;
293
294 // Memory slabs allocated by the JIT. We refer to them as slabs so we don't
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000295 // confuse them with the blocks of memory described above.
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000296 std::vector<sys::MemoryBlock> CodeSlabs;
297 JITSlabAllocator BumpSlabAllocator;
298 BumpPtrAllocator StubAllocator;
299 BumpPtrAllocator DataAllocator;
300
301 // Circular list of free blocks.
302 FreeRangeHeader *FreeMemoryList;
303
Chris Lattner8907b4b2007-12-05 23:39:57 +0000304 // When emitting code into a memory block, this is the block.
305 MemoryRangeHeader *CurBlock;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000306
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000307 uint8_t *GOTBase; // Target Specific reserved memory
Chris Lattner8907b4b2007-12-05 23:39:57 +0000308 public:
309 DefaultJITMemoryManager();
310 ~DefaultJITMemoryManager();
311
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000312 /// allocateNewSlab - Allocates a new MemoryBlock and remembers it as the
313 /// last slab it allocated, so that subsequent allocations follow it.
314 sys::MemoryBlock allocateNewSlab(size_t size);
315
316 /// DefaultCodeSlabSize - When we have to go map more memory, we allocate at
317 /// least this much unless more is requested.
318 static const size_t DefaultCodeSlabSize;
319
320 /// DefaultSlabSize - Allocate data into slabs of this size unless we get
321 /// an allocation above SizeThreshold.
322 static const size_t DefaultSlabSize;
323
324 /// DefaultSizeThreshold - For any allocation larger than this threshold, we
325 /// should allocate a separate slab.
326 static const size_t DefaultSizeThreshold;
327
Danil Malyshev30b9e322012-03-28 21:46:36 +0000328 /// getPointerToNamedFunction - This method returns the address of the
329 /// specified function by using the dlsym function call.
330 virtual void *getPointerToNamedFunction(const std::string &Name,
331 bool AbortOnFailure = true);
332
Chris Lattner8907b4b2007-12-05 23:39:57 +0000333 void AllocateGOT();
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000334
335 // Testing methods.
336 virtual bool CheckInvariants(std::string &ErrorStr);
337 size_t GetDefaultCodeSlabSize() { return DefaultCodeSlabSize; }
338 size_t GetDefaultDataSlabSize() { return DefaultSlabSize; }
339 size_t GetDefaultStubSlabSize() { return DefaultSlabSize; }
340 unsigned GetNumCodeSlabs() { return CodeSlabs.size(); }
341 unsigned GetNumDataSlabs() { return DataAllocator.GetNumSlabs(); }
342 unsigned GetNumStubSlabs() { return StubAllocator.GetNumSlabs(); }
343
Chris Lattner8907b4b2007-12-05 23:39:57 +0000344 /// startFunctionBody - When a function starts, allocate a block of free
345 /// executable memory, returning a pointer to it and its actual size.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000346 uint8_t *startFunctionBody(const Function *F, uintptr_t &ActualSize) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000347
Chris Lattner96c96b42009-03-09 21:34:10 +0000348 FreeRangeHeader* candidateBlock = FreeMemoryList;
349 FreeRangeHeader* head = FreeMemoryList;
350 FreeRangeHeader* iter = head->Next;
351
352 uintptr_t largest = candidateBlock->BlockSize;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000353
Chris Lattner96c96b42009-03-09 21:34:10 +0000354 // Search for the largest free block
355 while (iter != head) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000356 if (iter->BlockSize > largest) {
357 largest = iter->BlockSize;
358 candidateBlock = iter;
359 }
360 iter = iter->Next;
Chris Lattner96c96b42009-03-09 21:34:10 +0000361 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000362
Nicolas Geoffray1b10d792009-07-29 22:55:02 +0000363 largest = largest - sizeof(MemoryRangeHeader);
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000364
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000365 // If this block isn't big enough for the allocation desired, allocate
366 // another block of memory and add it to the free list.
Nicolas Geoffray1b10d792009-07-29 22:55:02 +0000367 if (largest < ActualSize ||
368 largest <= FreeRangeHeader::getMinBlockSize()) {
David Greenebd8c8af2010-01-05 01:23:38 +0000369 DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000370 candidateBlock = allocateNewCodeSlab((size_t)ActualSize);
371 }
372
Chris Lattner96c96b42009-03-09 21:34:10 +0000373 // Select this candidate block for allocation
374 CurBlock = candidateBlock;
375
Chris Lattner8907b4b2007-12-05 23:39:57 +0000376 // Allocate the entire memory block.
Chris Lattner96c96b42009-03-09 21:34:10 +0000377 FreeMemoryList = candidateBlock->AllocateBlock();
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000378 ActualSize = CurBlock->BlockSize - sizeof(MemoryRangeHeader);
379 return (uint8_t *)(CurBlock + 1);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000380 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000381
382 /// allocateNewCodeSlab - Helper method to allocate a new slab of code
383 /// memory from the OS and add it to the free list. Returns the new
384 /// FreeRangeHeader at the base of the slab.
385 FreeRangeHeader *allocateNewCodeSlab(size_t MinSize) {
386 // If the user needs at least MinSize free memory, then we account for
387 // two MemoryRangeHeaders: the one in the user's block, and the one at the
388 // end of the slab.
389 size_t PaddedMin = MinSize + 2 * sizeof(MemoryRangeHeader);
390 size_t SlabSize = std::max(DefaultCodeSlabSize, PaddedMin);
391 sys::MemoryBlock B = allocateNewSlab(SlabSize);
392 CodeSlabs.push_back(B);
393 char *MemBase = (char*)(B.base());
394
395 // Put a tiny allocated block at the end of the memory chunk, so when
396 // FreeBlock calls getBlockAfter it doesn't fall off the end.
397 MemoryRangeHeader *EndBlock =
398 (MemoryRangeHeader*)(MemBase + B.size()) - 1;
399 EndBlock->ThisAllocated = 1;
400 EndBlock->PrevAllocated = 0;
401 EndBlock->BlockSize = sizeof(MemoryRangeHeader);
402
403 // Start out with a vast new block of free memory.
404 FreeRangeHeader *NewBlock = (FreeRangeHeader*)MemBase;
405 NewBlock->ThisAllocated = 0;
406 // Make sure getFreeBlockBefore doesn't look into unmapped memory.
407 NewBlock->PrevAllocated = 1;
408 NewBlock->BlockSize = (uintptr_t)EndBlock - (uintptr_t)NewBlock;
409 NewBlock->SetEndOfBlockSizeMarker();
410 NewBlock->AddToFreeList(FreeMemoryList);
411
412 assert(NewBlock->BlockSize - sizeof(MemoryRangeHeader) >= MinSize &&
413 "The block was too small!");
414 return NewBlock;
415 }
416
Chris Lattner8907b4b2007-12-05 23:39:57 +0000417 /// endFunctionBody - The function F is now allocated, and takes the memory
418 /// in the range [FunctionStart,FunctionEnd).
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000419 void endFunctionBody(const Function *F, uint8_t *FunctionStart,
420 uint8_t *FunctionEnd) {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000421 assert(FunctionEnd > FunctionStart);
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000422 assert(FunctionStart == (uint8_t *)(CurBlock+1) &&
Chris Lattner8907b4b2007-12-05 23:39:57 +0000423 "Mismatched function start/end!");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000424
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000425 uintptr_t BlockSize = FunctionEnd - (uint8_t *)CurBlock;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000426
427 // Release the memory at the end of this block that isn't needed.
428 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
429 }
Nuno Lopescef75272008-10-21 11:42:16 +0000430
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000431 /// allocateSpace - Allocate a memory block of the given size. This method
432 /// cannot be called between calls to startFunctionBody and endFunctionBody.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000433 uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
Nuno Lopescef75272008-10-21 11:42:16 +0000434 CurBlock = FreeMemoryList;
435 FreeMemoryList = FreeMemoryList->AllocateBlock();
436
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000437 uint8_t *result = (uint8_t *)(CurBlock + 1);
Nuno Lopescef75272008-10-21 11:42:16 +0000438
439 if (Alignment == 0) Alignment = 1;
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000440 result = (uint8_t*)(((intptr_t)result+Alignment-1) &
Nuno Lopescef75272008-10-21 11:42:16 +0000441 ~(intptr_t)(Alignment-1));
442
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000443 uintptr_t BlockSize = result + Size - (uint8_t *)CurBlock;
Nuno Lopescef75272008-10-21 11:42:16 +0000444 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
445
446 return result;
447 }
448
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000449 /// allocateStub - Allocate memory for a function stub.
450 uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
451 unsigned Alignment) {
452 return (uint8_t*)StubAllocator.Allocate(StubSize, Alignment);
453 }
454
455 /// allocateGlobal - Allocate memory for a global.
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000456 uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000457 return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000458 }
459
Jim Grosbach61425c02012-01-16 22:26:39 +0000460 /// allocateCodeSection - Allocate memory for a code section.
461 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
462 unsigned SectionID) {
Sean Callananf92bbcd2012-08-15 20:53:52 +0000463 // Grow the required block size to account for the block header
464 Size += sizeof(*CurBlock);
465
Jim Grosbach61425c02012-01-16 22:26:39 +0000466 // FIXME: Alignement handling.
467 FreeRangeHeader* candidateBlock = FreeMemoryList;
468 FreeRangeHeader* head = FreeMemoryList;
469 FreeRangeHeader* iter = head->Next;
470
471 uintptr_t largest = candidateBlock->BlockSize;
472
473 // Search for the largest free block.
474 while (iter != head) {
475 if (iter->BlockSize > largest) {
476 largest = iter->BlockSize;
477 candidateBlock = iter;
478 }
479 iter = iter->Next;
480 }
481
482 largest = largest - sizeof(MemoryRangeHeader);
483
484 // If this block isn't big enough for the allocation desired, allocate
485 // another block of memory and add it to the free list.
486 if (largest < Size || largest <= FreeRangeHeader::getMinBlockSize()) {
487 DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
488 candidateBlock = allocateNewCodeSlab((size_t)Size);
489 }
490
491 // Select this candidate block for allocation
492 CurBlock = candidateBlock;
493
494 // Allocate the entire memory block.
495 FreeMemoryList = candidateBlock->AllocateBlock();
496 // Release the memory at the end of this block that isn't needed.
497 FreeMemoryList = CurBlock->TrimAllocationToSize(FreeMemoryList, Size);
498 return (uint8_t *)(CurBlock + 1);
499 }
500
501 /// allocateDataSection - Allocate memory for a data section.
502 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Andrew Kaylor53608a32012-11-15 23:50:01 +0000503 unsigned SectionID, bool IsReadOnly) {
Jim Grosbach61425c02012-01-16 22:26:39 +0000504 return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
505 }
506
Andrew Kaylor53608a32012-11-15 23:50:01 +0000507 bool applyPermissions(std::string *ErrMsg) {
508 return false;
509 }
510
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000511 /// startExceptionTable - Use startFunctionBody to allocate memory for the
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000512 /// function's exception table.
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000513 uint8_t* startExceptionTable(const Function* F, uintptr_t &ActualSize) {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000514 return startFunctionBody(F, ActualSize);
515 }
516
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000517 /// endExceptionTable - The exception table of F is now allocated,
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000518 /// and takes the memory in the range [TableStart,TableEnd).
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000519 void endExceptionTable(const Function *F, uint8_t *TableStart,
520 uint8_t *TableEnd, uint8_t* FrameRegister) {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000521 assert(TableEnd > TableStart);
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000522 assert(TableStart == (uint8_t *)(CurBlock+1) &&
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000523 "Mismatched table start/end!");
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000524
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000525 uintptr_t BlockSize = TableEnd - (uint8_t *)CurBlock;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000526
527 // Release the memory at the end of this block that isn't needed.
528 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
529 }
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000530
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000531 uint8_t *getGOTBase() const {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000532 return GOTBase;
533 }
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000534
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000535 void deallocateBlock(void *Block) {
536 // Find the block that is allocated for this function.
537 MemoryRangeHeader *MemRange = static_cast<MemoryRangeHeader*>(Block) - 1;
538 assert(MemRange->ThisAllocated && "Block isn't allocated!");
539
540 // Fill the buffer with garbage!
541 if (PoisonMemory) {
542 memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
543 }
544
545 // Free the memory.
546 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
547 }
548
549 /// deallocateFunctionBody - Deallocate all memory for the specified
Chris Lattner8907b4b2007-12-05 23:39:57 +0000550 /// function body.
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000551 void deallocateFunctionBody(void *Body) {
Nicolas Geoffray71e0b7c2009-10-22 14:35:57 +0000552 if (Body) deallocateBlock(Body);
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000553 }
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000554
Jeffrey Yasskin1e861322009-10-20 18:13:21 +0000555 /// deallocateExceptionTable - Deallocate memory for the specified
556 /// exception table.
557 void deallocateExceptionTable(void *ET) {
Nicolas Geoffray71e0b7c2009-10-22 14:35:57 +0000558 if (ET) deallocateBlock(ET);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000559 }
Jim Grosbachcce6c292008-10-03 16:17:20 +0000560
561 /// setMemoryWritable - When code generation is in progress,
562 /// the code pages may need permissions changed.
Dan Gohmana9ad0412009-08-12 22:10:57 +0000563 void setMemoryWritable()
Jim Grosbachcce6c292008-10-03 16:17:20 +0000564 {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000565 for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
566 sys::Memory::setWritable(CodeSlabs[i]);
Jim Grosbachcce6c292008-10-03 16:17:20 +0000567 }
568 /// setMemoryExecutable - When code generation is done and we're ready to
569 /// start execution, the code pages may need permissions changed.
Dan Gohmana9ad0412009-08-12 22:10:57 +0000570 void setMemoryExecutable()
Jim Grosbachcce6c292008-10-03 16:17:20 +0000571 {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000572 for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
573 sys::Memory::setExecutable(CodeSlabs[i]);
Jim Grosbachcce6c292008-10-03 16:17:20 +0000574 }
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000575
576 /// setPoisonMemory - Controls whether we write garbage over freed memory.
577 ///
578 void setPoisonMemory(bool poison) {
579 PoisonMemory = poison;
580 }
Chris Lattner8907b4b2007-12-05 23:39:57 +0000581 };
582}
583
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000584MemSlab *JITSlabAllocator::Allocate(size_t Size) {
585 sys::MemoryBlock B = JMM.allocateNewSlab(Size);
586 MemSlab *Slab = (MemSlab*)B.base();
587 Slab->Size = B.size();
588 Slab->NextPtr = 0;
589 return Slab;
590}
591
592void JITSlabAllocator::Deallocate(MemSlab *Slab) {
593 sys::MemoryBlock B(Slab, Slab->Size);
594 sys::Memory::ReleaseRWX(B);
595}
596
597DefaultJITMemoryManager::DefaultJITMemoryManager()
Dan Gohman5b78d502009-08-27 01:25:57 +0000598 :
599#ifdef NDEBUG
600 PoisonMemory(false),
601#else
602 PoisonMemory(true),
603#endif
604 LastSlab(0, 0),
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000605 BumpSlabAllocator(*this),
606 StubAllocator(DefaultSlabSize, DefaultSizeThreshold, BumpSlabAllocator),
607 DataAllocator(DefaultSlabSize, DefaultSizeThreshold, BumpSlabAllocator) {
608
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000609 // Allocate space for code.
610 sys::MemoryBlock MemBlock = allocateNewSlab(DefaultCodeSlabSize);
611 CodeSlabs.push_back(MemBlock);
612 uint8_t *MemBase = (uint8_t*)MemBlock.base();
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000613
Chris Lattner8907b4b2007-12-05 23:39:57 +0000614 // We set up the memory chunk with 4 mem regions, like this:
615 // [ START
616 // [ Free #0 ] -> Large space to allocate functions from.
617 // [ Allocated #1 ] -> Tiny space to separate regions.
618 // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
619 // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
620 // END ]
621 //
622 // The last three blocks are never deallocated or touched.
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000623
Chris Lattner8907b4b2007-12-05 23:39:57 +0000624 // Add MemoryRangeHeader to the end of the memory region, indicating that
625 // the space after the block of memory is allocated. This is block #3.
626 MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
627 Mem3->ThisAllocated = 1;
628 Mem3->PrevAllocated = 0;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000629 Mem3->BlockSize = sizeof(MemoryRangeHeader);
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000630
Chris Lattner8907b4b2007-12-05 23:39:57 +0000631 /// Add a tiny free region so that the free list always has one entry.
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000632 FreeRangeHeader *Mem2 =
Chris Lattner8907b4b2007-12-05 23:39:57 +0000633 (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
634 Mem2->ThisAllocated = 0;
635 Mem2->PrevAllocated = 1;
636 Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
637 Mem2->SetEndOfBlockSizeMarker();
638 Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
639 Mem2->Next = Mem2;
640
641 /// Add a tiny allocated region so that Mem2 is never coalesced away.
642 MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
643 Mem1->ThisAllocated = 1;
644 Mem1->PrevAllocated = 0;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000645 Mem1->BlockSize = sizeof(MemoryRangeHeader);
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000646
Chris Lattner8907b4b2007-12-05 23:39:57 +0000647 // Add a FreeRangeHeader to the start of the function body region, indicating
648 // that the space is free. Mark the previous block allocated so we never look
649 // at it.
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000650 FreeRangeHeader *Mem0 = (FreeRangeHeader*)MemBase;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000651 Mem0->ThisAllocated = 0;
652 Mem0->PrevAllocated = 1;
653 Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
654 Mem0->SetEndOfBlockSizeMarker();
655 Mem0->AddToFreeList(Mem2);
Eric Christopher5cf0aed2009-11-12 01:06:08 +0000656
Chris Lattner8907b4b2007-12-05 23:39:57 +0000657 // Start out with the freelist pointing to Mem0.
658 FreeMemoryList = Mem0;
659
660 GOTBase = NULL;
661}
662
663void DefaultJITMemoryManager::AllocateGOT() {
664 assert(GOTBase == 0 && "Cannot allocate the got multiple times");
Bruno Cardoso Lopes186c6702009-06-04 00:15:51 +0000665 GOTBase = new uint8_t[sizeof(void*) * 8192];
Chris Lattner8907b4b2007-12-05 23:39:57 +0000666 HasGOT = true;
667}
668
Chris Lattner8907b4b2007-12-05 23:39:57 +0000669DefaultJITMemoryManager::~DefaultJITMemoryManager() {
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000670 for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
671 sys::Memory::ReleaseRWX(CodeSlabs[i]);
672
Chris Lattner8907b4b2007-12-05 23:39:57 +0000673 delete[] GOTBase;
Chris Lattner8907b4b2007-12-05 23:39:57 +0000674}
675
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000676sys::MemoryBlock DefaultJITMemoryManager::allocateNewSlab(size_t size) {
Chris Lattner8907b4b2007-12-05 23:39:57 +0000677 // Allocate a new block close to the last one.
Chris Lattner8907b4b2007-12-05 23:39:57 +0000678 std::string ErrMsg;
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000679 sys::MemoryBlock *LastSlabPtr = LastSlab.base() ? &LastSlab : 0;
680 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, LastSlabPtr, &ErrMsg);
Chris Lattner8907b4b2007-12-05 23:39:57 +0000681 if (B.base() == 0) {
Chris Lattner75361b62010-04-07 22:58:41 +0000682 report_fatal_error("Allocation failed when allocating new memory in the"
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000683 " JIT\n" + Twine(ErrMsg));
Chris Lattner8907b4b2007-12-05 23:39:57 +0000684 }
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000685 LastSlab = B;
686 ++NumSlabs;
Reid Kleckner01248e62009-08-21 21:03:57 +0000687 // Initialize the slab to garbage when debugging.
688 if (PoisonMemory) {
689 memset(B.base(), 0xCD, B.size());
690 }
Chris Lattner8907b4b2007-12-05 23:39:57 +0000691 return B;
692}
693
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000694/// CheckInvariants - For testing only. Return "" if all internal invariants
695/// are preserved, and a helpful error message otherwise. For free and
696/// allocated blocks, make sure that adding BlockSize gives a valid block.
697/// For free blocks, make sure they're in the free list and that their end of
698/// block size marker is correct. This function should return an error before
699/// accessing bad memory. This function is defined here instead of in
700/// JITMemoryManagerTest.cpp so that we don't have to expose all of the
701/// implementation details of DefaultJITMemoryManager.
702bool DefaultJITMemoryManager::CheckInvariants(std::string &ErrorStr) {
703 raw_string_ostream Err(ErrorStr);
704
705 // Construct a the set of FreeRangeHeader pointers so we can query it
706 // efficiently.
707 llvm::SmallPtrSet<MemoryRangeHeader*, 16> FreeHdrSet;
708 FreeRangeHeader* FreeHead = FreeMemoryList;
709 FreeRangeHeader* FreeRange = FreeHead;
710
711 do {
712 // Check that the free range pointer is in the blocks we've allocated.
713 bool Found = false;
714 for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
715 E = CodeSlabs.end(); I != E && !Found; ++I) {
716 char *Start = (char*)I->base();
717 char *End = Start + I->size();
718 Found = (Start <= (char*)FreeRange && (char*)FreeRange < End);
719 }
720 if (!Found) {
721 Err << "Corrupt free list; points to " << FreeRange;
722 return false;
723 }
724
725 if (FreeRange->Next->Prev != FreeRange) {
726 Err << "Next and Prev pointers do not match.";
727 return false;
728 }
729
730 // Otherwise, add it to the set.
731 FreeHdrSet.insert(FreeRange);
732 FreeRange = FreeRange->Next;
733 } while (FreeRange != FreeHead);
734
735 // Go over each block, and look at each MemoryRangeHeader.
736 for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
737 E = CodeSlabs.end(); I != E; ++I) {
738 char *Start = (char*)I->base();
739 char *End = Start + I->size();
740
741 // Check each memory range.
742 for (MemoryRangeHeader *Hdr = (MemoryRangeHeader*)Start, *LastHdr = NULL;
743 Start <= (char*)Hdr && (char*)Hdr < End;
744 Hdr = &Hdr->getBlockAfter()) {
745 if (Hdr->ThisAllocated == 0) {
746 // Check that this range is in the free list.
747 if (!FreeHdrSet.count(Hdr)) {
748 Err << "Found free header at " << Hdr << " that is not in free list.";
749 return false;
750 }
751
752 // Now make sure the size marker at the end of the block is correct.
753 uintptr_t *Marker = ((uintptr_t*)&Hdr->getBlockAfter()) - 1;
754 if (!(Start <= (char*)Marker && (char*)Marker < End)) {
755 Err << "Block size in header points out of current MemoryBlock.";
756 return false;
757 }
758 if (Hdr->BlockSize != *Marker) {
759 Err << "End of block size marker (" << *Marker << ") "
760 << "and BlockSize (" << Hdr->BlockSize << ") don't match.";
761 return false;
762 }
763 }
764
765 if (LastHdr && LastHdr->ThisAllocated != Hdr->PrevAllocated) {
766 Err << "Hdr->PrevAllocated (" << Hdr->PrevAllocated << ") != "
767 << "LastHdr->ThisAllocated (" << LastHdr->ThisAllocated << ")";
768 return false;
769 } else if (!LastHdr && !Hdr->PrevAllocated) {
770 Err << "The first header should have PrevAllocated true.";
771 return false;
772 }
773
774 // Remember the last header.
775 LastHdr = Hdr;
776 }
777 }
778
779 // All invariants are preserved.
780 return true;
781}
Chris Lattner8907b4b2007-12-05 23:39:57 +0000782
Danil Malyshev30b9e322012-03-28 21:46:36 +0000783//===----------------------------------------------------------------------===//
784// getPointerToNamedFunction() implementation.
785//===----------------------------------------------------------------------===//
786
787// AtExitHandlers - List of functions to call when the program exits,
788// registered with the atexit() library function.
789static std::vector<void (*)()> AtExitHandlers;
790
791/// runAtExitHandlers - Run any functions registered by the program's
792/// calls to atexit(3), which we intercept and store in
793/// AtExitHandlers.
794///
795static void runAtExitHandlers() {
796 while (!AtExitHandlers.empty()) {
797 void (*Fn)() = AtExitHandlers.back();
798 AtExitHandlers.pop_back();
799 Fn();
800 }
801}
802
803//===----------------------------------------------------------------------===//
804// Function stubs that are invoked instead of certain library calls
805//
806// Force the following functions to be linked in to anything that uses the
807// JIT. This is a hack designed to work around the all-too-clever Glibc
808// strategy of making these functions work differently when inlined vs. when
809// not inlined, and hiding their real definitions in a separate archive file
810// that the dynamic linker can't see. For more info, search for
811// 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
812#if defined(__linux__)
813/* stat functions are redirecting to __xstat with a version number. On x86-64
814 * linking with libc_nonshared.a and -Wl,--export-dynamic doesn't make 'stat'
815 * available as an exported symbol, so we have to add it explicitly.
816 */
817namespace {
818class StatSymbols {
819public:
820 StatSymbols() {
821 sys::DynamicLibrary::AddSymbol("stat", (void*)(intptr_t)stat);
822 sys::DynamicLibrary::AddSymbol("fstat", (void*)(intptr_t)fstat);
823 sys::DynamicLibrary::AddSymbol("lstat", (void*)(intptr_t)lstat);
824 sys::DynamicLibrary::AddSymbol("stat64", (void*)(intptr_t)stat64);
825 sys::DynamicLibrary::AddSymbol("\x1stat64", (void*)(intptr_t)stat64);
826 sys::DynamicLibrary::AddSymbol("\x1open64", (void*)(intptr_t)open64);
827 sys::DynamicLibrary::AddSymbol("\x1lseek64", (void*)(intptr_t)lseek64);
828 sys::DynamicLibrary::AddSymbol("fstat64", (void*)(intptr_t)fstat64);
829 sys::DynamicLibrary::AddSymbol("lstat64", (void*)(intptr_t)lstat64);
830 sys::DynamicLibrary::AddSymbol("atexit", (void*)(intptr_t)atexit);
831 sys::DynamicLibrary::AddSymbol("mknod", (void*)(intptr_t)mknod);
832 }
833};
834}
835static StatSymbols initStatSymbols;
836#endif // __linux__
837
838// jit_exit - Used to intercept the "exit" library call.
839static void jit_exit(int Status) {
840 runAtExitHandlers(); // Run atexit handlers...
841 exit(Status);
842}
843
844// jit_atexit - Used to intercept the "atexit" library call.
845static int jit_atexit(void (*Fn)()) {
846 AtExitHandlers.push_back(Fn); // Take note of atexit handler...
847 return 0; // Always successful
848}
849
850static int jit_noop() {
851 return 0;
852}
853
854//===----------------------------------------------------------------------===//
855//
856/// getPointerToNamedFunction - This method returns the address of the specified
857/// function by using the dynamic loader interface. As such it is only useful
858/// for resolving library symbols, not code generated symbols.
859///
860void *DefaultJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky5fe01982012-04-29 12:40:47 +0000861 bool AbortOnFailure) {
Danil Malyshev30b9e322012-03-28 21:46:36 +0000862 // Check to see if this is one of the functions we want to intercept. Note,
863 // we cast to intptr_t here to silence a -pedantic warning that complains
864 // about casting a function pointer to a normal pointer.
865 if (Name == "exit") return (void*)(intptr_t)&jit_exit;
866 if (Name == "atexit") return (void*)(intptr_t)&jit_atexit;
867
868 // We should not invoke parent's ctors/dtors from generated main()!
869 // On Mingw and Cygwin, the symbol __main is resolved to
870 // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
871 // (and register wrong callee's dtors with atexit(3)).
872 // We expect ExecutionEngine::runStaticConstructorsDestructors()
873 // is called before ExecutionEngine::runFunctionAsMain() is called.
874 if (Name == "__main") return (void*)(intptr_t)&jit_noop;
875
876 const char *NameStr = Name.c_str();
877 // If this is an asm specifier, skip the sentinal.
878 if (NameStr[0] == 1) ++NameStr;
879
880 // If it's an external function, look it up in the process image...
881 void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
882 if (Ptr) return Ptr;
883
884 // If it wasn't found and if it starts with an underscore ('_') character,
885 // try again without the underscore.
886 if (NameStr[0] == '_') {
887 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
888 if (Ptr) return Ptr;
889 }
890
891 // Darwin/PPC adds $LDBLStub suffixes to various symbols like printf. These
892 // are references to hidden visibility symbols that dlsym cannot resolve.
893 // If we have one of these, strip off $LDBLStub and try again.
894#if defined(__APPLE__) && defined(__ppc__)
895 if (Name.size() > 9 && Name[Name.size()-9] == '$' &&
896 memcmp(&Name[Name.size()-8], "LDBLStub", 8) == 0) {
897 // First try turning $LDBLStub into $LDBL128. If that fails, strip it off.
898 // This mirrors logic in libSystemStubs.a.
899 std::string Prefix = std::string(Name.begin(), Name.end()-9);
900 if (void *Ptr = getPointerToNamedFunction(Prefix+"$LDBL128", false))
901 return Ptr;
902 if (void *Ptr = getPointerToNamedFunction(Prefix, false))
903 return Ptr;
904 }
905#endif
906
907 if (AbortOnFailure) {
908 report_fatal_error("Program used external function '"+Name+
909 "' which could not be resolved!");
910 }
911 return 0;
912}
913
914
915
Chris Lattner8907b4b2007-12-05 23:39:57 +0000916JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
917 return new DefaultJITMemoryManager();
918}
Reid Kleckner10b4fc52009-07-23 21:46:56 +0000919
920// Allocate memory for code in 512K slabs.
921const size_t DefaultJITMemoryManager::DefaultCodeSlabSize = 512 * 1024;
922
923// Allocate globals and stubs in slabs of 64K. (probably 16 pages)
924const size_t DefaultJITMemoryManager::DefaultSlabSize = 64 * 1024;
925
926// Waste at most 16K at the end of each bump slab. (probably 4 pages)
927const size_t DefaultJITMemoryManager::DefaultSizeThreshold = 16 * 1024;