1 //===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a MachineCodeEmitter object that is used by the JIT to
11 // write machine code to memory and remember where relocatable values are.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "jit"
17 #include "llvm/Constant.h"
18 #include "llvm/Module.h"
19 #include "llvm/Type.h"
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineRelocation.h"
25 #include "llvm/ExecutionEngine/GenericValue.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetJITInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MutexGuard.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/System/Memory.h"
37 Statistic NumBytes("jit", "Number of bytes of machine code compiled");
38 Statistic NumRelos("jit", "Number of relocations applied");
43 //===----------------------------------------------------------------------===//
44 // JITMemoryManager code.
47 /// MemoryRangeHeader - For a range of memory, this is the header that we put
48 /// on the block of memory. It is carefully crafted to be one word of memory.
49 /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
50 /// which starts with this.
51 struct FreeRangeHeader;
52 struct MemoryRangeHeader {
53 /// ThisAllocated - This is true if this block is currently allocated. If
54 /// not, this can be converted to a FreeRangeHeader.
55 intptr_t ThisAllocated : 1;
57 /// PrevAllocated - Keep track of whether the block immediately before us is
58 /// allocated. If not, the word immediately before this header is the size
59 /// of the previous block.
60 intptr_t PrevAllocated : 1;
62 /// BlockSize - This is the size in bytes of this memory block,
63 /// including this header.
64 uintptr_t BlockSize : (sizeof(intptr_t)*8 - 2);
67 /// getBlockAfter - Return the memory block immediately after this one.
69 MemoryRangeHeader &getBlockAfter() const {
70 return *(MemoryRangeHeader*)((char*)this+BlockSize);
73 /// getFreeBlockBefore - If the block before this one is free, return it,
74 /// otherwise return null.
75 FreeRangeHeader *getFreeBlockBefore() const {
76 if (PrevAllocated) return 0;
77 intptr_t PrevSize = ((intptr_t *)this)[-1];
78 return (FreeRangeHeader*)((char*)this-PrevSize);
81 /// FreeBlock - Turn an allocated block into a free block, adjusting
82 /// bits in the object headers, and adding an end of region memory block.
83 FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
85 /// TrimAllocationToSize - If this allocated block is significantly larger
86 /// than NewSize, split it into two pieces (where the former is NewSize
87 /// bytes, including the header), and add the new block to the free list.
88 FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
92 /// FreeRangeHeader - For a memory block that isn't already allocated, this
93 /// keeps track of the current block and has a pointer to the next free block.
94 /// Free blocks are kept on a circularly linked list.
95 struct FreeRangeHeader : public MemoryRangeHeader {
96 FreeRangeHeader *Prev;
97 FreeRangeHeader *Next;
99 /// getMinBlockSize - Get the minimum size for a memory block. Blocks
100 /// smaller than this size cannot be created.
101 static unsigned getMinBlockSize() {
102 return sizeof(FreeRangeHeader)+sizeof(intptr_t);
105 /// SetEndOfBlockSizeMarker - The word at the end of every free block is
106 /// known to be the size of the free block. Set it for this block.
107 void SetEndOfBlockSizeMarker() {
108 void *EndOfBlock = (char*)this + BlockSize;
109 ((intptr_t *)EndOfBlock)[-1] = BlockSize;
112 FreeRangeHeader *RemoveFromFreeList() {
113 assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
115 return Prev->Next = Next;
118 void AddToFreeList(FreeRangeHeader *FreeList) {
120 Prev = FreeList->Prev;
125 /// GrowBlock - The block after this block just got deallocated. Merge it
126 /// into the current block.
127 void GrowBlock(uintptr_t NewSize);
129 /// AllocateBlock - Mark this entire block allocated, updating freelists
130 /// etc. This returns a pointer to the circular free-list.
131 FreeRangeHeader *AllocateBlock();
136 /// AllocateBlock - Mark this entire block allocated, updating freelists
137 /// etc. This returns a pointer to the circular free-list.
138 FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
139 assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
140 "Cannot allocate an allocated block!");
141 // Mark this block allocated.
143 getBlockAfter().PrevAllocated = 1;
145 // Remove it from the free list.
146 return RemoveFromFreeList();
149 /// FreeBlock - Turn an allocated block into a free block, adjusting
150 /// bits in the object headers, and adding an end of region memory block.
151 /// If possible, coallesce this block with neighboring blocks. Return the
152 /// FreeRangeHeader to allocate from.
153 FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
154 MemoryRangeHeader *FollowingBlock = &getBlockAfter();
155 assert(ThisAllocated && "This block is already allocated!");
156 assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
158 FreeRangeHeader *FreeListToReturn = FreeList;
160 // If the block after this one is free, merge it into this block.
161 if (!FollowingBlock->ThisAllocated) {
162 FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
163 // "FreeList" always needs to be a valid free block. If we're about to
164 // coallesce with it, update our notion of what the free list is.
165 if (&FollowingFreeBlock == FreeList) {
166 FreeList = FollowingFreeBlock.Next;
167 FreeListToReturn = 0;
168 assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
170 FollowingFreeBlock.RemoveFromFreeList();
172 // Include the following block into this one.
173 BlockSize += FollowingFreeBlock.BlockSize;
174 FollowingBlock = &FollowingFreeBlock.getBlockAfter();
176 // Tell the block after the block we are coallescing that this block is
178 FollowingBlock->PrevAllocated = 1;
181 assert(FollowingBlock->ThisAllocated && "Missed coallescing?");
183 if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
184 PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
185 return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
188 // Otherwise, mark this block free.
189 FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
190 FollowingBlock->PrevAllocated = 0;
191 FreeBlock.ThisAllocated = 0;
193 // Link this into the linked list of free blocks.
194 FreeBlock.AddToFreeList(FreeList);
196 // Add a marker at the end of the block, indicating the size of this free
198 FreeBlock.SetEndOfBlockSizeMarker();
199 return FreeListToReturn ? FreeListToReturn : &FreeBlock;
202 /// GrowBlock - The block after this block just got deallocated. Merge it
203 /// into the current block.
204 void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
205 assert(NewSize > BlockSize && "Not growing block?");
207 SetEndOfBlockSizeMarker();
208 getBlockAfter().PrevAllocated = 0;
211 /// TrimAllocationToSize - If this allocated block is significantly larger
212 /// than NewSize, split it into two pieces (where the former is NewSize
213 /// bytes, including the header), and add the new block to the free list.
214 FreeRangeHeader *MemoryRangeHeader::
215 TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
216 assert(ThisAllocated && getBlockAfter().PrevAllocated &&
217 "Cannot deallocate part of an allocated block!");
219 // Round up size for alignment of header.
220 unsigned HeaderAlign = __alignof(FreeRangeHeader);
221 NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
223 // Size is now the size of the block we will remove from the start of the
225 assert(NewSize <= BlockSize &&
226 "Allocating more space from this block than exists!");
228 // If splitting this block will cause the remainder to be too small, do not
230 if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
233 // Otherwise, we splice the required number of bytes out of this block, form
234 // a new block immediately after it, then mark this block allocated.
235 MemoryRangeHeader &FormerNextBlock = getBlockAfter();
237 // Change the size of this block.
240 // Get the new block we just sliced out and turn it into a free block.
241 FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
242 NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
243 NewNextBlock.ThisAllocated = 0;
244 NewNextBlock.PrevAllocated = 1;
245 NewNextBlock.SetEndOfBlockSizeMarker();
246 FormerNextBlock.PrevAllocated = 0;
247 NewNextBlock.AddToFreeList(FreeList);
248 return &NewNextBlock;
253 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
254 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
255 /// sections, one for function stubs, one for the functions themselves. We
256 /// have to do this because we may need to emit a function stub while in the
257 /// middle of emitting a function, and we don't know how large the function we
258 /// are emitting is. This never bothers to release the memory, because when
259 /// we are ready to destroy the JIT, the program exits.
260 class JITMemoryManager {
261 std::vector<sys::MemoryBlock> Blocks; // Memory blocks allocated by the JIT
262 FreeRangeHeader *FreeMemoryList; // Circular list of free blocks.
264 // When emitting code into a memory block, this is the block.
265 MemoryRangeHeader *CurBlock;
267 unsigned char *CurStubPtr, *StubBase;
268 unsigned char *GOTBase; // Target Specific reserved memory
270 // Centralize memory block allocation.
271 sys::MemoryBlock getNewMemoryBlock(unsigned size);
273 std::map<const Function*, MemoryRangeHeader*> FunctionBlocks;
275 JITMemoryManager(bool useGOT);
278 inline unsigned char *allocateStub(unsigned StubSize, unsigned Alignment);
280 /// startFunctionBody - When a function starts, allocate a block of free
281 /// executable memory, returning a pointer to it and its actual size.
282 unsigned char *startFunctionBody(uintptr_t &ActualSize) {
283 CurBlock = FreeMemoryList;
285 // Allocate the entire memory block.
286 FreeMemoryList = FreeMemoryList->AllocateBlock();
287 ActualSize = CurBlock->BlockSize-sizeof(MemoryRangeHeader);
288 return (unsigned char *)(CurBlock+1);
291 /// endFunctionBody - The function F is now allocated, and takes the memory
292 /// in the range [FunctionStart,FunctionEnd).
293 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
294 unsigned char *FunctionEnd) {
295 assert(FunctionEnd > FunctionStart);
296 assert(FunctionStart == (unsigned char *)(CurBlock+1) &&
297 "Mismatched function start/end!");
299 uintptr_t BlockSize = FunctionEnd - (unsigned char *)CurBlock;
300 FunctionBlocks[F] = CurBlock;
302 // Release the memory at the end of this block that isn't needed.
303 FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
306 unsigned char *getGOTBase() const {
309 bool isManagingGOT() const {
310 return GOTBase != NULL;
313 /// deallocateMemForFunction - Deallocate all memory for the specified
315 void deallocateMemForFunction(const Function *F) {
316 std::map<const Function*, MemoryRangeHeader*>::iterator
317 I = FunctionBlocks.find(F);
318 if (I == FunctionBlocks.end()) return;
320 // Find the block that is allocated for this function.
321 MemoryRangeHeader *MemRange = I->second;
322 assert(MemRange->ThisAllocated && "Block isn't allocated!");
324 // Fill the buffer with garbage!
325 DEBUG(memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange)));
328 FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
330 // Finally, remove this entry from FunctionBlocks.
331 FunctionBlocks.erase(I);
336 JITMemoryManager::JITMemoryManager(bool useGOT) {
337 // Allocate a 16M block of memory for functions.
338 sys::MemoryBlock MemBlock = getNewMemoryBlock(16 << 20);
340 unsigned char *MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
342 // Allocate stubs backwards from the base, allocate functions forward
345 CurStubPtr = MemBase + 512*1024; // Use 512k for stubs, working backwards.
347 // We set up the memory chunk with 4 mem regions, like this:
349 // [ Free #0 ] -> Large space to allocate functions from.
350 // [ Allocated #1 ] -> Tiny space to separate regions.
351 // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
352 // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
355 // The last three blocks are never deallocated or touched.
357 // Add MemoryRangeHeader to the end of the memory region, indicating that
358 // the space after the block of memory is allocated. This is block #3.
359 MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
360 Mem3->ThisAllocated = 1;
361 Mem3->PrevAllocated = 0;
364 /// Add a tiny free region so that the free list always has one entry.
365 FreeRangeHeader *Mem2 =
366 (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
367 Mem2->ThisAllocated = 0;
368 Mem2->PrevAllocated = 1;
369 Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
370 Mem2->SetEndOfBlockSizeMarker();
371 Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
374 /// Add a tiny allocated region so that Mem2 is never coallesced away.
375 MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
376 Mem1->ThisAllocated = 1;
377 Mem1->PrevAllocated = 0;
378 Mem1->BlockSize = (char*)Mem2 - (char*)Mem1;
380 // Add a FreeRangeHeader to the start of the function body region, indicating
381 // that the space is free. Mark the previous block allocated so we never look
383 FreeRangeHeader *Mem0 = (FreeRangeHeader*)CurStubPtr;
384 Mem0->ThisAllocated = 0;
385 Mem0->PrevAllocated = 1;
386 Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
387 Mem0->SetEndOfBlockSizeMarker();
388 Mem0->AddToFreeList(Mem2);
390 // Start out with the freelist pointing to Mem0.
391 FreeMemoryList = Mem0;
395 if (useGOT) GOTBase = new unsigned char[sizeof(void*) * 8192];
398 JITMemoryManager::~JITMemoryManager() {
399 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
400 sys::Memory::ReleaseRWX(Blocks[i]);
406 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize,
407 unsigned Alignment) {
408 CurStubPtr -= StubSize;
409 CurStubPtr = (unsigned char*)(((intptr_t)CurStubPtr) &
410 ~(intptr_t)(Alignment-1));
411 if (CurStubPtr < StubBase) {
412 // FIXME: allocate a new block
413 cerr << "JIT ran out of memory for function stubs!\n";
419 sys::MemoryBlock JITMemoryManager::getNewMemoryBlock(unsigned size) {
420 // Allocate a new block close to the last one.
421 const sys::MemoryBlock *BOld = Blocks.empty() ? 0 : &Blocks.front();
423 sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld, &ErrMsg);
425 cerr << "Allocation failed when allocating new memory in the JIT\n";
426 cerr << ErrMsg << "\n";
433 //===----------------------------------------------------------------------===//
434 // JIT lazy compilation code.
437 class JITResolverState {
439 /// FunctionToStubMap - Keep track of the stub created for a particular
440 /// function so that we can reuse them if necessary.
441 std::map<Function*, void*> FunctionToStubMap;
443 /// StubToFunctionMap - Keep track of the function that each stub
445 std::map<void*, Function*> StubToFunctionMap;
448 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
449 assert(locked.holds(TheJIT->lock));
450 return FunctionToStubMap;
453 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
454 assert(locked.holds(TheJIT->lock));
455 return StubToFunctionMap;
459 /// JITResolver - Keep track of, and resolve, call sites for functions that
460 /// have not yet been compiled.
462 /// MCE - The MachineCodeEmitter to use to emit stubs with.
463 MachineCodeEmitter &MCE;
465 /// LazyResolverFn - The target lazy resolver function that we actually
466 /// rewrite instructions to use.
467 TargetJITInfo::LazyResolverFn LazyResolverFn;
469 JITResolverState state;
471 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
472 /// external functions.
473 std::map<void*, void*> ExternalFnToStubMap;
475 //map addresses to indexes in the GOT
476 std::map<void*, unsigned> revGOTMap;
477 unsigned nextGOTIndex;
480 JITResolver(MachineCodeEmitter &mce) : MCE(mce), nextGOTIndex(0) {
482 TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
485 /// getFunctionStub - This returns a pointer to a function stub, creating
486 /// one on demand as needed.
487 void *getFunctionStub(Function *F);
489 /// getExternalFunctionStub - Return a stub for the function at the
490 /// specified address, created lazily on demand.
491 void *getExternalFunctionStub(void *FnAddr);
493 /// AddCallbackAtLocation - If the target is capable of rewriting an
494 /// instruction without the use of a stub, record the location of the use so
495 /// we know which function is being used at the location.
496 void *AddCallbackAtLocation(Function *F, void *Location) {
497 MutexGuard locked(TheJIT->lock);
498 /// Get the target-specific JIT resolver function.
499 state.getStubToFunctionMap(locked)[Location] = F;
500 return (void*)(intptr_t)LazyResolverFn;
503 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
504 /// and address. This function only manages slots, it does not manage the
505 /// contents of the slots or the memory associated with the GOT.
506 unsigned getGOTIndexForAddr(void* addr);
508 /// JITCompilerFn - This function is called to resolve a stub to a compiled
509 /// address. If the LLVM Function corresponding to the stub has not yet
510 /// been compiled, this function compiles it first.
511 static void *JITCompilerFn(void *Stub);
515 /// getJITResolver - This function returns the one instance of the JIT resolver.
517 static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
518 static JITResolver TheJITResolver(*MCE);
519 return TheJITResolver;
522 #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
524 extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
527 /// synchronizeICache - On some targets, the JIT emitted code must be
528 /// explicitly refetched to ensure correct execution.
529 static void synchronizeICache(const void *Addr, size_t len) {
530 #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
532 sys_icache_invalidate(Addr, len);
536 /// getFunctionStub - This returns a pointer to a function stub, creating
537 /// one on demand as needed.
538 void *JITResolver::getFunctionStub(Function *F) {
539 MutexGuard locked(TheJIT->lock);
541 // If we already have a stub for this function, recycle it.
542 void *&Stub = state.getFunctionToStubMap(locked)[F];
543 if (Stub) return Stub;
545 // Call the lazy resolver function unless we already KNOW it is an external
546 // function, in which case we just skip the lazy resolution step.
547 void *Actual = (void*)(intptr_t)LazyResolverFn;
548 if (F->isExternal() && !F->hasNotBeenReadFromBytecode())
549 Actual = TheJIT->getPointerToFunction(F);
551 // Otherwise, codegen a new stub. For now, the stub will call the lazy
552 // resolver function.
553 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
555 if (Actual != (void*)(intptr_t)LazyResolverFn) {
556 // If we are getting the stub for an external function, we really want the
557 // address of the stub in the GlobalAddressMap for the JIT, not the address
558 // of the external function.
559 TheJIT->updateGlobalMapping(F, Stub);
562 // Invalidate the icache if necessary.
563 synchronizeICache(Stub, MCE.getCurrentPCValue()-(intptr_t)Stub);
565 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
566 << F->getName() << "'\n";
568 // Finally, keep track of the stub-to-Function mapping so that the
569 // JITCompilerFn knows which function to compile!
570 state.getStubToFunctionMap(locked)[Stub] = F;
574 /// getExternalFunctionStub - Return a stub for the function at the
575 /// specified address, created lazily on demand.
576 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
577 // If we already have a stub for this function, recycle it.
578 void *&Stub = ExternalFnToStubMap[FnAddr];
579 if (Stub) return Stub;
581 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
583 // Invalidate the icache if necessary.
584 synchronizeICache(Stub, MCE.getCurrentPCValue()-(intptr_t)Stub);
586 DOUT << "JIT: Stub emitted at [" << Stub
587 << "] for external function at '" << FnAddr << "'\n";
591 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
592 unsigned idx = revGOTMap[addr];
594 idx = ++nextGOTIndex;
595 revGOTMap[addr] = idx;
596 DOUT << "Adding GOT entry " << idx
597 << " for addr " << addr << "\n";
598 // ((void**)MemMgr.getGOTBase())[idx] = addr;
603 /// JITCompilerFn - This function is called when a lazy compilation stub has
604 /// been entered. It looks up which function this stub corresponds to, compiles
605 /// it if necessary, then returns the resultant function pointer.
606 void *JITResolver::JITCompilerFn(void *Stub) {
607 JITResolver &JR = getJITResolver();
609 MutexGuard locked(TheJIT->lock);
611 // The address given to us for the stub may not be exactly right, it might be
612 // a little bit after the stub. As such, use upper_bound to find it.
613 std::map<void*, Function*>::iterator I =
614 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
615 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
616 "This is not a known stub!");
617 Function *F = (--I)->second;
619 // If disabled, emit a useful error message and abort.
620 if (TheJIT->isLazyCompilationDisabled()) {
621 cerr << "LLVM JIT requested to do lazy compilation of function '"
622 << F->getName() << "' when lazy compiles are disabled!\n";
626 // We might like to remove the stub from the StubToFunction map.
627 // We can't do that! Multiple threads could be stuck, waiting to acquire the
628 // lock above. As soon as the 1st function finishes compiling the function,
629 // the next one will be released, and needs to be able to find the function it
631 //JR.state.getStubToFunctionMap(locked).erase(I);
633 DOUT << "JIT: Lazily resolving function '" << F->getName()
634 << "' In stub ptr = " << Stub << " actual ptr = "
637 void *Result = TheJIT->getPointerToFunction(F);
639 // We don't need to reuse this stub in the future, as F is now compiled.
640 JR.state.getFunctionToStubMap(locked).erase(F);
642 // FIXME: We could rewrite all references to this stub if we knew them.
644 // What we will do is set the compiled function address to map to the
645 // same GOT entry as the stub so that later clients may update the GOT
646 // if they see it still using the stub address.
647 // Note: this is done so the Resolver doesn't have to manage GOT memory
648 // Do this without allocating map space if the target isn't using a GOT
649 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
650 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
656 //===----------------------------------------------------------------------===//
660 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
661 /// used to output functions to memory for execution.
662 class JITEmitter : public MachineCodeEmitter {
663 JITMemoryManager MemMgr;
665 // When outputting a function stub in the context of some other function, we
666 // save BufferBegin/BufferEnd/CurBufferPtr here.
667 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
669 /// Relocations - These are the relocations that the function needs, as
671 std::vector<MachineRelocation> Relocations;
673 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
674 /// It is filled in by the StartMachineBasicBlock callback and queried by
675 /// the getMachineBasicBlockAddress callback.
676 std::vector<intptr_t> MBBLocations;
678 /// ConstantPool - The constant pool for the current function.
680 MachineConstantPool *ConstantPool;
682 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
684 void *ConstantPoolBase;
686 /// JumpTable - The jump tables for the current function.
688 MachineJumpTableInfo *JumpTable;
690 /// JumpTableBase - A pointer to the first entry in the jump table.
694 JITEmitter(JIT &jit) : MemMgr(jit.getJITInfo().needsGOT()) {
696 if (MemMgr.isManagingGOT()) DOUT << "JIT is managing a GOT\n";
699 virtual void startFunction(MachineFunction &F);
700 virtual bool finishFunction(MachineFunction &F);
702 void emitConstantPool(MachineConstantPool *MCP);
703 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
704 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
706 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1);
707 virtual void* finishFunctionStub(const Function *F);
709 virtual void addRelocation(const MachineRelocation &MR) {
710 Relocations.push_back(MR);
713 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
714 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
715 MBBLocations.resize((MBB->getNumber()+1)*2);
716 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
719 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
720 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
722 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
723 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
724 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
725 return MBBLocations[MBB->getNumber()];
728 /// deallocateMemForFunction - Deallocate all memory for the specified
730 void deallocateMemForFunction(Function *F) {
731 MemMgr.deallocateMemForFunction(F);
734 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
738 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
739 bool DoesntNeedStub) {
740 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
741 /// FIXME: If we straightened things out, this could actually emit the
742 /// global immediately instead of queuing it for codegen later!
743 return TheJIT->getOrEmitGlobalVariable(GV);
746 // If we have already compiled the function, return a pointer to its body.
747 Function *F = cast<Function>(V);
748 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
749 if (ResultPtr) return ResultPtr;
751 if (F->isExternal() && !F->hasNotBeenReadFromBytecode()) {
752 // If this is an external function pointer, we can force the JIT to
753 // 'compile' it, which really just adds it to the map.
755 return TheJIT->getPointerToFunction(F);
757 return getJITResolver(this).getFunctionStub(F);
760 // Okay, the function has not been compiled yet, if the target callback
761 // mechanism is capable of rewriting the instruction directly, prefer to do
762 // that instead of emitting a stub.
764 return getJITResolver(this).AddCallbackAtLocation(F, Reference);
766 // Otherwise, we have to emit a lazy resolving stub.
767 return getJITResolver(this).getFunctionStub(F);
770 void JITEmitter::startFunction(MachineFunction &F) {
771 uintptr_t ActualSize;
772 BufferBegin = CurBufferPtr = MemMgr.startFunctionBody(ActualSize);
773 BufferEnd = BufferBegin+ActualSize;
775 // Ensure the constant pool/jump table info is at least 4-byte aligned.
778 emitConstantPool(F.getConstantPool());
779 initJumpTableInfo(F.getJumpTableInfo());
781 // About to start emitting the machine code for the function.
782 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
783 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
785 MBBLocations.clear();
788 bool JITEmitter::finishFunction(MachineFunction &F) {
789 if (CurBufferPtr == BufferEnd) {
790 // FIXME: Allocate more space, then try again.
791 cerr << "JIT: Ran out of space for generated machine code!\n";
795 emitJumpTableInfo(F.getJumpTableInfo());
797 // FnStart is the start of the text, not the start of the constant pool and
798 // other per-function data.
799 unsigned char *FnStart =
800 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
801 unsigned char *FnEnd = CurBufferPtr;
803 MemMgr.endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
804 NumBytes += FnEnd-FnStart;
806 if (!Relocations.empty()) {
807 NumRelos += Relocations.size();
809 // Resolve the relocations to concrete pointers.
810 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
811 MachineRelocation &MR = Relocations[i];
814 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
816 // If the target REALLY wants a stub for this function, emit it now.
817 if (!MR.doesntNeedFunctionStub())
818 ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
819 } else if (MR.isGlobalValue()) {
820 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
821 BufferBegin+MR.getMachineCodeOffset(),
822 MR.doesntNeedFunctionStub());
823 } else if (MR.isBasicBlock()) {
824 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
825 } else if (MR.isConstantPoolIndex()) {
826 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
828 assert(MR.isJumpTableIndex());
829 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
832 MR.setResultPointer(ResultPtr);
834 // if we are managing the GOT and the relocation wants an index,
836 if (MemMgr.isManagingGOT() && MR.isGOTRelative()) {
837 unsigned idx = getJITResolver(this).getGOTIndexForAddr(ResultPtr);
839 if (((void**)MemMgr.getGOTBase())[idx] != ResultPtr) {
840 DOUT << "GOT was out of date for " << ResultPtr
841 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx]
843 ((void**)MemMgr.getGOTBase())[idx] = ResultPtr;
848 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
849 Relocations.size(), MemMgr.getGOTBase());
852 // Update the GOT entry for F to point to the new code.
853 if(MemMgr.isManagingGOT()) {
854 unsigned idx = getJITResolver(this).getGOTIndexForAddr((void*)BufferBegin);
855 if (((void**)MemMgr.getGOTBase())[idx] != (void*)BufferBegin) {
856 DOUT << "GOT was out of date for " << (void*)BufferBegin
857 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n";
858 ((void**)MemMgr.getGOTBase())[idx] = (void*)BufferBegin;
862 // Invalidate the icache if necessary.
863 synchronizeICache(FnStart, FnEnd-FnStart);
865 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
866 << "] Function: " << F.getFunction()->getName()
867 << ": " << (FnEnd-FnStart) << " bytes of text, "
868 << Relocations.size() << " relocations\n";
873 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
874 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
875 if (Constants.empty()) return;
877 MachineConstantPoolEntry CPE = Constants.back();
878 unsigned Size = CPE.Offset;
879 const Type *Ty = CPE.isMachineConstantPoolEntry()
880 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
881 Size += TheJIT->getTargetData()->getTypeSize(Ty);
883 ConstantPoolBase = allocateSpace(Size, 1 << MCP->getConstantPoolAlignment());
886 if (ConstantPoolBase == 0) return; // Buffer overflow.
888 // Initialize the memory for all of the constant pool entries.
889 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
890 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
891 if (Constants[i].isMachineConstantPoolEntry()) {
892 // FIXME: add support to lower machine constant pool values into bytes!
893 cerr << "Initialize memory with machine specific constant pool entry"
894 << " has not been implemented!\n";
897 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
901 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
902 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
903 if (JT.empty()) return;
905 unsigned NumEntries = 0;
906 for (unsigned i = 0, e = JT.size(); i != e; ++i)
907 NumEntries += JT[i].MBBs.size();
909 unsigned EntrySize = MJTI->getEntrySize();
911 // Just allocate space for all the jump tables now. We will fix up the actual
912 // MBB entries in the tables after we emit the code for each block, since then
913 // we will know the final locations of the MBBs in memory.
915 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
918 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
919 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
920 if (JT.empty() || JumpTableBase == 0) return;
922 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
923 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
924 // For each jump table, place the offset from the beginning of the table
925 // to the target address.
926 int *SlotPtr = (int*)JumpTableBase;
928 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
929 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
930 // Store the offset of the basic block for this jump table slot in the
931 // memory we allocated for the jump table in 'initJumpTableInfo'
932 intptr_t Base = (intptr_t)SlotPtr;
933 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
934 *SlotPtr++ = (intptr_t)getMachineBasicBlockAddress(MBBs[mi]) - Base;
937 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
939 // For each jump table, map each target in the jump table to the address of
940 // an emitted MachineBasicBlock.
941 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
943 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
944 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
945 // Store the address of the basic block for this jump table slot in the
946 // memory we allocated for the jump table in 'initJumpTableInfo'
947 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
948 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
953 void JITEmitter::startFunctionStub(unsigned StubSize, unsigned Alignment) {
954 SavedBufferBegin = BufferBegin;
955 SavedBufferEnd = BufferEnd;
956 SavedCurBufferPtr = CurBufferPtr;
958 BufferBegin = CurBufferPtr = MemMgr.allocateStub(StubSize, Alignment);
959 BufferEnd = BufferBegin+StubSize+1;
962 void *JITEmitter::finishFunctionStub(const Function *F) {
963 NumBytes += getCurrentPCOffset();
964 std::swap(SavedBufferBegin, BufferBegin);
965 BufferEnd = SavedBufferEnd;
966 CurBufferPtr = SavedCurBufferPtr;
967 return SavedBufferBegin;
970 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
971 // in the constant pool that was last emitted with the 'emitConstantPool'
974 intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
975 assert(ConstantNum < ConstantPool->getConstants().size() &&
976 "Invalid ConstantPoolIndex!");
977 return (intptr_t)ConstantPoolBase +
978 ConstantPool->getConstants()[ConstantNum].Offset;
981 // getJumpTableEntryAddress - Return the address of the JumpTable with index
982 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
984 intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
985 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
986 assert(Index < JT.size() && "Invalid jump table index!");
989 unsigned EntrySize = JumpTable->getEntrySize();
991 for (unsigned i = 0; i < Index; ++i)
992 Offset += JT[i].MBBs.size();
996 return (intptr_t)((char *)JumpTableBase + Offset);
999 //===----------------------------------------------------------------------===//
1000 // Public interface to this file
1001 //===----------------------------------------------------------------------===//
1003 MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
1004 return new JITEmitter(jit);
1007 // getPointerToNamedFunction - This function is used as a global wrapper to
1008 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1009 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1010 // need to resolve function(s) that are being mis-codegenerated, so we need to
1011 // resolve their addresses at runtime, and this is the way to do it.
1013 void *getPointerToNamedFunction(const char *Name) {
1014 if (Function *F = TheJIT->FindFunctionNamed(Name))
1015 return TheJIT->getPointerToFunction(F);
1016 return TheJIT->getPointerToNamedFunction(Name);
1020 // getPointerToFunctionOrStub - If the specified function has been
1021 // code-gen'd, return a pointer to the function. If not, compile it, or use
1022 // a stub to implement lazy compilation if available.
1024 void *JIT::getPointerToFunctionOrStub(Function *F) {
1025 // If we have already code generated the function, just return the address.
1026 if (void *Addr = getPointerToGlobalIfAvailable(F))
1029 // Get a stub if the target supports it
1030 return getJITResolver(MCE).getFunctionStub(F);
1033 /// freeMachineCodeForFunction - release machine code memory for given Function.
1035 void JIT::freeMachineCodeForFunction(Function *F) {
1036 // Delete translation for this from the ExecutionEngine, so it will get
1037 // retranslated next time it is used.
1038 updateGlobalMapping(F, 0);
1040 // Free the actual memory for the function body and related stuff.
1041 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
1042 dynamic_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);