JITMemoryManager.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. #include "llvm/ExecutionEngine/JITMemoryManager.h"
  14. #include "llvm/Support/Compiler.h"
  15. #include "llvm/System/Memory.h"
  16. #include <map>
  17. #include <vector>
  18. #include <cassert>
  19. #include <cstdlib>
  20. #include <cstring>
  21. using namespace llvm;
  22. JITMemoryManager::~JITMemoryManager() {}
  23. //===----------------------------------------------------------------------===//
  24. // Memory Block Implementation.
  25. //===----------------------------------------------------------------------===//
  26. namespace {
  27. /// MemoryRangeHeader - For a range of memory, this is the header that we put
  28. /// on the block of memory. It is carefully crafted to be one word of memory.
  29. /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
  30. /// which starts with this.
  31. struct FreeRangeHeader;
  32. struct MemoryRangeHeader {
  33. /// ThisAllocated - This is true if this block is currently allocated. If
  34. /// not, this can be converted to a FreeRangeHeader.
  35. unsigned ThisAllocated : 1;
  36. /// PrevAllocated - Keep track of whether the block immediately before us is
  37. /// allocated. If not, the word immediately before this header is the size
  38. /// of the previous block.
  39. unsigned PrevAllocated : 1;
  40. /// BlockSize - This is the size in bytes of this memory block,
  41. /// including this header.
  42. uintptr_t BlockSize : (sizeof(intptr_t)*8 - 2);
  43. /// getBlockAfter - Return the memory block immediately after this one.
  44. ///
  45. MemoryRangeHeader &getBlockAfter() const {
  46. return *(MemoryRangeHeader*)((char*)this+BlockSize);
  47. }
  48. /// getFreeBlockBefore - If the block before this one is free, return it,
  49. /// otherwise return null.
  50. FreeRangeHeader *getFreeBlockBefore() const {
  51. if (PrevAllocated) return 0;
  52. intptr_t PrevSize = ((intptr_t *)this)[-1];
  53. return (FreeRangeHeader*)((char*)this-PrevSize);
  54. }
  55. /// FreeBlock - Turn an allocated block into a free block, adjusting
  56. /// bits in the object headers, and adding an end of region memory block.
  57. FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
  58. /// TrimAllocationToSize - If this allocated block is significantly larger
  59. /// than NewSize, split it into two pieces (where the former is NewSize
  60. /// bytes, including the header), and add the new block to the free list.
  61. FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
  62. uint64_t NewSize);
  63. };
  64. /// FreeRangeHeader - For a memory block that isn't already allocated, this
  65. /// keeps track of the current block and has a pointer to the next free block.
  66. /// Free blocks are kept on a circularly linked list.
  67. struct FreeRangeHeader : public MemoryRangeHeader {
  68. FreeRangeHeader *Prev;
  69. FreeRangeHeader *Next;
  70. /// getMinBlockSize - Get the minimum size for a memory block. Blocks
  71. /// smaller than this size cannot be created.
  72. static unsigned getMinBlockSize() {
  73. return sizeof(FreeRangeHeader)+sizeof(intptr_t);
  74. }
  75. /// SetEndOfBlockSizeMarker - The word at the end of every free block is
  76. /// known to be the size of the free block. Set it for this block.
  77. void SetEndOfBlockSizeMarker() {
  78. void *EndOfBlock = (char*)this + BlockSize;
  79. ((intptr_t *)EndOfBlock)[-1] = BlockSize;
  80. }
  81. FreeRangeHeader *RemoveFromFreeList() {
  82. assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
  83. Next->Prev = Prev;
  84. return Prev->Next = Next;
  85. }
  86. void AddToFreeList(FreeRangeHeader *FreeList) {
  87. Next = FreeList;
  88. Prev = FreeList->Prev;
  89. Prev->Next = this;
  90. Next->Prev = this;
  91. }
  92. /// GrowBlock - The block after this block just got deallocated. Merge it
  93. /// into the current block.
  94. void GrowBlock(uintptr_t NewSize);
  95. /// AllocateBlock - Mark this entire block allocated, updating freelists
  96. /// etc. This returns a pointer to the circular free-list.
  97. FreeRangeHeader *AllocateBlock();
  98. };
  99. }
  100. /// AllocateBlock - Mark this entire block allocated, updating freelists
  101. /// etc. This returns a pointer to the circular free-list.
  102. FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
  103. assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
  104. "Cannot allocate an allocated block!");
  105. // Mark this block allocated.
  106. ThisAllocated = 1;
  107. getBlockAfter().PrevAllocated = 1;
  108. // Remove it from the free list.
  109. return RemoveFromFreeList();
  110. }
  111. /// FreeBlock - Turn an allocated block into a free block, adjusting
  112. /// bits in the object headers, and adding an end of region memory block.
  113. /// If possible, coalesce this block with neighboring blocks. Return the
  114. /// FreeRangeHeader to allocate from.
  115. FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
  116. MemoryRangeHeader *FollowingBlock = &getBlockAfter();
  117. assert(ThisAllocated && "This block is already allocated!");
  118. assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
  119. FreeRangeHeader *FreeListToReturn = FreeList;
  120. // If the block after this one is free, merge it into this block.
  121. if (!FollowingBlock->ThisAllocated) {
  122. FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
  123. // "FreeList" always needs to be a valid free block. If we're about to
  124. // coalesce with it, update our notion of what the free list is.
  125. if (&FollowingFreeBlock == FreeList) {
  126. FreeList = FollowingFreeBlock.Next;
  127. FreeListToReturn = 0;
  128. assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
  129. }
  130. FollowingFreeBlock.RemoveFromFreeList();
  131. // Include the following block into this one.
  132. BlockSize += FollowingFreeBlock.BlockSize;
  133. FollowingBlock = &FollowingFreeBlock.getBlockAfter();
  134. // Tell the block after the block we are coalescing that this block is
  135. // allocated.
  136. FollowingBlock->PrevAllocated = 1;
  137. }
  138. assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
  139. if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
  140. PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
  141. return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
  142. }
  143. // Otherwise, mark this block free.
  144. FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
  145. FollowingBlock->PrevAllocated = 0;
  146. FreeBlock.ThisAllocated = 0;
  147. // Link this into the linked list of free blocks.
  148. FreeBlock.AddToFreeList(FreeList);
  149. // Add a marker at the end of the block, indicating the size of this free
  150. // block.
  151. FreeBlock.SetEndOfBlockSizeMarker();
  152. return FreeListToReturn ? FreeListToReturn : &FreeBlock;
  153. }
  154. /// GrowBlock - The block after this block just got deallocated. Merge it
  155. /// into the current block.
  156. void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
  157. assert(NewSize > BlockSize && "Not growing block?");
  158. BlockSize = NewSize;
  159. SetEndOfBlockSizeMarker();
  160. getBlockAfter().PrevAllocated = 0;
  161. }
  162. /// TrimAllocationToSize - If this allocated block is significantly larger
  163. /// than NewSize, split it into two pieces (where the former is NewSize
  164. /// bytes, including the header), and add the new block to the free list.
  165. FreeRangeHeader *MemoryRangeHeader::
  166. TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
  167. assert(ThisAllocated && getBlockAfter().PrevAllocated &&
  168. "Cannot deallocate part of an allocated block!");
  169. // Round up size for alignment of header.
  170. unsigned HeaderAlign = __alignof(FreeRangeHeader);
  171. NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
  172. // Size is now the size of the block we will remove from the start of the
  173. // current block.
  174. assert(NewSize <= BlockSize &&
  175. "Allocating more space from this block than exists!");
  176. // If splitting this block will cause the remainder to be too small, do not
  177. // split the block.
  178. if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
  179. return FreeList;
  180. // Otherwise, we splice the required number of bytes out of this block, form
  181. // a new block immediately after it, then mark this block allocated.
  182. MemoryRangeHeader &FormerNextBlock = getBlockAfter();
  183. // Change the size of this block.
  184. BlockSize = NewSize;
  185. // Get the new block we just sliced out and turn it into a free block.
  186. FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
  187. NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
  188. NewNextBlock.ThisAllocated = 0;
  189. NewNextBlock.PrevAllocated = 1;
  190. NewNextBlock.SetEndOfBlockSizeMarker();
  191. FormerNextBlock.PrevAllocated = 0;
  192. NewNextBlock.AddToFreeList(FreeList);
  193. return &NewNextBlock;
  194. }
  195. //===----------------------------------------------------------------------===//
  196. // Memory Block Implementation.
  197. //===----------------------------------------------------------------------===//
  198. namespace {
  199. /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
  200. /// This splits a large block of MAP_NORESERVE'd memory into two
  201. /// sections, one for function stubs, one for the functions themselves. We
  202. /// have to do this because we may need to emit a function stub while in the
  203. /// middle of emitting a function, and we don't know how large the function we
  204. /// are emitting is.
  205. class VISIBILITY_HIDDEN DefaultJITMemoryManager : public JITMemoryManager {
  206. std::vector<sys::MemoryBlock> Blocks; // Memory blocks allocated by the JIT
  207. FreeRangeHeader *FreeMemoryList; // Circular list of free blocks.
  208. // When emitting code into a memory block, this is the block.
  209. MemoryRangeHeader *CurBlock;
  210. unsigned char *CurStubPtr, *StubBase;
  211. unsigned char *GOTBase; // Target Specific reserved memory
  212. // Centralize memory block allocation.
  213. sys::MemoryBlock getNewMemoryBlock(unsigned size);
  214. std::map<const Function*, MemoryRangeHeader*> FunctionBlocks;
  215. std::map<const Function*, MemoryRangeHeader*> TableBlocks;
  216. public:
  217. DefaultJITMemoryManager();
  218. ~DefaultJITMemoryManager();
  219. void AllocateGOT();
  220. unsigned char *allocateStub(unsigned StubSize, unsigned Alignment);
  221. /// startFunctionBody - When a function starts, allocate a block of free
  222. /// executable memory, returning a pointer to it and its actual size.
  223. unsigned char *startFunctionBody(const Function *F, uintptr_t &ActualSize) {
  224. CurBlock = FreeMemoryList;
  225. // Allocate the entire memory block.
  226. FreeMemoryList = FreeMemoryList->AllocateBlock();
  227. ActualSize = CurBlock->BlockSize-sizeof(MemoryRangeHeader);
  228. return (unsigned char *)(CurBlock+1);
  229. }
  230. /// endFunctionBody - The function F is now allocated, and takes the memory
  231. /// in the range [FunctionStart,FunctionEnd).
  232. void endFunctionBody(const Function *F, unsigned char *FunctionStart,
  233. unsigned char *FunctionEnd) {
  234. assert(FunctionEnd > FunctionStart);
  235. assert(FunctionStart == (unsigned char *)(CurBlock+1) &&
  236. "Mismatched function start/end!");
  237. uintptr_t BlockSize = FunctionEnd - (unsigned char *)CurBlock;
  238. FunctionBlocks[F] = CurBlock;
  239. // Release the memory at the end of this block that isn't needed.
  240. FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
  241. }
  242. /// startExceptionTable - Use startFunctionBody to allocate memory for the
  243. /// function's exception table.
  244. unsigned char* startExceptionTable(const Function* F, uintptr_t &ActualSize) {
  245. return startFunctionBody(F, ActualSize);
  246. }
  247. /// endExceptionTable - The exception table of F is now allocated,
  248. /// and takes the memory in the range [TableStart,TableEnd).
  249. void endExceptionTable(const Function *F, unsigned char *TableStart,
  250. unsigned char *TableEnd,
  251. unsigned char* FrameRegister) {
  252. assert(TableEnd > TableStart);
  253. assert(TableStart == (unsigned char *)(CurBlock+1) &&
  254. "Mismatched table start/end!");
  255. uintptr_t BlockSize = TableEnd - (unsigned char *)CurBlock;
  256. TableBlocks[F] = CurBlock;
  257. // Release the memory at the end of this block that isn't needed.
  258. FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
  259. }
  260. unsigned char *getGOTBase() const {
  261. return GOTBase;
  262. }
  263. /// deallocateMemForFunction - Deallocate all memory for the specified
  264. /// function body.
  265. void deallocateMemForFunction(const Function *F) {
  266. std::map<const Function*, MemoryRangeHeader*>::iterator
  267. I = FunctionBlocks.find(F);
  268. if (I == FunctionBlocks.end()) return;
  269. // Find the block that is allocated for this function.
  270. MemoryRangeHeader *MemRange = I->second;
  271. assert(MemRange->ThisAllocated && "Block isn't allocated!");
  272. // Fill the buffer with garbage!
  273. #ifndef NDEBUG
  274. memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
  275. #endif
  276. // Free the memory.
  277. FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
  278. // Finally, remove this entry from FunctionBlocks.
  279. FunctionBlocks.erase(I);
  280. I = TableBlocks.find(F);
  281. if (I == TableBlocks.end()) return;
  282. // Find the block that is allocated for this function.
  283. MemRange = I->second;
  284. assert(MemRange->ThisAllocated && "Block isn't allocated!");
  285. // Fill the buffer with garbage!
  286. #ifndef NDEBUG
  287. memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
  288. #endif
  289. // Free the memory.
  290. FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
  291. // Finally, remove this entry from TableBlocks.
  292. TableBlocks.erase(I);
  293. }
  294. };
  295. }
  296. DefaultJITMemoryManager::DefaultJITMemoryManager() {
  297. // Allocate a 16M block of memory for functions.
  298. sys::MemoryBlock MemBlock = getNewMemoryBlock(16 << 20);
  299. unsigned char *MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
  300. // Allocate stubs backwards from the base, allocate functions forward
  301. // from the base.
  302. StubBase = MemBase;
  303. CurStubPtr = MemBase + 512*1024; // Use 512k for stubs, working backwards.
  304. // We set up the memory chunk with 4 mem regions, like this:
  305. // [ START
  306. // [ Free #0 ] -> Large space to allocate functions from.
  307. // [ Allocated #1 ] -> Tiny space to separate regions.
  308. // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
  309. // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
  310. // END ]
  311. //
  312. // The last three blocks are never deallocated or touched.
  313. // Add MemoryRangeHeader to the end of the memory region, indicating that
  314. // the space after the block of memory is allocated. This is block #3.
  315. MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
  316. Mem3->ThisAllocated = 1;
  317. Mem3->PrevAllocated = 0;
  318. Mem3->BlockSize = 0;
  319. /// Add a tiny free region so that the free list always has one entry.
  320. FreeRangeHeader *Mem2 =
  321. (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
  322. Mem2->ThisAllocated = 0;
  323. Mem2->PrevAllocated = 1;
  324. Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
  325. Mem2->SetEndOfBlockSizeMarker();
  326. Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
  327. Mem2->Next = Mem2;
  328. /// Add a tiny allocated region so that Mem2 is never coalesced away.
  329. MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
  330. Mem1->ThisAllocated = 1;
  331. Mem1->PrevAllocated = 0;
  332. Mem1->BlockSize = (char*)Mem2 - (char*)Mem1;
  333. // Add a FreeRangeHeader to the start of the function body region, indicating
  334. // that the space is free. Mark the previous block allocated so we never look
  335. // at it.
  336. FreeRangeHeader *Mem0 = (FreeRangeHeader*)CurStubPtr;
  337. Mem0->ThisAllocated = 0;
  338. Mem0->PrevAllocated = 1;
  339. Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
  340. Mem0->SetEndOfBlockSizeMarker();
  341. Mem0->AddToFreeList(Mem2);
  342. // Start out with the freelist pointing to Mem0.
  343. FreeMemoryList = Mem0;
  344. GOTBase = NULL;
  345. }
  346. void DefaultJITMemoryManager::AllocateGOT() {
  347. assert(GOTBase == 0 && "Cannot allocate the got multiple times");
  348. GOTBase = new unsigned char[sizeof(void*) * 8192];
  349. HasGOT = true;
  350. }
  351. DefaultJITMemoryManager::~DefaultJITMemoryManager() {
  352. for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
  353. sys::Memory::ReleaseRWX(Blocks[i]);
  354. delete[] GOTBase;
  355. Blocks.clear();
  356. }
  357. unsigned char *DefaultJITMemoryManager::allocateStub(unsigned StubSize,
  358. unsigned Alignment) {
  359. CurStubPtr -= StubSize;
  360. CurStubPtr = (unsigned char*)(((intptr_t)CurStubPtr) &
  361. ~(intptr_t)(Alignment-1));
  362. if (CurStubPtr < StubBase) {
  363. // FIXME: allocate a new block
  364. fprintf(stderr, "JIT ran out of memory for function stubs!\n");
  365. abort();
  366. }
  367. return CurStubPtr;
  368. }
  369. sys::MemoryBlock DefaultJITMemoryManager::getNewMemoryBlock(unsigned size) {
  370. // Allocate a new block close to the last one.
  371. const sys::MemoryBlock *BOld = Blocks.empty() ? 0 : &Blocks.front();
  372. std::string ErrMsg;
  373. sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld, &ErrMsg);
  374. if (B.base() == 0) {
  375. fprintf(stderr,
  376. "Allocation failed when allocating new memory in the JIT\n%s\n",
  377. ErrMsg.c_str());
  378. abort();
  379. }
  380. Blocks.push_back(B);
  381. return B;
  382. }
  383. JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
  384. return new DefaultJITMemoryManager();
  385. }