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");
37 //===----------------------------------------------------------------------===//
38 // JITMemoryManager code.
41 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
42 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
43 /// sections, one for function stubs, one for the functions themselves. We
44 /// have to do this because we may need to emit a function stub while in the
45 /// middle of emitting a function, and we don't know how large the function we
46 /// are emitting is. This never bothers to release the memory, because when
47 /// we are ready to destroy the JIT, the program exits.
48 class JITMemoryManager {
49 sys::MemoryBlock MemBlock; // Virtual memory block allocated RWX
50 unsigned char *MemBase; // Base of block of memory, start of stub mem
51 unsigned char *FunctionBase; // Start of the function body area
52 unsigned char *ConstantPool; // Memory allocated for constant pools
53 unsigned char *CurStubPtr, *CurFunctionPtr, *CurConstantPtr;
58 inline unsigned char *allocateStub(unsigned StubSize);
59 inline unsigned char *allocateConstant(unsigned ConstantSize,
61 inline unsigned char *startFunctionBody();
62 inline void endFunctionBody(unsigned char *FunctionEnd);
66 JITMemoryManager::JITMemoryManager() {
67 // Allocate a 16M block of memory...
68 MemBlock = sys::Memory::AllocateRWX((16 << 20));
69 MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
70 FunctionBase = MemBase + 512*1024; // Use 512k for stubs
72 // Allocate stubs backwards from the function base, allocate functions forward
73 // from the function base.
74 CurStubPtr = CurFunctionPtr = FunctionBase;
76 ConstantPool = new unsigned char [512*1024]; // Use 512k for constant pools
77 CurConstantPtr = ConstantPool + 512*1024;
80 JITMemoryManager::~JITMemoryManager() {
81 sys::Memory::ReleaseRWX(MemBlock);
82 delete[] ConstantPool;
85 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
86 CurStubPtr -= StubSize;
87 if (CurStubPtr < MemBase) {
88 std::cerr << "JIT ran out of memory for function stubs!\n";
94 unsigned char *JITMemoryManager::allocateConstant(unsigned ConstantSize,
96 // Reserve space and align pointer.
97 CurConstantPtr -= ConstantSize;
99 (unsigned char *)((intptr_t)CurConstantPtr & ~((intptr_t)Alignment - 1));
101 if (CurConstantPtr < ConstantPool) {
102 std::cerr << "JIT ran out of memory for constant pools!\n";
105 return CurConstantPtr;
108 unsigned char *JITMemoryManager::startFunctionBody() {
109 // Round up to an even multiple of 8 bytes, this should eventually be target
111 return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
114 void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
115 assert(FunctionEnd > CurFunctionPtr);
116 CurFunctionPtr = FunctionEnd;
119 //===----------------------------------------------------------------------===//
120 // JIT lazy compilation code.
123 /// JITResolver - Keep track of, and resolve, call sites for functions that
124 /// have not yet been compiled.
126 /// MCE - The MachineCodeEmitter to use to emit stubs with.
127 MachineCodeEmitter &MCE;
129 /// LazyResolverFn - The target lazy resolver function that we actually
130 /// rewrite instructions to use.
131 TargetJITInfo::LazyResolverFn LazyResolverFn;
133 // FunctionToStubMap - Keep track of the stub created for a particular
134 // function so that we can reuse them if necessary.
135 std::map<Function*, void*> FunctionToStubMap;
137 // StubToFunctionMap - Keep track of the function that each stub corresponds
139 std::map<void*, Function*> StubToFunctionMap;
141 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
142 /// external functions.
143 std::map<void*, void*> ExternalFnToStubMap;
145 JITResolver(MachineCodeEmitter &mce) : MCE(mce) {
147 TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
150 /// getFunctionStub - This returns a pointer to a function stub, creating
151 /// one on demand as needed.
152 void *getFunctionStub(Function *F);
154 /// getExternalFunctionStub - Return a stub for the function at the
155 /// specified address, created lazily on demand.
156 void *getExternalFunctionStub(void *FnAddr);
158 /// AddCallbackAtLocation - If the target is capable of rewriting an
159 /// instruction without the use of a stub, record the location of the use so
160 /// we know which function is being used at the location.
161 void *AddCallbackAtLocation(Function *F, void *Location) {
162 /// Get the target-specific JIT resolver function.
163 StubToFunctionMap[Location] = F;
164 return (void*)LazyResolverFn;
167 /// JITCompilerFn - This function is called to resolve a stub to a compiled
168 /// address. If the LLVM Function corresponding to the stub has not yet
169 /// been compiled, this function compiles it first.
170 static void *JITCompilerFn(void *Stub);
174 /// getJITResolver - This function returns the one instance of the JIT resolver.
176 static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
177 static JITResolver TheJITResolver(*MCE);
178 return TheJITResolver;
181 /// getFunctionStub - This returns a pointer to a function stub, creating
182 /// one on demand as needed.
183 void *JITResolver::getFunctionStub(Function *F) {
184 // If we already have a stub for this function, recycle it.
185 void *&Stub = FunctionToStubMap[F];
186 if (Stub) return Stub;
188 // Call the lazy resolver function unless we already KNOW it is an external
189 // function, in which case we just skip the lazy resolution step.
190 void *Actual = (void*)LazyResolverFn;
191 if (F->isExternal() && F->hasExternalLinkage())
192 Actual = TheJIT->getPointerToFunction(F);
194 // Otherwise, codegen a new stub. For now, the stub will call the lazy
195 // resolver function.
196 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
198 if (Actual != (void*)LazyResolverFn) {
199 // If we are getting the stub for an external function, we really want the
200 // address of the stub in the GlobalAddressMap for the JIT, not the address
201 // of the external function.
202 TheJIT->updateGlobalMapping(F, Stub);
205 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
206 << F->getName() << "'\n");
208 // Finally, keep track of the stub-to-Function mapping so that the
209 // JITCompilerFn knows which function to compile!
210 StubToFunctionMap[Stub] = F;
214 /// getExternalFunctionStub - Return a stub for the function at the
215 /// specified address, created lazily on demand.
216 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
217 // If we already have a stub for this function, recycle it.
218 void *&Stub = ExternalFnToStubMap[FnAddr];
219 if (Stub) return Stub;
221 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
222 DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub
223 << "] for external function at '" << FnAddr << "'\n");
228 /// JITCompilerFn - This function is called when a lazy compilation stub has
229 /// been entered. It looks up which function this stub corresponds to, compiles
230 /// it if necessary, then returns the resultant function pointer.
231 void *JITResolver::JITCompilerFn(void *Stub) {
232 JITResolver &JR = getJITResolver();
234 // The address given to us for the stub may not be exactly right, it might be
235 // a little bit after the stub. As such, use upper_bound to find it.
236 std::map<void*, Function*>::iterator I =
237 JR.StubToFunctionMap.upper_bound(Stub);
238 assert(I != JR.StubToFunctionMap.begin() && "This is not a known stub!");
239 Function *F = (--I)->second;
241 // The target function will rewrite the stub so that the compilation callback
242 // function is no longer called from this stub.
243 JR.StubToFunctionMap.erase(I);
245 DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
246 << "' In stub ptr = " << Stub << " actual ptr = "
247 << I->first << "\n");
249 void *Result = TheJIT->getPointerToFunction(F);
251 // We don't need to reuse this stub in the future, as F is now compiled.
252 JR.FunctionToStubMap.erase(F);
254 // FIXME: We could rewrite all references to this stub if we knew them.
259 // getPointerToFunctionOrStub - If the specified function has been
260 // code-gen'd, return a pointer to the function. If not, compile it, or use
261 // a stub to implement lazy compilation if available.
263 void *JIT::getPointerToFunctionOrStub(Function *F) {
264 // If we have already code generated the function, just return the address.
265 if (void *Addr = getPointerToGlobalIfAvailable(F))
268 // Get a stub if the target supports it
269 return getJITResolver(MCE).getFunctionStub(F);
274 //===----------------------------------------------------------------------===//
278 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
279 /// used to output functions to memory for execution.
280 class JITEmitter : public MachineCodeEmitter {
281 JITMemoryManager MemMgr;
283 // CurBlock - The start of the current block of memory. CurByte - The
284 // current byte being emitted to.
285 unsigned char *CurBlock, *CurByte;
287 // When outputting a function stub in the context of some other function, we
288 // save CurBlock and CurByte here.
289 unsigned char *SavedCurBlock, *SavedCurByte;
291 // ConstantPoolAddresses - Contains the location for each entry in the
293 std::vector<void*> ConstantPoolAddresses;
295 /// Relocations - These are the relocations that the function needs, as
297 std::vector<MachineRelocation> Relocations;
299 JITEmitter(JIT &jit) { TheJIT = &jit; }
301 virtual void startFunction(MachineFunction &F);
302 virtual void finishFunction(MachineFunction &F);
303 virtual void emitConstantPool(MachineConstantPool *MCP);
304 virtual void startFunctionStub(unsigned StubSize);
305 virtual void* finishFunctionStub(const Function *F);
306 virtual void emitByte(unsigned char B);
307 virtual void emitWord(unsigned W);
308 virtual void emitWordAt(unsigned W, unsigned *Ptr);
310 virtual void addRelocation(const MachineRelocation &MR) {
311 Relocations.push_back(MR);
314 virtual uint64_t getCurrentPCValue();
315 virtual uint64_t getCurrentPCOffset();
316 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
319 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
323 MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
324 return new JITEmitter(jit);
327 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
328 bool DoesntNeedStub) {
329 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
330 /// FIXME: If we straightened things out, this could actually emit the
331 /// global immediately instead of queuing it for codegen later!
332 return TheJIT->getOrEmitGlobalVariable(GV);
335 // If we have already compiled the function, return a pointer to its body.
336 Function *F = cast<Function>(V);
337 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
338 if (ResultPtr) return ResultPtr;
340 if (F->hasExternalLinkage() && F->isExternal()) {
341 // If this is an external function pointer, we can force the JIT to
342 // 'compile' it, which really just adds it to the map.
344 return TheJIT->getPointerToFunction(F);
346 return getJITResolver(this).getFunctionStub(F);
349 // Okay, the function has not been compiled yet, if the target callback
350 // mechanism is capable of rewriting the instruction directly, prefer to do
351 // that instead of emitting a stub.
353 return getJITResolver(this).AddCallbackAtLocation(F, Reference);
355 // Otherwise, we have to emit a lazy resolving stub.
356 return getJITResolver(this).getFunctionStub(F);
359 void JITEmitter::startFunction(MachineFunction &F) {
360 CurByte = CurBlock = MemMgr.startFunctionBody();
361 TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
364 void JITEmitter::finishFunction(MachineFunction &F) {
365 MemMgr.endFunctionBody(CurByte);
366 ConstantPoolAddresses.clear();
367 NumBytes += CurByte-CurBlock;
369 if (!Relocations.empty()) {
370 // Resolve the relocations to concrete pointers.
371 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
372 MachineRelocation &MR = Relocations[i];
375 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
377 // If the target REALLY wants a stub for this function, emit it now.
378 if (!MR.doesntNeedFunctionStub())
379 ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
381 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
382 CurBlock+MR.getMachineCodeOffset(),
383 MR.doesntNeedFunctionStub());
384 MR.setResultPointer(ResultPtr);
387 TheJIT->getJITInfo().relocate(CurBlock, &Relocations[0],
391 DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)CurBlock
392 << "] Function: " << F.getFunction()->getName()
393 << ": " << CurByte-CurBlock << " bytes of text, "
394 << Relocations.size() << " relocations\n");
398 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
399 const std::vector<Constant*> &Constants = MCP->getConstants();
400 if (Constants.empty()) return;
402 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
403 const Type *Ty = Constants[i]->getType();
404 unsigned Size = (unsigned)TheJIT->getTargetData().getTypeSize(Ty);
405 unsigned Alignment = TheJIT->getTargetData().getTypeAlignment(Ty);
407 void *Addr = MemMgr.allocateConstant(Size, Alignment);
408 TheJIT->InitializeMemory(Constants[i], Addr);
409 ConstantPoolAddresses.push_back(Addr);
413 void JITEmitter::startFunctionStub(unsigned StubSize) {
414 SavedCurBlock = CurBlock; SavedCurByte = CurByte;
415 CurByte = CurBlock = MemMgr.allocateStub(StubSize);
418 void *JITEmitter::finishFunctionStub(const Function *F) {
419 NumBytes += CurByte-CurBlock;
420 std::swap(CurBlock, SavedCurBlock);
421 CurByte = SavedCurByte;
422 return SavedCurBlock;
425 void JITEmitter::emitByte(unsigned char B) {
426 *CurByte++ = B; // Write the byte to memory
429 void JITEmitter::emitWord(unsigned W) {
430 // This won't work if the endianness of the host and target don't agree! (For
431 // a JIT this can't happen though. :)
432 *(unsigned*)CurByte = W;
433 CurByte += sizeof(unsigned);
436 void JITEmitter::emitWordAt(unsigned W, unsigned *Ptr) {
440 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
441 // in the constant pool that was last emitted with the 'emitConstantPool'
444 uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
445 assert(ConstantNum < ConstantPoolAddresses.size() &&
446 "Invalid ConstantPoolIndex!");
447 return (intptr_t)ConstantPoolAddresses[ConstantNum];
450 // getCurrentPCValue - This returns the address that the next emitted byte
451 // will be output to.
453 uint64_t JITEmitter::getCurrentPCValue() {
454 return (intptr_t)CurByte;
457 uint64_t JITEmitter::getCurrentPCOffset() {
458 return (intptr_t)CurByte-(intptr_t)CurBlock;
461 // getPointerToNamedFunction - This function is used as a global wrapper to
462 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
463 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
464 // need to resolve function(s) that are being mis-codegenerated, so we need to
465 // resolve their addresses at runtime, and this is the way to do it.
467 void *getPointerToNamedFunction(const char *Name) {
468 Module &M = TheJIT->getModule();
469 if (Function *F = M.getNamedFunction(Name))
470 return TheJIT->getPointerToFunction(F);
471 return TheJIT->getPointerToNamedFunction(Name);