LLVM API Documentation

JITMemoryManager.cpp
Go to the documentation of this file.
00001 //===-- JITMemoryManager.cpp - Memory Allocator for JIT'd code ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the DefaultJITMemoryManager class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "jit"
00015 #include "llvm/ExecutionEngine/JITMemoryManager.h"
00016 #include "llvm/ADT/SmallPtrSet.h"
00017 #include "llvm/ADT/Statistic.h"
00018 #include "llvm/ADT/Twine.h"
00019 #include "llvm/Config/config.h"
00020 #include "llvm/IR/GlobalValue.h"
00021 #include "llvm/Support/Allocator.h"
00022 #include "llvm/Support/Compiler.h"
00023 #include "llvm/Support/Debug.h"
00024 #include "llvm/Support/DynamicLibrary.h"
00025 #include "llvm/Support/ErrorHandling.h"
00026 #include "llvm/Support/Memory.h"
00027 #include "llvm/Support/raw_ostream.h"
00028 #include <cassert>
00029 #include <climits>
00030 #include <cstring>
00031 #include <vector>
00032 
00033 #if defined(__linux__)
00034 #if defined(HAVE_SYS_STAT_H)
00035 #include <sys/stat.h>
00036 #endif
00037 #include <fcntl.h>
00038 #include <unistd.h>
00039 #endif
00040 
00041 using namespace llvm;
00042 
00043 STATISTIC(NumSlabs, "Number of slabs of memory allocated by the JIT");
00044 
00045 JITMemoryManager::~JITMemoryManager() {}
00046 
00047 //===----------------------------------------------------------------------===//
00048 // Memory Block Implementation.
00049 //===----------------------------------------------------------------------===//
00050 
00051 namespace {
00052   /// MemoryRangeHeader - For a range of memory, this is the header that we put
00053   /// on the block of memory.  It is carefully crafted to be one word of memory.
00054   /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
00055   /// which starts with this.
00056   struct FreeRangeHeader;
00057   struct MemoryRangeHeader {
00058     /// ThisAllocated - This is true if this block is currently allocated.  If
00059     /// not, this can be converted to a FreeRangeHeader.
00060     unsigned ThisAllocated : 1;
00061 
00062     /// PrevAllocated - Keep track of whether the block immediately before us is
00063     /// allocated.  If not, the word immediately before this header is the size
00064     /// of the previous block.
00065     unsigned PrevAllocated : 1;
00066 
00067     /// BlockSize - This is the size in bytes of this memory block,
00068     /// including this header.
00069     uintptr_t BlockSize : (sizeof(intptr_t)*CHAR_BIT - 2);
00070 
00071 
00072     /// getBlockAfter - Return the memory block immediately after this one.
00073     ///
00074     MemoryRangeHeader &getBlockAfter() const {
00075       return *reinterpret_cast<MemoryRangeHeader *>(
00076                 reinterpret_cast<char*>(
00077                   const_cast<MemoryRangeHeader *>(this))+BlockSize);
00078     }
00079 
00080     /// getFreeBlockBefore - If the block before this one is free, return it,
00081     /// otherwise return null.
00082     FreeRangeHeader *getFreeBlockBefore() const {
00083       if (PrevAllocated) return 0;
00084       intptr_t PrevSize = reinterpret_cast<intptr_t *>(
00085                             const_cast<MemoryRangeHeader *>(this))[-1];
00086       return reinterpret_cast<FreeRangeHeader *>(
00087                reinterpret_cast<char*>(
00088                  const_cast<MemoryRangeHeader *>(this))-PrevSize);
00089     }
00090 
00091     /// FreeBlock - Turn an allocated block into a free block, adjusting
00092     /// bits in the object headers, and adding an end of region memory block.
00093     FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
00094 
00095     /// TrimAllocationToSize - If this allocated block is significantly larger
00096     /// than NewSize, split it into two pieces (where the former is NewSize
00097     /// bytes, including the header), and add the new block to the free list.
00098     FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
00099                                           uint64_t NewSize);
00100   };
00101 
00102   /// FreeRangeHeader - For a memory block that isn't already allocated, this
00103   /// keeps track of the current block and has a pointer to the next free block.
00104   /// Free blocks are kept on a circularly linked list.
00105   struct FreeRangeHeader : public MemoryRangeHeader {
00106     FreeRangeHeader *Prev;
00107     FreeRangeHeader *Next;
00108 
00109     /// getMinBlockSize - Get the minimum size for a memory block.  Blocks
00110     /// smaller than this size cannot be created.
00111     static unsigned getMinBlockSize() {
00112       return sizeof(FreeRangeHeader)+sizeof(intptr_t);
00113     }
00114 
00115     /// SetEndOfBlockSizeMarker - The word at the end of every free block is
00116     /// known to be the size of the free block.  Set it for this block.
00117     void SetEndOfBlockSizeMarker() {
00118       void *EndOfBlock = (char*)this + BlockSize;
00119       ((intptr_t *)EndOfBlock)[-1] = BlockSize;
00120     }
00121 
00122     FreeRangeHeader *RemoveFromFreeList() {
00123       assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
00124       Next->Prev = Prev;
00125       return Prev->Next = Next;
00126     }
00127 
00128     void AddToFreeList(FreeRangeHeader *FreeList) {
00129       Next = FreeList;
00130       Prev = FreeList->Prev;
00131       Prev->Next = this;
00132       Next->Prev = this;
00133     }
00134 
00135     /// GrowBlock - The block after this block just got deallocated.  Merge it
00136     /// into the current block.
00137     void GrowBlock(uintptr_t NewSize);
00138 
00139     /// AllocateBlock - Mark this entire block allocated, updating freelists
00140     /// etc.  This returns a pointer to the circular free-list.
00141     FreeRangeHeader *AllocateBlock();
00142   };
00143 }
00144 
00145 
00146 /// AllocateBlock - Mark this entire block allocated, updating freelists
00147 /// etc.  This returns a pointer to the circular free-list.
00148 FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
00149   assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
00150          "Cannot allocate an allocated block!");
00151   // Mark this block allocated.
00152   ThisAllocated = 1;
00153   getBlockAfter().PrevAllocated = 1;
00154 
00155   // Remove it from the free list.
00156   return RemoveFromFreeList();
00157 }
00158 
00159 /// FreeBlock - Turn an allocated block into a free block, adjusting
00160 /// bits in the object headers, and adding an end of region memory block.
00161 /// If possible, coalesce this block with neighboring blocks.  Return the
00162 /// FreeRangeHeader to allocate from.
00163 FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
00164   MemoryRangeHeader *FollowingBlock = &getBlockAfter();
00165   assert(ThisAllocated && "This block is already free!");
00166   assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
00167 
00168   FreeRangeHeader *FreeListToReturn = FreeList;
00169 
00170   // If the block after this one is free, merge it into this block.
00171   if (!FollowingBlock->ThisAllocated) {
00172     FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
00173     // "FreeList" always needs to be a valid free block.  If we're about to
00174     // coalesce with it, update our notion of what the free list is.
00175     if (&FollowingFreeBlock == FreeList) {
00176       FreeList = FollowingFreeBlock.Next;
00177       FreeListToReturn = 0;
00178       assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
00179     }
00180     FollowingFreeBlock.RemoveFromFreeList();
00181 
00182     // Include the following block into this one.
00183     BlockSize += FollowingFreeBlock.BlockSize;
00184     FollowingBlock = &FollowingFreeBlock.getBlockAfter();
00185 
00186     // Tell the block after the block we are coalescing that this block is
00187     // allocated.
00188     FollowingBlock->PrevAllocated = 1;
00189   }
00190 
00191   assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
00192 
00193   if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
00194     PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
00195     return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
00196   }
00197 
00198   // Otherwise, mark this block free.
00199   FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
00200   FollowingBlock->PrevAllocated = 0;
00201   FreeBlock.ThisAllocated = 0;
00202 
00203   // Link this into the linked list of free blocks.
00204   FreeBlock.AddToFreeList(FreeList);
00205 
00206   // Add a marker at the end of the block, indicating the size of this free
00207   // block.
00208   FreeBlock.SetEndOfBlockSizeMarker();
00209   return FreeListToReturn ? FreeListToReturn : &FreeBlock;
00210 }
00211 
00212 /// GrowBlock - The block after this block just got deallocated.  Merge it
00213 /// into the current block.
00214 void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
00215   assert(NewSize > BlockSize && "Not growing block?");
00216   BlockSize = NewSize;
00217   SetEndOfBlockSizeMarker();
00218   getBlockAfter().PrevAllocated = 0;
00219 }
00220 
00221 /// TrimAllocationToSize - If this allocated block is significantly larger
00222 /// than NewSize, split it into two pieces (where the former is NewSize
00223 /// bytes, including the header), and add the new block to the free list.
00224 FreeRangeHeader *MemoryRangeHeader::
00225 TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
00226   assert(ThisAllocated && getBlockAfter().PrevAllocated &&
00227          "Cannot deallocate part of an allocated block!");
00228 
00229   // Don't allow blocks to be trimmed below minimum required size
00230   NewSize = std::max<uint64_t>(FreeRangeHeader::getMinBlockSize(), NewSize);
00231 
00232   // Round up size for alignment of header.
00233   unsigned HeaderAlign = __alignof(FreeRangeHeader);
00234   NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
00235 
00236   // Size is now the size of the block we will remove from the start of the
00237   // current block.
00238   assert(NewSize <= BlockSize &&
00239          "Allocating more space from this block than exists!");
00240 
00241   // If splitting this block will cause the remainder to be too small, do not
00242   // split the block.
00243   if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
00244     return FreeList;
00245 
00246   // Otherwise, we splice the required number of bytes out of this block, form
00247   // a new block immediately after it, then mark this block allocated.
00248   MemoryRangeHeader &FormerNextBlock = getBlockAfter();
00249 
00250   // Change the size of this block.
00251   BlockSize = NewSize;
00252 
00253   // Get the new block we just sliced out and turn it into a free block.
00254   FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
00255   NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
00256   NewNextBlock.ThisAllocated = 0;
00257   NewNextBlock.PrevAllocated = 1;
00258   NewNextBlock.SetEndOfBlockSizeMarker();
00259   FormerNextBlock.PrevAllocated = 0;
00260   NewNextBlock.AddToFreeList(FreeList);
00261   return &NewNextBlock;
00262 }
00263 
00264 //===----------------------------------------------------------------------===//
00265 // Memory Block Implementation.
00266 //===----------------------------------------------------------------------===//
00267 
00268 namespace {
00269 
00270   class DefaultJITMemoryManager;
00271 
00272   class JITSlabAllocator : public SlabAllocator {
00273     DefaultJITMemoryManager &JMM;
00274   public:
00275     JITSlabAllocator(DefaultJITMemoryManager &jmm) : JMM(jmm) { }
00276     virtual ~JITSlabAllocator() { }
00277     virtual MemSlab *Allocate(size_t Size);
00278     virtual void Deallocate(MemSlab *Slab);
00279   };
00280 
00281   /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
00282   /// This splits a large block of MAP_NORESERVE'd memory into two
00283   /// sections, one for function stubs, one for the functions themselves.  We
00284   /// have to do this because we may need to emit a function stub while in the
00285   /// middle of emitting a function, and we don't know how large the function we
00286   /// are emitting is.
00287   class DefaultJITMemoryManager : public JITMemoryManager {
00288 
00289     // Whether to poison freed memory.
00290     bool PoisonMemory;
00291 
00292     /// LastSlab - This points to the last slab allocated and is used as the
00293     /// NearBlock parameter to AllocateRWX so that we can attempt to lay out all
00294     /// stubs, data, and code contiguously in memory.  In general, however, this
00295     /// is not possible because the NearBlock parameter is ignored on Windows
00296     /// platforms and even on Unix it works on a best-effort pasis.
00297     sys::MemoryBlock LastSlab;
00298 
00299     // Memory slabs allocated by the JIT.  We refer to them as slabs so we don't
00300     // confuse them with the blocks of memory described above.
00301     std::vector<sys::MemoryBlock> CodeSlabs;
00302     JITSlabAllocator BumpSlabAllocator;
00303     BumpPtrAllocator StubAllocator;
00304     BumpPtrAllocator DataAllocator;
00305 
00306     // Circular list of free blocks.
00307     FreeRangeHeader *FreeMemoryList;
00308 
00309     // When emitting code into a memory block, this is the block.
00310     MemoryRangeHeader *CurBlock;
00311 
00312     uint8_t *GOTBase;     // Target Specific reserved memory
00313   public:
00314     DefaultJITMemoryManager();
00315     ~DefaultJITMemoryManager();
00316 
00317     /// allocateNewSlab - Allocates a new MemoryBlock and remembers it as the
00318     /// last slab it allocated, so that subsequent allocations follow it.
00319     sys::MemoryBlock allocateNewSlab(size_t size);
00320 
00321     /// DefaultCodeSlabSize - When we have to go map more memory, we allocate at
00322     /// least this much unless more is requested.
00323     static const size_t DefaultCodeSlabSize;
00324 
00325     /// DefaultSlabSize - Allocate data into slabs of this size unless we get
00326     /// an allocation above SizeThreshold.
00327     static const size_t DefaultSlabSize;
00328 
00329     /// DefaultSizeThreshold - For any allocation larger than this threshold, we
00330     /// should allocate a separate slab.
00331     static const size_t DefaultSizeThreshold;
00332 
00333     /// getPointerToNamedFunction - This method returns the address of the
00334     /// specified function by using the dlsym function call.
00335     virtual void *getPointerToNamedFunction(const std::string &Name,
00336                                             bool AbortOnFailure = true);
00337 
00338     void AllocateGOT();
00339 
00340     // Testing methods.
00341     virtual bool CheckInvariants(std::string &ErrorStr);
00342     size_t GetDefaultCodeSlabSize() { return DefaultCodeSlabSize; }
00343     size_t GetDefaultDataSlabSize() { return DefaultSlabSize; }
00344     size_t GetDefaultStubSlabSize() { return DefaultSlabSize; }
00345     unsigned GetNumCodeSlabs() { return CodeSlabs.size(); }
00346     unsigned GetNumDataSlabs() { return DataAllocator.GetNumSlabs(); }
00347     unsigned GetNumStubSlabs() { return StubAllocator.GetNumSlabs(); }
00348 
00349     /// startFunctionBody - When a function starts, allocate a block of free
00350     /// executable memory, returning a pointer to it and its actual size.
00351     uint8_t *startFunctionBody(const Function *F, uintptr_t &ActualSize) {
00352 
00353       FreeRangeHeader* candidateBlock = FreeMemoryList;
00354       FreeRangeHeader* head = FreeMemoryList;
00355       FreeRangeHeader* iter = head->Next;
00356 
00357       uintptr_t largest = candidateBlock->BlockSize;
00358 
00359       // Search for the largest free block
00360       while (iter != head) {
00361         if (iter->BlockSize > largest) {
00362           largest = iter->BlockSize;
00363           candidateBlock = iter;
00364         }
00365         iter = iter->Next;
00366       }
00367 
00368       largest = largest - sizeof(MemoryRangeHeader);
00369 
00370       // If this block isn't big enough for the allocation desired, allocate
00371       // another block of memory and add it to the free list.
00372       if (largest < ActualSize ||
00373           largest <= FreeRangeHeader::getMinBlockSize()) {
00374         DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
00375         candidateBlock = allocateNewCodeSlab((size_t)ActualSize);
00376       }
00377 
00378       // Select this candidate block for allocation
00379       CurBlock = candidateBlock;
00380 
00381       // Allocate the entire memory block.
00382       FreeMemoryList = candidateBlock->AllocateBlock();
00383       ActualSize = CurBlock->BlockSize - sizeof(MemoryRangeHeader);
00384       return (uint8_t *)(CurBlock + 1);
00385     }
00386 
00387     /// allocateNewCodeSlab - Helper method to allocate a new slab of code
00388     /// memory from the OS and add it to the free list.  Returns the new
00389     /// FreeRangeHeader at the base of the slab.
00390     FreeRangeHeader *allocateNewCodeSlab(size_t MinSize) {
00391       // If the user needs at least MinSize free memory, then we account for
00392       // two MemoryRangeHeaders: the one in the user's block, and the one at the
00393       // end of the slab.
00394       size_t PaddedMin = MinSize + 2 * sizeof(MemoryRangeHeader);
00395       size_t SlabSize = std::max(DefaultCodeSlabSize, PaddedMin);
00396       sys::MemoryBlock B = allocateNewSlab(SlabSize);
00397       CodeSlabs.push_back(B);
00398       char *MemBase = (char*)(B.base());
00399 
00400       // Put a tiny allocated block at the end of the memory chunk, so when
00401       // FreeBlock calls getBlockAfter it doesn't fall off the end.
00402       MemoryRangeHeader *EndBlock =
00403           (MemoryRangeHeader*)(MemBase + B.size()) - 1;
00404       EndBlock->ThisAllocated = 1;
00405       EndBlock->PrevAllocated = 0;
00406       EndBlock->BlockSize = sizeof(MemoryRangeHeader);
00407 
00408       // Start out with a vast new block of free memory.
00409       FreeRangeHeader *NewBlock = (FreeRangeHeader*)MemBase;
00410       NewBlock->ThisAllocated = 0;
00411       // Make sure getFreeBlockBefore doesn't look into unmapped memory.
00412       NewBlock->PrevAllocated = 1;
00413       NewBlock->BlockSize = (uintptr_t)EndBlock - (uintptr_t)NewBlock;
00414       NewBlock->SetEndOfBlockSizeMarker();
00415       NewBlock->AddToFreeList(FreeMemoryList);
00416 
00417       assert(NewBlock->BlockSize - sizeof(MemoryRangeHeader) >= MinSize &&
00418              "The block was too small!");
00419       return NewBlock;
00420     }
00421 
00422     /// endFunctionBody - The function F is now allocated, and takes the memory
00423     /// in the range [FunctionStart,FunctionEnd).
00424     void endFunctionBody(const Function *F, uint8_t *FunctionStart,
00425                          uint8_t *FunctionEnd) {
00426       assert(FunctionEnd > FunctionStart);
00427       assert(FunctionStart == (uint8_t *)(CurBlock+1) &&
00428              "Mismatched function start/end!");
00429 
00430       uintptr_t BlockSize = FunctionEnd - (uint8_t *)CurBlock;
00431 
00432       // Release the memory at the end of this block that isn't needed.
00433       FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
00434     }
00435 
00436     /// allocateSpace - Allocate a memory block of the given size.  This method
00437     /// cannot be called between calls to startFunctionBody and endFunctionBody.
00438     uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
00439       CurBlock = FreeMemoryList;
00440       FreeMemoryList = FreeMemoryList->AllocateBlock();
00441 
00442       uint8_t *result = (uint8_t *)(CurBlock + 1);
00443 
00444       if (Alignment == 0) Alignment = 1;
00445       result = (uint8_t*)(((intptr_t)result+Alignment-1) &
00446                ~(intptr_t)(Alignment-1));
00447 
00448       uintptr_t BlockSize = result + Size - (uint8_t *)CurBlock;
00449       FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
00450 
00451       return result;
00452     }
00453 
00454     /// allocateStub - Allocate memory for a function stub.
00455     uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
00456                           unsigned Alignment) {
00457       return (uint8_t*)StubAllocator.Allocate(StubSize, Alignment);
00458     }
00459 
00460     /// allocateGlobal - Allocate memory for a global.
00461     uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
00462       return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
00463     }
00464 
00465     /// allocateCodeSection - Allocate memory for a code section.
00466     uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
00467                                  unsigned SectionID) {
00468       // Grow the required block size to account for the block header
00469       Size += sizeof(*CurBlock);
00470 
00471       // FIXME: Alignement handling.
00472       FreeRangeHeader* candidateBlock = FreeMemoryList;
00473       FreeRangeHeader* head = FreeMemoryList;
00474       FreeRangeHeader* iter = head->Next;
00475 
00476       uintptr_t largest = candidateBlock->BlockSize;
00477 
00478       // Search for the largest free block.
00479       while (iter != head) {
00480         if (iter->BlockSize > largest) {
00481           largest = iter->BlockSize;
00482           candidateBlock = iter;
00483         }
00484         iter = iter->Next;
00485       }
00486 
00487       largest = largest - sizeof(MemoryRangeHeader);
00488 
00489       // If this block isn't big enough for the allocation desired, allocate
00490       // another block of memory and add it to the free list.
00491       if (largest < Size || largest <= FreeRangeHeader::getMinBlockSize()) {
00492         DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
00493         candidateBlock = allocateNewCodeSlab((size_t)Size);
00494       }
00495 
00496       // Select this candidate block for allocation
00497       CurBlock = candidateBlock;
00498 
00499       // Allocate the entire memory block.
00500       FreeMemoryList = candidateBlock->AllocateBlock();
00501       // Release the memory at the end of this block that isn't needed.
00502       FreeMemoryList = CurBlock->TrimAllocationToSize(FreeMemoryList, Size);
00503       return (uint8_t *)(CurBlock + 1);
00504     }
00505 
00506     /// allocateDataSection - Allocate memory for a data section.
00507     uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
00508                                  unsigned SectionID, bool IsReadOnly) {
00509       return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
00510     }
00511 
00512     bool finalizeMemory(std::string *ErrMsg) {
00513       return false;
00514     }
00515 
00516     uint8_t *getGOTBase() const {
00517       return GOTBase;
00518     }
00519 
00520     void deallocateBlock(void *Block) {
00521       // Find the block that is allocated for this function.
00522       MemoryRangeHeader *MemRange = static_cast<MemoryRangeHeader*>(Block) - 1;
00523       assert(MemRange->ThisAllocated && "Block isn't allocated!");
00524 
00525       // Fill the buffer with garbage!
00526       if (PoisonMemory) {
00527         memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
00528       }
00529 
00530       // Free the memory.
00531       FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
00532     }
00533 
00534     /// deallocateFunctionBody - Deallocate all memory for the specified
00535     /// function body.
00536     void deallocateFunctionBody(void *Body) {
00537       if (Body) deallocateBlock(Body);
00538     }
00539 
00540     /// setMemoryWritable - When code generation is in progress,
00541     /// the code pages may need permissions changed.
00542     void setMemoryWritable()
00543     {
00544       for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
00545         sys::Memory::setWritable(CodeSlabs[i]);
00546     }
00547     /// setMemoryExecutable - When code generation is done and we're ready to
00548     /// start execution, the code pages may need permissions changed.
00549     void setMemoryExecutable()
00550     {
00551       for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
00552         sys::Memory::setExecutable(CodeSlabs[i]);
00553     }
00554 
00555     /// setPoisonMemory - Controls whether we write garbage over freed memory.
00556     ///
00557     void setPoisonMemory(bool poison) {
00558       PoisonMemory = poison;
00559     }
00560   };
00561 }
00562 
00563 MemSlab *JITSlabAllocator::Allocate(size_t Size) {
00564   sys::MemoryBlock B = JMM.allocateNewSlab(Size);
00565   MemSlab *Slab = (MemSlab*)B.base();
00566   Slab->Size = B.size();
00567   Slab->NextPtr = 0;
00568   return Slab;
00569 }
00570 
00571 void JITSlabAllocator::Deallocate(MemSlab *Slab) {
00572   sys::MemoryBlock B(Slab, Slab->Size);
00573   sys::Memory::ReleaseRWX(B);
00574 }
00575 
00576 DefaultJITMemoryManager::DefaultJITMemoryManager()
00577   :
00578 #ifdef NDEBUG
00579     PoisonMemory(false),
00580 #else
00581     PoisonMemory(true),
00582 #endif
00583     LastSlab(0, 0),
00584     BumpSlabAllocator(*this),
00585     StubAllocator(DefaultSlabSize, DefaultSizeThreshold, BumpSlabAllocator),
00586     DataAllocator(DefaultSlabSize, DefaultSizeThreshold, BumpSlabAllocator) {
00587 
00588   // Allocate space for code.
00589   sys::MemoryBlock MemBlock = allocateNewSlab(DefaultCodeSlabSize);
00590   CodeSlabs.push_back(MemBlock);
00591   uint8_t *MemBase = (uint8_t*)MemBlock.base();
00592 
00593   // We set up the memory chunk with 4 mem regions, like this:
00594   //  [ START
00595   //    [ Free      #0 ] -> Large space to allocate functions from.
00596   //    [ Allocated #1 ] -> Tiny space to separate regions.
00597   //    [ Free      #2 ] -> Tiny space so there is always at least 1 free block.
00598   //    [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
00599   //  END ]
00600   //
00601   // The last three blocks are never deallocated or touched.
00602 
00603   // Add MemoryRangeHeader to the end of the memory region, indicating that
00604   // the space after the block of memory is allocated.  This is block #3.
00605   MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
00606   Mem3->ThisAllocated = 1;
00607   Mem3->PrevAllocated = 0;
00608   Mem3->BlockSize     = sizeof(MemoryRangeHeader);
00609 
00610   /// Add a tiny free region so that the free list always has one entry.
00611   FreeRangeHeader *Mem2 =
00612     (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
00613   Mem2->ThisAllocated = 0;
00614   Mem2->PrevAllocated = 1;
00615   Mem2->BlockSize     = FreeRangeHeader::getMinBlockSize();
00616   Mem2->SetEndOfBlockSizeMarker();
00617   Mem2->Prev = Mem2;   // Mem2 *is* the free list for now.
00618   Mem2->Next = Mem2;
00619 
00620   /// Add a tiny allocated region so that Mem2 is never coalesced away.
00621   MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
00622   Mem1->ThisAllocated = 1;
00623   Mem1->PrevAllocated = 0;
00624   Mem1->BlockSize     = sizeof(MemoryRangeHeader);
00625 
00626   // Add a FreeRangeHeader to the start of the function body region, indicating
00627   // that the space is free.  Mark the previous block allocated so we never look
00628   // at it.
00629   FreeRangeHeader *Mem0 = (FreeRangeHeader*)MemBase;
00630   Mem0->ThisAllocated = 0;
00631   Mem0->PrevAllocated = 1;
00632   Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
00633   Mem0->SetEndOfBlockSizeMarker();
00634   Mem0->AddToFreeList(Mem2);
00635 
00636   // Start out with the freelist pointing to Mem0.
00637   FreeMemoryList = Mem0;
00638 
00639   GOTBase = NULL;
00640 }
00641 
00642 void DefaultJITMemoryManager::AllocateGOT() {
00643   assert(GOTBase == 0 && "Cannot allocate the got multiple times");
00644   GOTBase = new uint8_t[sizeof(void*) * 8192];
00645   HasGOT = true;
00646 }
00647 
00648 DefaultJITMemoryManager::~DefaultJITMemoryManager() {
00649   for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
00650     sys::Memory::ReleaseRWX(CodeSlabs[i]);
00651 
00652   delete[] GOTBase;
00653 }
00654 
00655 sys::MemoryBlock DefaultJITMemoryManager::allocateNewSlab(size_t size) {
00656   // Allocate a new block close to the last one.
00657   std::string ErrMsg;
00658   sys::MemoryBlock *LastSlabPtr = LastSlab.base() ? &LastSlab : 0;
00659   sys::MemoryBlock B = sys::Memory::AllocateRWX(size, LastSlabPtr, &ErrMsg);
00660   if (B.base() == 0) {
00661     report_fatal_error("Allocation failed when allocating new memory in the"
00662                        " JIT\n" + Twine(ErrMsg));
00663   }
00664   LastSlab = B;
00665   ++NumSlabs;
00666   // Initialize the slab to garbage when debugging.
00667   if (PoisonMemory) {
00668     memset(B.base(), 0xCD, B.size());
00669   }
00670   return B;
00671 }
00672 
00673 /// CheckInvariants - For testing only.  Return "" if all internal invariants
00674 /// are preserved, and a helpful error message otherwise.  For free and
00675 /// allocated blocks, make sure that adding BlockSize gives a valid block.
00676 /// For free blocks, make sure they're in the free list and that their end of
00677 /// block size marker is correct.  This function should return an error before
00678 /// accessing bad memory.  This function is defined here instead of in
00679 /// JITMemoryManagerTest.cpp so that we don't have to expose all of the
00680 /// implementation details of DefaultJITMemoryManager.
00681 bool DefaultJITMemoryManager::CheckInvariants(std::string &ErrorStr) {
00682   raw_string_ostream Err(ErrorStr);
00683 
00684   // Construct a the set of FreeRangeHeader pointers so we can query it
00685   // efficiently.
00686   llvm::SmallPtrSet<MemoryRangeHeader*, 16> FreeHdrSet;
00687   FreeRangeHeader* FreeHead = FreeMemoryList;
00688   FreeRangeHeader* FreeRange = FreeHead;
00689 
00690   do {
00691     // Check that the free range pointer is in the blocks we've allocated.
00692     bool Found = false;
00693     for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
00694          E = CodeSlabs.end(); I != E && !Found; ++I) {
00695       char *Start = (char*)I->base();
00696       char *End = Start + I->size();
00697       Found = (Start <= (char*)FreeRange && (char*)FreeRange < End);
00698     }
00699     if (!Found) {
00700       Err << "Corrupt free list; points to " << FreeRange;
00701       return false;
00702     }
00703 
00704     if (FreeRange->Next->Prev != FreeRange) {
00705       Err << "Next and Prev pointers do not match.";
00706       return false;
00707     }
00708 
00709     // Otherwise, add it to the set.
00710     FreeHdrSet.insert(FreeRange);
00711     FreeRange = FreeRange->Next;
00712   } while (FreeRange != FreeHead);
00713 
00714   // Go over each block, and look at each MemoryRangeHeader.
00715   for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
00716        E = CodeSlabs.end(); I != E; ++I) {
00717     char *Start = (char*)I->base();
00718     char *End = Start + I->size();
00719 
00720     // Check each memory range.
00721     for (MemoryRangeHeader *Hdr = (MemoryRangeHeader*)Start, *LastHdr = NULL;
00722          Start <= (char*)Hdr && (char*)Hdr < End;
00723          Hdr = &Hdr->getBlockAfter()) {
00724       if (Hdr->ThisAllocated == 0) {
00725         // Check that this range is in the free list.
00726         if (!FreeHdrSet.count(Hdr)) {
00727           Err << "Found free header at " << Hdr << " that is not in free list.";
00728           return false;
00729         }
00730 
00731         // Now make sure the size marker at the end of the block is correct.
00732         uintptr_t *Marker = ((uintptr_t*)&Hdr->getBlockAfter()) - 1;
00733         if (!(Start <= (char*)Marker && (char*)Marker < End)) {
00734           Err << "Block size in header points out of current MemoryBlock.";
00735           return false;
00736         }
00737         if (Hdr->BlockSize != *Marker) {
00738           Err << "End of block size marker (" << *Marker << ") "
00739               << "and BlockSize (" << Hdr->BlockSize << ") don't match.";
00740           return false;
00741         }
00742       }
00743 
00744       if (LastHdr && LastHdr->ThisAllocated != Hdr->PrevAllocated) {
00745         Err << "Hdr->PrevAllocated (" << Hdr->PrevAllocated << ") != "
00746             << "LastHdr->ThisAllocated (" << LastHdr->ThisAllocated << ")";
00747         return false;
00748       } else if (!LastHdr && !Hdr->PrevAllocated) {
00749         Err << "The first header should have PrevAllocated true.";
00750         return false;
00751       }
00752 
00753       // Remember the last header.
00754       LastHdr = Hdr;
00755     }
00756   }
00757 
00758   // All invariants are preserved.
00759   return true;
00760 }
00761 
00762 //===----------------------------------------------------------------------===//
00763 // getPointerToNamedFunction() implementation.
00764 //===----------------------------------------------------------------------===//
00765 
00766 // AtExitHandlers - List of functions to call when the program exits,
00767 // registered with the atexit() library function.
00768 static std::vector<void (*)()> AtExitHandlers;
00769 
00770 /// runAtExitHandlers - Run any functions registered by the program's
00771 /// calls to atexit(3), which we intercept and store in
00772 /// AtExitHandlers.
00773 ///
00774 static void runAtExitHandlers() {
00775   while (!AtExitHandlers.empty()) {
00776     void (*Fn)() = AtExitHandlers.back();
00777     AtExitHandlers.pop_back();
00778     Fn();
00779   }
00780 }
00781 
00782 //===----------------------------------------------------------------------===//
00783 // Function stubs that are invoked instead of certain library calls
00784 //
00785 // Force the following functions to be linked in to anything that uses the
00786 // JIT. This is a hack designed to work around the all-too-clever Glibc
00787 // strategy of making these functions work differently when inlined vs. when
00788 // not inlined, and hiding their real definitions in a separate archive file
00789 // that the dynamic linker can't see. For more info, search for
00790 // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
00791 #if defined(__linux__)
00792 /* stat functions are redirecting to __xstat with a version number.  On x86-64
00793  * linking with libc_nonshared.a and -Wl,--export-dynamic doesn't make 'stat'
00794  * available as an exported symbol, so we have to add it explicitly.
00795  */
00796 namespace {
00797 class StatSymbols {
00798 public:
00799   StatSymbols() {
00800     sys::DynamicLibrary::AddSymbol("stat", (void*)(intptr_t)stat);
00801     sys::DynamicLibrary::AddSymbol("fstat", (void*)(intptr_t)fstat);
00802     sys::DynamicLibrary::AddSymbol("lstat", (void*)(intptr_t)lstat);
00803     sys::DynamicLibrary::AddSymbol("stat64", (void*)(intptr_t)stat64);
00804     sys::DynamicLibrary::AddSymbol("\x1stat64", (void*)(intptr_t)stat64);
00805     sys::DynamicLibrary::AddSymbol("\x1open64", (void*)(intptr_t)open64);
00806     sys::DynamicLibrary::AddSymbol("\x1lseek64", (void*)(intptr_t)lseek64);
00807     sys::DynamicLibrary::AddSymbol("fstat64", (void*)(intptr_t)fstat64);
00808     sys::DynamicLibrary::AddSymbol("lstat64", (void*)(intptr_t)lstat64);
00809     sys::DynamicLibrary::AddSymbol("atexit", (void*)(intptr_t)atexit);
00810     sys::DynamicLibrary::AddSymbol("mknod", (void*)(intptr_t)mknod);
00811   }
00812 };
00813 }
00814 static StatSymbols initStatSymbols;
00815 #endif // __linux__
00816 
00817 // jit_exit - Used to intercept the "exit" library call.
00818 static void jit_exit(int Status) {
00819   runAtExitHandlers();   // Run atexit handlers...
00820   exit(Status);
00821 }
00822 
00823 // jit_atexit - Used to intercept the "atexit" library call.
00824 static int jit_atexit(void (*Fn)()) {
00825   AtExitHandlers.push_back(Fn);    // Take note of atexit handler...
00826   return 0;  // Always successful
00827 }
00828 
00829 static int jit_noop() {
00830   return 0;
00831 }
00832 
00833 //===----------------------------------------------------------------------===//
00834 //
00835 /// getPointerToNamedFunction - This method returns the address of the specified
00836 /// function by using the dynamic loader interface.  As such it is only useful
00837 /// for resolving library symbols, not code generated symbols.
00838 ///
00839 void *DefaultJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
00840                                                          bool AbortOnFailure) {
00841   // Check to see if this is one of the functions we want to intercept.  Note,
00842   // we cast to intptr_t here to silence a -pedantic warning that complains
00843   // about casting a function pointer to a normal pointer.
00844   if (Name == "exit") return (void*)(intptr_t)&jit_exit;
00845   if (Name == "atexit") return (void*)(intptr_t)&jit_atexit;
00846 
00847   // We should not invoke parent's ctors/dtors from generated main()!
00848   // On Mingw and Cygwin, the symbol __main is resolved to
00849   // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
00850   // (and register wrong callee's dtors with atexit(3)).
00851   // We expect ExecutionEngine::runStaticConstructorsDestructors()
00852   // is called before ExecutionEngine::runFunctionAsMain() is called.
00853   if (Name == "__main") return (void*)(intptr_t)&jit_noop;
00854 
00855   const char *NameStr = Name.c_str();
00856   // If this is an asm specifier, skip the sentinal.
00857   if (NameStr[0] == 1) ++NameStr;
00858 
00859   // If it's an external function, look it up in the process image...
00860   void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
00861   if (Ptr) return Ptr;
00862 
00863   // If it wasn't found and if it starts with an underscore ('_') character,
00864   // try again without the underscore.
00865   if (NameStr[0] == '_') {
00866     Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
00867     if (Ptr) return Ptr;
00868   }
00869 
00870   // Darwin/PPC adds $LDBLStub suffixes to various symbols like printf.  These
00871   // are references to hidden visibility symbols that dlsym cannot resolve.
00872   // If we have one of these, strip off $LDBLStub and try again.
00873 #if defined(__APPLE__) && defined(__ppc__)
00874   if (Name.size() > 9 && Name[Name.size()-9] == '$' &&
00875       memcmp(&Name[Name.size()-8], "LDBLStub", 8) == 0) {
00876     // First try turning $LDBLStub into $LDBL128. If that fails, strip it off.
00877     // This mirrors logic in libSystemStubs.a.
00878     std::string Prefix = std::string(Name.begin(), Name.end()-9);
00879     if (void *Ptr = getPointerToNamedFunction(Prefix+"$LDBL128", false))
00880       return Ptr;
00881     if (void *Ptr = getPointerToNamedFunction(Prefix, false))
00882       return Ptr;
00883   }
00884 #endif
00885 
00886   if (AbortOnFailure) {
00887     report_fatal_error("Program used external function '"+Name+
00888                       "' which could not be resolved!");
00889   }
00890   return 0;
00891 }
00892 
00893 
00894 
00895 JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
00896   return new DefaultJITMemoryManager();
00897 }
00898 
00899 // Allocate memory for code in 512K slabs.
00900 const size_t DefaultJITMemoryManager::DefaultCodeSlabSize = 512 * 1024;
00901 
00902 // Allocate globals and stubs in slabs of 64K.  (probably 16 pages)
00903 const size_t DefaultJITMemoryManager::DefaultSlabSize = 64 * 1024;
00904 
00905 // Waste at most 16K at the end of each bump slab.  (probably 4 pages)
00906 const size_t DefaultJITMemoryManager::DefaultSizeThreshold = 16 * 1024;