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