b0e48cae18c91572a76985bbb741888f726aad2c
[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 "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/JITCodeEmitter.h"
22 #include "llvm/CodeGen/MachineCodeInfo.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineJumpTableInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/MachineRelocation.h"
28 #include "llvm/ExecutionEngine/GenericValue.h"
29 #include "llvm/ExecutionEngine/JITEventListener.h"
30 #include "llvm/ExecutionEngine/JITMemoryManager.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/ValueHandle.h"
37 #include "llvm/IR/ValueMap.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Disassembler.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/Memory.h"
43 #include "llvm/Support/MutexGuard.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetJITInfo.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include <algorithm>
50 #ifndef NDEBUG
51 #include <iomanip>
52 #endif
53 using namespace llvm;
54
55 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
56 STATISTIC(NumRelos, "Number of relocations applied");
57 STATISTIC(NumRetries, "Number of retries with more memory");
58
59
60 // A declaration may stop being a declaration once it's fully read from bitcode.
61 // This function returns true if F is fully read and is still a declaration.
62 static bool isNonGhostDeclaration(const Function *F) {
63   return F->isDeclaration() && !F->isMaterializable();
64 }
65
66 //===----------------------------------------------------------------------===//
67 // JIT lazy compilation code.
68 //
69 namespace {
70   class JITEmitter;
71   class JITResolverState;
72
73   template<typename ValueTy>
74   struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
75     typedef JITResolverState *ExtraData;
76     static void onRAUW(JITResolverState *, Value *Old, Value *New) {
77       llvm_unreachable("The JIT doesn't know how to handle a"
78                        " RAUW on a value it has emitted.");
79     }
80   };
81
82   struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
83     typedef JITResolverState *ExtraData;
84     static void onDelete(JITResolverState *JRS, Function *F);
85   };
86
87   class JITResolverState {
88   public:
89     typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
90       FunctionToLazyStubMapTy;
91     typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
92     typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
93                      CallSiteValueMapConfig> FunctionToCallSitesMapTy;
94     typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
95   private:
96     /// FunctionToLazyStubMap - Keep track of the lazy stub created for a
97     /// particular function so that we can reuse them if necessary.
98     FunctionToLazyStubMapTy FunctionToLazyStubMap;
99
100     /// CallSiteToFunctionMap - Keep track of the function that each lazy call
101     /// site corresponds to, and vice versa.
102     CallSiteToFunctionMapTy CallSiteToFunctionMap;
103     FunctionToCallSitesMapTy FunctionToCallSitesMap;
104
105     /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
106     /// particular GlobalVariable so that we can reuse them if necessary.
107     GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
108
109 #ifndef NDEBUG
110     /// Instance of the JIT this ResolverState serves.
111     JIT *TheJIT;
112 #endif
113
114   public:
115     JITResolverState(JIT *jit) : FunctionToLazyStubMap(this),
116                                  FunctionToCallSitesMap(this) {
117 #ifndef NDEBUG
118       TheJIT = jit;
119 #endif
120     }
121
122     FunctionToLazyStubMapTy& getFunctionToLazyStubMap(
123       const MutexGuard& locked) {
124       assert(locked.holds(TheJIT->lock));
125       return FunctionToLazyStubMap;
126     }
127
128     GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& lck) {
129       assert(lck.holds(TheJIT->lock));
130       return GlobalToIndirectSymMap;
131     }
132
133     std::pair<void *, Function *> LookupFunctionFromCallSite(
134         const MutexGuard &locked, void *CallSite) const {
135       assert(locked.holds(TheJIT->lock));
136
137       // The address given to us for the stub may not be exactly right, it
138       // might be a little bit after the stub.  As such, use upper_bound to
139       // find it.
140       CallSiteToFunctionMapTy::const_iterator I =
141         CallSiteToFunctionMap.upper_bound(CallSite);
142       assert(I != CallSiteToFunctionMap.begin() &&
143              "This is not a known call site!");
144       --I;
145       return *I;
146     }
147
148     void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
149       assert(locked.holds(TheJIT->lock));
150
151       bool Inserted = CallSiteToFunctionMap.insert(
152           std::make_pair(CallSite, F)).second;
153       (void)Inserted;
154       assert(Inserted && "Pair was already in CallSiteToFunctionMap");
155       FunctionToCallSitesMap[F].insert(CallSite);
156     }
157
158     void EraseAllCallSitesForPrelocked(Function *F);
159
160     // Erases _all_ call sites regardless of their function.  This is used to
161     // unregister the stub addresses from the StubToResolverMap in
162     // ~JITResolver().
163     void EraseAllCallSitesPrelocked();
164   };
165
166   /// JITResolver - Keep track of, and resolve, call sites for functions that
167   /// have not yet been compiled.
168   class JITResolver {
169     typedef JITResolverState::FunctionToLazyStubMapTy FunctionToLazyStubMapTy;
170     typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
171     typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
172
173     /// LazyResolverFn - The target lazy resolver function that we actually
174     /// rewrite instructions to use.
175     TargetJITInfo::LazyResolverFn LazyResolverFn;
176
177     JITResolverState state;
178
179     /// ExternalFnToStubMap - This is the equivalent of FunctionToLazyStubMap
180     /// for external functions.  TODO: Of course, external functions don't need
181     /// a lazy stub.  It's actually here to make it more likely that far calls
182     /// succeed, but no single stub can guarantee that.  I'll remove this in a
183     /// subsequent checkin when I actually fix far calls.
184     std::map<void*, void*> ExternalFnToStubMap;
185
186     /// revGOTMap - map addresses to indexes in the GOT
187     std::map<void*, unsigned> revGOTMap;
188     unsigned nextGOTIndex;
189
190     JITEmitter &JE;
191
192     /// Instance of JIT corresponding to this Resolver.
193     JIT *TheJIT;
194
195   public:
196     explicit JITResolver(JIT &jit, JITEmitter &je)
197       : state(&jit), nextGOTIndex(0), JE(je), TheJIT(&jit) {
198       LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
199     }
200
201     ~JITResolver();
202
203     /// getLazyFunctionStubIfAvailable - This returns a pointer to a function's
204     /// lazy-compilation stub if it has already been created.
205     void *getLazyFunctionStubIfAvailable(Function *F);
206
207     /// getLazyFunctionStub - This returns a pointer to a function's
208     /// lazy-compilation stub, creating one on demand as needed.
209     void *getLazyFunctionStub(Function *F);
210
211     /// getExternalFunctionStub - Return a stub for the function at the
212     /// specified address, created lazily on demand.
213     void *getExternalFunctionStub(void *FnAddr);
214
215     /// getGlobalValueIndirectSym - Return an indirect symbol containing the
216     /// specified GV address.
217     void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
218
219     /// getGOTIndexForAddress - Return a new or existing index in the GOT for
220     /// an address.  This function only manages slots, it does not manage the
221     /// contents of the slots or the memory associated with the GOT.
222     unsigned getGOTIndexForAddr(void *addr);
223
224     /// JITCompilerFn - This function is called to resolve a stub to a compiled
225     /// address.  If the LLVM Function corresponding to the stub has not yet
226     /// been compiled, this function compiles it first.
227     static void *JITCompilerFn(void *Stub);
228   };
229
230   class StubToResolverMapTy {
231     /// Map a stub address to a specific instance of a JITResolver so that
232     /// lazily-compiled functions can find the right resolver to use.
233     ///
234     /// Guarded by Lock.
235     std::map<void*, JITResolver*> Map;
236
237     /// Guards Map from concurrent accesses.
238     mutable sys::Mutex Lock;
239
240   public:
241     /// Registers a Stub to be resolved by Resolver.
242     void RegisterStubResolver(void *Stub, JITResolver *Resolver) {
243       MutexGuard guard(Lock);
244       Map.insert(std::make_pair(Stub, Resolver));
245     }
246     /// Unregisters the Stub when it's invalidated.
247     void UnregisterStubResolver(void *Stub) {
248       MutexGuard guard(Lock);
249       Map.erase(Stub);
250     }
251     /// Returns the JITResolver instance that owns the Stub.
252     JITResolver *getResolverFromStub(void *Stub) const {
253       MutexGuard guard(Lock);
254       // The address given to us for the stub may not be exactly right, it might
255       // be a little bit after the stub.  As such, use upper_bound to find it.
256       // This is the same trick as in LookupFunctionFromCallSite from
257       // JITResolverState.
258       std::map<void*, JITResolver*>::const_iterator I = Map.upper_bound(Stub);
259       assert(I != Map.begin() && "This is not a known stub!");
260       --I;
261       return I->second;
262     }
263     /// True if any stubs refer to the given resolver. Only used in an assert().
264     /// O(N)
265     bool ResolverHasStubs(JITResolver* Resolver) const {
266       MutexGuard guard(Lock);
267       for (std::map<void*, JITResolver*>::const_iterator I = Map.begin(),
268              E = Map.end(); I != E; ++I) {
269         if (I->second == Resolver)
270           return true;
271       }
272       return false;
273     }
274   };
275   /// This needs to be static so that a lazy call stub can access it with no
276   /// context except the address of the stub.
277   ManagedStatic<StubToResolverMapTy> StubToResolverMap;
278
279   /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
280   /// used to output functions to memory for execution.
281   class JITEmitter : public JITCodeEmitter {
282     JITMemoryManager *MemMgr;
283
284     // When outputting a function stub in the context of some other function, we
285     // save BufferBegin/BufferEnd/CurBufferPtr here.
286     uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
287
288     // When reattempting to JIT a function after running out of space, we store
289     // the estimated size of the function we're trying to JIT here, so we can
290     // ask the memory manager for at least this much space.  When we
291     // successfully emit the function, we reset this back to zero.
292     uintptr_t SizeEstimate;
293
294     /// Relocations - These are the relocations that the function needs, as
295     /// emitted.
296     std::vector<MachineRelocation> Relocations;
297
298     /// MBBLocations - This vector is a mapping from MBB ID's to their address.
299     /// It is filled in by the StartMachineBasicBlock callback and queried by
300     /// the getMachineBasicBlockAddress callback.
301     std::vector<uintptr_t> MBBLocations;
302
303     /// ConstantPool - The constant pool for the current function.
304     ///
305     MachineConstantPool *ConstantPool;
306
307     /// ConstantPoolBase - A pointer to the first entry in the constant pool.
308     ///
309     void *ConstantPoolBase;
310
311     /// ConstPoolAddresses - Addresses of individual constant pool entries.
312     ///
313     SmallVector<uintptr_t, 8> ConstPoolAddresses;
314
315     /// JumpTable - The jump tables for the current function.
316     ///
317     MachineJumpTableInfo *JumpTable;
318
319     /// JumpTableBase - A pointer to the first entry in the jump table.
320     ///
321     void *JumpTableBase;
322
323     /// Resolver - This contains info about the currently resolved functions.
324     JITResolver Resolver;
325
326     /// LabelLocations - This vector is a mapping from Label ID's to their
327     /// address.
328     DenseMap<MCSymbol*, uintptr_t> LabelLocations;
329
330     /// MMI - Machine module info for exception informations
331     MachineModuleInfo* MMI;
332
333     // CurFn - The llvm function being emitted.  Only valid during
334     // finishFunction().
335     const Function *CurFn;
336
337     /// Information about emitted code, which is passed to the
338     /// JITEventListeners.  This is reset in startFunction and used in
339     /// finishFunction.
340     JITEvent_EmittedFunctionDetails EmissionDetails;
341
342     struct EmittedCode {
343       void *FunctionBody;  // Beginning of the function's allocation.
344       void *Code;  // The address the function's code actually starts at.
345       void *ExceptionTable;
346       EmittedCode() : FunctionBody(0), Code(0), ExceptionTable(0) {}
347     };
348     struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
349       typedef JITEmitter *ExtraData;
350       static void onDelete(JITEmitter *, const Function*);
351       static void onRAUW(JITEmitter *, const Function*, const Function*);
352     };
353     ValueMap<const Function *, EmittedCode,
354              EmittedFunctionConfig> EmittedFunctions;
355
356     DebugLoc PrevDL;
357
358     /// Instance of the JIT
359     JIT *TheJIT;
360
361   public:
362     JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
363       : SizeEstimate(0), Resolver(jit, *this), MMI(0), CurFn(0),
364         EmittedFunctions(this), TheJIT(&jit) {
365       MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
366       if (jit.getJITInfo().needsGOT()) {
367         MemMgr->AllocateGOT();
368         DEBUG(dbgs() << "JIT is managing a GOT\n");
369       }
370
371     }
372     ~JITEmitter() {
373       delete MemMgr;
374     }
375
376     JITResolver &getJITResolver() { return Resolver; }
377
378     virtual void startFunction(MachineFunction &F);
379     virtual bool finishFunction(MachineFunction &F);
380
381     void emitConstantPool(MachineConstantPool *MCP);
382     void initJumpTableInfo(MachineJumpTableInfo *MJTI);
383     void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
384
385     void startGVStub(const GlobalValue* GV,
386                      unsigned StubSize, unsigned Alignment = 1);
387     void startGVStub(void *Buffer, unsigned StubSize);
388     void finishGVStub();
389     virtual void *allocIndirectGV(const GlobalValue *GV,
390                                   const uint8_t *Buffer, size_t Size,
391                                   unsigned Alignment);
392
393     /// allocateSpace - Reserves space in the current block if any, or
394     /// allocate a new one of the given size.
395     virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
396
397     /// allocateGlobal - Allocate memory for a global.  Unlike allocateSpace,
398     /// this method does not allocate memory in the current output buffer,
399     /// because a global may live longer than the current function.
400     virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
401
402     virtual void addRelocation(const MachineRelocation &MR) {
403       Relocations.push_back(MR);
404     }
405
406     virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
407       if (MBBLocations.size() <= (unsigned)MBB->getNumber())
408         MBBLocations.resize((MBB->getNumber()+1)*2);
409       MBBLocations[MBB->getNumber()] = getCurrentPCValue();
410       if (MBB->hasAddressTaken())
411         TheJIT->addPointerToBasicBlock(MBB->getBasicBlock(),
412                                        (void*)getCurrentPCValue());
413       DEBUG(dbgs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
414                    << (void*) getCurrentPCValue() << "]\n");
415     }
416
417     virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
418     virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
419
420     virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const{
421       assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
422              MBBLocations[MBB->getNumber()] && "MBB not emitted!");
423       return MBBLocations[MBB->getNumber()];
424     }
425
426     /// retryWithMoreMemory - Log a retry and deallocate all memory for the
427     /// given function.  Increase the minimum allocation size so that we get
428     /// more memory next time.
429     void retryWithMoreMemory(MachineFunction &F);
430
431     /// deallocateMemForFunction - Deallocate all memory for the specified
432     /// function body.
433     void deallocateMemForFunction(const Function *F);
434
435     virtual void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn);
436
437     virtual void emitLabel(MCSymbol *Label) {
438       LabelLocations[Label] = getCurrentPCValue();
439     }
440
441     virtual DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() {
442       return &LabelLocations;
443     }
444
445     virtual uintptr_t getLabelAddress(MCSymbol *Label) const {
446       assert(LabelLocations.count(Label) && "Label not emitted!");
447       return LabelLocations.find(Label)->second;
448     }
449
450     virtual void setModuleInfo(MachineModuleInfo* Info) {
451       MMI = Info;
452     }
453
454   private:
455     void *getPointerToGlobal(GlobalValue *GV, void *Reference,
456                              bool MayNeedFarStub);
457     void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference);
458   };
459 }
460
461 void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
462   JRS->EraseAllCallSitesForPrelocked(F);
463 }
464
465 void JITResolverState::EraseAllCallSitesForPrelocked(Function *F) {
466   FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
467   if (F2C == FunctionToCallSitesMap.end())
468     return;
469   StubToResolverMapTy &S2RMap = *StubToResolverMap;
470   for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
471          E = F2C->second.end(); I != E; ++I) {
472     S2RMap.UnregisterStubResolver(*I);
473     bool Erased = CallSiteToFunctionMap.erase(*I);
474     (void)Erased;
475     assert(Erased && "Missing call site->function mapping");
476   }
477   FunctionToCallSitesMap.erase(F2C);
478 }
479
480 void JITResolverState::EraseAllCallSitesPrelocked() {
481   StubToResolverMapTy &S2RMap = *StubToResolverMap;
482   for (CallSiteToFunctionMapTy::const_iterator
483          I = CallSiteToFunctionMap.begin(),
484          E = CallSiteToFunctionMap.end(); I != E; ++I) {
485     S2RMap.UnregisterStubResolver(I->first);
486   }
487   CallSiteToFunctionMap.clear();
488   FunctionToCallSitesMap.clear();
489 }
490
491 JITResolver::~JITResolver() {
492   // No need to lock because we're in the destructor, and state isn't shared.
493   state.EraseAllCallSitesPrelocked();
494   assert(!StubToResolverMap->ResolverHasStubs(this) &&
495          "Resolver destroyed with stubs still alive.");
496 }
497
498 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function stub
499 /// if it has already been created.
500 void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
501   MutexGuard locked(TheJIT->lock);
502
503   // If we already have a stub for this function, recycle it.
504   return state.getFunctionToLazyStubMap(locked).lookup(F);
505 }
506
507 /// getFunctionStub - This returns a pointer to a function stub, creating
508 /// one on demand as needed.
509 void *JITResolver::getLazyFunctionStub(Function *F) {
510   MutexGuard locked(TheJIT->lock);
511
512   // If we already have a lazy stub for this function, recycle it.
513   void *&Stub = state.getFunctionToLazyStubMap(locked)[F];
514   if (Stub) return Stub;
515
516   // Call the lazy resolver function if we are JIT'ing lazily.  Otherwise we
517   // must resolve the symbol now.
518   void *Actual = TheJIT->isCompilingLazily()
519     ? (void *)(intptr_t)LazyResolverFn : (void *)0;
520
521   // If this is an external declaration, attempt to resolve the address now
522   // to place in the stub.
523   if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage()) {
524     Actual = TheJIT->getPointerToFunction(F);
525
526     // If we resolved the symbol to a null address (eg. a weak external)
527     // don't emit a stub. Return a null pointer to the application.
528     if (!Actual) return 0;
529   }
530
531   TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
532   JE.startGVStub(F, SL.Size, SL.Alignment);
533   // Codegen a new stub, calling the lazy resolver or the actual address of the
534   // external function, if it was resolved.
535   Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
536   JE.finishGVStub();
537
538   if (Actual != (void*)(intptr_t)LazyResolverFn) {
539     // If we are getting the stub for an external function, we really want the
540     // address of the stub in the GlobalAddressMap for the JIT, not the address
541     // of the external function.
542     TheJIT->updateGlobalMapping(F, Stub);
543   }
544
545   DEBUG(dbgs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
546         << F->getName() << "'\n");
547
548   if (TheJIT->isCompilingLazily()) {
549     // Register this JITResolver as the one corresponding to this call site so
550     // JITCompilerFn will be able to find it.
551     StubToResolverMap->RegisterStubResolver(Stub, this);
552
553     // Finally, keep track of the stub-to-Function mapping so that the
554     // JITCompilerFn knows which function to compile!
555     state.AddCallSite(locked, Stub, F);
556   } else if (!Actual) {
557     // If we are JIT'ing non-lazily but need to call a function that does not
558     // exist yet, add it to the JIT's work list so that we can fill in the
559     // stub address later.
560     assert(!isNonGhostDeclaration(F) && !F->hasAvailableExternallyLinkage() &&
561            "'Actual' should have been set above.");
562     TheJIT->addPendingFunction(F);
563   }
564
565   return Stub;
566 }
567
568 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
569 /// GV address.
570 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
571   MutexGuard locked(TheJIT->lock);
572
573   // If we already have a stub for this global variable, recycle it.
574   void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
575   if (IndirectSym) return IndirectSym;
576
577   // Otherwise, codegen a new indirect symbol.
578   IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
579                                                                 JE);
580
581   DEBUG(dbgs() << "JIT: Indirect symbol emitted at [" << IndirectSym
582         << "] for GV '" << GV->getName() << "'\n");
583
584   return IndirectSym;
585 }
586
587 /// getExternalFunctionStub - Return a stub for the function at the
588 /// specified address, created lazily on demand.
589 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
590   // If we already have a stub for this function, recycle it.
591   void *&Stub = ExternalFnToStubMap[FnAddr];
592   if (Stub) return Stub;
593
594   TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
595   JE.startGVStub(0, SL.Size, SL.Alignment);
596   Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr, JE);
597   JE.finishGVStub();
598
599   DEBUG(dbgs() << "JIT: Stub emitted at [" << Stub
600                << "] for external function at '" << FnAddr << "'\n");
601   return Stub;
602 }
603
604 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
605   unsigned idx = revGOTMap[addr];
606   if (!idx) {
607     idx = ++nextGOTIndex;
608     revGOTMap[addr] = idx;
609     DEBUG(dbgs() << "JIT: Adding GOT entry " << idx << " for addr ["
610                  << addr << "]\n");
611   }
612   return idx;
613 }
614
615 /// JITCompilerFn - This function is called when a lazy compilation stub has
616 /// been entered.  It looks up which function this stub corresponds to, compiles
617 /// it if necessary, then returns the resultant function pointer.
618 void *JITResolver::JITCompilerFn(void *Stub) {
619   JITResolver *JR = StubToResolverMap->getResolverFromStub(Stub);
620   assert(JR && "Unable to find the corresponding JITResolver to the call site");
621
622   Function* F = 0;
623   void* ActualPtr = 0;
624
625   {
626     // Only lock for getting the Function. The call getPointerToFunction made
627     // in this function might trigger function materializing, which requires
628     // JIT lock to be unlocked.
629     MutexGuard locked(JR->TheJIT->lock);
630
631     // The address given to us for the stub may not be exactly right, it might
632     // be a little bit after the stub.  As such, use upper_bound to find it.
633     std::pair<void*, Function*> I =
634       JR->state.LookupFunctionFromCallSite(locked, Stub);
635     F = I.second;
636     ActualPtr = I.first;
637   }
638
639   // If we have already code generated the function, just return the address.
640   void *Result = JR->TheJIT->getPointerToGlobalIfAvailable(F);
641
642   if (!Result) {
643     // Otherwise we don't have it, do lazy compilation now.
644
645     // If lazy compilation is disabled, emit a useful error message and abort.
646     if (!JR->TheJIT->isCompilingLazily()) {
647       report_fatal_error("LLVM JIT requested to do lazy compilation of"
648                          " function '"
649                         + F->getName() + "' when lazy compiles are disabled!");
650     }
651
652     DEBUG(dbgs() << "JIT: Lazily resolving function '" << F->getName()
653           << "' In stub ptr = " << Stub << " actual ptr = "
654           << ActualPtr << "\n");
655     (void)ActualPtr;
656
657     Result = JR->TheJIT->getPointerToFunction(F);
658   }
659
660   // Reacquire the lock to update the GOT map.
661   MutexGuard locked(JR->TheJIT->lock);
662
663   // We might like to remove the call site from the CallSiteToFunction map, but
664   // we can't do that! Multiple threads could be stuck, waiting to acquire the
665   // lock above. As soon as the 1st function finishes compiling the function,
666   // the next one will be released, and needs to be able to find the function it
667   // needs to call.
668
669   // FIXME: We could rewrite all references to this stub if we knew them.
670
671   // What we will do is set the compiled function address to map to the
672   // same GOT entry as the stub so that later clients may update the GOT
673   // if they see it still using the stub address.
674   // Note: this is done so the Resolver doesn't have to manage GOT memory
675   // Do this without allocating map space if the target isn't using a GOT
676   if(JR->revGOTMap.find(Stub) != JR->revGOTMap.end())
677     JR->revGOTMap[Result] = JR->revGOTMap[Stub];
678
679   return Result;
680 }
681
682 //===----------------------------------------------------------------------===//
683 // JITEmitter code.
684 //
685 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
686                                      bool MayNeedFarStub) {
687   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
688     return TheJIT->getOrEmitGlobalVariable(GV);
689
690   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
691     return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
692
693   // If we have already compiled the function, return a pointer to its body.
694   Function *F = cast<Function>(V);
695
696   void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
697   if (FnStub) {
698     // Return the function stub if it's already created.  We do this first so
699     // that we're returning the same address for the function as any previous
700     // call.  TODO: Yes, this is wrong. The lazy stub isn't guaranteed to be
701     // close enough to call.
702     return FnStub;
703   }
704
705   // If we know the target can handle arbitrary-distance calls, try to
706   // return a direct pointer.
707   if (!MayNeedFarStub) {
708     // If we have code, go ahead and return that.
709     void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
710     if (ResultPtr) return ResultPtr;
711
712     // If this is an external function pointer, we can force the JIT to
713     // 'compile' it, which really just adds it to the map.
714     if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage())
715       return TheJIT->getPointerToFunction(F);
716   }
717
718   // Otherwise, we may need a to emit a stub, and, conservatively, we always do
719   // so.  Note that it's possible to return null from getLazyFunctionStub in the
720   // case of a weak extern that fails to resolve.
721   return Resolver.getLazyFunctionStub(F);
722 }
723
724 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
725   // Make sure GV is emitted first, and create a stub containing the fully
726   // resolved address.
727   void *GVAddress = getPointerToGlobal(V, Reference, false);
728   void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
729   return StubAddr;
730 }
731
732 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
733   if (DL.isUnknown()) return;
734   if (!BeforePrintingInsn) return;
735
736   const LLVMContext &Context = EmissionDetails.MF->getFunction()->getContext();
737
738   if (DL.getScope(Context) != 0 && PrevDL != DL) {
739     JITEvent_EmittedFunctionDetails::LineStart NextLine;
740     NextLine.Address = getCurrentPCValue();
741     NextLine.Loc = DL;
742     EmissionDetails.LineStarts.push_back(NextLine);
743   }
744
745   PrevDL = DL;
746 }
747
748 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
749                                            const DataLayout *TD) {
750   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
751   if (Constants.empty()) return 0;
752
753   unsigned Size = 0;
754   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
755     MachineConstantPoolEntry CPE = Constants[i];
756     unsigned AlignMask = CPE.getAlignment() - 1;
757     Size = (Size + AlignMask) & ~AlignMask;
758     Type *Ty = CPE.getType();
759     Size += TD->getTypeAllocSize(Ty);
760   }
761   return Size;
762 }
763
764 void JITEmitter::startFunction(MachineFunction &F) {
765   DEBUG(dbgs() << "JIT: Starting CodeGen of Function "
766         << F.getName() << "\n");
767
768   uintptr_t ActualSize = 0;
769   // Set the memory writable, if it's not already
770   MemMgr->setMemoryWritable();
771
772   if (SizeEstimate > 0) {
773     // SizeEstimate will be non-zero on reallocation attempts.
774     ActualSize = SizeEstimate;
775   }
776
777   BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
778                                                          ActualSize);
779   BufferEnd = BufferBegin+ActualSize;
780   EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
781
782   // Ensure the constant pool/jump table info is at least 4-byte aligned.
783   emitAlignment(16);
784
785   emitConstantPool(F.getConstantPool());
786   if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
787     initJumpTableInfo(MJTI);
788
789   // About to start emitting the machine code for the function.
790   emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
791   TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
792   EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
793
794   MBBLocations.clear();
795
796   EmissionDetails.MF = &F;
797   EmissionDetails.LineStarts.clear();
798 }
799
800 bool JITEmitter::finishFunction(MachineFunction &F) {
801   if (CurBufferPtr == BufferEnd) {
802     // We must call endFunctionBody before retrying, because
803     // deallocateMemForFunction requires it.
804     MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
805     retryWithMoreMemory(F);
806     return true;
807   }
808
809   if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
810     emitJumpTableInfo(MJTI);
811
812   // FnStart is the start of the text, not the start of the constant pool and
813   // other per-function data.
814   uint8_t *FnStart =
815     (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
816
817   // FnEnd is the end of the function's machine code.
818   uint8_t *FnEnd = CurBufferPtr;
819
820   if (!Relocations.empty()) {
821     CurFn = F.getFunction();
822     NumRelos += Relocations.size();
823
824     // Resolve the relocations to concrete pointers.
825     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
826       MachineRelocation &MR = Relocations[i];
827       void *ResultPtr = 0;
828       if (!MR.letTargetResolve()) {
829         if (MR.isExternalSymbol()) {
830           ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
831                                                         false);
832           DEBUG(dbgs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
833                        << ResultPtr << "]\n");
834
835           // If the target REALLY wants a stub for this function, emit it now.
836           if (MR.mayNeedFarStub()) {
837             ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
838           }
839         } else if (MR.isGlobalValue()) {
840           ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
841                                          BufferBegin+MR.getMachineCodeOffset(),
842                                          MR.mayNeedFarStub());
843         } else if (MR.isIndirectSymbol()) {
844           ResultPtr = getPointerToGVIndirectSym(
845               MR.getGlobalValue(), BufferBegin+MR.getMachineCodeOffset());
846         } else if (MR.isBasicBlock()) {
847           ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
848         } else if (MR.isConstantPoolIndex()) {
849           ResultPtr =
850             (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
851         } else {
852           assert(MR.isJumpTableIndex());
853           ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
854         }
855
856         MR.setResultPointer(ResultPtr);
857       }
858
859       // if we are managing the GOT and the relocation wants an index,
860       // give it one
861       if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
862         unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
863         MR.setGOTIndex(idx);
864         if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
865           DEBUG(dbgs() << "JIT: GOT was out of date for " << ResultPtr
866                        << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
867                        << "\n");
868           ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
869         }
870       }
871     }
872
873     CurFn = 0;
874     TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
875                                   Relocations.size(), MemMgr->getGOTBase());
876   }
877
878   // Update the GOT entry for F to point to the new code.
879   if (MemMgr->isManagingGOT()) {
880     unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
881     if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
882       DEBUG(dbgs() << "JIT: GOT was out of date for " << (void*)BufferBegin
883                    << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
884                    << "\n");
885       ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
886     }
887   }
888
889   // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
890   // global variables that were referenced in the relocations.
891   MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
892
893   if (CurBufferPtr == BufferEnd) {
894     retryWithMoreMemory(F);
895     return true;
896   } else {
897     // Now that we've succeeded in emitting the function, reset the
898     // SizeEstimate back down to zero.
899     SizeEstimate = 0;
900   }
901
902   BufferBegin = CurBufferPtr = 0;
903   NumBytes += FnEnd-FnStart;
904
905   // Invalidate the icache if necessary.
906   sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
907
908   TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
909                                 EmissionDetails);
910
911   // Reset the previous debug location.
912   PrevDL = DebugLoc();
913
914   DEBUG(dbgs() << "JIT: Finished CodeGen of [" << (void*)FnStart
915         << "] Function: " << F.getName()
916         << ": " << (FnEnd-FnStart) << " bytes of text, "
917         << Relocations.size() << " relocations\n");
918
919   Relocations.clear();
920   ConstPoolAddresses.clear();
921
922   // Mark code region readable and executable if it's not so already.
923   MemMgr->setMemoryExecutable();
924
925   DEBUG({
926       if (sys::hasDisassembler()) {
927         dbgs() << "JIT: Disassembled code:\n";
928         dbgs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
929                                          (uintptr_t)FnStart);
930       } else {
931         dbgs() << "JIT: Binary code:\n";
932         uint8_t* q = FnStart;
933         for (int i = 0; q < FnEnd; q += 4, ++i) {
934           if (i == 4)
935             i = 0;
936           if (i == 0)
937             dbgs() << "JIT: " << (long)(q - FnStart) << ": ";
938           bool Done = false;
939           for (int j = 3; j >= 0; --j) {
940             if (q + j >= FnEnd)
941               Done = true;
942             else
943               dbgs() << (unsigned short)q[j];
944           }
945           if (Done)
946             break;
947           dbgs() << ' ';
948           if (i == 3)
949             dbgs() << '\n';
950         }
951         dbgs()<< '\n';
952       }
953     });
954
955   if (MMI)
956     MMI->EndFunction();
957
958   return false;
959 }
960
961 void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
962   DEBUG(dbgs() << "JIT: Ran out of space for native code.  Reattempting.\n");
963   Relocations.clear();  // Clear the old relocations or we'll reapply them.
964   ConstPoolAddresses.clear();
965   ++NumRetries;
966   deallocateMemForFunction(F.getFunction());
967   // Try again with at least twice as much free space.
968   SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
969
970   for (MachineFunction::iterator MBB = F.begin(), E = F.end(); MBB != E; ++MBB){
971     if (MBB->hasAddressTaken())
972       TheJIT->clearPointerToBasicBlock(MBB->getBasicBlock());
973   }
974 }
975
976 /// deallocateMemForFunction - Deallocate all memory for the specified
977 /// function body.  Also drop any references the function has to stubs.
978 /// May be called while the Function is being destroyed inside ~Value().
979 void JITEmitter::deallocateMemForFunction(const Function *F) {
980   ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
981     Emitted = EmittedFunctions.find(F);
982   if (Emitted != EmittedFunctions.end()) {
983     MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
984     TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
985
986     EmittedFunctions.erase(Emitted);
987   }
988 }
989
990
991 void *JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
992   if (BufferBegin)
993     return JITCodeEmitter::allocateSpace(Size, Alignment);
994
995   // create a new memory block if there is no active one.
996   // care must be taken so that BufferBegin is invalidated when a
997   // block is trimmed
998   BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
999   BufferEnd = BufferBegin+Size;
1000   return CurBufferPtr;
1001 }
1002
1003 void *JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1004   // Delegate this call through the memory manager.
1005   return MemMgr->allocateGlobal(Size, Alignment);
1006 }
1007
1008 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1009   if (TheJIT->getJITInfo().hasCustomConstantPool())
1010     return;
1011
1012   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1013   if (Constants.empty()) return;
1014
1015   unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getDataLayout());
1016   unsigned Align = MCP->getConstantPoolAlignment();
1017   ConstantPoolBase = allocateSpace(Size, Align);
1018   ConstantPool = MCP;
1019
1020   if (ConstantPoolBase == 0) return;  // Buffer overflow.
1021
1022   DEBUG(dbgs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1023                << "] (size: " << Size << ", alignment: " << Align << ")\n");
1024
1025   // Initialize the memory for all of the constant pool entries.
1026   unsigned Offset = 0;
1027   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1028     MachineConstantPoolEntry CPE = Constants[i];
1029     unsigned AlignMask = CPE.getAlignment() - 1;
1030     Offset = (Offset + AlignMask) & ~AlignMask;
1031
1032     uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1033     ConstPoolAddresses.push_back(CAddr);
1034     if (CPE.isMachineConstantPoolEntry()) {
1035       // FIXME: add support to lower machine constant pool values into bytes!
1036       report_fatal_error("Initialize memory with machine specific constant pool"
1037                         "entry has not been implemented!");
1038     }
1039     TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1040     DEBUG(dbgs() << "JIT:   CP" << i << " at [0x";
1041           dbgs().write_hex(CAddr) << "]\n");
1042
1043     Type *Ty = CPE.Val.ConstVal->getType();
1044     Offset += TheJIT->getDataLayout()->getTypeAllocSize(Ty);
1045   }
1046 }
1047
1048 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1049   if (TheJIT->getJITInfo().hasCustomJumpTables())
1050     return;
1051   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline)
1052     return;
1053
1054   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1055   if (JT.empty()) return;
1056
1057   unsigned NumEntries = 0;
1058   for (unsigned i = 0, e = JT.size(); i != e; ++i)
1059     NumEntries += JT[i].MBBs.size();
1060
1061   unsigned EntrySize = MJTI->getEntrySize(*TheJIT->getDataLayout());
1062
1063   // Just allocate space for all the jump tables now.  We will fix up the actual
1064   // MBB entries in the tables after we emit the code for each block, since then
1065   // we will know the final locations of the MBBs in memory.
1066   JumpTable = MJTI;
1067   JumpTableBase = allocateSpace(NumEntries * EntrySize,
1068                              MJTI->getEntryAlignment(*TheJIT->getDataLayout()));
1069 }
1070
1071 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1072   if (TheJIT->getJITInfo().hasCustomJumpTables())
1073     return;
1074
1075   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1076   if (JT.empty() || JumpTableBase == 0) return;
1077
1078
1079   switch (MJTI->getEntryKind()) {
1080   case MachineJumpTableInfo::EK_Inline:
1081     return;
1082   case MachineJumpTableInfo::EK_BlockAddress: {
1083     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1084     //     .word LBB123
1085     assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == sizeof(void*) &&
1086            "Cross JIT'ing?");
1087
1088     // For each jump table, map each target in the jump table to the address of
1089     // an emitted MachineBasicBlock.
1090     intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1091
1092     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1093       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1094       // Store the address of the basic block for this jump table slot in the
1095       // memory we allocated for the jump table in 'initJumpTableInfo'
1096       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1097         *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1098     }
1099     break;
1100   }
1101
1102   case MachineJumpTableInfo::EK_Custom32:
1103   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1104   case MachineJumpTableInfo::EK_LabelDifference32: {
1105     assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == 4&&"Cross JIT'ing?");
1106     // For each jump table, place the offset from the beginning of the table
1107     // to the target address.
1108     int *SlotPtr = (int*)JumpTableBase;
1109
1110     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1111       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1112       // Store the offset of the basic block for this jump table slot in the
1113       // memory we allocated for the jump table in 'initJumpTableInfo'
1114       uintptr_t Base = (uintptr_t)SlotPtr;
1115       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1116         uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1117         /// FIXME: USe EntryKind instead of magic "getPICJumpTableEntry" hook.
1118         *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1119       }
1120     }
1121     break;
1122   }
1123   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1124     llvm_unreachable(
1125            "JT Info emission not implemented for GPRel64BlockAddress yet.");
1126   }
1127 }
1128
1129 void JITEmitter::startGVStub(const GlobalValue* GV,
1130                              unsigned StubSize, unsigned Alignment) {
1131   SavedBufferBegin = BufferBegin;
1132   SavedBufferEnd = BufferEnd;
1133   SavedCurBufferPtr = CurBufferPtr;
1134
1135   BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1136   BufferEnd = BufferBegin+StubSize+1;
1137 }
1138
1139 void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
1140   SavedBufferBegin = BufferBegin;
1141   SavedBufferEnd = BufferEnd;
1142   SavedCurBufferPtr = CurBufferPtr;
1143
1144   BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1145   BufferEnd = BufferBegin+StubSize+1;
1146 }
1147
1148 void JITEmitter::finishGVStub() {
1149   assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
1150   NumBytes += getCurrentPCOffset();
1151   BufferBegin = SavedBufferBegin;
1152   BufferEnd = SavedBufferEnd;
1153   CurBufferPtr = SavedCurBufferPtr;
1154 }
1155
1156 void *JITEmitter::allocIndirectGV(const GlobalValue *GV,
1157                                   const uint8_t *Buffer, size_t Size,
1158                                   unsigned Alignment) {
1159   uint8_t *IndGV = MemMgr->allocateStub(GV, Size, Alignment);
1160   memcpy(IndGV, Buffer, Size);
1161   return IndGV;
1162 }
1163
1164 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1165 // in the constant pool that was last emitted with the 'emitConstantPool'
1166 // method.
1167 //
1168 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1169   assert(ConstantNum < ConstantPool->getConstants().size() &&
1170          "Invalid ConstantPoolIndex!");
1171   return ConstPoolAddresses[ConstantNum];
1172 }
1173
1174 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1175 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1176 //
1177 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1178   const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1179   assert(Index < JT.size() && "Invalid jump table index!");
1180
1181   unsigned EntrySize = JumpTable->getEntrySize(*TheJIT->getDataLayout());
1182
1183   unsigned Offset = 0;
1184   for (unsigned i = 0; i < Index; ++i)
1185     Offset += JT[i].MBBs.size();
1186
1187    Offset *= EntrySize;
1188
1189   return (uintptr_t)((char *)JumpTableBase + Offset);
1190 }
1191
1192 void JITEmitter::EmittedFunctionConfig::onDelete(
1193   JITEmitter *Emitter, const Function *F) {
1194   Emitter->deallocateMemForFunction(F);
1195 }
1196 void JITEmitter::EmittedFunctionConfig::onRAUW(
1197   JITEmitter *, const Function*, const Function*) {
1198   llvm_unreachable("The JIT doesn't know how to handle a"
1199                    " RAUW on a value it has emitted.");
1200 }
1201
1202
1203 //===----------------------------------------------------------------------===//
1204 //  Public interface to this file
1205 //===----------------------------------------------------------------------===//
1206
1207 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1208                                    TargetMachine &tm) {
1209   return new JITEmitter(jit, JMM, tm);
1210 }
1211
1212 // getPointerToFunctionOrStub - If the specified function has been
1213 // code-gen'd, return a pointer to the function.  If not, compile it, or use
1214 // a stub to implement lazy compilation if available.
1215 //
1216 void *JIT::getPointerToFunctionOrStub(Function *F) {
1217   // If we have already code generated the function, just return the address.
1218   if (void *Addr = getPointerToGlobalIfAvailable(F))
1219     return Addr;
1220
1221   // Get a stub if the target supports it.
1222   JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1223   return JE->getJITResolver().getLazyFunctionStub(F);
1224 }
1225
1226 void JIT::updateFunctionStub(Function *F) {
1227   // Get the empty stub we generated earlier.
1228   JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1229   void *Stub = JE->getJITResolver().getLazyFunctionStub(F);
1230   void *Addr = getPointerToGlobalIfAvailable(F);
1231   assert(Addr != Stub && "Function must have non-stub address to be updated.");
1232
1233   // Tell the target jit info to rewrite the stub at the specified address,
1234   // rather than creating a new one.
1235   TargetJITInfo::StubLayout layout = getJITInfo().getStubLayout();
1236   JE->startGVStub(Stub, layout.Size);
1237   getJITInfo().emitFunctionStub(F, Addr, *getCodeEmitter());
1238   JE->finishGVStub();
1239 }
1240
1241 /// freeMachineCodeForFunction - release machine code memory for given Function.
1242 ///
1243 void JIT::freeMachineCodeForFunction(Function *F) {
1244   // Delete translation for this from the ExecutionEngine, so it will get
1245   // retranslated next time it is used.
1246   updateGlobalMapping(F, 0);
1247
1248   // Free the actual memory for the function body and related stuff.
1249   static_cast<JITEmitter*>(JCE)->deallocateMemForFunction(F);
1250 }