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