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/MachineRelocation.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetJITInfo.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/System/Memory.h"
32 Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
33 Statistic<> NumRelos("jit", "Number of relocations applied");
38 //===----------------------------------------------------------------------===//
39 // JITMemoryManager code.
42 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
43 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
44 /// sections, one for function stubs, one for the functions themselves. We
45 /// have to do this because we may need to emit a function stub while in the
46 /// middle of emitting a function, and we don't know how large the function we
47 /// are emitting is. This never bothers to release the memory, because when
48 /// we are ready to destroy the JIT, the program exits.
49 class JITMemoryManager {
50 sys::MemoryBlock MemBlock; // Virtual memory block allocated RWX
51 unsigned char *MemBase; // Base of block of memory, start of stub mem
52 unsigned char *FunctionBase; // Start of the function body area
53 unsigned char *ConstantPool; // Memory allocated for constant pools
54 unsigned char *CurStubPtr, *CurFunctionPtr, *CurConstantPtr;
55 unsigned char *GOTBase; //Target Specific reserved memory
57 JITMemoryManager(bool useGOT);
60 inline unsigned char *allocateStub(unsigned StubSize);
61 inline unsigned char *allocateConstant(unsigned ConstantSize,
63 inline unsigned char *startFunctionBody();
64 inline void endFunctionBody(unsigned char *FunctionEnd);
65 inline unsigned char* getGOTBase() const;
67 inline bool isManagingGOT() const;
71 JITMemoryManager::JITMemoryManager(bool useGOT) {
72 // Allocate a 16M block of memory...
73 MemBlock = sys::Memory::AllocateRWX((16 << 20));
74 MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
75 ConstantPool = MemBase;
76 GOTBase = ConstantPool + 512*1024; //512 for constants
77 //8k number of entries in the GOT
78 FunctionBase = GOTBase + 8192 * sizeof(void*) + 512*1024; // Use 512k for stubs
80 //make it easier to tell if we are managing the GOT
84 // Allocate stubs backwards from the function base, allocate functions forward
85 // from the function base.
86 CurStubPtr = CurFunctionPtr = FunctionBase;
88 CurConstantPtr = ConstantPool + 512*1024;
91 JITMemoryManager::~JITMemoryManager() {
92 sys::Memory::ReleaseRWX(MemBlock);
95 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
96 CurStubPtr -= StubSize;
97 if (CurStubPtr < MemBase) {
98 std::cerr << "JIT ran out of memory for function stubs!\n";
104 unsigned char *JITMemoryManager::allocateConstant(unsigned ConstantSize,
105 unsigned Alignment) {
106 // Reserve space and align pointer.
107 CurConstantPtr -= ConstantSize;
109 (unsigned char *)((intptr_t)CurConstantPtr & ~((intptr_t)Alignment - 1));
111 if (CurConstantPtr < ConstantPool) {
112 std::cerr << "JIT ran out of memory for constant pools!\n";
115 return CurConstantPtr;
118 unsigned char *JITMemoryManager::startFunctionBody() {
119 // Round up to an even multiple of 8 bytes, this should eventually be target
121 return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
124 void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
125 assert(FunctionEnd > CurFunctionPtr);
126 CurFunctionPtr = FunctionEnd;
129 unsigned char* JITMemoryManager::getGOTBase() const {
133 bool JITMemoryManager::isManagingGOT() const {
134 return GOTBase != NULL;
137 //===----------------------------------------------------------------------===//
138 // JIT lazy compilation code.
141 class JITResolverState {
143 /// FunctionToStubMap - Keep track of the stub created for a particular
144 /// function so that we can reuse them if necessary.
145 std::map<Function*, void*> FunctionToStubMap;
147 /// StubToFunctionMap - Keep track of the function that each stub
149 std::map<void*, Function*> StubToFunctionMap;
152 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
153 assert(locked.holds(TheJIT->lock));
154 return FunctionToStubMap;
157 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
158 assert(locked.holds(TheJIT->lock));
159 return StubToFunctionMap;
163 /// JITResolver - Keep track of, and resolve, call sites for functions that
164 /// have not yet been compiled.
166 /// MCE - The MachineCodeEmitter to use to emit stubs with.
167 MachineCodeEmitter &MCE;
169 /// LazyResolverFn - The target lazy resolver function that we actually
170 /// rewrite instructions to use.
171 TargetJITInfo::LazyResolverFn LazyResolverFn;
173 JITResolverState state;
175 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
176 /// external functions.
177 std::map<void*, void*> ExternalFnToStubMap;
179 JITResolver(MachineCodeEmitter &mce) : MCE(mce) {
181 TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
184 /// getFunctionStub - This returns a pointer to a function stub, creating
185 /// one on demand as needed.
186 void *getFunctionStub(Function *F);
188 /// getExternalFunctionStub - Return a stub for the function at the
189 /// specified address, created lazily on demand.
190 void *getExternalFunctionStub(void *FnAddr);
192 /// AddCallbackAtLocation - If the target is capable of rewriting an
193 /// instruction without the use of a stub, record the location of the use so
194 /// we know which function is being used at the location.
195 void *AddCallbackAtLocation(Function *F, void *Location) {
196 MutexGuard locked(TheJIT->lock);
197 /// Get the target-specific JIT resolver function.
198 state.getStubToFunctionMap(locked)[Location] = F;
199 return (void*)LazyResolverFn;
202 /// JITCompilerFn - This function is called to resolve a stub to a compiled
203 /// address. If the LLVM Function corresponding to the stub has not yet
204 /// been compiled, this function compiles it first.
205 static void *JITCompilerFn(void *Stub);
209 /// getJITResolver - This function returns the one instance of the JIT resolver.
211 static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
212 static JITResolver TheJITResolver(*MCE);
213 return TheJITResolver;
216 /// getFunctionStub - This returns a pointer to a function stub, creating
217 /// one on demand as needed.
218 void *JITResolver::getFunctionStub(Function *F) {
219 MutexGuard locked(TheJIT->lock);
221 // If we already have a stub for this function, recycle it.
222 void *&Stub = state.getFunctionToStubMap(locked)[F];
223 if (Stub) return Stub;
225 // Call the lazy resolver function unless we already KNOW it is an external
226 // function, in which case we just skip the lazy resolution step.
227 void *Actual = (void*)LazyResolverFn;
228 if (F->isExternal() && F->hasExternalLinkage())
229 Actual = TheJIT->getPointerToFunction(F);
231 // Otherwise, codegen a new stub. For now, the stub will call the lazy
232 // resolver function.
233 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
235 if (Actual != (void*)LazyResolverFn) {
236 // If we are getting the stub for an external function, we really want the
237 // address of the stub in the GlobalAddressMap for the JIT, not the address
238 // of the external function.
239 TheJIT->updateGlobalMapping(F, Stub);
242 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
243 << F->getName() << "'\n");
245 // Finally, keep track of the stub-to-Function mapping so that the
246 // JITCompilerFn knows which function to compile!
247 state.getStubToFunctionMap(locked)[Stub] = F;
251 /// getExternalFunctionStub - Return a stub for the function at the
252 /// specified address, created lazily on demand.
253 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
254 // If we already have a stub for this function, recycle it.
255 void *&Stub = ExternalFnToStubMap[FnAddr];
256 if (Stub) return Stub;
258 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
259 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub
260 << "] for external function at '" << FnAddr << "'\n");
265 /// JITCompilerFn - This function is called when a lazy compilation stub has
266 /// been entered. It looks up which function this stub corresponds to, compiles
267 /// it if necessary, then returns the resultant function pointer.
268 void *JITResolver::JITCompilerFn(void *Stub) {
269 JITResolver &JR = getJITResolver();
271 MutexGuard locked(TheJIT->lock);
273 // The address given to us for the stub may not be exactly right, it might be
274 // a little bit after the stub. As such, use upper_bound to find it.
275 std::map<void*, Function*>::iterator I =
276 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
277 assert(I != JR.state.getStubToFunctionMap(locked).begin() && "This is not a known stub!");
278 Function *F = (--I)->second;
280 // We might like to remove the stub from the StubToFunction map.
281 // We can't do that! Multiple threads could be stuck, waiting to acquire the
282 // lock above. As soon as the 1st function finishes compiling the function,
283 // the next one will be released, and needs to be able to find the function it needs
285 //JR.state.getStubToFunctionMap(locked).erase(I);
287 DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
288 << "' In stub ptr = " << Stub << " actual ptr = "
289 << I->first << "\n");
291 void *Result = TheJIT->getPointerToFunction(F);
293 // We don't need to reuse this stub in the future, as F is now compiled.
294 JR.state.getFunctionToStubMap(locked).erase(F);
296 // FIXME: We could rewrite all references to this stub if we knew them.
301 // getPointerToFunctionOrStub - If the specified function has been
302 // code-gen'd, return a pointer to the function. If not, compile it, or use
303 // a stub to implement lazy compilation if available.
305 void *JIT::getPointerToFunctionOrStub(Function *F) {
306 // If we have already code generated the function, just return the address.
307 if (void *Addr = getPointerToGlobalIfAvailable(F))
310 // Get a stub if the target supports it
311 return getJITResolver(MCE).getFunctionStub(F);
316 //===----------------------------------------------------------------------===//
320 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
321 /// used to output functions to memory for execution.
322 class JITEmitter : public MachineCodeEmitter {
323 JITMemoryManager MemMgr;
325 // CurBlock - The start of the current block of memory. CurByte - The
326 // current byte being emitted to.
327 unsigned char *CurBlock, *CurByte;
329 // When outputting a function stub in the context of some other function, we
330 // save CurBlock and CurByte here.
331 unsigned char *SavedCurBlock, *SavedCurByte;
333 // ConstantPoolAddresses - Contains the location for each entry in the
335 std::vector<void*> ConstantPoolAddresses;
337 /// Relocations - These are the relocations that the function needs, as
339 std::vector<MachineRelocation> Relocations;
343 :MemMgr(jit.getJITInfo().needsGOT()),
348 (MemMgr.isManagingGOT() ? "JIT is managing GOT\n"
349 : "JIT is not managing GOT\n"));
352 virtual void startFunction(MachineFunction &F);
353 virtual void finishFunction(MachineFunction &F);
354 virtual void emitConstantPool(MachineConstantPool *MCP);
355 virtual void startFunctionStub(unsigned StubSize);
356 virtual void* finishFunctionStub(const Function *F);
357 virtual void emitByte(unsigned char B);
358 virtual void emitWord(unsigned W);
359 virtual void emitWordAt(unsigned W, unsigned *Ptr);
361 virtual void addRelocation(const MachineRelocation &MR) {
362 Relocations.push_back(MR);
365 virtual uint64_t getCurrentPCValue();
366 virtual uint64_t getCurrentPCOffset();
367 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
370 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
371 unsigned nextGOTIndex;
372 std::map<void*, unsigned> revGOTMap;
376 MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
377 return new JITEmitter(jit);
380 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
381 bool DoesntNeedStub) {
382 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
383 /// FIXME: If we straightened things out, this could actually emit the
384 /// global immediately instead of queuing it for codegen later!
385 return TheJIT->getOrEmitGlobalVariable(GV);
388 // If we have already compiled the function, return a pointer to its body.
389 Function *F = cast<Function>(V);
390 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
391 if (ResultPtr) return ResultPtr;
393 if (F->hasExternalLinkage() && F->isExternal()) {
394 // If this is an external function pointer, we can force the JIT to
395 // 'compile' it, which really just adds it to the map.
397 return TheJIT->getPointerToFunction(F);
399 return getJITResolver(this).getFunctionStub(F);
402 // Okay, the function has not been compiled yet, if the target callback
403 // mechanism is capable of rewriting the instruction directly, prefer to do
404 // that instead of emitting a stub.
406 return getJITResolver(this).AddCallbackAtLocation(F, Reference);
408 // Otherwise, we have to emit a lazy resolving stub.
409 return getJITResolver(this).getFunctionStub(F);
412 void JITEmitter::startFunction(MachineFunction &F) {
413 CurByte = CurBlock = MemMgr.startFunctionBody();
414 TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
417 void JITEmitter::finishFunction(MachineFunction &F) {
418 MemMgr.endFunctionBody(CurByte);
419 NumBytes += CurByte-CurBlock;
421 if (!Relocations.empty()) {
422 NumRelos += Relocations.size();
424 // Resolve the relocations to concrete pointers.
425 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
426 MachineRelocation &MR = Relocations[i];
429 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
431 // If the target REALLY wants a stub for this function, emit it now.
432 if (!MR.doesntNeedFunctionStub())
433 ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
434 } else if (MR.isGlobalValue())
435 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
436 CurBlock+MR.getMachineCodeOffset(),
437 MR.doesntNeedFunctionStub());
438 else //ConstantPoolIndex
440 (void*)(intptr_t)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
442 MR.setResultPointer(ResultPtr);
444 // if we are managing the got, check to see if this pointer has all ready
445 // been allocated a GOT entry. If not, give it the next one.
446 if (MemMgr.isManagingGOT()) {
447 if (!revGOTMap[ResultPtr])
448 revGOTMap[ResultPtr] = ++nextGOTIndex;
449 ((void**)MemMgr.getGOTBase())[revGOTMap[ResultPtr]] = ResultPtr;
450 if(MR.isGOTRelative())
451 MR.setGOTIndex(revGOTMap[ResultPtr]);
455 TheJIT->getJITInfo().relocate(CurBlock, &Relocations[0],
456 Relocations.size(), MemMgr.getGOTBase());
459 DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)CurBlock
460 << "] Function: " << F.getFunction()->getName()
461 << ": " << CurByte-CurBlock << " bytes of text, "
462 << Relocations.size() << " relocations\n");
464 ConstantPoolAddresses.clear();
467 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
468 const std::vector<Constant*> &Constants = MCP->getConstants();
469 if (Constants.empty()) return;
471 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
472 const Type *Ty = Constants[i]->getType();
473 unsigned Size = (unsigned)TheJIT->getTargetData().getTypeSize(Ty);
474 unsigned Alignment = TheJIT->getTargetData().getTypeAlignment(Ty);
476 void *Addr = MemMgr.allocateConstant(Size, Alignment);
477 TheJIT->InitializeMemory(Constants[i], Addr);
478 ConstantPoolAddresses.push_back(Addr);
482 void JITEmitter::startFunctionStub(unsigned StubSize) {
483 SavedCurBlock = CurBlock; SavedCurByte = CurByte;
484 CurByte = CurBlock = MemMgr.allocateStub(StubSize);
487 void *JITEmitter::finishFunctionStub(const Function *F) {
488 NumBytes += CurByte-CurBlock;
489 std::swap(CurBlock, SavedCurBlock);
490 CurByte = SavedCurByte;
491 return SavedCurBlock;
494 void JITEmitter::emitByte(unsigned char B) {
495 *CurByte++ = B; // Write the byte to memory
498 void JITEmitter::emitWord(unsigned W) {
499 // This won't work if the endianness of the host and target don't agree! (For
500 // a JIT this can't happen though. :)
501 *(unsigned*)CurByte = W;
502 CurByte += sizeof(unsigned);
505 void JITEmitter::emitWordAt(unsigned W, unsigned *Ptr) {
509 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
510 // in the constant pool that was last emitted with the 'emitConstantPool'
513 uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
514 assert(ConstantNum < ConstantPoolAddresses.size() &&
515 "Invalid ConstantPoolIndex!");
516 return (intptr_t)ConstantPoolAddresses[ConstantNum];
519 // getCurrentPCValue - This returns the address that the next emitted byte
520 // will be output to.
522 uint64_t JITEmitter::getCurrentPCValue() {
523 return (intptr_t)CurByte;
526 uint64_t JITEmitter::getCurrentPCOffset() {
527 return (intptr_t)CurByte-(intptr_t)CurBlock;
530 // getPointerToNamedFunction - This function is used as a global wrapper to
531 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
532 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
533 // need to resolve function(s) that are being mis-codegenerated, so we need to
534 // resolve their addresses at runtime, and this is the way to do it.
536 void *getPointerToNamedFunction(const char *Name) {
537 Module &M = TheJIT->getModule();
538 if (Function *F = M.getNamedFunction(Name))
539 return TheJIT->getPointerToFunction(F);
540 return TheJIT->getPointerToNamedFunction(Name);