Eliminate all remaining tabs and trailing spaces.
[oota-llvm.git] / lib / ExecutionEngine / JIT / JITEmitter.cpp
1 //===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "jit"
16 #include "JIT.h"
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"
29 using namespace llvm;
30
31 namespace {
32   Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
33   Statistic<> NumRelos("jit", "Number of relocations applied");
34   JIT *TheJIT = 0;
35 }
36
37
38 //===----------------------------------------------------------------------===//
39 // JITMemoryManager code.
40 //
41 namespace {
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
56   public:
57     JITMemoryManager(bool useGOT);
58     ~JITMemoryManager();
59
60     inline unsigned char *allocateStub(unsigned StubSize);
61     inline unsigned char *allocateConstant(unsigned ConstantSize,
62                                            unsigned Alignment);
63     inline unsigned char *startFunctionBody();
64     inline void endFunctionBody(unsigned char *FunctionEnd);
65     inline unsigned char* getGOTBase() const;
66
67     inline bool isManagingGOT() const;
68   };
69 }
70
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
79
80   //make it easier to tell if we are managing the GOT
81   if (!useGOT)
82     GOTBase = NULL;
83
84   // Allocate stubs backwards from the function base, allocate functions forward
85   // from the function base.
86   CurStubPtr = CurFunctionPtr = FunctionBase;
87
88   CurConstantPtr = ConstantPool + 512*1024;
89 }
90
91 JITMemoryManager::~JITMemoryManager() {
92   sys::Memory::ReleaseRWX(MemBlock);
93 }
94
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";
99     abort();
100   }
101   return CurStubPtr;
102 }
103
104 unsigned char *JITMemoryManager::allocateConstant(unsigned ConstantSize,
105                                                   unsigned Alignment) {
106   // Reserve space and align pointer.
107   CurConstantPtr -= ConstantSize;
108   CurConstantPtr =
109     (unsigned char *)((intptr_t)CurConstantPtr & ~((intptr_t)Alignment - 1));
110
111   if (CurConstantPtr < ConstantPool) {
112     std::cerr << "JIT ran out of memory for constant pools!\n";
113     abort();
114   }
115   return CurConstantPtr;
116 }
117
118 unsigned char *JITMemoryManager::startFunctionBody() {
119   // Round up to an even multiple of 8 bytes, this should eventually be target
120   // specific.
121   return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
122 }
123
124 void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
125   assert(FunctionEnd > CurFunctionPtr);
126   CurFunctionPtr = FunctionEnd;
127 }
128
129 unsigned char* JITMemoryManager::getGOTBase() const {
130   return GOTBase;
131 }
132
133 bool JITMemoryManager::isManagingGOT() const {
134   return GOTBase != NULL;
135 }
136
137 //===----------------------------------------------------------------------===//
138 // JIT lazy compilation code.
139 //
140 namespace {
141   class JITResolverState {
142   private:
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;
146
147     /// StubToFunctionMap - Keep track of the function that each stub
148     /// corresponds to.
149     std::map<void*, Function*> StubToFunctionMap;
150
151   public:
152     std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
153       assert(locked.holds(TheJIT->lock));
154       return FunctionToStubMap;
155     }
156
157     std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
158       assert(locked.holds(TheJIT->lock));
159       return StubToFunctionMap;
160     }
161   };
162
163   /// JITResolver - Keep track of, and resolve, call sites for functions that
164   /// have not yet been compiled.
165   class JITResolver {
166     /// MCE - The MachineCodeEmitter to use to emit stubs with.
167     MachineCodeEmitter &MCE;
168
169     /// LazyResolverFn - The target lazy resolver function that we actually
170     /// rewrite instructions to use.
171     TargetJITInfo::LazyResolverFn LazyResolverFn;
172
173     JITResolverState state;
174
175     /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
176     /// external functions.
177     std::map<void*, void*> ExternalFnToStubMap;
178   public:
179     JITResolver(MachineCodeEmitter &mce) : MCE(mce) {
180       LazyResolverFn =
181         TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
182     }
183
184     /// getFunctionStub - This returns a pointer to a function stub, creating
185     /// one on demand as needed.
186     void *getFunctionStub(Function *F);
187
188     /// getExternalFunctionStub - Return a stub for the function at the
189     /// specified address, created lazily on demand.
190     void *getExternalFunctionStub(void *FnAddr);
191
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;
200     }
201
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);
206   };
207 }
208
209 /// getJITResolver - This function returns the one instance of the JIT resolver.
210 ///
211 static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
212   static JITResolver TheJITResolver(*MCE);
213   return TheJITResolver;
214 }
215
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);
220
221   // If we already have a stub for this function, recycle it.
222   void *&Stub = state.getFunctionToStubMap(locked)[F];
223   if (Stub) return Stub;
224
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);
230
231   // Otherwise, codegen a new stub.  For now, the stub will call the lazy
232   // resolver function.
233   Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
234
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);
240   }
241
242   DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
243                   << F->getName() << "'\n");
244
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;
248   return Stub;
249 }
250
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;
257
258   Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
259   DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub
260         << "] for external function at '" << FnAddr << "'\n");
261   return Stub;
262 }
263
264
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();
270
271   MutexGuard locked(TheJIT->lock);
272
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;
279
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
284   // to call.
285   //JR.state.getStubToFunctionMap(locked).erase(I);
286
287   DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
288                   << "' In stub ptr = " << Stub << " actual ptr = "
289                   << I->first << "\n");
290
291   void *Result = TheJIT->getPointerToFunction(F);
292
293   // We don't need to reuse this stub in the future, as F is now compiled.
294   JR.state.getFunctionToStubMap(locked).erase(F);
295
296   // FIXME: We could rewrite all references to this stub if we knew them.
297   return Result;
298 }
299
300
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.
304 //
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))
308     return Addr;
309
310   // Get a stub if the target supports it
311   return getJITResolver(MCE).getFunctionStub(F);
312 }
313
314
315
316 //===----------------------------------------------------------------------===//
317 // JITEmitter code.
318 //
319 namespace {
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;
324
325     // CurBlock - The start of the current block of memory.  CurByte - The
326     // current byte being emitted to.
327     unsigned char *CurBlock, *CurByte;
328
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;
332
333     // ConstantPoolAddresses - Contains the location for each entry in the
334     // constant pool.
335     std::vector<void*> ConstantPoolAddresses;
336
337     /// Relocations - These are the relocations that the function needs, as
338     /// emitted.
339     std::vector<MachineRelocation> Relocations;
340
341   public:
342     JITEmitter(JIT &jit)
343       :MemMgr(jit.getJITInfo().needsGOT()),
344        nextGOTIndex(0)
345     {
346       TheJIT = &jit;
347       DEBUG(std::cerr <<
348             (MemMgr.isManagingGOT() ? "JIT is managing GOT\n"
349              : "JIT is not managing GOT\n"));
350     }
351
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);
360
361     virtual void addRelocation(const MachineRelocation &MR) {
362       Relocations.push_back(MR);
363     }
364
365     virtual uint64_t getCurrentPCValue();
366     virtual uint64_t getCurrentPCOffset();
367     virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
368
369   private:
370     void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
371     unsigned nextGOTIndex;
372     std::map<void*, unsigned> revGOTMap;
373   };
374 }
375
376 MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
377   return new JITEmitter(jit);
378 }
379
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);
386   }
387
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;
392
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.
396     if (DoesntNeedStub)
397       return TheJIT->getPointerToFunction(F);
398
399     return getJITResolver(this).getFunctionStub(F);
400   }
401
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.
405   if (DoesntNeedStub)
406     return getJITResolver(this).AddCallbackAtLocation(F, Reference);
407
408   // Otherwise, we have to emit a lazy resolving stub.
409   return getJITResolver(this).getFunctionStub(F);
410 }
411
412 void JITEmitter::startFunction(MachineFunction &F) {
413   CurByte = CurBlock = MemMgr.startFunctionBody();
414   TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
415 }
416
417 void JITEmitter::finishFunction(MachineFunction &F) {
418   MemMgr.endFunctionBody(CurByte);
419   NumBytes += CurByte-CurBlock;
420
421   if (!Relocations.empty()) {
422     NumRelos += Relocations.size();
423
424     // Resolve the relocations to concrete pointers.
425     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
426       MachineRelocation &MR = Relocations[i];
427       void *ResultPtr;
428       if (MR.isString()) {
429         ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
430
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
439         ResultPtr =
440        (void*)(intptr_t)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
441
442       MR.setResultPointer(ResultPtr);
443
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]);
452       }
453     }
454
455     TheJIT->getJITInfo().relocate(CurBlock, &Relocations[0],
456                                   Relocations.size(), MemMgr.getGOTBase());
457   }
458
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");
463   Relocations.clear();
464   ConstantPoolAddresses.clear();
465 }
466
467 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
468   const std::vector<Constant*> &Constants = MCP->getConstants();
469   if (Constants.empty()) return;
470
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);
475
476     void *Addr = MemMgr.allocateConstant(Size, Alignment);
477     TheJIT->InitializeMemory(Constants[i], Addr);
478     ConstantPoolAddresses.push_back(Addr);
479   }
480 }
481
482 void JITEmitter::startFunctionStub(unsigned StubSize) {
483   SavedCurBlock = CurBlock;  SavedCurByte = CurByte;
484   CurByte = CurBlock = MemMgr.allocateStub(StubSize);
485 }
486
487 void *JITEmitter::finishFunctionStub(const Function *F) {
488   NumBytes += CurByte-CurBlock;
489   std::swap(CurBlock, SavedCurBlock);
490   CurByte = SavedCurByte;
491   return SavedCurBlock;
492 }
493
494 void JITEmitter::emitByte(unsigned char B) {
495   *CurByte++ = B;   // Write the byte to memory
496 }
497
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);
503 }
504
505 void JITEmitter::emitWordAt(unsigned W, unsigned *Ptr) {
506   *Ptr = W;
507 }
508
509 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
510 // in the constant pool that was last emitted with the 'emitConstantPool'
511 // method.
512 //
513 uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
514   assert(ConstantNum < ConstantPoolAddresses.size() &&
515          "Invalid ConstantPoolIndex!");
516   return (intptr_t)ConstantPoolAddresses[ConstantNum];
517 }
518
519 // getCurrentPCValue - This returns the address that the next emitted byte
520 // will be output to.
521 //
522 uint64_t JITEmitter::getCurrentPCValue() {
523   return (intptr_t)CurByte;
524 }
525
526 uint64_t JITEmitter::getCurrentPCOffset() {
527   return (intptr_t)CurByte-(intptr_t)CurBlock;
528 }
529
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.
535 extern "C" {
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);
541   }
542 }