JITEmitter.cpp was trying to sync the icache for function stubs, but
[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 is distributed under the University of Illinois Open Source
6 // 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/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineRelocation.h"
25 #include "llvm/ExecutionEngine/JITMemoryManager.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/System/Disassembler.h"
32 #include "llvm/ADT/Statistic.h"
33 #include <algorithm>
34 using namespace llvm;
35
36 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
37 STATISTIC(NumRelos, "Number of relocations applied");
38 static JIT *TheJIT = 0;
39
40
41 //===----------------------------------------------------------------------===//
42 // JIT lazy compilation code.
43 //
44 namespace {
45   class JITResolverState {
46   private:
47     /// FunctionToStubMap - Keep track of the stub created for a particular
48     /// function so that we can reuse them if necessary.
49     std::map<Function*, void*> FunctionToStubMap;
50
51     /// StubToFunctionMap - Keep track of the function that each stub
52     /// corresponds to.
53     std::map<void*, Function*> StubToFunctionMap;
54
55     /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a
56     /// particular GlobalVariable so that we can reuse them if necessary.
57     std::map<GlobalValue*, void*> GlobalToLazyPtrMap;
58
59   public:
60     std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
61       assert(locked.holds(TheJIT->lock));
62       return FunctionToStubMap;
63     }
64
65     std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
66       assert(locked.holds(TheJIT->lock));
67       return StubToFunctionMap;
68     }
69
70     std::map<GlobalValue*, void*>&
71     getGlobalToLazyPtrMap(const MutexGuard& locked) {
72       assert(locked.holds(TheJIT->lock));
73       return GlobalToLazyPtrMap;
74     }
75   };
76
77   /// JITResolver - Keep track of, and resolve, call sites for functions that
78   /// have not yet been compiled.
79   class JITResolver {
80     /// LazyResolverFn - The target lazy resolver function that we actually
81     /// rewrite instructions to use.
82     TargetJITInfo::LazyResolverFn LazyResolverFn;
83
84     JITResolverState state;
85
86     /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
87     /// external functions.
88     std::map<void*, void*> ExternalFnToStubMap;
89
90     //map addresses to indexes in the GOT
91     std::map<void*, unsigned> revGOTMap;
92     unsigned nextGOTIndex;
93
94     static JITResolver *TheJITResolver;
95   public:
96     JITResolver(JIT &jit) : nextGOTIndex(0) {
97       TheJIT = &jit;
98
99       LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
100       assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
101       TheJITResolver = this;
102     }
103     
104     ~JITResolver() {
105       TheJITResolver = 0;
106     }
107
108     /// getFunctionStub - This returns a pointer to a function stub, creating
109     /// one on demand as needed.
110     void *getFunctionStub(Function *F);
111
112     /// getExternalFunctionStub - Return a stub for the function at the
113     /// specified address, created lazily on demand.
114     void *getExternalFunctionStub(void *FnAddr);
115
116     /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
117     /// GV address.
118     void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress);
119
120     /// AddCallbackAtLocation - If the target is capable of rewriting an
121     /// instruction without the use of a stub, record the location of the use so
122     /// we know which function is being used at the location.
123     void *AddCallbackAtLocation(Function *F, void *Location) {
124       MutexGuard locked(TheJIT->lock);
125       /// Get the target-specific JIT resolver function.
126       state.getStubToFunctionMap(locked)[Location] = F;
127       return (void*)(intptr_t)LazyResolverFn;
128     }
129
130     /// getGOTIndexForAddress - Return a new or existing index in the GOT for
131     /// an address.  This function only manages slots, it does not manage the
132     /// contents of the slots or the memory associated with the GOT.
133     unsigned getGOTIndexForAddr(void *addr);
134
135     /// JITCompilerFn - This function is called to resolve a stub to a compiled
136     /// address.  If the LLVM Function corresponding to the stub has not yet
137     /// been compiled, this function compiles it first.
138     static void *JITCompilerFn(void *Stub);
139   };
140 }
141
142 JITResolver *JITResolver::TheJITResolver = 0;
143
144 #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
145     defined(__APPLE__)
146 extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
147 #endif
148
149 /// synchronizeICache - On some targets, the JIT emitted code must be
150 /// explicitly refetched to ensure correct execution.
151 static void synchronizeICache(const void *Addr, size_t len) {
152 #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
153     defined(__APPLE__)
154   sys_icache_invalidate(Addr, len);
155 #endif
156 }
157
158 /// getFunctionStub - This returns a pointer to a function stub, creating
159 /// one on demand as needed.
160 void *JITResolver::getFunctionStub(Function *F) {
161   MutexGuard locked(TheJIT->lock);
162
163   // If we already have a stub for this function, recycle it.
164   void *&Stub = state.getFunctionToStubMap(locked)[F];
165   if (Stub) return Stub;
166
167   // Call the lazy resolver function unless we already KNOW it is an external
168   // function, in which case we just skip the lazy resolution step.
169   void *Actual = (void*)(intptr_t)LazyResolverFn;
170   if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
171     Actual = TheJIT->getPointerToFunction(F);
172
173   // Otherwise, codegen a new stub.  For now, the stub will call the lazy
174   // resolver function.
175   Stub = TheJIT->getJITInfo().emitFunctionStub(Actual,
176                                                *TheJIT->getCodeEmitter());
177
178   if (Actual != (void*)(intptr_t)LazyResolverFn) {
179     // If we are getting the stub for an external function, we really want the
180     // address of the stub in the GlobalAddressMap for the JIT, not the address
181     // of the external function.
182     TheJIT->updateGlobalMapping(F, Stub);
183   }
184
185   DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
186        << F->getName() << "'\n";
187
188   // Finally, keep track of the stub-to-Function mapping so that the
189   // JITCompilerFn knows which function to compile!
190   state.getStubToFunctionMap(locked)[Stub] = F;
191   return Stub;
192 }
193
194 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
195 /// GV address.
196 void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) {
197   MutexGuard locked(TheJIT->lock);
198
199   // If we already have a stub for this global variable, recycle it.
200   void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV];
201   if (LazyPtr) return LazyPtr;
202
203   // Otherwise, codegen a new lazy pointer.
204   LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GVAddress,
205                                                     *TheJIT->getCodeEmitter());
206
207   DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '"
208        << GV->getName() << "'\n";
209
210   return LazyPtr;
211 }
212
213 /// getExternalFunctionStub - Return a stub for the function at the
214 /// specified address, created lazily on demand.
215 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
216   // If we already have a stub for this function, recycle it.
217   void *&Stub = ExternalFnToStubMap[FnAddr];
218   if (Stub) return Stub;
219
220   Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr,
221                                                *TheJIT->getCodeEmitter());
222
223   DOUT << "JIT: Stub emitted at [" << Stub
224        << "] for external function at '" << FnAddr << "'\n";
225   return Stub;
226 }
227
228 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
229   unsigned idx = revGOTMap[addr];
230   if (!idx) {
231     idx = ++nextGOTIndex;
232     revGOTMap[addr] = idx;
233     DOUT << "Adding GOT entry " << idx
234          << " for addr " << addr << "\n";
235   }
236   return idx;
237 }
238
239 /// JITCompilerFn - This function is called when a lazy compilation stub has
240 /// been entered.  It looks up which function this stub corresponds to, compiles
241 /// it if necessary, then returns the resultant function pointer.
242 void *JITResolver::JITCompilerFn(void *Stub) {
243   JITResolver &JR = *TheJITResolver;
244
245   MutexGuard locked(TheJIT->lock);
246
247   // The address given to us for the stub may not be exactly right, it might be
248   // a little bit after the stub.  As such, use upper_bound to find it.
249   std::map<void*, Function*>::iterator I =
250     JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
251   assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
252          "This is not a known stub!");
253   Function *F = (--I)->second;
254
255   // If we have already code generated the function, just return the address.
256   void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
257   
258   if (!Result) {
259     // Otherwise we don't have it, do lazy compilation now.
260     
261     // If lazy compilation is disabled, emit a useful error message and abort.
262     if (TheJIT->isLazyCompilationDisabled()) {
263       cerr << "LLVM JIT requested to do lazy compilation of function '"
264       << F->getName() << "' when lazy compiles are disabled!\n";
265       abort();
266     }
267   
268     // We might like to remove the stub from the StubToFunction map.
269     // We can't do that! Multiple threads could be stuck, waiting to acquire the
270     // lock above. As soon as the 1st function finishes compiling the function,
271     // the next one will be released, and needs to be able to find the function
272     // it needs to call.
273     //JR.state.getStubToFunctionMap(locked).erase(I);
274
275     DOUT << "JIT: Lazily resolving function '" << F->getName()
276          << "' In stub ptr = " << Stub << " actual ptr = "
277          << I->first << "\n";
278
279     Result = TheJIT->getPointerToFunction(F);
280   }
281
282   // We don't need to reuse this stub in the future, as F is now compiled.
283   JR.state.getFunctionToStubMap(locked).erase(F);
284
285   // FIXME: We could rewrite all references to this stub if we knew them.
286
287   // What we will do is set the compiled function address to map to the
288   // same GOT entry as the stub so that later clients may update the GOT
289   // if they see it still using the stub address.
290   // Note: this is done so the Resolver doesn't have to manage GOT memory
291   // Do this without allocating map space if the target isn't using a GOT
292   if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
293     JR.revGOTMap[Result] = JR.revGOTMap[Stub];
294
295   return Result;
296 }
297
298
299 //===----------------------------------------------------------------------===//
300 // JITEmitter code.
301 //
302 namespace {
303   /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
304   /// used to output functions to memory for execution.
305   class JITEmitter : public MachineCodeEmitter {
306     JITMemoryManager *MemMgr;
307
308     // When outputting a function stub in the context of some other function, we
309     // save BufferBegin/BufferEnd/CurBufferPtr here.
310     unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
311
312     /// Relocations - These are the relocations that the function needs, as
313     /// emitted.
314     std::vector<MachineRelocation> Relocations;
315     
316     /// MBBLocations - This vector is a mapping from MBB ID's to their address.
317     /// It is filled in by the StartMachineBasicBlock callback and queried by
318     /// the getMachineBasicBlockAddress callback.
319     std::vector<intptr_t> MBBLocations;
320
321     /// ConstantPool - The constant pool for the current function.
322     ///
323     MachineConstantPool *ConstantPool;
324
325     /// ConstantPoolBase - A pointer to the first entry in the constant pool.
326     ///
327     void *ConstantPoolBase;
328
329     /// JumpTable - The jump tables for the current function.
330     ///
331     MachineJumpTableInfo *JumpTable;
332     
333     /// JumpTableBase - A pointer to the first entry in the jump table.
334     ///
335     void *JumpTableBase;
336
337     /// Resolver - This contains info about the currently resolved functions.
338     JITResolver Resolver;
339   public:
340     JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
341       MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
342       if (jit.getJITInfo().needsGOT()) {
343         MemMgr->AllocateGOT();
344         DOUT << "JIT is managing a GOT\n";
345       }
346     }
347     ~JITEmitter() { 
348       delete MemMgr;
349     }
350     
351     JITResolver &getJITResolver() { return Resolver; }
352
353     virtual void startFunction(MachineFunction &F);
354     virtual bool finishFunction(MachineFunction &F);
355     
356     void emitConstantPool(MachineConstantPool *MCP);
357     void initJumpTableInfo(MachineJumpTableInfo *MJTI);
358     void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
359     
360     virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1);
361     virtual void* finishFunctionStub(const Function *F);
362
363     virtual void addRelocation(const MachineRelocation &MR) {
364       Relocations.push_back(MR);
365     }
366     
367     virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
368       if (MBBLocations.size() <= (unsigned)MBB->getNumber())
369         MBBLocations.resize((MBB->getNumber()+1)*2);
370       MBBLocations[MBB->getNumber()] = getCurrentPCValue();
371     }
372
373     virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
374     virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
375
376     virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
377       assert(MBBLocations.size() > (unsigned)MBB->getNumber() && 
378              MBBLocations[MBB->getNumber()] && "MBB not emitted!");
379       return MBBLocations[MBB->getNumber()];
380     }
381
382     /// deallocateMemForFunction - Deallocate all memory for the specified
383     /// function body.
384     void deallocateMemForFunction(Function *F) {
385       MemMgr->deallocateMemForFunction(F);
386     }
387   private:
388     void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
389     void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
390                                 bool NoNeedStub);
391   };
392 }
393
394 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
395                                      bool DoesntNeedStub) {
396   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
397     /// FIXME: If we straightened things out, this could actually emit the
398     /// global immediately instead of queuing it for codegen later!
399     return TheJIT->getOrEmitGlobalVariable(GV);
400   }
401
402   // If we have already compiled the function, return a pointer to its body.
403   Function *F = cast<Function>(V);
404   void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
405   if (ResultPtr) return ResultPtr;
406
407   if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
408     // If this is an external function pointer, we can force the JIT to
409     // 'compile' it, which really just adds it to the map.
410     if (DoesntNeedStub)
411       return TheJIT->getPointerToFunction(F);
412
413     return Resolver.getFunctionStub(F);
414   }
415
416   // Okay, the function has not been compiled yet, if the target callback
417   // mechanism is capable of rewriting the instruction directly, prefer to do
418   // that instead of emitting a stub.
419   if (DoesntNeedStub)
420     return Resolver.AddCallbackAtLocation(F, Reference);
421
422   // Otherwise, we have to emit a lazy resolving stub.
423   return Resolver.getFunctionStub(F);
424 }
425
426 void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
427                                         bool DoesntNeedStub) {
428   // Make sure GV is emitted first.
429   // FIXME: For now, if the GV is an external function we force the JIT to
430   // compile it so the lazy pointer will contain the fully resolved address.
431   void *GVAddress = getPointerToGlobal(V, Reference, true);
432   return Resolver.getGlobalValueLazyPtr(V, GVAddress);
433 }
434
435
436 void JITEmitter::startFunction(MachineFunction &F) {
437   uintptr_t ActualSize;
438   BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
439                                                          ActualSize);
440   BufferEnd = BufferBegin+ActualSize;
441   
442   // Ensure the constant pool/jump table info is at least 4-byte aligned.
443   emitAlignment(16);
444
445   emitConstantPool(F.getConstantPool());
446   initJumpTableInfo(F.getJumpTableInfo());
447
448   // About to start emitting the machine code for the function.
449   emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
450   TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
451
452   MBBLocations.clear();
453 }
454
455 bool JITEmitter::finishFunction(MachineFunction &F) {
456   if (CurBufferPtr == BufferEnd) {
457     // FIXME: Allocate more space, then try again.
458     cerr << "JIT: Ran out of space for generated machine code!\n";
459     abort();
460   }
461   
462   emitJumpTableInfo(F.getJumpTableInfo());
463   
464   // FnStart is the start of the text, not the start of the constant pool and
465   // other per-function data.
466   unsigned char *FnStart =
467     (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
468   unsigned char *FnEnd   = CurBufferPtr;
469   
470   MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
471   NumBytes += FnEnd-FnStart;
472
473   if (!Relocations.empty()) {
474     NumRelos += Relocations.size();
475
476     // Resolve the relocations to concrete pointers.
477     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
478       MachineRelocation &MR = Relocations[i];
479       void *ResultPtr;
480       if (MR.isString()) {
481         ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
482
483         // If the target REALLY wants a stub for this function, emit it now.
484         if (!MR.doesntNeedStub())
485           ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
486       } else if (MR.isGlobalValue()) {
487         ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
488                                        BufferBegin+MR.getMachineCodeOffset(),
489                                        MR.doesntNeedStub());
490       } else if (MR.isGlobalValueLazyPtr()) {
491         ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(),
492                                           BufferBegin+MR.getMachineCodeOffset(),
493                                           MR.doesntNeedStub());
494       } else if (MR.isBasicBlock()) {
495         ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
496       } else if (MR.isConstantPoolIndex()) {
497         ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
498       } else {
499         assert(MR.isJumpTableIndex());
500         ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
501       }
502
503       MR.setResultPointer(ResultPtr);
504
505       // if we are managing the GOT and the relocation wants an index,
506       // give it one
507       if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
508         unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
509         MR.setGOTIndex(idx);
510         if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
511           DOUT << "GOT was out of date for " << ResultPtr
512                << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
513                << "\n";
514           ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
515         }
516       }
517     }
518
519     TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
520                                   Relocations.size(), MemMgr->getGOTBase());
521   }
522
523   // Update the GOT entry for F to point to the new code.
524   if (MemMgr->isManagingGOT()) {
525     unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
526     if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
527       DOUT << "GOT was out of date for " << (void*)BufferBegin
528            << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
529       ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
530     }
531   }
532
533   // Invalidate the icache if necessary.
534   synchronizeICache(FnStart, FnEnd-FnStart);
535
536   DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
537        << "] Function: " << F.getFunction()->getName()
538        << ": " << (FnEnd-FnStart) << " bytes of text, "
539        << Relocations.size() << " relocations\n";
540   Relocations.clear();
541
542 #ifndef NDEBUG
543   if (sys::hasDisassembler())
544     DOUT << "Disassembled code:\n"
545          << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
546 #endif
547   
548   return false;
549 }
550
551 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
552   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
553   if (Constants.empty()) return;
554
555   MachineConstantPoolEntry CPE = Constants.back();
556   unsigned Size = CPE.Offset;
557   const Type *Ty = CPE.isMachineConstantPoolEntry()
558     ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
559   Size += TheJIT->getTargetData()->getABITypeSize(Ty);
560
561   ConstantPoolBase = allocateSpace(Size, 1 << MCP->getConstantPoolAlignment());
562   ConstantPool = MCP;
563
564   if (ConstantPoolBase == 0) return;  // Buffer overflow.
565
566   // Initialize the memory for all of the constant pool entries.
567   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
568     void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
569     if (Constants[i].isMachineConstantPoolEntry()) {
570       // FIXME: add support to lower machine constant pool values into bytes!
571       cerr << "Initialize memory with machine specific constant pool entry"
572            << " has not been implemented!\n";
573       abort();
574     }
575     TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
576   }
577 }
578
579 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
580   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
581   if (JT.empty()) return;
582   
583   unsigned NumEntries = 0;
584   for (unsigned i = 0, e = JT.size(); i != e; ++i)
585     NumEntries += JT[i].MBBs.size();
586
587   unsigned EntrySize = MJTI->getEntrySize();
588
589   // Just allocate space for all the jump tables now.  We will fix up the actual
590   // MBB entries in the tables after we emit the code for each block, since then
591   // we will know the final locations of the MBBs in memory.
592   JumpTable = MJTI;
593   JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
594 }
595
596 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
597   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
598   if (JT.empty() || JumpTableBase == 0) return;
599   
600   if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
601     assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
602     // For each jump table, place the offset from the beginning of the table
603     // to the target address.
604     int *SlotPtr = (int*)JumpTableBase;
605
606     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
607       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
608       // Store the offset of the basic block for this jump table slot in the
609       // memory we allocated for the jump table in 'initJumpTableInfo'
610       intptr_t Base = (intptr_t)SlotPtr;
611       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
612         intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
613         *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
614       }
615     }
616   } else {
617     assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
618     
619     // For each jump table, map each target in the jump table to the address of 
620     // an emitted MachineBasicBlock.
621     intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
622
623     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
624       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
625       // Store the address of the basic block for this jump table slot in the
626       // memory we allocated for the jump table in 'initJumpTableInfo'
627       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
628         *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
629     }
630   }
631 }
632
633 void JITEmitter::startFunctionStub(unsigned StubSize, unsigned Alignment) {
634   SavedBufferBegin = BufferBegin;
635   SavedBufferEnd = BufferEnd;
636   SavedCurBufferPtr = CurBufferPtr;
637   
638   BufferBegin = CurBufferPtr = MemMgr->allocateStub(StubSize, Alignment);
639   BufferEnd = BufferBegin+StubSize+1;
640 }
641
642 void *JITEmitter::finishFunctionStub(const Function *F) {
643   NumBytes += getCurrentPCOffset();
644   std::swap(SavedBufferBegin, BufferBegin);
645   BufferEnd = SavedBufferEnd;
646   CurBufferPtr = SavedCurBufferPtr;
647   return SavedBufferBegin;
648 }
649
650 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
651 // in the constant pool that was last emitted with the 'emitConstantPool'
652 // method.
653 //
654 intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
655   assert(ConstantNum < ConstantPool->getConstants().size() &&
656          "Invalid ConstantPoolIndex!");
657   return (intptr_t)ConstantPoolBase +
658          ConstantPool->getConstants()[ConstantNum].Offset;
659 }
660
661 // getJumpTableEntryAddress - Return the address of the JumpTable with index
662 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
663 //
664 intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
665   const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
666   assert(Index < JT.size() && "Invalid jump table index!");
667   
668   unsigned Offset = 0;
669   unsigned EntrySize = JumpTable->getEntrySize();
670   
671   for (unsigned i = 0; i < Index; ++i)
672     Offset += JT[i].MBBs.size();
673   
674    Offset *= EntrySize;
675   
676   return (intptr_t)((char *)JumpTableBase + Offset);
677 }
678
679 //===----------------------------------------------------------------------===//
680 //  Public interface to this file
681 //===----------------------------------------------------------------------===//
682
683 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
684   return new JITEmitter(jit, JMM);
685 }
686
687 // getPointerToNamedFunction - This function is used as a global wrapper to
688 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
689 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
690 // need to resolve function(s) that are being mis-codegenerated, so we need to
691 // resolve their addresses at runtime, and this is the way to do it.
692 extern "C" {
693   void *getPointerToNamedFunction(const char *Name) {
694     if (Function *F = TheJIT->FindFunctionNamed(Name))
695       return TheJIT->getPointerToFunction(F);
696     return TheJIT->getPointerToNamedFunction(Name);
697   }
698 }
699
700 // getPointerToFunctionOrStub - If the specified function has been
701 // code-gen'd, return a pointer to the function.  If not, compile it, or use
702 // a stub to implement lazy compilation if available.
703 //
704 void *JIT::getPointerToFunctionOrStub(Function *F) {
705   // If we have already code generated the function, just return the address.
706   if (void *Addr = getPointerToGlobalIfAvailable(F))
707     return Addr;
708   
709   // Get a stub if the target supports it.
710   assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
711   JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
712   return JE->getJITResolver().getFunctionStub(F);
713 }
714
715 /// freeMachineCodeForFunction - release machine code memory for given Function.
716 ///
717 void JIT::freeMachineCodeForFunction(Function *F) {
718   // Delete translation for this from the ExecutionEngine, so it will get
719   // retranslated next time it is used.
720   updateGlobalMapping(F, 0);
721
722   // Free the actual memory for the function body and related stuff.
723   assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
724   static_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);
725 }
726