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