JITMemoryManager.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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. #define DEBUG_TYPE "jit"
  14. #include "llvm/ExecutionEngine/JITMemoryManager.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/ADT/Statistic.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include "llvm/Config/config.h"
  19. #include "llvm/IR/GlobalValue.h"
  20. #include "llvm/Support/Allocator.h"
  21. #include "llvm/Support/Compiler.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/DynamicLibrary.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/Memory.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <cassert>
  28. #include <climits>
  29. #include <cstring>
  30. #include <vector>
  31. #if defined(__linux__)
  32. #if defined(HAVE_SYS_STAT_H)
  33. #include <sys/stat.h>
  34. #endif
  35. #include <fcntl.h>
  36. #include <unistd.h>
  37. #endif
  38. using namespace llvm;
  39. STATISTIC(NumSlabs, "Number of slabs of memory allocated by the JIT");
  40. JITMemoryManager::~JITMemoryManager() {}
  41. //===----------------------------------------------------------------------===//
  42. // Memory Block Implementation.
  43. //===----------------------------------------------------------------------===//
  44. namespace {
  45. /// MemoryRangeHeader - For a range of memory, this is the header that we put
  46. /// on the block of memory. It is carefully crafted to be one word of memory.
  47. /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
  48. /// which starts with this.
  49. struct FreeRangeHeader;
  50. struct MemoryRangeHeader {
  51. /// ThisAllocated - This is true if this block is currently allocated. If
  52. /// not, this can be converted to a FreeRangeHeader.
  53. unsigned ThisAllocated : 1;
  54. /// PrevAllocated - Keep track of whether the block immediately before us is
  55. /// allocated. If not, the word immediately before this header is the size
  56. /// of the previous block.
  57. unsigned PrevAllocated : 1;
  58. /// BlockSize - This is the size in bytes of this memory block,
  59. /// including this header.
  60. uintptr_t BlockSize : (sizeof(intptr_t)*CHAR_BIT - 2);
  61. /// getBlockAfter - Return the memory block immediately after this one.
  62. ///
  63. MemoryRangeHeader &getBlockAfter() const {
  64. return *reinterpret_cast<MemoryRangeHeader *>(
  65. reinterpret_cast<char*>(
  66. const_cast<MemoryRangeHeader *>(this))+BlockSize);
  67. }
  68. /// getFreeBlockBefore - If the block before this one is free, return it,
  69. /// otherwise return null.
  70. FreeRangeHeader *getFreeBlockBefore() const {
  71. if (PrevAllocated) return 0;
  72. intptr_t PrevSize = reinterpret_cast<intptr_t *>(
  73. const_cast<MemoryRangeHeader *>(this))[-1];
  74. return reinterpret_cast<FreeRangeHeader *>(
  75. reinterpret_cast<char*>(
  76. const_cast<MemoryRangeHeader *>(this))-PrevSize);
  77. }
  78. /// FreeBlock - Turn an allocated block into a free block, adjusting
  79. /// bits in the object headers, and adding an end of region memory block.
  80. FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
  81. /// TrimAllocationToSize - If this allocated block is significantly larger
  82. /// than NewSize, split it into two pieces (where the former is NewSize
  83. /// bytes, including the header), and add the new block to the free list.
  84. FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
  85. uint64_t NewSize);
  86. };
  87. /// FreeRangeHeader - For a memory block that isn't already allocated, this
  88. /// keeps track of the current block and has a pointer to the next free block.
  89. /// Free blocks are kept on a circularly linked list.
  90. struct FreeRangeHeader : public MemoryRangeHeader {
  91. FreeRangeHeader *Prev;
  92. FreeRangeHeader *Next;
  93. /// getMinBlockSize - Get the minimum size for a memory block. Blocks
  94. /// smaller than this size cannot be created.
  95. static unsigned getMinBlockSize() {
  96. return sizeof(FreeRangeHeader)+sizeof(intptr_t);
  97. }
  98. /// SetEndOfBlockSizeMarker - The word at the end of every free block is
  99. /// known to be the size of the free block. Set it for this block.
  100. void SetEndOfBlockSizeMarker() {
  101. void *EndOfBlock = (char*)this + BlockSize;
  102. ((intptr_t *)EndOfBlock)[-1] = BlockSize;
  103. }
  104. FreeRangeHeader *RemoveFromFreeList() {
  105. assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
  106. Next->Prev = Prev;
  107. return Prev->Next = Next;
  108. }
  109. void AddToFreeList(FreeRangeHeader *FreeList) {
  110. Next = FreeList;
  111. Prev = FreeList->Prev;
  112. Prev->Next = this;
  113. Next->Prev = this;
  114. }
  115. /// GrowBlock - The block after this block just got deallocated. Merge it
  116. /// into the current block.
  117. void GrowBlock(uintptr_t NewSize);
  118. /// AllocateBlock - Mark this entire block allocated, updating freelists
  119. /// etc. This returns a pointer to the circular free-list.
  120. FreeRangeHeader *AllocateBlock();
  121. };
  122. }
  123. /// AllocateBlock - Mark this entire block allocated, updating freelists
  124. /// etc. This returns a pointer to the circular free-list.
  125. FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
  126. assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
  127. "Cannot allocate an allocated block!");
  128. // Mark this block allocated.
  129. ThisAllocated = 1;
  130. getBlockAfter().PrevAllocated = 1;
  131. // Remove it from the free list.
  132. return RemoveFromFreeList();
  133. }
  134. /// FreeBlock - Turn an allocated block into a free block, adjusting
  135. /// bits in the object headers, and adding an end of region memory block.
  136. /// If possible, coalesce this block with neighboring blocks. Return the
  137. /// FreeRangeHeader to allocate from.
  138. FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
  139. MemoryRangeHeader *FollowingBlock = &getBlockAfter();
  140. assert(ThisAllocated && "This block is already free!");
  141. assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
  142. FreeRangeHeader *FreeListToReturn = FreeList;
  143. // If the block after this one is free, merge it into this block.
  144. if (!FollowingBlock->ThisAllocated) {
  145. FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
  146. // "FreeList" always needs to be a valid free block. If we're about to
  147. // coalesce with it, update our notion of what the free list is.
  148. if (&FollowingFreeBlock == FreeList) {
  149. FreeList = FollowingFreeBlock.Next;
  150. FreeListToReturn = 0;
  151. assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
  152. }
  153. FollowingFreeBlock.RemoveFromFreeList();
  154. // Include the following block into this one.
  155. BlockSize += FollowingFreeBlock.BlockSize;
  156. FollowingBlock = &FollowingFreeBlock.getBlockAfter();
  157. // Tell the block after the block we are coalescing that this block is
  158. // allocated.
  159. FollowingBlock->PrevAllocated = 1;
  160. }
  161. assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
  162. if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
  163. PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
  164. return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
  165. }
  166. // Otherwise, mark this block free.
  167. FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
  168. FollowingBlock->PrevAllocated = 0;
  169. FreeBlock.ThisAllocated = 0;
  170. // Link this into the linked list of free blocks.
  171. FreeBlock.AddToFreeList(FreeList);
  172. // Add a marker at the end of the block, indicating the size of this free
  173. // block.
  174. FreeBlock.SetEndOfBlockSizeMarker();
  175. return FreeListToReturn ? FreeListToReturn : &FreeBlock;
  176. }
  177. /// GrowBlock - The block after this block just got deallocated. Merge it
  178. /// into the current block.
  179. void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
  180. assert(NewSize > BlockSize && "Not growing block?");
  181. BlockSize = NewSize;
  182. SetEndOfBlockSizeMarker();
  183. getBlockAfter().PrevAllocated = 0;
  184. }
  185. /// TrimAllocationToSize - If this allocated block is significantly larger
  186. /// than NewSize, split it into two pieces (where the former is NewSize
  187. /// bytes, including the header), and add the new block to the free list.
  188. FreeRangeHeader *MemoryRangeHeader::
  189. TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
  190. assert(ThisAllocated && getBlockAfter().PrevAllocated &&
  191. "Cannot deallocate part of an allocated block!");
  192. // Don't allow blocks to be trimmed below minimum required size
  193. NewSize = std::max<uint64_t>(FreeRangeHeader::getMinBlockSize(), NewSize);
  194. // Round up size for alignment of header.
  195. unsigned HeaderAlign = __alignof(FreeRangeHeader);
  196. NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
  197. // Size is now the size of the block we will remove from the start of the
  198. // current block.
  199. assert(NewSize <= BlockSize &&
  200. "Allocating more space from this block than exists!");
  201. // If splitting this block will cause the remainder to be too small, do not
  202. // split the block.
  203. if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
  204. return FreeList;
  205. // Otherwise, we splice the required number of bytes out of this block, form
  206. // a new block immediately after it, then mark this block allocated.
  207. MemoryRangeHeader &FormerNextBlock = getBlockAfter();
  208. // Change the size of this block.
  209. BlockSize = NewSize;
  210. // Get the new block we just sliced out and turn it into a free block.
  211. FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
  212. NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
  213. NewNextBlock.ThisAllocated = 0;
  214. NewNextBlock.PrevAllocated = 1;
  215. NewNextBlock.SetEndOfBlockSizeMarker();
  216. FormerNextBlock.PrevAllocated = 0;
  217. NewNextBlock.AddToFreeList(FreeList);
  218. return &NewNextBlock;
  219. }
  220. //===----------------------------------------------------------------------===//
  221. // Memory Block Implementation.
  222. //===----------------------------------------------------------------------===//
  223. namespace {
  224. class DefaultJITMemoryManager;
  225. class JITSlabAllocator : public SlabAllocator {
  226. DefaultJITMemoryManager &JMM;
  227. public:
  228. JITSlabAllocator(DefaultJITMemoryManager &jmm) : JMM(jmm) { }
  229. virtual ~JITSlabAllocator() { }
  230. MemSlab *Allocate(size_t Size) override;
  231. void Deallocate(MemSlab *Slab) override;
  232. };
  233. /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
  234. /// This splits a large block of MAP_NORESERVE'd memory into two
  235. /// sections, one for function stubs, one for the functions themselves. We
  236. /// have to do this because we may need to emit a function stub while in the
  237. /// middle of emitting a function, and we don't know how large the function we
  238. /// are emitting is.
  239. class DefaultJITMemoryManager : public JITMemoryManager {
  240. // Whether to poison freed memory.
  241. bool PoisonMemory;
  242. /// LastSlab - This points to the last slab allocated and is used as the
  243. /// NearBlock parameter to AllocateRWX so that we can attempt to lay out all
  244. /// stubs, data, and code contiguously in memory. In general, however, this
  245. /// is not possible because the NearBlock parameter is ignored on Windows
  246. /// platforms and even on Unix it works on a best-effort pasis.
  247. sys::MemoryBlock LastSlab;
  248. // Memory slabs allocated by the JIT. We refer to them as slabs so we don't
  249. // confuse them with the blocks of memory described above.
  250. std::vector<sys::MemoryBlock> CodeSlabs;
  251. JITSlabAllocator BumpSlabAllocator;
  252. BumpPtrAllocator StubAllocator;
  253. BumpPtrAllocator DataAllocator;
  254. // Circular list of free blocks.
  255. FreeRangeHeader *FreeMemoryList;
  256. // When emitting code into a memory block, this is the block.
  257. MemoryRangeHeader *CurBlock;
  258. uint8_t *GOTBase; // Target Specific reserved memory
  259. public:
  260. DefaultJITMemoryManager();
  261. ~DefaultJITMemoryManager();
  262. /// allocateNewSlab - Allocates a new MemoryBlock and remembers it as the
  263. /// last slab it allocated, so that subsequent allocations follow it.
  264. sys::MemoryBlock allocateNewSlab(size_t size);
  265. /// DefaultCodeSlabSize - When we have to go map more memory, we allocate at
  266. /// least this much unless more is requested.
  267. static const size_t DefaultCodeSlabSize;
  268. /// DefaultSlabSize - Allocate data into slabs of this size unless we get
  269. /// an allocation above SizeThreshold.
  270. static const size_t DefaultSlabSize;
  271. /// DefaultSizeThreshold - For any allocation larger than this threshold, we
  272. /// should allocate a separate slab.
  273. static const size_t DefaultSizeThreshold;
  274. /// getPointerToNamedFunction - This method returns the address of the
  275. /// specified function by using the dlsym function call.
  276. void *getPointerToNamedFunction(const std::string &Name,
  277. bool AbortOnFailure = true) override;
  278. void AllocateGOT() override;
  279. // Testing methods.
  280. bool CheckInvariants(std::string &ErrorStr) override;
  281. size_t GetDefaultCodeSlabSize() override { return DefaultCodeSlabSize; }
  282. size_t GetDefaultDataSlabSize() override { return DefaultSlabSize; }
  283. size_t GetDefaultStubSlabSize() override { return DefaultSlabSize; }
  284. unsigned GetNumCodeSlabs() override { return CodeSlabs.size(); }
  285. unsigned GetNumDataSlabs() override { return DataAllocator.GetNumSlabs(); }
  286. unsigned GetNumStubSlabs() override { return StubAllocator.GetNumSlabs(); }
  287. /// startFunctionBody - When a function starts, allocate a block of free
  288. /// executable memory, returning a pointer to it and its actual size.
  289. uint8_t *startFunctionBody(const Function *F,
  290. uintptr_t &ActualSize) override {
  291. FreeRangeHeader* candidateBlock = FreeMemoryList;
  292. FreeRangeHeader* head = FreeMemoryList;
  293. FreeRangeHeader* iter = head->Next;
  294. uintptr_t largest = candidateBlock->BlockSize;
  295. // Search for the largest free block
  296. while (iter != head) {
  297. if (iter->BlockSize > largest) {
  298. largest = iter->BlockSize;
  299. candidateBlock = iter;
  300. }
  301. iter = iter->Next;
  302. }
  303. largest = largest - sizeof(MemoryRangeHeader);
  304. // If this block isn't big enough for the allocation desired, allocate
  305. // another block of memory and add it to the free list.
  306. if (largest < ActualSize ||
  307. largest <= FreeRangeHeader::getMinBlockSize()) {
  308. DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
  309. candidateBlock = allocateNewCodeSlab((size_t)ActualSize);
  310. }
  311. // Select this candidate block for allocation
  312. CurBlock = candidateBlock;
  313. // Allocate the entire memory block.
  314. FreeMemoryList = candidateBlock->AllocateBlock();
  315. ActualSize = CurBlock->BlockSize - sizeof(MemoryRangeHeader);
  316. return (uint8_t *)(CurBlock + 1);
  317. }
  318. /// allocateNewCodeSlab - Helper method to allocate a new slab of code
  319. /// memory from the OS and add it to the free list. Returns the new
  320. /// FreeRangeHeader at the base of the slab.
  321. FreeRangeHeader *allocateNewCodeSlab(size_t MinSize) {
  322. // If the user needs at least MinSize free memory, then we account for
  323. // two MemoryRangeHeaders: the one in the user's block, and the one at the
  324. // end of the slab.
  325. size_t PaddedMin = MinSize + 2 * sizeof(MemoryRangeHeader);
  326. size_t SlabSize = std::max(DefaultCodeSlabSize, PaddedMin);
  327. sys::MemoryBlock B = allocateNewSlab(SlabSize);
  328. CodeSlabs.push_back(B);
  329. char *MemBase = (char*)(B.base());
  330. // Put a tiny allocated block at the end of the memory chunk, so when
  331. // FreeBlock calls getBlockAfter it doesn't fall off the end.
  332. MemoryRangeHeader *EndBlock =
  333. (MemoryRangeHeader*)(MemBase + B.size()) - 1;
  334. EndBlock->ThisAllocated = 1;
  335. EndBlock->PrevAllocated = 0;
  336. EndBlock->BlockSize = sizeof(MemoryRangeHeader);
  337. // Start out with a vast new block of free memory.
  338. FreeRangeHeader *NewBlock = (FreeRangeHeader*)MemBase;
  339. NewBlock->ThisAllocated = 0;
  340. // Make sure getFreeBlockBefore doesn't look into unmapped memory.
  341. NewBlock->PrevAllocated = 1;
  342. NewBlock->BlockSize = (uintptr_t)EndBlock - (uintptr_t)NewBlock;
  343. NewBlock->SetEndOfBlockSizeMarker();
  344. NewBlock->AddToFreeList(FreeMemoryList);
  345. assert(NewBlock->BlockSize - sizeof(MemoryRangeHeader) >= MinSize &&
  346. "The block was too small!");
  347. return NewBlock;
  348. }
  349. /// endFunctionBody - The function F is now allocated, and takes the memory
  350. /// in the range [FunctionStart,FunctionEnd).
  351. void endFunctionBody(const Function *F, uint8_t *FunctionStart,
  352. uint8_t *FunctionEnd) override {
  353. assert(FunctionEnd > FunctionStart);
  354. assert(FunctionStart == (uint8_t *)(CurBlock+1) &&
  355. "Mismatched function start/end!");
  356. uintptr_t BlockSize = FunctionEnd - (uint8_t *)CurBlock;
  357. // Release the memory at the end of this block that isn't needed.
  358. FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
  359. }
  360. /// allocateSpace - Allocate a memory block of the given size. This method
  361. /// cannot be called between calls to startFunctionBody and endFunctionBody.
  362. uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) override {
  363. CurBlock = FreeMemoryList;
  364. FreeMemoryList = FreeMemoryList->AllocateBlock();
  365. uint8_t *result = (uint8_t *)(CurBlock + 1);
  366. if (Alignment == 0) Alignment = 1;
  367. result = (uint8_t*)(((intptr_t)result+Alignment-1) &
  368. ~(intptr_t)(Alignment-1));
  369. uintptr_t BlockSize = result + Size - (uint8_t *)CurBlock;
  370. FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
  371. return result;
  372. }
  373. /// allocateStub - Allocate memory for a function stub.
  374. uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
  375. unsigned Alignment) override {
  376. return (uint8_t*)StubAllocator.Allocate(StubSize, Alignment);
  377. }
  378. /// allocateGlobal - Allocate memory for a global.
  379. uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) override {
  380. return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
  381. }
  382. /// allocateCodeSection - Allocate memory for a code section.
  383. uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
  384. unsigned SectionID,
  385. StringRef SectionName) override {
  386. // Grow the required block size to account for the block header
  387. Size += sizeof(*CurBlock);
  388. // Alignment handling.
  389. if (!Alignment)
  390. Alignment = 16;
  391. Size += Alignment - 1;
  392. FreeRangeHeader* candidateBlock = FreeMemoryList;
  393. FreeRangeHeader* head = FreeMemoryList;
  394. FreeRangeHeader* iter = head->Next;
  395. uintptr_t largest = candidateBlock->BlockSize;
  396. // Search for the largest free block.
  397. while (iter != head) {
  398. if (iter->BlockSize > largest) {
  399. largest = iter->BlockSize;
  400. candidateBlock = iter;
  401. }
  402. iter = iter->Next;
  403. }
  404. largest = largest - sizeof(MemoryRangeHeader);
  405. // If this block isn't big enough for the allocation desired, allocate
  406. // another block of memory and add it to the free list.
  407. if (largest < Size || largest <= FreeRangeHeader::getMinBlockSize()) {
  408. DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
  409. candidateBlock = allocateNewCodeSlab((size_t)Size);
  410. }
  411. // Select this candidate block for allocation
  412. CurBlock = candidateBlock;
  413. // Allocate the entire memory block.
  414. FreeMemoryList = candidateBlock->AllocateBlock();
  415. // Release the memory at the end of this block that isn't needed.
  416. FreeMemoryList = CurBlock->TrimAllocationToSize(FreeMemoryList, Size);
  417. uintptr_t unalignedAddr = (uintptr_t)CurBlock + sizeof(*CurBlock);
  418. return (uint8_t*)RoundUpToAlignment((uint64_t)unalignedAddr, Alignment);
  419. }
  420. /// allocateDataSection - Allocate memory for a data section.
  421. uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
  422. unsigned SectionID, StringRef SectionName,
  423. bool IsReadOnly) override {
  424. return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
  425. }
  426. bool finalizeMemory(std::string *ErrMsg) override {
  427. return false;
  428. }
  429. uint8_t *getGOTBase() const override {
  430. return GOTBase;
  431. }
  432. void deallocateBlock(void *Block) {
  433. // Find the block that is allocated for this function.
  434. MemoryRangeHeader *MemRange = static_cast<MemoryRangeHeader*>(Block) - 1;
  435. assert(MemRange->ThisAllocated && "Block isn't allocated!");
  436. // Fill the buffer with garbage!
  437. if (PoisonMemory) {
  438. memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
  439. }
  440. // Free the memory.
  441. FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
  442. }
  443. /// deallocateFunctionBody - Deallocate all memory for the specified
  444. /// function body.
  445. void deallocateFunctionBody(void *Body) override {
  446. if (Body) deallocateBlock(Body);
  447. }
  448. /// setMemoryWritable - When code generation is in progress,
  449. /// the code pages may need permissions changed.
  450. void setMemoryWritable() override {
  451. for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
  452. sys::Memory::setWritable(CodeSlabs[i]);
  453. }
  454. /// setMemoryExecutable - When code generation is done and we're ready to
  455. /// start execution, the code pages may need permissions changed.
  456. void setMemoryExecutable() override {
  457. for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
  458. sys::Memory::setExecutable(CodeSlabs[i]);
  459. }
  460. /// setPoisonMemory - Controls whether we write garbage over freed memory.
  461. ///
  462. void setPoisonMemory(bool poison) override {
  463. PoisonMemory = poison;
  464. }
  465. };
  466. }
  467. MemSlab *JITSlabAllocator::Allocate(size_t Size) {
  468. sys::MemoryBlock B = JMM.allocateNewSlab(Size);
  469. MemSlab *Slab = (MemSlab*)B.base();
  470. Slab->Size = B.size();
  471. Slab->NextPtr = 0;
  472. return Slab;
  473. }
  474. void JITSlabAllocator::Deallocate(MemSlab *Slab) {
  475. sys::MemoryBlock B(Slab, Slab->Size);
  476. sys::Memory::ReleaseRWX(B);
  477. }
  478. DefaultJITMemoryManager::DefaultJITMemoryManager()
  479. :
  480. #ifdef NDEBUG
  481. PoisonMemory(false),
  482. #else
  483. PoisonMemory(true),
  484. #endif
  485. LastSlab(0, 0),
  486. BumpSlabAllocator(*this),
  487. StubAllocator(DefaultSlabSize, DefaultSizeThreshold, BumpSlabAllocator),
  488. DataAllocator(DefaultSlabSize, DefaultSizeThreshold, BumpSlabAllocator) {
  489. // Allocate space for code.
  490. sys::MemoryBlock MemBlock = allocateNewSlab(DefaultCodeSlabSize);
  491. CodeSlabs.push_back(MemBlock);
  492. uint8_t *MemBase = (uint8_t*)MemBlock.base();
  493. // We set up the memory chunk with 4 mem regions, like this:
  494. // [ START
  495. // [ Free #0 ] -> Large space to allocate functions from.
  496. // [ Allocated #1 ] -> Tiny space to separate regions.
  497. // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
  498. // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
  499. // END ]
  500. //
  501. // The last three blocks are never deallocated or touched.
  502. // Add MemoryRangeHeader to the end of the memory region, indicating that
  503. // the space after the block of memory is allocated. This is block #3.
  504. MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
  505. Mem3->ThisAllocated = 1;
  506. Mem3->PrevAllocated = 0;
  507. Mem3->BlockSize = sizeof(MemoryRangeHeader);
  508. /// Add a tiny free region so that the free list always has one entry.
  509. FreeRangeHeader *Mem2 =
  510. (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
  511. Mem2->ThisAllocated = 0;
  512. Mem2->PrevAllocated = 1;
  513. Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
  514. Mem2->SetEndOfBlockSizeMarker();
  515. Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
  516. Mem2->Next = Mem2;
  517. /// Add a tiny allocated region so that Mem2 is never coalesced away.
  518. MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
  519. Mem1->ThisAllocated = 1;
  520. Mem1->PrevAllocated = 0;
  521. Mem1->BlockSize = sizeof(MemoryRangeHeader);
  522. // Add a FreeRangeHeader to the start of the function body region, indicating
  523. // that the space is free. Mark the previous block allocated so we never look
  524. // at it.
  525. FreeRangeHeader *Mem0 = (FreeRangeHeader*)MemBase;
  526. Mem0->ThisAllocated = 0;
  527. Mem0->PrevAllocated = 1;
  528. Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
  529. Mem0->SetEndOfBlockSizeMarker();
  530. Mem0->AddToFreeList(Mem2);
  531. // Start out with the freelist pointing to Mem0.
  532. FreeMemoryList = Mem0;
  533. GOTBase = NULL;
  534. }
  535. void DefaultJITMemoryManager::AllocateGOT() {
  536. assert(GOTBase == 0 && "Cannot allocate the got multiple times");
  537. GOTBase = new uint8_t[sizeof(void*) * 8192];
  538. HasGOT = true;
  539. }
  540. DefaultJITMemoryManager::~DefaultJITMemoryManager() {
  541. for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
  542. sys::Memory::ReleaseRWX(CodeSlabs[i]);
  543. delete[] GOTBase;
  544. }
  545. sys::MemoryBlock DefaultJITMemoryManager::allocateNewSlab(size_t size) {
  546. // Allocate a new block close to the last one.
  547. std::string ErrMsg;
  548. sys::MemoryBlock *LastSlabPtr = LastSlab.base() ? &LastSlab : 0;
  549. sys::MemoryBlock B = sys::Memory::AllocateRWX(size, LastSlabPtr, &ErrMsg);
  550. if (B.base() == 0) {
  551. report_fatal_error("Allocation failed when allocating new memory in the"
  552. " JIT\n" + Twine(ErrMsg));
  553. }
  554. LastSlab = B;
  555. ++NumSlabs;
  556. // Initialize the slab to garbage when debugging.
  557. if (PoisonMemory) {
  558. memset(B.base(), 0xCD, B.size());
  559. }
  560. return B;
  561. }
  562. /// CheckInvariants - For testing only. Return "" if all internal invariants
  563. /// are preserved, and a helpful error message otherwise. For free and
  564. /// allocated blocks, make sure that adding BlockSize gives a valid block.
  565. /// For free blocks, make sure they're in the free list and that their end of
  566. /// block size marker is correct. This function should return an error before
  567. /// accessing bad memory. This function is defined here instead of in
  568. /// JITMemoryManagerTest.cpp so that we don't have to expose all of the
  569. /// implementation details of DefaultJITMemoryManager.
  570. bool DefaultJITMemoryManager::CheckInvariants(std::string &ErrorStr) {
  571. raw_string_ostream Err(ErrorStr);
  572. // Construct a the set of FreeRangeHeader pointers so we can query it
  573. // efficiently.
  574. llvm::SmallPtrSet<MemoryRangeHeader*, 16> FreeHdrSet;
  575. FreeRangeHeader* FreeHead = FreeMemoryList;
  576. FreeRangeHeader* FreeRange = FreeHead;
  577. do {
  578. // Check that the free range pointer is in the blocks we've allocated.
  579. bool Found = false;
  580. for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
  581. E = CodeSlabs.end(); I != E && !Found; ++I) {
  582. char *Start = (char*)I->base();
  583. char *End = Start + I->size();
  584. Found = (Start <= (char*)FreeRange && (char*)FreeRange < End);
  585. }
  586. if (!Found) {
  587. Err << "Corrupt free list; points to " << FreeRange;
  588. return false;
  589. }
  590. if (FreeRange->Next->Prev != FreeRange) {
  591. Err << "Next and Prev pointers do not match.";
  592. return false;
  593. }
  594. // Otherwise, add it to the set.
  595. FreeHdrSet.insert(FreeRange);
  596. FreeRange = FreeRange->Next;
  597. } while (FreeRange != FreeHead);
  598. // Go over each block, and look at each MemoryRangeHeader.
  599. for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
  600. E = CodeSlabs.end(); I != E; ++I) {
  601. char *Start = (char*)I->base();
  602. char *End = Start + I->size();
  603. // Check each memory range.
  604. for (MemoryRangeHeader *Hdr = (MemoryRangeHeader*)Start, *LastHdr = NULL;
  605. Start <= (char*)Hdr && (char*)Hdr < End;
  606. Hdr = &Hdr->getBlockAfter()) {
  607. if (Hdr->ThisAllocated == 0) {
  608. // Check that this range is in the free list.
  609. if (!FreeHdrSet.count(Hdr)) {
  610. Err << "Found free header at " << Hdr << " that is not in free list.";
  611. return false;
  612. }
  613. // Now make sure the size marker at the end of the block is correct.
  614. uintptr_t *Marker = ((uintptr_t*)&Hdr->getBlockAfter()) - 1;
  615. if (!(Start <= (char*)Marker && (char*)Marker < End)) {
  616. Err << "Block size in header points out of current MemoryBlock.";
  617. return false;
  618. }
  619. if (Hdr->BlockSize != *Marker) {
  620. Err << "End of block size marker (" << *Marker << ") "
  621. << "and BlockSize (" << Hdr->BlockSize << ") don't match.";
  622. return false;
  623. }
  624. }
  625. if (LastHdr && LastHdr->ThisAllocated != Hdr->PrevAllocated) {
  626. Err << "Hdr->PrevAllocated (" << Hdr->PrevAllocated << ") != "
  627. << "LastHdr->ThisAllocated (" << LastHdr->ThisAllocated << ")";
  628. return false;
  629. } else if (!LastHdr && !Hdr->PrevAllocated) {
  630. Err << "The first header should have PrevAllocated true.";
  631. return false;
  632. }
  633. // Remember the last header.
  634. LastHdr = Hdr;
  635. }
  636. }
  637. // All invariants are preserved.
  638. return true;
  639. }
  640. //===----------------------------------------------------------------------===//
  641. // getPointerToNamedFunction() implementation.
  642. //===----------------------------------------------------------------------===//
  643. // AtExitHandlers - List of functions to call when the program exits,
  644. // registered with the atexit() library function.
  645. static std::vector<void (*)()> AtExitHandlers;
  646. /// runAtExitHandlers - Run any functions registered by the program's
  647. /// calls to atexit(3), which we intercept and store in
  648. /// AtExitHandlers.
  649. ///
  650. static void runAtExitHandlers() {
  651. while (!AtExitHandlers.empty()) {
  652. void (*Fn)() = AtExitHandlers.back();
  653. AtExitHandlers.pop_back();
  654. Fn();
  655. }
  656. }
  657. //===----------------------------------------------------------------------===//
  658. // Function stubs that are invoked instead of certain library calls
  659. //
  660. // Force the following functions to be linked in to anything that uses the
  661. // JIT. This is a hack designed to work around the all-too-clever Glibc
  662. // strategy of making these functions work differently when inlined vs. when
  663. // not inlined, and hiding their real definitions in a separate archive file
  664. // that the dynamic linker can't see. For more info, search for
  665. // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
  666. #if defined(__linux__) && defined(__GLIBC__)
  667. /* stat functions are redirecting to __xstat with a version number. On x86-64
  668. * linking with libc_nonshared.a and -Wl,--export-dynamic doesn't make 'stat'
  669. * available as an exported symbol, so we have to add it explicitly.
  670. */
  671. namespace {
  672. class StatSymbols {
  673. public:
  674. StatSymbols() {
  675. sys::DynamicLibrary::AddSymbol("stat", (void*)(intptr_t)stat);
  676. sys::DynamicLibrary::AddSymbol("fstat", (void*)(intptr_t)fstat);
  677. sys::DynamicLibrary::AddSymbol("lstat", (void*)(intptr_t)lstat);
  678. sys::DynamicLibrary::AddSymbol("stat64", (void*)(intptr_t)stat64);
  679. sys::DynamicLibrary::AddSymbol("\x1stat64", (void*)(intptr_t)stat64);
  680. sys::DynamicLibrary::AddSymbol("\x1open64", (void*)(intptr_t)open64);
  681. sys::DynamicLibrary::AddSymbol("\x1lseek64", (void*)(intptr_t)lseek64);
  682. sys::DynamicLibrary::AddSymbol("fstat64", (void*)(intptr_t)fstat64);
  683. sys::DynamicLibrary::AddSymbol("lstat64", (void*)(intptr_t)lstat64);
  684. sys::DynamicLibrary::AddSymbol("atexit", (void*)(intptr_t)atexit);
  685. sys::DynamicLibrary::AddSymbol("mknod", (void*)(intptr_t)mknod);
  686. }
  687. };
  688. }
  689. static StatSymbols initStatSymbols;
  690. #endif // __linux__
  691. // jit_exit - Used to intercept the "exit" library call.
  692. static void jit_exit(int Status) {
  693. runAtExitHandlers(); // Run atexit handlers...
  694. exit(Status);
  695. }
  696. // jit_atexit - Used to intercept the "atexit" library call.
  697. static int jit_atexit(void (*Fn)()) {
  698. AtExitHandlers.push_back(Fn); // Take note of atexit handler...
  699. return 0; // Always successful
  700. }
  701. static int jit_noop() {
  702. return 0;
  703. }
  704. //===----------------------------------------------------------------------===//
  705. //
  706. /// getPointerToNamedFunction - This method returns the address of the specified
  707. /// function by using the dynamic loader interface. As such it is only useful
  708. /// for resolving library symbols, not code generated symbols.
  709. ///
  710. void *DefaultJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
  711. bool AbortOnFailure) {
  712. // Check to see if this is one of the functions we want to intercept. Note,
  713. // we cast to intptr_t here to silence a -pedantic warning that complains
  714. // about casting a function pointer to a normal pointer.
  715. if (Name == "exit") return (void*)(intptr_t)&jit_exit;
  716. if (Name == "atexit") return (void*)(intptr_t)&jit_atexit;
  717. // We should not invoke parent's ctors/dtors from generated main()!
  718. // On Mingw and Cygwin, the symbol __main is resolved to
  719. // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
  720. // (and register wrong callee's dtors with atexit(3)).
  721. // We expect ExecutionEngine::runStaticConstructorsDestructors()
  722. // is called before ExecutionEngine::runFunctionAsMain() is called.
  723. if (Name == "__main") return (void*)(intptr_t)&jit_noop;
  724. const char *NameStr = Name.c_str();
  725. // If this is an asm specifier, skip the sentinal.
  726. if (NameStr[0] == 1) ++NameStr;
  727. // If it's an external function, look it up in the process image...
  728. void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
  729. if (Ptr) return Ptr;
  730. // If it wasn't found and if it starts with an underscore ('_') character,
  731. // try again without the underscore.
  732. if (NameStr[0] == '_') {
  733. Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
  734. if (Ptr) return Ptr;
  735. }
  736. // Darwin/PPC adds $LDBLStub suffixes to various symbols like printf. These
  737. // are references to hidden visibility symbols that dlsym cannot resolve.
  738. // If we have one of these, strip off $LDBLStub and try again.
  739. #if defined(__APPLE__) && defined(__ppc__)
  740. if (Name.size() > 9 && Name[Name.size()-9] == '$' &&
  741. memcmp(&Name[Name.size()-8], "LDBLStub", 8) == 0) {
  742. // First try turning $LDBLStub into $LDBL128. If that fails, strip it off.
  743. // This mirrors logic in libSystemStubs.a.
  744. std::string Prefix = std::string(Name.begin(), Name.end()-9);
  745. if (void *Ptr = getPointerToNamedFunction(Prefix+"$LDBL128", false))
  746. return Ptr;
  747. if (void *Ptr = getPointerToNamedFunction(Prefix, false))
  748. return Ptr;
  749. }
  750. #endif
  751. if (AbortOnFailure) {
  752. report_fatal_error("Program used external function '"+Name+
  753. "' which could not be resolved!");
  754. }
  755. return 0;
  756. }
  757. JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
  758. return new DefaultJITMemoryManager();
  759. }
  760. // Allocate memory for code in 512K slabs.
  761. const size_t DefaultJITMemoryManager::DefaultCodeSlabSize = 512 * 1024;
  762. // Allocate globals and stubs in slabs of 64K. (probably 16 pages)
  763. const size_t DefaultJITMemoryManager::DefaultSlabSize = 64 * 1024;
  764. // Waste at most 16K at the end of each bump slab. (probably 4 pages)
  765. const size_t DefaultJITMemoryManager::DefaultSizeThreshold = 16 * 1024;