10384656cade6f5331ae0b88d6835affa8c6098e
[oota-llvm.git] / lib / ExecutionEngine / JIT / JITMemoryManager.cpp
1 //===-- JITMemoryManager.cpp - Memory Allocator for JIT'd code ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the DefaultJITMemoryManager class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "jit"
15 #include "llvm/ExecutionEngine/JITMemoryManager.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/GlobalValue.h"
21 #include "llvm/Support/Allocator.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/DynamicLibrary.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/Memory.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <cassert>
29 #include <climits>
30 #include <cstring>
31 #include <vector>
32
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
41 using namespace llvm;
42
43 STATISTIC(NumSlabs, "Number of slabs of memory allocated by the JIT");
44
45 JITMemoryManager::~JITMemoryManager() {}
46
47 //===----------------------------------------------------------------------===//
48 // Memory Block Implementation.
49 //===----------------------------------------------------------------------===//
50
51 namespace {
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;
61
62     /// 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;
66
67     /// BlockSize - This is the size in bytes of this memory block,
68     /// including this header.
69     uintptr_t BlockSize : (sizeof(intptr_t)*CHAR_BIT - 2);
70
71
72     /// getBlockAfter - Return the memory block immediately after this one.
73     ///
74     MemoryRangeHeader &getBlockAfter() const {
75       return *(MemoryRangeHeader*)((char*)this+BlockSize);
76     }
77
78     /// 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     }
85
86     /// 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);
89
90     /// 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.
93     FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
94                                           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;
103
104     /// 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     }
109
110     /// 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     }
122
123     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);
133
134     /// 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.
143 FreeRangeHeader *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;
149
150   // 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.
158 FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
159   MemoryRangeHeader *FollowingBlock = &getBlockAfter();
160   assert(ThisAllocated && "This block is already free!");
161   assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
162
163   FreeRangeHeader *FreeListToReturn = FreeList;
164
165   // 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();
176
177     // Include the following block into this one.
178     BlockSize += FollowingFreeBlock.BlockSize;
179     FollowingBlock = &FollowingFreeBlock.getBlockAfter();
180
181     // Tell the block after the block we are coalescing that this block is
182     // allocated.
183     FollowingBlock->PrevAllocated = 1;
184   }
185
186   assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
187
188   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.
209 void 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.
219 FreeRangeHeader *MemoryRangeHeader::
220 TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
221   assert(ThisAllocated && getBlockAfter().PrevAllocated &&
222          "Cannot deallocate part of an allocated block!");
223
224   // Don't allow blocks to be trimmed below minimum required size
225   NewSize = std::max<uint64_t>(FreeRangeHeader::getMinBlockSize(), NewSize);
226
227   // Round up size for alignment of header.
228   unsigned HeaderAlign = __alignof(FreeRangeHeader);
229   NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
230
231   // 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!");
235
236   // 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;
240
241   // 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();
244
245   // Change the size of this block.
246   BlockSize = NewSize;
247
248   // 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
263 namespace {
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
276   /// 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.
282   class DefaultJITMemoryManager : public JITMemoryManager {
283
284     // 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
295     // confuse them with the blocks of memory described above.
296     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
304     // When emitting code into a memory block, this is the block.
305     MemoryRangeHeader *CurBlock;
306
307     uint8_t *GOTBase;     // Target Specific reserved memory
308   public:
309     DefaultJITMemoryManager();
310     ~DefaultJITMemoryManager();
311
312     /// 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
328     /// 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
333     void AllocateGOT();
334
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
344     /// startFunctionBody - When a function starts, allocate a block of free
345     /// executable memory, returning a pointer to it and its actual size.
346     uint8_t *startFunctionBody(const Function *F, uintptr_t &ActualSize) {
347
348       FreeRangeHeader* candidateBlock = FreeMemoryList;
349       FreeRangeHeader* head = FreeMemoryList;
350       FreeRangeHeader* iter = head->Next;
351
352       uintptr_t largest = candidateBlock->BlockSize;
353
354       // Search for the largest free block
355       while (iter != head) {
356         if (iter->BlockSize > largest) {
357           largest = iter->BlockSize;
358           candidateBlock = iter;
359         }
360         iter = iter->Next;
361       }
362
363       largest = largest - sizeof(MemoryRangeHeader);
364
365       // If this block isn't big enough for the allocation desired, allocate
366       // another block of memory and add it to the free list.
367       if (largest < ActualSize ||
368           largest <= FreeRangeHeader::getMinBlockSize()) {
369         DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
370         candidateBlock = allocateNewCodeSlab((size_t)ActualSize);
371       }
372
373       // Select this candidate block for allocation
374       CurBlock = candidateBlock;
375
376       // Allocate the entire memory block.
377       FreeMemoryList = candidateBlock->AllocateBlock();
378       ActualSize = CurBlock->BlockSize - sizeof(MemoryRangeHeader);
379       return (uint8_t *)(CurBlock + 1);
380     }
381
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
417     /// endFunctionBody - The function F is now allocated, and takes the memory
418     /// in the range [FunctionStart,FunctionEnd).
419     void endFunctionBody(const Function *F, uint8_t *FunctionStart,
420                          uint8_t *FunctionEnd) {
421       assert(FunctionEnd > FunctionStart);
422       assert(FunctionStart == (uint8_t *)(CurBlock+1) &&
423              "Mismatched function start/end!");
424
425       uintptr_t BlockSize = FunctionEnd - (uint8_t *)CurBlock;
426
427       // Release the memory at the end of this block that isn't needed.
428       FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
429     }
430
431     /// allocateSpace - Allocate a memory block of the given size.  This method
432     /// cannot be called between calls to startFunctionBody and endFunctionBody.
433     uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
434       CurBlock = FreeMemoryList;
435       FreeMemoryList = FreeMemoryList->AllocateBlock();
436
437       uint8_t *result = (uint8_t *)(CurBlock + 1);
438
439       if (Alignment == 0) Alignment = 1;
440       result = (uint8_t*)(((intptr_t)result+Alignment-1) &
441                ~(intptr_t)(Alignment-1));
442
443       uintptr_t BlockSize = result + Size - (uint8_t *)CurBlock;
444       FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
445
446       return result;
447     }
448
449     /// 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.
456     uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
457       return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
458     }
459
460     /// allocateCodeSection - Allocate memory for a code section.
461     uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
462                                  unsigned SectionID) {
463       // Grow the required block size to account for the block header
464       Size += sizeof(*CurBlock);
465
466       // 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,
503                                  unsigned SectionID, bool IsReadOnly) {
504       return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
505     }
506
507     bool applyPermissions(std::string *ErrMsg) {
508       return false;
509     }
510
511     /// startExceptionTable - Use startFunctionBody to allocate memory for the
512     /// function's exception table.
513     uint8_t* startExceptionTable(const Function* F, uintptr_t &ActualSize) {
514       return startFunctionBody(F, ActualSize);
515     }
516
517     /// endExceptionTable - The exception table of F is now allocated,
518     /// and takes the memory in the range [TableStart,TableEnd).
519     void endExceptionTable(const Function *F, uint8_t *TableStart,
520                            uint8_t *TableEnd, uint8_t* FrameRegister) {
521       assert(TableEnd > TableStart);
522       assert(TableStart == (uint8_t *)(CurBlock+1) &&
523              "Mismatched table start/end!");
524
525       uintptr_t BlockSize = TableEnd - (uint8_t *)CurBlock;
526
527       // Release the memory at the end of this block that isn't needed.
528       FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
529     }
530
531     uint8_t *getGOTBase() const {
532       return GOTBase;
533     }
534
535     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
550     /// function body.
551     void deallocateFunctionBody(void *Body) {
552       if (Body) deallocateBlock(Body);
553     }
554
555     /// deallocateExceptionTable - Deallocate memory for the specified
556     /// exception table.
557     void deallocateExceptionTable(void *ET) {
558       if (ET) deallocateBlock(ET);
559     }
560
561     /// setMemoryWritable - When code generation is in progress,
562     /// the code pages may need permissions changed.
563     void setMemoryWritable()
564     {
565       for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
566         sys::Memory::setWritable(CodeSlabs[i]);
567     }
568     /// setMemoryExecutable - When code generation is done and we're ready to
569     /// start execution, the code pages may need permissions changed.
570     void setMemoryExecutable()
571     {
572       for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
573         sys::Memory::setExecutable(CodeSlabs[i]);
574     }
575
576     /// setPoisonMemory - Controls whether we write garbage over freed memory.
577     ///
578     void setPoisonMemory(bool poison) {
579       PoisonMemory = poison;
580     }
581   };
582 }
583
584 MemSlab *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
592 void JITSlabAllocator::Deallocate(MemSlab *Slab) {
593   sys::MemoryBlock B(Slab, Slab->Size);
594   sys::Memory::ReleaseRWX(B);
595 }
596
597 DefaultJITMemoryManager::DefaultJITMemoryManager()
598   :
599 #ifdef NDEBUG
600     PoisonMemory(false),
601 #else
602     PoisonMemory(true),
603 #endif
604     LastSlab(0, 0),
605     BumpSlabAllocator(*this),
606     StubAllocator(DefaultSlabSize, DefaultSizeThreshold, BumpSlabAllocator),
607     DataAllocator(DefaultSlabSize, DefaultSizeThreshold, BumpSlabAllocator) {
608
609   // Allocate space for code.
610   sys::MemoryBlock MemBlock = allocateNewSlab(DefaultCodeSlabSize);
611   CodeSlabs.push_back(MemBlock);
612   uint8_t *MemBase = (uint8_t*)MemBlock.base();
613
614   // 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.
623
624   // 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;
629   Mem3->BlockSize     = sizeof(MemoryRangeHeader);
630
631   /// Add a tiny free region so that the free list always has one entry.
632   FreeRangeHeader *Mem2 =
633     (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;
645   Mem1->BlockSize     = sizeof(MemoryRangeHeader);
646
647   // 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.
650   FreeRangeHeader *Mem0 = (FreeRangeHeader*)MemBase;
651   Mem0->ThisAllocated = 0;
652   Mem0->PrevAllocated = 1;
653   Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
654   Mem0->SetEndOfBlockSizeMarker();
655   Mem0->AddToFreeList(Mem2);
656
657   // Start out with the freelist pointing to Mem0.
658   FreeMemoryList = Mem0;
659
660   GOTBase = NULL;
661 }
662
663 void DefaultJITMemoryManager::AllocateGOT() {
664   assert(GOTBase == 0 && "Cannot allocate the got multiple times");
665   GOTBase = new uint8_t[sizeof(void*) * 8192];
666   HasGOT = true;
667 }
668
669 DefaultJITMemoryManager::~DefaultJITMemoryManager() {
670   for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
671     sys::Memory::ReleaseRWX(CodeSlabs[i]);
672
673   delete[] GOTBase;
674 }
675
676 sys::MemoryBlock DefaultJITMemoryManager::allocateNewSlab(size_t size) {
677   // Allocate a new block close to the last one.
678   std::string ErrMsg;
679   sys::MemoryBlock *LastSlabPtr = LastSlab.base() ? &LastSlab : 0;
680   sys::MemoryBlock B = sys::Memory::AllocateRWX(size, LastSlabPtr, &ErrMsg);
681   if (B.base() == 0) {
682     report_fatal_error("Allocation failed when allocating new memory in the"
683                        " JIT\n" + Twine(ErrMsg));
684   }
685   LastSlab = B;
686   ++NumSlabs;
687   // Initialize the slab to garbage when debugging.
688   if (PoisonMemory) {
689     memset(B.base(), 0xCD, B.size());
690   }
691   return B;
692 }
693
694 /// 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.
702 bool 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 }
782
783 //===----------------------------------------------------------------------===//
784 // getPointerToNamedFunction() implementation.
785 //===----------------------------------------------------------------------===//
786
787 // AtExitHandlers - List of functions to call when the program exits,
788 // registered with the atexit() library function.
789 static 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 ///
795 static 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  */
817 namespace {
818 class StatSymbols {
819 public:
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 }
835 static StatSymbols initStatSymbols;
836 #endif // __linux__
837
838 // jit_exit - Used to intercept the "exit" library call.
839 static 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.
845 static int jit_atexit(void (*Fn)()) {
846   AtExitHandlers.push_back(Fn);    // Take note of atexit handler...
847   return 0;  // Always successful
848 }
849
850 static 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 ///
860 void *DefaultJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
861                                                          bool AbortOnFailure) {
862   // 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
916 JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
917   return new DefaultJITMemoryManager();
918 }
919
920 // Allocate memory for code in 512K slabs.
921 const size_t DefaultJITMemoryManager::DefaultCodeSlabSize = 512 * 1024;
922
923 // Allocate globals and stubs in slabs of 64K.  (probably 16 pages)
924 const size_t DefaultJITMemoryManager::DefaultSlabSize = 64 * 1024;
925
926 // Waste at most 16K at the end of each bump slab.  (probably 4 pages)
927 const size_t DefaultJITMemoryManager::DefaultSizeThreshold = 16 * 1024;