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