[CFLAA] LLVM_CONSTEXPR -> const
[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 (void *C : F2C->second) {
466     S2RMap.UnregisterStubResolver(C);
467     bool Erased = CallSiteToFunctionMap.erase(C);
468     (void)Erased;
469     assert(Erased && "Missing call site->function mapping");
470   }
471   FunctionToCallSitesMap.erase(F2C);
472 }
473
474 void JITResolverState::EraseAllCallSitesPrelocked() {
475   StubToResolverMapTy &S2RMap = *StubToResolverMap;
476   for (CallSiteToFunctionMapTy::const_iterator
477          I = CallSiteToFunctionMap.begin(),
478          E = CallSiteToFunctionMap.end(); I != E; ++I) {
479     S2RMap.UnregisterStubResolver(I->first);
480   }
481   CallSiteToFunctionMap.clear();
482   FunctionToCallSitesMap.clear();
483 }
484
485 JITResolver::~JITResolver() {
486   // No need to lock because we're in the destructor, and state isn't shared.
487   state.EraseAllCallSitesPrelocked();
488   assert(!StubToResolverMap->ResolverHasStubs(this) &&
489          "Resolver destroyed with stubs still alive.");
490 }
491
492 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function stub
493 /// if it has already been created.
494 void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
495   MutexGuard locked(TheJIT->lock);
496
497   // If we already have a stub for this function, recycle it.
498   return state.getFunctionToLazyStubMap().lookup(F);
499 }
500
501 /// getFunctionStub - This returns a pointer to a function stub, creating
502 /// one on demand as needed.
503 void *JITResolver::getLazyFunctionStub(Function *F) {
504   MutexGuard locked(TheJIT->lock);
505
506   // If we already have a lazy stub for this function, recycle it.
507   void *&Stub = state.getFunctionToLazyStubMap()[F];
508   if (Stub) return Stub;
509
510   // Call the lazy resolver function if we are JIT'ing lazily.  Otherwise we
511   // must resolve the symbol now.
512   void *Actual = TheJIT->isCompilingLazily()
513     ? (void *)(intptr_t)LazyResolverFn : (void *)nullptr;
514
515   // If this is an external declaration, attempt to resolve the address now
516   // to place in the stub.
517   if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage()) {
518     Actual = TheJIT->getPointerToFunction(F);
519
520     // If we resolved the symbol to a null address (eg. a weak external)
521     // don't emit a stub. Return a null pointer to the application.
522     if (!Actual) return nullptr;
523   }
524
525   TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
526   JE.startGVStub(F, SL.Size, SL.Alignment);
527   // Codegen a new stub, calling the lazy resolver or the actual address of the
528   // external function, if it was resolved.
529   Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
530   JE.finishGVStub();
531
532   if (Actual != (void*)(intptr_t)LazyResolverFn) {
533     // If we are getting the stub for an external function, we really want the
534     // address of the stub in the GlobalAddressMap for the JIT, not the address
535     // of the external function.
536     TheJIT->updateGlobalMapping(F, Stub);
537   }
538
539   DEBUG(dbgs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
540         << F->getName() << "'\n");
541
542   if (TheJIT->isCompilingLazily()) {
543     // Register this JITResolver as the one corresponding to this call site so
544     // JITCompilerFn will be able to find it.
545     StubToResolverMap->RegisterStubResolver(Stub, this);
546
547     // Finally, keep track of the stub-to-Function mapping so that the
548     // JITCompilerFn knows which function to compile!
549     state.AddCallSite(Stub, F);
550   } else if (!Actual) {
551     // If we are JIT'ing non-lazily but need to call a function that does not
552     // exist yet, add it to the JIT's work list so that we can fill in the
553     // stub address later.
554     assert(!isNonGhostDeclaration(F) && !F->hasAvailableExternallyLinkage() &&
555            "'Actual' should have been set above.");
556     TheJIT->addPendingFunction(F);
557   }
558
559   return Stub;
560 }
561
562 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
563 /// GV address.
564 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
565   MutexGuard locked(TheJIT->lock);
566
567   // If we already have a stub for this global variable, recycle it.
568   void *&IndirectSym = state.getGlobalToIndirectSymMap()[GV];
569   if (IndirectSym) return IndirectSym;
570
571   // Otherwise, codegen a new indirect symbol.
572   IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
573                                                                 JE);
574
575   DEBUG(dbgs() << "JIT: Indirect symbol emitted at [" << IndirectSym
576         << "] for GV '" << GV->getName() << "'\n");
577
578   return IndirectSym;
579 }
580
581 /// getExternalFunctionStub - Return a stub for the function at the
582 /// specified address, created lazily on demand.
583 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
584   // If we already have a stub for this function, recycle it.
585   void *&Stub = ExternalFnToStubMap[FnAddr];
586   if (Stub) return Stub;
587
588   TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
589   JE.startGVStub(nullptr, SL.Size, SL.Alignment);
590   Stub = TheJIT->getJITInfo().emitFunctionStub(nullptr, FnAddr, JE);
591   JE.finishGVStub();
592
593   DEBUG(dbgs() << "JIT: Stub emitted at [" << Stub
594                << "] for external function at '" << FnAddr << "'\n");
595   return Stub;
596 }
597
598 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
599   unsigned idx = revGOTMap[addr];
600   if (!idx) {
601     idx = ++nextGOTIndex;
602     revGOTMap[addr] = idx;
603     DEBUG(dbgs() << "JIT: Adding GOT entry " << idx << " for addr ["
604                  << addr << "]\n");
605   }
606   return idx;
607 }
608
609 /// JITCompilerFn - This function is called when a lazy compilation stub has
610 /// been entered.  It looks up which function this stub corresponds to, compiles
611 /// it if necessary, then returns the resultant function pointer.
612 void *JITResolver::JITCompilerFn(void *Stub) {
613   JITResolver *JR = StubToResolverMap->getResolverFromStub(Stub);
614   assert(JR && "Unable to find the corresponding JITResolver to the call site");
615
616   Function* F = nullptr;
617   void* ActualPtr = nullptr;
618
619   {
620     // Only lock for getting the Function. The call getPointerToFunction made
621     // in this function might trigger function materializing, which requires
622     // JIT lock to be unlocked.
623     MutexGuard locked(JR->TheJIT->lock);
624
625     // The address given to us for the stub may not be exactly right, it might
626     // be a little bit after the stub.  As such, use upper_bound to find it.
627     std::pair<void*, Function*> I =
628       JR->state.LookupFunctionFromCallSite(Stub);
629     F = I.second;
630     ActualPtr = I.first;
631   }
632
633   // If we have already code generated the function, just return the address.
634   void *Result = JR->TheJIT->getPointerToGlobalIfAvailable(F);
635
636   if (!Result) {
637     // Otherwise we don't have it, do lazy compilation now.
638
639     // If lazy compilation is disabled, emit a useful error message and abort.
640     if (!JR->TheJIT->isCompilingLazily()) {
641       report_fatal_error("LLVM JIT requested to do lazy compilation of"
642                          " function '"
643                         + F->getName() + "' when lazy compiles are disabled!");
644     }
645
646     DEBUG(dbgs() << "JIT: Lazily resolving function '" << F->getName()
647           << "' In stub ptr = " << Stub << " actual ptr = "
648           << ActualPtr << "\n");
649     (void)ActualPtr;
650
651     Result = JR->TheJIT->getPointerToFunction(F);
652   }
653
654   // Reacquire the lock to update the GOT map.
655   MutexGuard locked(JR->TheJIT->lock);
656
657   // We might like to remove the call site from the CallSiteToFunction map, but
658   // we can't do that! Multiple threads could be stuck, waiting to acquire the
659   // lock above. As soon as the 1st function finishes compiling the function,
660   // the next one will be released, and needs to be able to find the function it
661   // needs to call.
662
663   // FIXME: We could rewrite all references to this stub if we knew them.
664
665   // What we will do is set the compiled function address to map to the
666   // same GOT entry as the stub so that later clients may update the GOT
667   // if they see it still using the stub address.
668   // Note: this is done so the Resolver doesn't have to manage GOT memory
669   // Do this without allocating map space if the target isn't using a GOT
670   if(JR->revGOTMap.find(Stub) != JR->revGOTMap.end())
671     JR->revGOTMap[Result] = JR->revGOTMap[Stub];
672
673   return Result;
674 }
675
676 //===----------------------------------------------------------------------===//
677 // JITEmitter code.
678 //
679
680 static GlobalObject *getSimpleAliasee(Constant *C) {
681   C = C->stripPointerCasts();
682   return dyn_cast<GlobalObject>(C);
683 }
684
685 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
686                                      bool MayNeedFarStub) {
687   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
688     return TheJIT->getOrEmitGlobalVariable(GV);
689
690   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
691     // We can only handle simple cases.
692     if (GlobalValue *GV = getSimpleAliasee(GA->getAliasee()))
693       return TheJIT->getPointerToGlobal(GV);
694     return nullptr;
695   }
696
697   // If we have already compiled the function, return a pointer to its body.
698   Function *F = cast<Function>(V);
699
700   void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
701   if (FnStub) {
702     // Return the function stub if it's already created.  We do this first so
703     // that we're returning the same address for the function as any previous
704     // call.  TODO: Yes, this is wrong. The lazy stub isn't guaranteed to be
705     // close enough to call.
706     return FnStub;
707   }
708
709   // If we know the target can handle arbitrary-distance calls, try to
710   // return a direct pointer.
711   if (!MayNeedFarStub) {
712     // If we have code, go ahead and return that.
713     void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
714     if (ResultPtr) return ResultPtr;
715
716     // If this is an external function pointer, we can force the JIT to
717     // 'compile' it, which really just adds it to the map.
718     if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage())
719       return TheJIT->getPointerToFunction(F);
720   }
721
722   // Otherwise, we may need a to emit a stub, and, conservatively, we always do
723   // so.  Note that it's possible to return null from getLazyFunctionStub in the
724   // case of a weak extern that fails to resolve.
725   return Resolver.getLazyFunctionStub(F);
726 }
727
728 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
729   // Make sure GV is emitted first, and create a stub containing the fully
730   // resolved address.
731   void *GVAddress = getPointerToGlobal(V, Reference, false);
732   void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
733   return StubAddr;
734 }
735
736 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
737   if (DL.isUnknown()) return;
738   if (!BeforePrintingInsn) return;
739
740   const LLVMContext &Context = EmissionDetails.MF->getFunction()->getContext();
741
742   if (DL.getScope(Context) != nullptr && PrevDL != DL) {
743     JITEvent_EmittedFunctionDetails::LineStart NextLine;
744     NextLine.Address = getCurrentPCValue();
745     NextLine.Loc = DL;
746     EmissionDetails.LineStarts.push_back(NextLine);
747   }
748
749   PrevDL = DL;
750 }
751
752 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
753                                            const DataLayout *TD) {
754   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
755   if (Constants.empty()) return 0;
756
757   unsigned Size = 0;
758   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
759     MachineConstantPoolEntry CPE = Constants[i];
760     unsigned AlignMask = CPE.getAlignment() - 1;
761     Size = (Size + AlignMask) & ~AlignMask;
762     Type *Ty = CPE.getType();
763     Size += TD->getTypeAllocSize(Ty);
764   }
765   return Size;
766 }
767
768 void JITEmitter::startFunction(MachineFunction &F) {
769   DEBUG(dbgs() << "JIT: Starting CodeGen of Function "
770         << F.getName() << "\n");
771
772   uintptr_t ActualSize = 0;
773   // Set the memory writable, if it's not already
774   MemMgr->setMemoryWritable();
775
776   if (SizeEstimate > 0) {
777     // SizeEstimate will be non-zero on reallocation attempts.
778     ActualSize = SizeEstimate;
779   }
780
781   BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
782                                                          ActualSize);
783   BufferEnd = BufferBegin+ActualSize;
784   EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
785
786   // Ensure the constant pool/jump table info is at least 4-byte aligned.
787   emitAlignment(16);
788
789   emitConstantPool(F.getConstantPool());
790   if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
791     initJumpTableInfo(MJTI);
792
793   // About to start emitting the machine code for the function.
794   emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
795   TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
796   EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
797
798   MBBLocations.clear();
799
800   EmissionDetails.MF = &F;
801   EmissionDetails.LineStarts.clear();
802 }
803
804 bool JITEmitter::finishFunction(MachineFunction &F) {
805   if (CurBufferPtr == BufferEnd) {
806     // We must call endFunctionBody before retrying, because
807     // deallocateMemForFunction requires it.
808     MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
809     retryWithMoreMemory(F);
810     return true;
811   }
812
813   if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
814     emitJumpTableInfo(MJTI);
815
816   // FnStart is the start of the text, not the start of the constant pool and
817   // other per-function data.
818   uint8_t *FnStart =
819     (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
820
821   // FnEnd is the end of the function's machine code.
822   uint8_t *FnEnd = CurBufferPtr;
823
824   if (!Relocations.empty()) {
825     CurFn = F.getFunction();
826     NumRelos += Relocations.size();
827
828     // Resolve the relocations to concrete pointers.
829     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
830       MachineRelocation &MR = Relocations[i];
831       void *ResultPtr = nullptr;
832       if (!MR.letTargetResolve()) {
833         if (MR.isExternalSymbol()) {
834           ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
835                                                         false);
836           DEBUG(dbgs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
837                        << ResultPtr << "]\n");
838
839           // If the target REALLY wants a stub for this function, emit it now.
840           if (MR.mayNeedFarStub()) {
841             ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
842           }
843         } else if (MR.isGlobalValue()) {
844           ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
845                                          BufferBegin+MR.getMachineCodeOffset(),
846                                          MR.mayNeedFarStub());
847         } else if (MR.isIndirectSymbol()) {
848           ResultPtr = getPointerToGVIndirectSym(
849               MR.getGlobalValue(), BufferBegin+MR.getMachineCodeOffset());
850         } else if (MR.isBasicBlock()) {
851           ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
852         } else if (MR.isConstantPoolIndex()) {
853           ResultPtr =
854             (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
855         } else {
856           assert(MR.isJumpTableIndex());
857           ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
858         }
859
860         MR.setResultPointer(ResultPtr);
861       }
862
863       // if we are managing the GOT and the relocation wants an index,
864       // give it one
865       if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
866         unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
867         MR.setGOTIndex(idx);
868         if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
869           DEBUG(dbgs() << "JIT: GOT was out of date for " << ResultPtr
870                        << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
871                        << "\n");
872           ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
873         }
874       }
875     }
876
877     CurFn = nullptr;
878     TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
879                                   Relocations.size(), MemMgr->getGOTBase());
880   }
881
882   // Update the GOT entry for F to point to the new code.
883   if (MemMgr->isManagingGOT()) {
884     unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
885     if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
886       DEBUG(dbgs() << "JIT: GOT was out of date for " << (void*)BufferBegin
887                    << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
888                    << "\n");
889       ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
890     }
891   }
892
893   // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
894   // global variables that were referenced in the relocations.
895   MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
896
897   if (CurBufferPtr == BufferEnd) {
898     retryWithMoreMemory(F);
899     return true;
900   } else {
901     // Now that we've succeeded in emitting the function, reset the
902     // SizeEstimate back down to zero.
903     SizeEstimate = 0;
904   }
905
906   BufferBegin = CurBufferPtr = nullptr;
907   NumBytes += FnEnd-FnStart;
908
909   // Invalidate the icache if necessary.
910   sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
911
912   TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
913                                 EmissionDetails);
914
915   // Reset the previous debug location.
916   PrevDL = DebugLoc();
917
918   DEBUG(dbgs() << "JIT: Finished CodeGen of [" << (void*)FnStart
919         << "] Function: " << F.getName()
920         << ": " << (FnEnd-FnStart) << " bytes of text, "
921         << Relocations.size() << " relocations\n");
922
923   Relocations.clear();
924   ConstPoolAddresses.clear();
925
926   // Mark code region readable and executable if it's not so already.
927   MemMgr->setMemoryExecutable();
928
929   DEBUG({
930         dbgs() << "JIT: Binary code:\n";
931         uint8_t* q = FnStart;
932         for (int i = 0; q < FnEnd; q += 4, ++i) {
933           if (i == 4)
934             i = 0;
935           if (i == 0)
936             dbgs() << "JIT: " << (long)(q - FnStart) << ": ";
937           bool Done = false;
938           for (int j = 3; j >= 0; --j) {
939             if (q + j >= FnEnd)
940               Done = true;
941             else
942               dbgs() << (unsigned short)q[j];
943           }
944           if (Done)
945             break;
946           dbgs() << ' ';
947           if (i == 3)
948             dbgs() << '\n';
949         }
950         dbgs()<< '\n';
951     });
952
953   if (MMI)
954     MMI->EndFunction();
955
956   return false;
957 }
958
959 void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
960   DEBUG(dbgs() << "JIT: Ran out of space for native code.  Reattempting.\n");
961   Relocations.clear();  // Clear the old relocations or we'll reapply them.
962   ConstPoolAddresses.clear();
963   ++NumRetries;
964   deallocateMemForFunction(F.getFunction());
965   // Try again with at least twice as much free space.
966   SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
967
968   for (MachineFunction::iterator MBB = F.begin(), E = F.end(); MBB != E; ++MBB){
969     if (MBB->hasAddressTaken())
970       TheJIT->clearPointerToBasicBlock(MBB->getBasicBlock());
971   }
972 }
973
974 /// deallocateMemForFunction - Deallocate all memory for the specified
975 /// function body.  Also drop any references the function has to stubs.
976 /// May be called while the Function is being destroyed inside ~Value().
977 void JITEmitter::deallocateMemForFunction(const Function *F) {
978   ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
979     Emitted = EmittedFunctions.find(F);
980   if (Emitted != EmittedFunctions.end()) {
981     MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
982     TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
983
984     EmittedFunctions.erase(Emitted);
985   }
986 }
987
988
989 void *JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
990   if (BufferBegin)
991     return JITCodeEmitter::allocateSpace(Size, Alignment);
992
993   // create a new memory block if there is no active one.
994   // care must be taken so that BufferBegin is invalidated when a
995   // block is trimmed
996   BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
997   BufferEnd = BufferBegin+Size;
998   return CurBufferPtr;
999 }
1000
1001 void *JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1002   // Delegate this call through the memory manager.
1003   return MemMgr->allocateGlobal(Size, Alignment);
1004 }
1005
1006 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1007   if (TheJIT->getJITInfo().hasCustomConstantPool())
1008     return;
1009
1010   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1011   if (Constants.empty()) return;
1012
1013   unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getDataLayout());
1014   unsigned Align = MCP->getConstantPoolAlignment();
1015   ConstantPoolBase = allocateSpace(Size, Align);
1016   ConstantPool = MCP;
1017
1018   if (!ConstantPoolBase) return;  // Buffer overflow.
1019
1020   DEBUG(dbgs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1021                << "] (size: " << Size << ", alignment: " << Align << ")\n");
1022
1023   // Initialize the memory for all of the constant pool entries.
1024   unsigned Offset = 0;
1025   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1026     MachineConstantPoolEntry CPE = Constants[i];
1027     unsigned AlignMask = CPE.getAlignment() - 1;
1028     Offset = (Offset + AlignMask) & ~AlignMask;
1029
1030     uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1031     ConstPoolAddresses.push_back(CAddr);
1032     if (CPE.isMachineConstantPoolEntry()) {
1033       // FIXME: add support to lower machine constant pool values into bytes!
1034       report_fatal_error("Initialize memory with machine specific constant pool"
1035                         "entry has not been implemented!");
1036     }
1037     TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1038     DEBUG(dbgs() << "JIT:   CP" << i << " at [0x";
1039           dbgs().write_hex(CAddr) << "]\n");
1040
1041     Type *Ty = CPE.Val.ConstVal->getType();
1042     Offset += TheJIT->getDataLayout()->getTypeAllocSize(Ty);
1043   }
1044 }
1045
1046 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1047   if (TheJIT->getJITInfo().hasCustomJumpTables())
1048     return;
1049   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline)
1050     return;
1051
1052   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1053   if (JT.empty()) return;
1054
1055   unsigned NumEntries = 0;
1056   for (unsigned i = 0, e = JT.size(); i != e; ++i)
1057     NumEntries += JT[i].MBBs.size();
1058
1059   unsigned EntrySize = MJTI->getEntrySize(*TheJIT->getDataLayout());
1060
1061   // Just allocate space for all the jump tables now.  We will fix up the actual
1062   // MBB entries in the tables after we emit the code for each block, since then
1063   // we will know the final locations of the MBBs in memory.
1064   JumpTable = MJTI;
1065   JumpTableBase = allocateSpace(NumEntries * EntrySize,
1066                              MJTI->getEntryAlignment(*TheJIT->getDataLayout()));
1067 }
1068
1069 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1070   if (TheJIT->getJITInfo().hasCustomJumpTables())
1071     return;
1072
1073   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1074   if (JT.empty() || !JumpTableBase) return;
1075
1076
1077   switch (MJTI->getEntryKind()) {
1078   case MachineJumpTableInfo::EK_Inline:
1079     return;
1080   case MachineJumpTableInfo::EK_BlockAddress: {
1081     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1082     //     .word LBB123
1083     assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == sizeof(void*) &&
1084            "Cross JIT'ing?");
1085
1086     // For each jump table, map each target in the jump table to the address of
1087     // an emitted MachineBasicBlock.
1088     intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1089
1090     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1091       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1092       // Store the address of the basic block for this jump table slot in the
1093       // memory we allocated for the jump table in 'initJumpTableInfo'
1094       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1095         *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1096     }
1097     break;
1098   }
1099
1100   case MachineJumpTableInfo::EK_Custom32:
1101   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1102   case MachineJumpTableInfo::EK_LabelDifference32: {
1103     assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == 4&&"Cross JIT'ing?");
1104     // For each jump table, place the offset from the beginning of the table
1105     // to the target address.
1106     int *SlotPtr = (int*)JumpTableBase;
1107
1108     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1109       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1110       // Store the offset of the basic block for this jump table slot in the
1111       // memory we allocated for the jump table in 'initJumpTableInfo'
1112       uintptr_t Base = (uintptr_t)SlotPtr;
1113       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1114         uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1115         /// FIXME: USe EntryKind instead of magic "getPICJumpTableEntry" hook.
1116         *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1117       }
1118     }
1119     break;
1120   }
1121   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1122     llvm_unreachable(
1123            "JT Info emission not implemented for GPRel64BlockAddress yet.");
1124   }
1125 }
1126
1127 void JITEmitter::startGVStub(const GlobalValue* GV,
1128                              unsigned StubSize, unsigned Alignment) {
1129   SavedBufferBegin = BufferBegin;
1130   SavedBufferEnd = BufferEnd;
1131   SavedCurBufferPtr = CurBufferPtr;
1132
1133   BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1134   BufferEnd = BufferBegin+StubSize+1;
1135 }
1136
1137 void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
1138   SavedBufferBegin = BufferBegin;
1139   SavedBufferEnd = BufferEnd;
1140   SavedCurBufferPtr = CurBufferPtr;
1141
1142   BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1143   BufferEnd = BufferBegin+StubSize+1;
1144 }
1145
1146 void JITEmitter::finishGVStub() {
1147   assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
1148   NumBytes += getCurrentPCOffset();
1149   BufferBegin = SavedBufferBegin;
1150   BufferEnd = SavedBufferEnd;
1151   CurBufferPtr = SavedCurBufferPtr;
1152 }
1153
1154 void *JITEmitter::allocIndirectGV(const GlobalValue *GV,
1155                                   const uint8_t *Buffer, size_t Size,
1156                                   unsigned Alignment) {
1157   uint8_t *IndGV = MemMgr->allocateStub(GV, Size, Alignment);
1158   memcpy(IndGV, Buffer, Size);
1159   return IndGV;
1160 }
1161
1162 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1163 // in the constant pool that was last emitted with the 'emitConstantPool'
1164 // method.
1165 //
1166 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1167   assert(ConstantNum < ConstantPool->getConstants().size() &&
1168          "Invalid ConstantPoolIndex!");
1169   return ConstPoolAddresses[ConstantNum];
1170 }
1171
1172 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1173 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1174 //
1175 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1176   const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1177   assert(Index < JT.size() && "Invalid jump table index!");
1178
1179   unsigned EntrySize = JumpTable->getEntrySize(*TheJIT->getDataLayout());
1180
1181   unsigned Offset = 0;
1182   for (unsigned i = 0; i < Index; ++i)
1183     Offset += JT[i].MBBs.size();
1184
1185    Offset *= EntrySize;
1186
1187   return (uintptr_t)((char *)JumpTableBase + Offset);
1188 }
1189
1190 void JITEmitter::EmittedFunctionConfig::onDelete(
1191   JITEmitter *Emitter, const Function *F) {
1192   Emitter->deallocateMemForFunction(F);
1193 }
1194 void JITEmitter::EmittedFunctionConfig::onRAUW(
1195   JITEmitter *, const Function*, const Function*) {
1196   llvm_unreachable("The JIT doesn't know how to handle a"
1197                    " RAUW on a value it has emitted.");
1198 }
1199
1200
1201 //===----------------------------------------------------------------------===//
1202 //  Public interface to this file
1203 //===----------------------------------------------------------------------===//
1204
1205 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1206                                    TargetMachine &tm) {
1207   return new JITEmitter(jit, JMM, tm);
1208 }
1209
1210 // getPointerToFunctionOrStub - If the specified function has been
1211 // code-gen'd, return a pointer to the function.  If not, compile it, or use
1212 // a stub to implement lazy compilation if available.
1213 //
1214 void *JIT::getPointerToFunctionOrStub(Function *F) {
1215   // If we have already code generated the function, just return the address.
1216   if (void *Addr = getPointerToGlobalIfAvailable(F))
1217     return Addr;
1218
1219   // Get a stub if the target supports it.
1220   JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1221   return JE->getJITResolver().getLazyFunctionStub(F);
1222 }
1223
1224 void JIT::updateFunctionStubUnlocked(Function *F) {
1225   // Get the empty stub we generated earlier.
1226   JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1227   void *Stub = JE->getJITResolver().getLazyFunctionStub(F);
1228   void *Addr = getPointerToGlobalIfAvailable(F);
1229   assert(Addr != Stub && "Function must have non-stub address to be updated.");
1230
1231   // Tell the target jit info to rewrite the stub at the specified address,
1232   // rather than creating a new one.
1233   TargetJITInfo::StubLayout layout = getJITInfo().getStubLayout();
1234   JE->startGVStub(Stub, layout.Size);
1235   getJITInfo().emitFunctionStub(F, Addr, *getCodeEmitter());
1236   JE->finishGVStub();
1237 }
1238
1239 /// freeMachineCodeForFunction - release machine code memory for given Function.
1240 ///
1241 void JIT::freeMachineCodeForFunction(Function *F) {
1242   // Delete translation for this from the ExecutionEngine, so it will get
1243   // retranslated next time it is used.
1244   updateGlobalMapping(F, nullptr);
1245
1246   // Free the actual memory for the function body and related stuff.
1247   static_cast<JITEmitter*>(JCE)->deallocateMemForFunction(F);
1248 }