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