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