3f3f681f6109dd4fe443f44c9ce8b4999dbfc5c9
[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 "JITDwarfEmitter.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/CodeGen/MachineCodeEmitter.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRelocation.h"
27 #include "llvm/ExecutionEngine/JITMemoryManager.h"
28 #include "llvm/ExecutionEngine/GenericValue.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetJITInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/MutexGuard.h"
35 #include "llvm/System/Disassembler.h"
36 #include "llvm/System/Memory.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/Statistic.h"
40 #include <algorithm>
41 #ifndef NDEBUG
42 #include <iomanip>
43 #endif
44 using namespace llvm;
45
46 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
47 STATISTIC(NumRelos, "Number of relocations applied");
48 static JIT *TheJIT = 0;
49
50
51 //===----------------------------------------------------------------------===//
52 // JIT lazy compilation code.
53 //
54 namespace {
55   class JITResolverState {
56   private:
57     /// FunctionToStubMap - Keep track of the stub created for a particular
58     /// function so that we can reuse them if necessary.
59     std::map<Function*, void*> FunctionToStubMap;
60
61     /// StubToFunctionMap - Keep track of the function that each stub
62     /// corresponds to.
63     std::map<void*, Function*> StubToFunctionMap;
64
65     /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
66     /// particular GlobalVariable so that we can reuse them if necessary.
67     std::map<GlobalValue*, void*> GlobalToIndirectSymMap;
68
69   public:
70     std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
71       assert(locked.holds(TheJIT->lock));
72       return FunctionToStubMap;
73     }
74
75     std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
76       assert(locked.holds(TheJIT->lock));
77       return StubToFunctionMap;
78     }
79
80     std::map<GlobalValue*, void*>&
81     getGlobalToIndirectSymMap(const MutexGuard& locked) {
82       assert(locked.holds(TheJIT->lock));
83       return GlobalToIndirectSymMap;
84     }
85   };
86
87   /// JITResolver - Keep track of, and resolve, call sites for functions that
88   /// have not yet been compiled.
89   class JITResolver {
90     /// LazyResolverFn - The target lazy resolver function that we actually
91     /// rewrite instructions to use.
92     TargetJITInfo::LazyResolverFn LazyResolverFn;
93
94     JITResolverState state;
95
96     /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
97     /// external functions.
98     std::map<void*, void*> ExternalFnToStubMap;
99
100     //map addresses to indexes in the GOT
101     std::map<void*, unsigned> revGOTMap;
102     unsigned nextGOTIndex;
103
104     static JITResolver *TheJITResolver;
105   public:
106     explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
107       TheJIT = &jit;
108
109       LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
110       assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
111       TheJITResolver = this;
112     }
113     
114     ~JITResolver() {
115       TheJITResolver = 0;
116     }
117
118     /// getFunctionStubIfAvailable - This returns a pointer to a function stub
119     /// if it has already been created.
120     void *getFunctionStubIfAvailable(Function *F);
121
122     /// getFunctionStub - This returns a pointer to a function stub, creating
123     /// one on demand as needed.
124     void *getFunctionStub(Function *F);
125
126     /// getExternalFunctionStub - Return a stub for the function at the
127     /// specified address, created lazily on demand.
128     void *getExternalFunctionStub(void *FnAddr);
129
130     /// getGlobalValueIndirectSym - Return an indirect symbol containing the
131     /// specified GV address.
132     void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
133
134     /// AddCallbackAtLocation - If the target is capable of rewriting an
135     /// instruction without the use of a stub, record the location of the use so
136     /// we know which function is being used at the location.
137     void *AddCallbackAtLocation(Function *F, void *Location) {
138       MutexGuard locked(TheJIT->lock);
139       /// Get the target-specific JIT resolver function.
140       state.getStubToFunctionMap(locked)[Location] = F;
141       return (void*)(intptr_t)LazyResolverFn;
142     }
143
144     /// getGOTIndexForAddress - Return a new or existing index in the GOT for
145     /// an address.  This function only manages slots, it does not manage the
146     /// contents of the slots or the memory associated with the GOT.
147     unsigned getGOTIndexForAddr(void *addr);
148
149     /// JITCompilerFn - This function is called to resolve a stub to a compiled
150     /// address.  If the LLVM Function corresponding to the stub has not yet
151     /// been compiled, this function compiles it first.
152     static void *JITCompilerFn(void *Stub);
153   };
154 }
155
156 JITResolver *JITResolver::TheJITResolver = 0;
157
158 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
159 /// if it has already been created.
160 void *JITResolver::getFunctionStubIfAvailable(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   return Stub;
166 }
167
168 /// getFunctionStub - This returns a pointer to a function stub, creating
169 /// one on demand as needed.
170 void *JITResolver::getFunctionStub(Function *F) {
171   MutexGuard locked(TheJIT->lock);
172
173   // If we already have a stub for this function, recycle it.
174   void *&Stub = state.getFunctionToStubMap(locked)[F];
175   if (Stub) return Stub;
176
177   // Call the lazy resolver function unless we already KNOW it is an external
178   // function, in which case we just skip the lazy resolution step.
179   void *Actual = (void*)(intptr_t)LazyResolverFn;
180   if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
181     Actual = TheJIT->getPointerToFunction(F);
182
183     // If we resolved the symbol to a null address (eg. a weak external)
184     // don't emit a stub. Return a null pointer to the application.
185     if (!Actual) return 0;
186   }
187
188   // Otherwise, codegen a new stub.  For now, the stub will call the lazy
189   // resolver function.
190   Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
191                                                *TheJIT->getCodeEmitter());
192
193   if (Actual != (void*)(intptr_t)LazyResolverFn) {
194     // If we are getting the stub for an external function, we really want the
195     // address of the stub in the GlobalAddressMap for the JIT, not the address
196     // of the external function.
197     TheJIT->updateGlobalMapping(F, Stub);
198   }
199
200   DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
201        << F->getName() << "'\n";
202
203   // Finally, keep track of the stub-to-Function mapping so that the
204   // JITCompilerFn knows which function to compile!
205   state.getStubToFunctionMap(locked)[Stub] = F;
206   return Stub;
207 }
208
209 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
210 /// GV address.
211 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
212   MutexGuard locked(TheJIT->lock);
213
214   // If we already have a stub for this global variable, recycle it.
215   void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
216   if (IndirectSym) return IndirectSym;
217
218   // Otherwise, codegen a new indirect symbol.
219   IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
220                                                      *TheJIT->getCodeEmitter());
221
222   DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
223        << GV->getName() << "'\n";
224
225   return IndirectSym;
226 }
227
228 /// getExternalFunctionStub - Return a stub for the function at the
229 /// specified address, created lazily on demand.
230 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
231   // If we already have a stub for this function, recycle it.
232   void *&Stub = ExternalFnToStubMap[FnAddr];
233   if (Stub) return Stub;
234
235   Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
236                                                *TheJIT->getCodeEmitter());
237
238   DOUT << "JIT: Stub emitted at [" << Stub
239        << "] for external function at '" << FnAddr << "'\n";
240   return Stub;
241 }
242
243 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
244   unsigned idx = revGOTMap[addr];
245   if (!idx) {
246     idx = ++nextGOTIndex;
247     revGOTMap[addr] = idx;
248     DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
249   }
250   return idx;
251 }
252
253 /// JITCompilerFn - This function is called when a lazy compilation stub has
254 /// been entered.  It looks up which function this stub corresponds to, compiles
255 /// it if necessary, then returns the resultant function pointer.
256 void *JITResolver::JITCompilerFn(void *Stub) {
257   JITResolver &JR = *TheJITResolver;
258   
259   Function* F = 0;
260   void* ActualPtr = 0;
261
262   {
263     // Only lock for getting the Function. The call getPointerToFunction made
264     // in this function might trigger function materializing, which requires
265     // JIT lock to be unlocked.
266     MutexGuard locked(TheJIT->lock);
267
268     // The address given to us for the stub may not be exactly right, it might be
269     // a little bit after the stub.  As such, use upper_bound to find it.
270     std::map<void*, Function*>::iterator I =
271       JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
272     assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
273            "This is not a known stub!");
274     F = (--I)->second;
275     ActualPtr = I->first;
276   }
277
278   // If we have already code generated the function, just return the address.
279   void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
280   
281   if (!Result) {
282     // Otherwise we don't have it, do lazy compilation now.
283     
284     // If lazy compilation is disabled, emit a useful error message and abort.
285     if (TheJIT->isLazyCompilationDisabled()) {
286       cerr << "LLVM JIT requested to do lazy compilation of function '"
287       << F->getName() << "' when lazy compiles are disabled!\n";
288       abort();
289     }
290   
291     // We might like to remove the stub from the StubToFunction map.
292     // We can't do that! Multiple threads could be stuck, waiting to acquire the
293     // lock above. As soon as the 1st function finishes compiling the function,
294     // the next one will be released, and needs to be able to find the function
295     // it needs to call.
296     //JR.state.getStubToFunctionMap(locked).erase(I);
297
298     DOUT << "JIT: Lazily resolving function '" << F->getName()
299          << "' In stub ptr = " << Stub << " actual ptr = "
300          << ActualPtr << "\n";
301
302     Result = TheJIT->getPointerToFunction(F);
303   }
304   
305   // Reacquire the lock to erase the stub in the map.
306   MutexGuard locked(TheJIT->lock);
307
308   // We don't need to reuse this stub in the future, as F is now compiled.
309   JR.state.getFunctionToStubMap(locked).erase(F);
310
311   // FIXME: We could rewrite all references to this stub if we knew them.
312
313   // What we will do is set the compiled function address to map to the
314   // same GOT entry as the stub so that later clients may update the GOT
315   // if they see it still using the stub address.
316   // Note: this is done so the Resolver doesn't have to manage GOT memory
317   // Do this without allocating map space if the target isn't using a GOT
318   if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
319     JR.revGOTMap[Result] = JR.revGOTMap[Stub];
320
321   return Result;
322 }
323
324 //===----------------------------------------------------------------------===//
325 // Function Index Support
326
327 // On MacOS we generate an index of currently JIT'd functions so that
328 // performance tools can determine a symbol name and accurate code range for a
329 // PC value.  Because performance tools are generally asynchronous, the code
330 // below is written with the hope that it could be interrupted at any time and
331 // have useful answers.  However, we don't go crazy with atomic operations, we
332 // just do a "reasonable effort".
333 #ifdef __APPLE__ 
334 #define ENABLE_JIT_SYMBOL_TABLE 0
335 #endif
336
337 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
338 /// being added to an array of symbols.  This indicates the name of the function
339 /// as well as the address range it occupies.  This allows the client to map
340 /// from a PC value to the name of the function.
341 struct JitSymbolEntry {
342   const char *FnName;   // FnName - a strdup'd string.
343   void *FnStart;
344   intptr_t FnSize;
345 };
346
347
348 struct JitSymbolTable {
349   /// NextPtr - This forms a linked list of JitSymbolTable entries.  This
350   /// pointer is not used right now, but might be used in the future.  Consider
351   /// it reserved for future use.
352   JitSymbolTable *NextPtr;
353   
354   /// Symbols - This is an array of JitSymbolEntry entries.  Only the first
355   /// 'NumSymbols' symbols are valid.
356   JitSymbolEntry *Symbols;
357   
358   /// NumSymbols - This indicates the number entries in the Symbols array that
359   /// are valid.
360   unsigned NumSymbols;
361   
362   /// NumAllocated - This indicates the amount of space we have in the Symbols
363   /// array.  This is a private field that should not be read by external tools.
364   unsigned NumAllocated;
365 };
366
367 #if ENABLE_JIT_SYMBOL_TABLE 
368 JitSymbolTable *__jitSymbolTable;
369 #endif
370
371 static void AddFunctionToSymbolTable(const char *FnName, 
372                                      void *FnStart, intptr_t FnSize) {
373   assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
374   JitSymbolTable **SymTabPtrPtr = 0;
375 #if !ENABLE_JIT_SYMBOL_TABLE
376   return;
377 #else
378   SymTabPtrPtr = &__jitSymbolTable;
379 #endif
380   
381   // If this is the first entry in the symbol table, add the JitSymbolTable
382   // index.
383   if (*SymTabPtrPtr == 0) {
384     JitSymbolTable *New = new JitSymbolTable();
385     New->NextPtr = 0;
386     New->Symbols = 0;
387     New->NumSymbols = 0;
388     New->NumAllocated = 0;
389     *SymTabPtrPtr = New;
390   }
391   
392   JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
393   
394   // If we have space in the table, reallocate the table.
395   if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
396     // If we don't have space, reallocate the table.
397     unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
398     JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
399     JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
400     
401     // Copy the old entries over.
402     memcpy(NewSymbols, OldSymbols,
403            SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
404     
405     // Swap the new symbols in, delete the old ones.
406     SymTabPtr->Symbols = NewSymbols;
407     SymTabPtr->NumAllocated = NewSize;
408     delete [] OldSymbols;
409   }
410   
411   // Otherwise, we have enough space, just tack it onto the end of the array.
412   JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
413   Entry.FnName = strdup(FnName);
414   Entry.FnStart = FnStart;
415   Entry.FnSize = FnSize;
416   ++SymTabPtr->NumSymbols;
417 }
418
419 static void RemoveFunctionFromSymbolTable(void *FnStart) {
420   assert(FnStart && "Invalid function pointer");
421   JitSymbolTable **SymTabPtrPtr = 0;
422 #if !ENABLE_JIT_SYMBOL_TABLE
423   return;
424 #else
425   SymTabPtrPtr = &__jitSymbolTable;
426 #endif
427   
428   JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
429   JitSymbolEntry *Symbols = SymTabPtr->Symbols;
430   
431   // Scan the table to find its index.  The table is not sorted, so do a linear
432   // scan.
433   unsigned Index;
434   for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
435     assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
436   
437   // Once we have an index, we know to nuke this entry, overwrite it with the
438   // entry at the end of the array, making the last entry redundant.
439   const char *OldName = Symbols[Index].FnName;
440   Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
441   free((void*)OldName);
442   
443   // Drop the number of symbols in the table.
444   --SymTabPtr->NumSymbols;
445
446   // Finally, if we deleted the final symbol, deallocate the table itself.
447   if (SymTabPtr->NumSymbols != 0) 
448     return;
449   
450   *SymTabPtrPtr = 0;
451   delete [] Symbols;
452   delete SymTabPtr;
453 }
454
455 //===----------------------------------------------------------------------===//
456 // JITEmitter code.
457 //
458 namespace {
459   /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
460   /// used to output functions to memory for execution.
461   class JITEmitter : public MachineCodeEmitter {
462     JITMemoryManager *MemMgr;
463
464     // When outputting a function stub in the context of some other function, we
465     // save BufferBegin/BufferEnd/CurBufferPtr here.
466     unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
467
468     /// Relocations - These are the relocations that the function needs, as
469     /// emitted.
470     std::vector<MachineRelocation> Relocations;
471     
472     /// MBBLocations - This vector is a mapping from MBB ID's to their address.
473     /// It is filled in by the StartMachineBasicBlock callback and queried by
474     /// the getMachineBasicBlockAddress callback.
475     std::vector<uintptr_t> MBBLocations;
476
477     /// ConstantPool - The constant pool for the current function.
478     ///
479     MachineConstantPool *ConstantPool;
480
481     /// ConstantPoolBase - A pointer to the first entry in the constant pool.
482     ///
483     void *ConstantPoolBase;
484
485     /// JumpTable - The jump tables for the current function.
486     ///
487     MachineJumpTableInfo *JumpTable;
488     
489     /// JumpTableBase - A pointer to the first entry in the jump table.
490     ///
491     void *JumpTableBase;
492
493     /// Resolver - This contains info about the currently resolved functions.
494     JITResolver Resolver;
495     
496     /// DE - The dwarf emitter for the jit.
497     JITDwarfEmitter *DE;
498
499     /// LabelLocations - This vector is a mapping from Label ID's to their 
500     /// address.
501     std::vector<uintptr_t> LabelLocations;
502
503     /// MMI - Machine module info for exception informations
504     MachineModuleInfo* MMI;
505
506     // GVSet - a set to keep track of which globals have been seen
507     SmallPtrSet<const GlobalVariable*, 8> GVSet;
508
509   public:
510     JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
511       MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
512       if (jit.getJITInfo().needsGOT()) {
513         MemMgr->AllocateGOT();
514         DOUT << "JIT is managing a GOT\n";
515       }
516
517       if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
518     }
519     ~JITEmitter() { 
520       delete MemMgr;
521       if (ExceptionHandling) delete DE;
522     }
523
524     /// classof - Methods for support type inquiry through isa, cast, and
525     /// dyn_cast:
526     ///
527     static inline bool classof(const JITEmitter*) { return true; }
528     static inline bool classof(const MachineCodeEmitter*) { return true; }
529     
530     JITResolver &getJITResolver() { return Resolver; }
531
532     virtual void startFunction(MachineFunction &F);
533     virtual bool finishFunction(MachineFunction &F);
534     
535     void emitConstantPool(MachineConstantPool *MCP);
536     void initJumpTableInfo(MachineJumpTableInfo *MJTI);
537     void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
538     
539     virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
540                                    unsigned Alignment = 1);
541     virtual void* finishGVStub(const GlobalValue *GV);
542
543     /// allocateSpace - Reserves space in the current block if any, or
544     /// allocate a new one of the given size.
545     virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
546
547     virtual void addRelocation(const MachineRelocation &MR) {
548       Relocations.push_back(MR);
549     }
550     
551     virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
552       if (MBBLocations.size() <= (unsigned)MBB->getNumber())
553         MBBLocations.resize((MBB->getNumber()+1)*2);
554       MBBLocations[MBB->getNumber()] = getCurrentPCValue();
555       DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
556            << (void*) getCurrentPCValue() << "]\n";
557     }
558
559     virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
560     virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
561
562     virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
563       assert(MBBLocations.size() > (unsigned)MBB->getNumber() && 
564              MBBLocations[MBB->getNumber()] && "MBB not emitted!");
565       return MBBLocations[MBB->getNumber()];
566     }
567
568     /// deallocateMemForFunction - Deallocate all memory for the specified
569     /// function body.
570     void deallocateMemForFunction(Function *F) {
571       MemMgr->deallocateMemForFunction(F);
572     }
573     
574     virtual void emitLabel(uint64_t LabelID) {
575       if (LabelLocations.size() <= LabelID)
576         LabelLocations.resize((LabelID+1)*2);
577       LabelLocations[LabelID] = getCurrentPCValue();
578     }
579
580     virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
581       assert(LabelLocations.size() > (unsigned)LabelID && 
582              LabelLocations[LabelID] && "Label not emitted!");
583       return LabelLocations[LabelID];
584     }
585  
586     virtual void setModuleInfo(MachineModuleInfo* Info) {
587       MMI = Info;
588       if (ExceptionHandling) DE->setModuleInfo(Info);
589     }
590
591     void setMemoryExecutable(void) {
592       MemMgr->setMemoryExecutable();
593     }
594
595   private:
596     void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
597     void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
598                                     bool NoNeedStub);
599     unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
600     unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
601     unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
602     unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
603   };
604 }
605
606 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
607                                      bool DoesntNeedStub) {
608   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
609     /// FIXME: If we straightened things out, this could actually emit the
610     /// global immediately instead of queuing it for codegen later!
611     return TheJIT->getOrEmitGlobalVariable(GV);
612   }
613   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
614     return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
615
616   // If we have already compiled the function, return a pointer to its body.
617   Function *F = cast<Function>(V);
618   void *ResultPtr;
619   if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
620     // Return the function stub if it's already created.
621     ResultPtr = Resolver.getFunctionStubIfAvailable(F);
622   else
623     ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
624   if (ResultPtr) return ResultPtr;
625
626   if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
627     // If this is an external function pointer, we can force the JIT to
628     // 'compile' it, which really just adds it to the map.
629     if (DoesntNeedStub)
630       return TheJIT->getPointerToFunction(F);
631
632     return Resolver.getFunctionStub(F);
633   }
634
635   // Okay, the function has not been compiled yet, if the target callback
636   // mechanism is capable of rewriting the instruction directly, prefer to do
637   // that instead of emitting a stub.
638   if (DoesntNeedStub)
639     return Resolver.AddCallbackAtLocation(F, Reference);
640
641   // Otherwise, we have to emit a lazy resolving stub.
642   return Resolver.getFunctionStub(F);
643 }
644
645 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
646                                             bool NoNeedStub) {
647   // Make sure GV is emitted first.
648   // FIXME: For now, if the GV is an external function we force the JIT to
649   // compile it so the indirect symbol will contain the fully resolved address.
650   void *GVAddress = getPointerToGlobal(V, Reference, true);
651   return Resolver.getGlobalValueIndirectSym(V, GVAddress);
652 }
653
654 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
655   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
656   if (Constants.empty()) return 0;
657
658   MachineConstantPoolEntry CPE = Constants.back();
659   unsigned Size = CPE.Offset;
660   const Type *Ty = CPE.isMachineConstantPoolEntry()
661     ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
662   Size += TheJIT->getTargetData()->getABITypeSize(Ty);
663   return Size;
664 }
665
666 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
667   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
668   if (JT.empty()) return 0;
669   
670   unsigned NumEntries = 0;
671   for (unsigned i = 0, e = JT.size(); i != e; ++i)
672     NumEntries += JT[i].MBBs.size();
673
674   unsigned EntrySize = MJTI->getEntrySize();
675
676   return NumEntries * EntrySize;
677 }
678
679 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
680   if (Alignment == 0) Alignment = 1;
681   // Since we do not know where the buffer will be allocated, be pessimistic. 
682   return Size + Alignment;
683 }
684
685 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
686 /// into the running total Size.
687
688 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
689   const Type *ElTy = GV->getType()->getElementType();
690   size_t GVSize = (size_t)TheJIT->getTargetData()->getABITypeSize(ElTy);
691   size_t GVAlign = 
692       (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
693   DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
694   DEBUG(GV->dump());
695   // Assume code section ends with worst possible alignment, so first
696   // variable needs maximal padding.
697   if (Size==0)
698     Size = 1;
699   Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
700   Size += GVSize;
701   return Size;
702 }
703
704 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
705 /// but are referenced from the constant; put them in GVSet and add their
706 /// size into the running total Size.
707
708 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C, 
709                                               unsigned Size) {
710   // If its undefined, return the garbage.
711   if (isa<UndefValue>(C))
712     return Size;
713
714   // If the value is a ConstantExpr
715   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
716     Constant *Op0 = CE->getOperand(0);
717     switch (CE->getOpcode()) {
718     case Instruction::GetElementPtr:
719     case Instruction::Trunc:
720     case Instruction::ZExt:
721     case Instruction::SExt:
722     case Instruction::FPTrunc:
723     case Instruction::FPExt:
724     case Instruction::UIToFP:
725     case Instruction::SIToFP:
726     case Instruction::FPToUI:
727     case Instruction::FPToSI:
728     case Instruction::PtrToInt:
729     case Instruction::IntToPtr:
730     case Instruction::BitCast: {
731       Size = addSizeOfGlobalsInConstantVal(Op0, Size);
732       break;
733     }
734     case Instruction::Add:
735     case Instruction::Sub:
736     case Instruction::Mul:
737     case Instruction::UDiv:
738     case Instruction::SDiv:
739     case Instruction::URem:
740     case Instruction::SRem:
741     case Instruction::And:
742     case Instruction::Or:
743     case Instruction::Xor: {
744       Size = addSizeOfGlobalsInConstantVal(Op0, Size);
745       Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
746       break;
747     }
748     default: {
749        cerr << "ConstantExpr not handled: " << *CE << "\n";
750       abort();
751     }
752     }
753   }
754
755   if (C->getType()->getTypeID() == Type::PointerTyID)
756     if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
757       if (GVSet.insert(GV))
758         Size = addSizeOfGlobal(GV, Size);
759
760   return Size;
761 }
762
763 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
764 /// but are referenced from the given initializer.
765
766 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init, 
767                                               unsigned Size) {
768   if (!isa<UndefValue>(Init) &&
769       !isa<ConstantVector>(Init) &&
770       !isa<ConstantAggregateZero>(Init) &&
771       !isa<ConstantArray>(Init) &&
772       !isa<ConstantStruct>(Init) &&
773       Init->getType()->isFirstClassType())
774     Size = addSizeOfGlobalsInConstantVal(Init, Size);
775   return Size;
776 }
777
778 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
779 /// globals; then walk the initializers of those globals looking for more.
780 /// If their size has not been considered yet, add it into the running total
781 /// Size.
782
783 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
784   unsigned Size = 0;
785   GVSet.clear();
786
787   for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
788        MBB != E; ++MBB) {
789     for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
790          I != E; ++I) {
791       const TargetInstrDesc &Desc = I->getDesc();
792       const MachineInstr &MI = *I;
793       unsigned NumOps = Desc.getNumOperands();
794       for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
795         const MachineOperand &MO = MI.getOperand(CurOp);
796         if (MO.isGlobal()) {
797           GlobalValue* V = MO.getGlobal();
798           const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
799           if (!GV)
800             continue;
801           // If seen in previous function, it will have an entry here.
802           if (TheJIT->getPointerToGlobalIfAvailable(GV))
803             continue;
804           // If seen earlier in this function, it will have an entry here.
805           // FIXME: it should be possible to combine these tables, by
806           // assuming the addresses of the new globals in this module
807           // start at 0 (or something) and adjusting them after codegen
808           // complete.  Another possibility is to grab a marker bit in GV.
809           if (GVSet.insert(GV))
810             // A variable as yet unseen.  Add in its size.
811             Size = addSizeOfGlobal(GV, Size);
812         }
813       }
814     }
815   }
816   DOUT << "JIT: About to look through initializers\n";
817   // Look for more globals that are referenced only from initializers.
818   // GVSet.end is computed each time because the set can grow as we go.
819   for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin(); 
820        I != GVSet.end(); I++) {
821     const GlobalVariable* GV = *I;
822     if (GV->hasInitializer())
823       Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
824   }
825
826   return Size;
827 }
828
829 void JITEmitter::startFunction(MachineFunction &F) {
830   DOUT << "JIT: Starting CodeGen of Function "
831        << F.getFunction()->getName() << "\n";
832
833   uintptr_t ActualSize = 0;
834   // Set the memory writable, if it's not already
835   MemMgr->setMemoryWritable();
836   if (MemMgr->NeedsExactSize()) {
837     DOUT << "JIT: ExactSize\n";
838     const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
839     MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
840     MachineConstantPool *MCP = F.getConstantPool();
841     
842     // Ensure the constant pool/jump table info is at least 4-byte aligned.
843     ActualSize = RoundUpToAlign(ActualSize, 16);
844     
845     // Add the alignment of the constant pool
846     ActualSize = RoundUpToAlign(ActualSize, 
847                                 1 << MCP->getConstantPoolAlignment());
848
849     // Add the constant pool size
850     ActualSize += GetConstantPoolSizeInBytes(MCP);
851
852     // Add the aligment of the jump table info
853     ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
854
855     // Add the jump table size
856     ActualSize += GetJumpTableSizeInBytes(MJTI);
857     
858     // Add the alignment for the function
859     ActualSize = RoundUpToAlign(ActualSize,
860                                 std::max(F.getFunction()->getAlignment(), 8U));
861
862     // Add the function size
863     ActualSize += TII->GetFunctionSizeInBytes(F);
864
865     DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
866     // Add the size of the globals that will be allocated after this function.
867     // These are all the ones referenced from this function that were not
868     // previously allocated.
869     ActualSize += GetSizeOfGlobalsInBytes(F);
870     DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
871   }
872
873   BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
874                                                          ActualSize);
875   BufferEnd = BufferBegin+ActualSize;
876   
877   // Ensure the constant pool/jump table info is at least 4-byte aligned.
878   emitAlignment(16);
879
880   emitConstantPool(F.getConstantPool());
881   initJumpTableInfo(F.getJumpTableInfo());
882
883   // About to start emitting the machine code for the function.
884   emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
885   TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
886
887   MBBLocations.clear();
888 }
889
890 bool JITEmitter::finishFunction(MachineFunction &F) {
891   if (CurBufferPtr == BufferEnd) {
892     // FIXME: Allocate more space, then try again.
893     cerr << "JIT: Ran out of space for generated machine code!\n";
894     abort();
895   }
896   
897   emitJumpTableInfo(F.getJumpTableInfo());
898   
899   // FnStart is the start of the text, not the start of the constant pool and
900   // other per-function data.
901   unsigned char *FnStart =
902     (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
903
904   if (!Relocations.empty()) {
905     NumRelos += Relocations.size();
906
907     // Resolve the relocations to concrete pointers.
908     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
909       MachineRelocation &MR = Relocations[i];
910       void *ResultPtr = 0;
911       if (!MR.letTargetResolve()) {
912         if (MR.isExternalSymbol()) {
913           ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
914                                                         false);
915           DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
916                << ResultPtr << "]\n";  
917
918           // If the target REALLY wants a stub for this function, emit it now.
919           if (!MR.doesntNeedStub())
920             ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
921         } else if (MR.isGlobalValue()) {
922           ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
923                                          BufferBegin+MR.getMachineCodeOffset(),
924                                          MR.doesntNeedStub());
925         } else if (MR.isIndirectSymbol()) {
926           ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
927                                           BufferBegin+MR.getMachineCodeOffset(),
928                                           MR.doesntNeedStub());
929         } else if (MR.isBasicBlock()) {
930           ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
931         } else if (MR.isConstantPoolIndex()) {
932           ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
933         } else {
934           assert(MR.isJumpTableIndex());
935           ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
936         }
937
938         MR.setResultPointer(ResultPtr);
939       }
940
941       // if we are managing the GOT and the relocation wants an index,
942       // give it one
943       if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
944         unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
945         MR.setGOTIndex(idx);
946         if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
947           DOUT << "JIT: GOT was out of date for " << ResultPtr
948                << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
949                << "\n";
950           ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
951         }
952       }
953     }
954
955     TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
956                                   Relocations.size(), MemMgr->getGOTBase());
957   }
958
959   // Update the GOT entry for F to point to the new code.
960   if (MemMgr->isManagingGOT()) {
961     unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
962     if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
963       DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
964            << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
965       ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
966     }
967   }
968
969   unsigned char *FnEnd = CurBufferPtr;
970
971   MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
972
973   if (CurBufferPtr == BufferEnd) {
974     // FIXME: Allocate more space, then try again.
975     cerr << "JIT: Ran out of space for generated machine code!\n";
976     abort();
977   }
978
979   BufferBegin = CurBufferPtr = 0;
980   NumBytes += FnEnd-FnStart;
981
982   // Invalidate the icache if necessary.
983   sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
984   
985   // Add it to the JIT symbol table if the host wants it.
986   AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
987                            FnStart, FnEnd-FnStart);
988
989   DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
990        << "] Function: " << F.getFunction()->getName()
991        << ": " << (FnEnd-FnStart) << " bytes of text, "
992        << Relocations.size() << " relocations\n";
993   Relocations.clear();
994
995   // Mark code region readable and executable if it's not so already.
996   MemMgr->setMemoryExecutable();
997
998 #ifndef NDEBUG
999   {
1000     if (sys::hasDisassembler()) {
1001       DOUT << "JIT: Disassembled code:\n";
1002       DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
1003     } else {
1004       DOUT << "JIT: Binary code:\n";
1005       DOUT << std::hex;
1006       unsigned char* q = FnStart;
1007       for (int i = 0; q < FnEnd; q += 4, ++i) {
1008         if (i == 4)
1009           i = 0;
1010         if (i == 0)
1011           DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1012                << (long)(q - FnStart) << ": ";
1013         bool Done = false;
1014         for (int j = 3; j >= 0; --j) {
1015           if (q + j >= FnEnd)
1016             Done = true;
1017           else
1018             DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1019         }
1020         if (Done)
1021           break;
1022         DOUT << ' ';
1023         if (i == 3)
1024           DOUT << '\n';
1025       }
1026       DOUT << std::dec;
1027       DOUT<< '\n';
1028     }
1029   }
1030 #endif
1031   if (ExceptionHandling) {
1032     uintptr_t ActualSize = 0;
1033     SavedBufferBegin = BufferBegin;
1034     SavedBufferEnd = BufferEnd;
1035     SavedCurBufferPtr = CurBufferPtr;
1036     
1037     if (MemMgr->NeedsExactSize()) {
1038       ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1039     }
1040
1041     BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1042                                                              ActualSize);
1043     BufferEnd = BufferBegin+ActualSize;
1044     unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
1045     MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1046                               FrameRegister);
1047     BufferBegin = SavedBufferBegin;
1048     BufferEnd = SavedBufferEnd;
1049     CurBufferPtr = SavedCurBufferPtr;
1050
1051     TheJIT->RegisterTable(FrameRegister);
1052   }
1053
1054   if (MMI)
1055     MMI->EndFunction();
1056  
1057   return false;
1058 }
1059
1060 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1061   if (BufferBegin)
1062     return MachineCodeEmitter::allocateSpace(Size, Alignment);
1063
1064   // create a new memory block if there is no active one.
1065   // care must be taken so that BufferBegin is invalidated when a
1066   // block is trimmed
1067   BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1068   BufferEnd = BufferBegin+Size;
1069   return CurBufferPtr;
1070 }
1071
1072 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1073   if (TheJIT->getJITInfo().hasCustomConstantPool())
1074     return;
1075
1076   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1077   if (Constants.empty()) return;
1078
1079   MachineConstantPoolEntry CPE = Constants.back();
1080   unsigned Size = CPE.Offset;
1081   const Type *Ty = CPE.isMachineConstantPoolEntry()
1082     ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
1083   Size += TheJIT->getTargetData()->getABITypeSize(Ty);
1084
1085   unsigned Align = 1 << MCP->getConstantPoolAlignment();
1086   ConstantPoolBase = allocateSpace(Size, Align);
1087   ConstantPool = MCP;
1088
1089   if (ConstantPoolBase == 0) return;  // Buffer overflow.
1090
1091   DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1092        << "] (size: " << Size << ", alignment: " << Align << ")\n";
1093
1094   // Initialize the memory for all of the constant pool entries.
1095   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1096     void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
1097     if (Constants[i].isMachineConstantPoolEntry()) {
1098       // FIXME: add support to lower machine constant pool values into bytes!
1099       cerr << "Initialize memory with machine specific constant pool entry"
1100            << " has not been implemented!\n";
1101       abort();
1102     }
1103     TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
1104     DOUT << "JIT:   CP" << i << " at [" << CAddr << "]\n";
1105   }
1106 }
1107
1108 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1109   if (TheJIT->getJITInfo().hasCustomJumpTables())
1110     return;
1111
1112   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1113   if (JT.empty()) return;
1114   
1115   unsigned NumEntries = 0;
1116   for (unsigned i = 0, e = JT.size(); i != e; ++i)
1117     NumEntries += JT[i].MBBs.size();
1118
1119   unsigned EntrySize = MJTI->getEntrySize();
1120
1121   // Just allocate space for all the jump tables now.  We will fix up the actual
1122   // MBB entries in the tables after we emit the code for each block, since then
1123   // we will know the final locations of the MBBs in memory.
1124   JumpTable = MJTI;
1125   JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1126 }
1127
1128 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1129   if (TheJIT->getJITInfo().hasCustomJumpTables())
1130     return;
1131
1132   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1133   if (JT.empty() || JumpTableBase == 0) return;
1134   
1135   if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1136     assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1137     // For each jump table, place the offset from the beginning of the table
1138     // to the target address.
1139     int *SlotPtr = (int*)JumpTableBase;
1140
1141     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1142       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1143       // Store the offset of the basic block for this jump table slot in the
1144       // memory we allocated for the jump table in 'initJumpTableInfo'
1145       uintptr_t Base = (uintptr_t)SlotPtr;
1146       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1147         uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1148         *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1149       }
1150     }
1151   } else {
1152     assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1153     
1154     // For each jump table, map each target in the jump table to the address of 
1155     // an emitted MachineBasicBlock.
1156     intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1157
1158     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1159       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1160       // Store the address of the basic block for this jump table slot in the
1161       // memory we allocated for the jump table in 'initJumpTableInfo'
1162       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1163         *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1164     }
1165   }
1166 }
1167
1168 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1169                              unsigned Alignment) {
1170   SavedBufferBegin = BufferBegin;
1171   SavedBufferEnd = BufferEnd;
1172   SavedCurBufferPtr = CurBufferPtr;
1173   
1174   BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1175   BufferEnd = BufferBegin+StubSize+1;
1176 }
1177
1178 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1179   NumBytes += getCurrentPCOffset();
1180   std::swap(SavedBufferBegin, BufferBegin);
1181   BufferEnd = SavedBufferEnd;
1182   CurBufferPtr = SavedCurBufferPtr;
1183   return SavedBufferBegin;
1184 }
1185
1186 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1187 // in the constant pool that was last emitted with the 'emitConstantPool'
1188 // method.
1189 //
1190 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1191   assert(ConstantNum < ConstantPool->getConstants().size() &&
1192          "Invalid ConstantPoolIndex!");
1193   return (uintptr_t)ConstantPoolBase +
1194          ConstantPool->getConstants()[ConstantNum].Offset;
1195 }
1196
1197 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1198 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1199 //
1200 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1201   const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1202   assert(Index < JT.size() && "Invalid jump table index!");
1203   
1204   unsigned Offset = 0;
1205   unsigned EntrySize = JumpTable->getEntrySize();
1206   
1207   for (unsigned i = 0; i < Index; ++i)
1208     Offset += JT[i].MBBs.size();
1209   
1210    Offset *= EntrySize;
1211   
1212   return (uintptr_t)((char *)JumpTableBase + Offset);
1213 }
1214
1215 //===----------------------------------------------------------------------===//
1216 //  Public interface to this file
1217 //===----------------------------------------------------------------------===//
1218
1219 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1220   return new JITEmitter(jit, JMM);
1221 }
1222
1223 // getPointerToNamedFunction - This function is used as a global wrapper to
1224 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1225 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1226 // need to resolve function(s) that are being mis-codegenerated, so we need to
1227 // resolve their addresses at runtime, and this is the way to do it.
1228 extern "C" {
1229   void *getPointerToNamedFunction(const char *Name) {
1230     if (Function *F = TheJIT->FindFunctionNamed(Name))
1231       return TheJIT->getPointerToFunction(F);
1232     return TheJIT->getPointerToNamedFunction(Name);
1233   }
1234 }
1235
1236 // getPointerToFunctionOrStub - If the specified function has been
1237 // code-gen'd, return a pointer to the function.  If not, compile it, or use
1238 // a stub to implement lazy compilation if available.
1239 //
1240 void *JIT::getPointerToFunctionOrStub(Function *F) {
1241   // If we have already code generated the function, just return the address.
1242   if (void *Addr = getPointerToGlobalIfAvailable(F))
1243     return Addr;
1244   
1245   // Get a stub if the target supports it.
1246   assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1247   JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1248   return JE->getJITResolver().getFunctionStub(F);
1249 }
1250
1251 /// freeMachineCodeForFunction - release machine code memory for given Function.
1252 ///
1253 void JIT::freeMachineCodeForFunction(Function *F) {
1254
1255   // Delete translation for this from the ExecutionEngine, so it will get
1256   // retranslated next time it is used.
1257   void *OldPtr = updateGlobalMapping(F, 0);
1258
1259   if (OldPtr)
1260     RemoveFunctionFromSymbolTable(OldPtr);
1261
1262   // Free the actual memory for the function body and related stuff.
1263   assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1264   cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
1265 }
1266