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