Align function bodies correctly.
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a MachineCodeEmitter object that is used by the JIT to
11 // write machine code to memory and remember where relocatable values are.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "jit"
16 #include "JIT.h"
17 #include "llvm/Constant.h"
18 #include "llvm/Module.h"
19 #include "llvm/Type.h"
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineRelocation.h"
25 #include "llvm/ExecutionEngine/GenericValue.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetJITInfo.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/System/Memory.h"
31 #include <algorithm>
32 #include <iostream>
33 using namespace llvm;
34
35 namespace {
36   Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
37   Statistic<> NumRelos("jit", "Number of relocations applied");
38   JIT *TheJIT = 0;
39 }
40
41
42 //===----------------------------------------------------------------------===//
43 // JITMemoryManager code.
44 //
45 namespace {
46   /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
47   /// sane way.  This splits a large block of MAP_NORESERVE'd memory into two
48   /// sections, one for function stubs, one for the functions themselves.  We
49   /// have to do this because we may need to emit a function stub while in the
50   /// middle of emitting a function, and we don't know how large the function we
51   /// are emitting is.  This never bothers to release the memory, because when
52   /// we are ready to destroy the JIT, the program exits.
53   class JITMemoryManager {
54     std::vector<sys::MemoryBlock> Blocks; // Memory blocks allocated by the JIT
55     unsigned char *FunctionBase; // Start of the function body area
56     unsigned char *CurStubPtr, *CurFunctionPtr;
57     unsigned char *GOTBase;      // Target Specific reserved memory
58
59     // centralize memory block allocation
60     sys::MemoryBlock getNewMemoryBlock(unsigned size);
61   public:
62     JITMemoryManager(bool useGOT);
63     ~JITMemoryManager();
64
65     inline unsigned char *allocateStub(unsigned StubSize);
66     inline unsigned char *startFunctionBody();
67     inline void endFunctionBody(unsigned char *FunctionEnd);
68     
69     unsigned char *getGOTBase() const {
70       return GOTBase;
71     }
72     bool isManagingGOT() const {
73       return GOTBase != NULL;
74     }
75   };
76 }
77
78 JITMemoryManager::JITMemoryManager(bool useGOT) {
79   // Allocate a 16M block of memory for functions
80   sys::MemoryBlock FunBlock = getNewMemoryBlock(16 << 20);
81
82   FunctionBase = reinterpret_cast<unsigned char*>(FunBlock.base());
83
84   // Allocate stubs backwards from the base, allocate functions forward
85   // from the base.
86   CurStubPtr = CurFunctionPtr = FunctionBase + 512*1024;// Use 512k for stubs
87
88   // Allocate the GOT.
89   GOTBase = NULL;
90   if (useGOT) GOTBase = (unsigned char*)malloc(sizeof(void*) * 8192);
91 }
92
93 JITMemoryManager::~JITMemoryManager() {
94   for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
95     sys::Memory::ReleaseRWX(Blocks[i]);
96   Blocks.clear();
97 }
98
99 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
100   CurStubPtr -= StubSize;
101   if (CurStubPtr < FunctionBase) {
102     // FIXME: allocate a new block
103     std::cerr << "JIT ran out of memory for function stubs!\n";
104     abort();
105   }
106   return CurStubPtr;
107 }
108
109 unsigned char *JITMemoryManager::startFunctionBody() {
110   return CurFunctionPtr;
111 }
112
113 void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
114   assert(FunctionEnd > CurFunctionPtr);
115   CurFunctionPtr = FunctionEnd;
116 }
117
118 sys::MemoryBlock JITMemoryManager::getNewMemoryBlock(unsigned size) {
119   try {
120     const sys::MemoryBlock *BOld = Blocks.empty() ? 0 : &Blocks.front();
121     sys::MemoryBlock B = sys::Memory::AllocateRWX(size, BOld);
122     Blocks.push_back(B);
123     return B;
124   } catch (std::string &err) {
125     std::cerr << "Allocation failed when allocating new memory in the JIT\n";
126     std::cerr << err << "\n";
127     abort();
128   }
129 }
130
131 //===----------------------------------------------------------------------===//
132 // JIT lazy compilation code.
133 //
134 namespace {
135   class JITResolverState {
136   private:
137     /// FunctionToStubMap - Keep track of the stub created for a particular
138     /// function so that we can reuse them if necessary.
139     std::map<Function*, void*> FunctionToStubMap;
140
141     /// StubToFunctionMap - Keep track of the function that each stub
142     /// corresponds to.
143     std::map<void*, Function*> StubToFunctionMap;
144
145   public:
146     std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
147       assert(locked.holds(TheJIT->lock));
148       return FunctionToStubMap;
149     }
150
151     std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
152       assert(locked.holds(TheJIT->lock));
153       return StubToFunctionMap;
154     }
155   };
156
157   /// JITResolver - Keep track of, and resolve, call sites for functions that
158   /// have not yet been compiled.
159   class JITResolver {
160     /// MCE - The MachineCodeEmitter to use to emit stubs with.
161     MachineCodeEmitter &MCE;
162
163     /// LazyResolverFn - The target lazy resolver function that we actually
164     /// rewrite instructions to use.
165     TargetJITInfo::LazyResolverFn LazyResolverFn;
166
167     JITResolverState state;
168
169     /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
170     /// external functions.
171     std::map<void*, void*> ExternalFnToStubMap;
172
173     //map addresses to indexes in the GOT
174     std::map<void*, unsigned> revGOTMap;
175     unsigned nextGOTIndex;
176
177   public:
178     JITResolver(MachineCodeEmitter &mce) : MCE(mce), nextGOTIndex(0) {
179       LazyResolverFn =
180         TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
181     }
182
183     /// getFunctionStub - This returns a pointer to a function stub, creating
184     /// one on demand as needed.
185     void *getFunctionStub(Function *F);
186
187     /// getExternalFunctionStub - Return a stub for the function at the
188     /// specified address, created lazily on demand.
189     void *getExternalFunctionStub(void *FnAddr);
190
191     /// AddCallbackAtLocation - If the target is capable of rewriting an
192     /// instruction without the use of a stub, record the location of the use so
193     /// we know which function is being used at the location.
194     void *AddCallbackAtLocation(Function *F, void *Location) {
195       MutexGuard locked(TheJIT->lock);
196       /// Get the target-specific JIT resolver function.
197       state.getStubToFunctionMap(locked)[Location] = F;
198       return (void*)LazyResolverFn;
199     }
200
201     /// getGOTIndexForAddress - Return a new or existing index in the GOT for
202     /// and address.  This function only manages slots, it does not manage the
203     /// contents of the slots or the memory associated with the GOT.
204     unsigned getGOTIndexForAddr(void* addr);
205
206     /// JITCompilerFn - This function is called to resolve a stub to a compiled
207     /// address.  If the LLVM Function corresponding to the stub has not yet
208     /// been compiled, this function compiles it first.
209     static void *JITCompilerFn(void *Stub);
210   };
211 }
212
213 /// getJITResolver - This function returns the one instance of the JIT resolver.
214 ///
215 static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
216   static JITResolver TheJITResolver(*MCE);
217   return TheJITResolver;
218 }
219
220 /// getFunctionStub - This returns a pointer to a function stub, creating
221 /// one on demand as needed.
222 void *JITResolver::getFunctionStub(Function *F) {
223   MutexGuard locked(TheJIT->lock);
224
225   // If we already have a stub for this function, recycle it.
226   void *&Stub = state.getFunctionToStubMap(locked)[F];
227   if (Stub) return Stub;
228
229   // Call the lazy resolver function unless we already KNOW it is an external
230   // function, in which case we just skip the lazy resolution step.
231   void *Actual = (void*)LazyResolverFn;
232   if (F->isExternal() && F->hasExternalLinkage())
233     Actual = TheJIT->getPointerToFunction(F);
234
235   // Otherwise, codegen a new stub.  For now, the stub will call the lazy
236   // resolver function.
237   Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, MCE);
238
239   if (Actual != (void*)LazyResolverFn) {
240     // If we are getting the stub for an external function, we really want the
241     // address of the stub in the GlobalAddressMap for the JIT, not the address
242     // of the external function.
243     TheJIT->updateGlobalMapping(F, Stub);
244   }
245
246   DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
247                   << F->getName() << "'\n");
248
249   // Finally, keep track of the stub-to-Function mapping so that the
250   // JITCompilerFn knows which function to compile!
251   state.getStubToFunctionMap(locked)[Stub] = F;
252   return Stub;
253 }
254
255 /// getExternalFunctionStub - Return a stub for the function at the
256 /// specified address, created lazily on demand.
257 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
258   // If we already have a stub for this function, recycle it.
259   void *&Stub = ExternalFnToStubMap[FnAddr];
260   if (Stub) return Stub;
261
262   Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, MCE);
263   DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub
264         << "] for external function at '" << FnAddr << "'\n");
265   return Stub;
266 }
267
268 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
269   unsigned idx = revGOTMap[addr];
270   if (!idx) {
271     idx = ++nextGOTIndex;
272     revGOTMap[addr] = idx;
273     DEBUG(std::cerr << "Adding GOT entry " << idx
274           << " for addr " << addr << "\n");
275     //    ((void**)MemMgr.getGOTBase())[idx] = addr;
276   }
277   return idx;
278 }
279
280 /// JITCompilerFn - This function is called when a lazy compilation stub has
281 /// been entered.  It looks up which function this stub corresponds to, compiles
282 /// it if necessary, then returns the resultant function pointer.
283 void *JITResolver::JITCompilerFn(void *Stub) {
284   JITResolver &JR = getJITResolver();
285
286   MutexGuard locked(TheJIT->lock);
287
288   // The address given to us for the stub may not be exactly right, it might be
289   // a little bit after the stub.  As such, use upper_bound to find it.
290   std::map<void*, Function*>::iterator I =
291     JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
292   assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
293          "This is not a known stub!");
294   Function *F = (--I)->second;
295
296   // We might like to remove the stub from the StubToFunction map.
297   // We can't do that! Multiple threads could be stuck, waiting to acquire the
298   // lock above. As soon as the 1st function finishes compiling the function,
299   // the next one will be released, and needs to be able to find the function it
300   // needs to call.
301   //JR.state.getStubToFunctionMap(locked).erase(I);
302
303   DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
304                   << "' In stub ptr = " << Stub << " actual ptr = "
305                   << I->first << "\n");
306
307   void *Result = TheJIT->getPointerToFunction(F);
308
309   // We don't need to reuse this stub in the future, as F is now compiled.
310   JR.state.getFunctionToStubMap(locked).erase(F);
311
312   // FIXME: We could rewrite all references to this stub if we knew them.
313
314   // What we will do is set the compiled function address to map to the
315   // same GOT entry as the stub so that later clients may update the GOT
316   // if they see it still using the stub address.
317   // Note: this is done so the Resolver doesn't have to manage GOT memory
318   // Do this without allocating map space if the target isn't using a GOT
319   if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
320     JR.revGOTMap[Result] = JR.revGOTMap[Stub];
321
322   return Result;
323 }
324
325
326 // getPointerToFunctionOrStub - If the specified function has been
327 // code-gen'd, return a pointer to the function.  If not, compile it, or use
328 // a stub to implement lazy compilation if available.
329 //
330 void *JIT::getPointerToFunctionOrStub(Function *F) {
331   // If we have already code generated the function, just return the address.
332   if (void *Addr = getPointerToGlobalIfAvailable(F))
333     return Addr;
334
335   // Get a stub if the target supports it
336   return getJITResolver(MCE).getFunctionStub(F);
337 }
338
339
340
341 //===----------------------------------------------------------------------===//
342 // JITEmitter code.
343 //
344 namespace {
345   /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
346   /// used to output functions to memory for execution.
347   class JITEmitter : public MachineCodeEmitter {
348     JITMemoryManager MemMgr;
349
350     // When outputting a function stub in the context of some other function, we
351     // save BufferBegin/BufferEnd/CurBufferPtr here.
352     unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
353
354     /// Relocations - These are the relocations that the function needs, as
355     /// emitted.
356     std::vector<MachineRelocation> Relocations;
357
358     /// ConstantPool - The constant pool for the current function.
359     ///
360     MachineConstantPool *ConstantPool;
361
362     /// ConstantPoolBase - A pointer to the first entry in the constant pool.
363     ///
364     void *ConstantPoolBase;
365
366     /// ConstantPool - The constant pool for the current function.
367     ///
368     MachineJumpTableInfo *JumpTable;
369     
370     /// JumpTableBase - A pointer to the first entry in the jump table.
371     ///
372     void *JumpTableBase;
373 public:
374     JITEmitter(JIT &jit) : MemMgr(jit.getJITInfo().needsGOT()) {
375       TheJIT = &jit;
376       DEBUG(if (MemMgr.isManagingGOT()) std::cerr << "JIT is managing a GOT\n");
377     }
378
379     virtual void startFunction(MachineFunction &F);
380     virtual bool finishFunction(MachineFunction &F);
381     
382     void emitConstantPool(MachineConstantPool *MCP);
383     void initJumpTableInfo(MachineJumpTableInfo *MJTI);
384     virtual void emitJumpTableInfo(MachineJumpTableInfo *MJTI,
385                                    std::vector<uint64_t> &MBBM);
386     
387     virtual void startFunctionStub(unsigned StubSize);
388     virtual void* finishFunctionStub(const Function *F);
389
390     virtual void addRelocation(const MachineRelocation &MR) {
391       Relocations.push_back(MR);
392     }
393
394     virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
395     virtual uint64_t getJumpTableEntryAddress(unsigned Entry);
396
397   private:
398     void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
399   };
400 }
401
402 MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
403   return new JITEmitter(jit);
404 }
405
406 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
407                                      bool DoesntNeedStub) {
408   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
409     /// FIXME: If we straightened things out, this could actually emit the
410     /// global immediately instead of queuing it for codegen later!
411     return TheJIT->getOrEmitGlobalVariable(GV);
412   }
413
414   // If we have already compiled the function, return a pointer to its body.
415   Function *F = cast<Function>(V);
416   void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
417   if (ResultPtr) return ResultPtr;
418
419   if (F->hasExternalLinkage() && F->isExternal()) {
420     // If this is an external function pointer, we can force the JIT to
421     // 'compile' it, which really just adds it to the map.
422     if (DoesntNeedStub)
423       return TheJIT->getPointerToFunction(F);
424
425     return getJITResolver(this).getFunctionStub(F);
426   }
427
428   // Okay, the function has not been compiled yet, if the target callback
429   // mechanism is capable of rewriting the instruction directly, prefer to do
430   // that instead of emitting a stub.
431   if (DoesntNeedStub)
432     return getJITResolver(this).AddCallbackAtLocation(F, Reference);
433
434   // Otherwise, we have to emit a lazy resolving stub.
435   return getJITResolver(this).getFunctionStub(F);
436 }
437
438 void JITEmitter::startFunction(MachineFunction &F) {
439   BufferBegin = CurBufferPtr = MemMgr.startFunctionBody();
440   
441   /// FIXME: implement out of space handling correctly!
442   BufferEnd = (unsigned char*)(intptr_t)~0ULL;
443   
444   emitConstantPool(F.getConstantPool());
445   initJumpTableInfo(F.getJumpTableInfo());
446
447   // About to start emitting the machine code for the function.
448   emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
449   TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
450 }
451
452 bool JITEmitter::finishFunction(MachineFunction &F) {
453   MemMgr.endFunctionBody(CurBufferPtr);
454   NumBytes += getCurrentPCOffset();
455
456   if (!Relocations.empty()) {
457     NumRelos += Relocations.size();
458
459     // Resolve the relocations to concrete pointers.
460     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
461       MachineRelocation &MR = Relocations[i];
462       void *ResultPtr;
463       if (MR.isString()) {
464         ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
465
466         // If the target REALLY wants a stub for this function, emit it now.
467         if (!MR.doesntNeedFunctionStub())
468           ResultPtr = getJITResolver(this).getExternalFunctionStub(ResultPtr);
469       } else if (MR.isGlobalValue())
470         ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
471                                        BufferBegin+MR.getMachineCodeOffset(),
472                                        MR.doesntNeedFunctionStub());
473       else //ConstantPoolIndex
474         ResultPtr =
475        (void*)(intptr_t)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
476
477       MR.setResultPointer(ResultPtr);
478
479       // if we are managing the GOT and the relocation wants an index,
480       // give it one
481       if (MemMgr.isManagingGOT() && !MR.isConstantPoolIndex() &&
482           MR.isGOTRelative()) {
483         unsigned idx = getJITResolver(this).getGOTIndexForAddr(ResultPtr);
484         MR.setGOTIndex(idx);
485         if (((void**)MemMgr.getGOTBase())[idx] != ResultPtr) {
486           DEBUG(std::cerr << "GOT was out of date for " << ResultPtr
487                 << " pointing at " << ((void**)MemMgr.getGOTBase())[idx]
488                 << "\n");
489           ((void**)MemMgr.getGOTBase())[idx] = ResultPtr;
490         }
491       }
492     }
493
494     TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
495                                   Relocations.size(), MemMgr.getGOTBase());
496   }
497
498   //Update the GOT entry for F to point to the new code.
499   if(MemMgr.isManagingGOT()) {
500     unsigned idx = getJITResolver(this).getGOTIndexForAddr((void*)BufferBegin);
501     if (((void**)MemMgr.getGOTBase())[idx] != (void*)BufferBegin) {
502       DEBUG(std::cerr << "GOT was out of date for " << (void*)BufferBegin
503             << " pointing at " << ((void**)MemMgr.getGOTBase())[idx] << "\n");
504       ((void**)MemMgr.getGOTBase())[idx] = (void*)BufferBegin;
505     }
506   }
507
508   DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)BufferBegin
509                   << "] Function: " << F.getFunction()->getName()
510                   << ": " << getCurrentPCOffset() << " bytes of text, "
511                   << Relocations.size() << " relocations\n");
512   Relocations.clear();
513   return false;
514 }
515
516 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
517   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
518   if (Constants.empty()) return;
519
520   unsigned Size = Constants.back().Offset;
521   Size += TheJIT->getTargetData().getTypeSize(Constants.back().Val->getType());
522
523   ConstantPoolBase = allocateSpace(Size, 1 << MCP->getConstantPoolAlignment());
524   ConstantPool = MCP;
525
526   if (ConstantPoolBase == 0) return;  // Buffer overflow.
527
528   // Initialize the memory for all of the constant pool entries.
529   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
530     void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
531     TheJIT->InitializeMemory(Constants[i].Val, CAddr);
532   }
533 }
534
535 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
536   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
537   if (JT.empty()) return;
538   
539   unsigned NumEntries = 0;
540   for (unsigned i = 0, e = JT.size(); i != e; ++i)
541     NumEntries += JT[i].MBBs.size();
542
543   unsigned EntrySize = MJTI->getEntrySize();
544
545   // Just allocate space for all the jump tables now.  We will fix up the actual
546   // MBB entries in the tables after we emit the code for each block, since then
547   // we will know the final locations of the MBBs in memory.
548   JumpTable = MJTI;
549   JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
550 }
551
552 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI,
553                                    std::vector<uint64_t> &MBBM) {
554   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
555   if (JT.empty() || JumpTableBase == 0) return;
556
557   unsigned Offset = 0;
558   assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
559   
560   // For each jump table, map each target in the jump table to the address of 
561   // an emitted MachineBasicBlock.
562   intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
563
564   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
565     const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
566     // Store the address of the basic block for this jump table slot in the
567     // memory we allocated for the jump table in 'initJumpTableInfo'
568     for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
569       *SlotPtr++ = (intptr_t)MBBM[MBBs[mi]->getNumber()];
570   }
571 }
572
573 void JITEmitter::startFunctionStub(unsigned StubSize) {
574   SavedBufferBegin = BufferBegin;
575   SavedBufferEnd = BufferEnd;
576   SavedCurBufferPtr = CurBufferPtr;
577   
578   BufferBegin = CurBufferPtr = MemMgr.allocateStub(StubSize);
579   BufferEnd = BufferBegin+StubSize+1;
580 }
581
582 void *JITEmitter::finishFunctionStub(const Function *F) {
583   NumBytes += getCurrentPCOffset();
584   std::swap(SavedBufferBegin, BufferBegin);
585   BufferEnd = SavedBufferEnd;
586   CurBufferPtr = SavedCurBufferPtr;
587   return SavedBufferBegin;
588 }
589
590 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
591 // in the constant pool that was last emitted with the 'emitConstantPool'
592 // method.
593 //
594 uint64_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
595   assert(ConstantNum < ConstantPool->getConstants().size() &&
596          "Invalid ConstantPoolIndex!");
597   return (intptr_t)ConstantPoolBase +
598          ConstantPool->getConstants()[ConstantNum].Offset;
599 }
600
601 // getJumpTableEntryAddress - Return the address of the JumpTable with index
602 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
603 //
604 uint64_t JITEmitter::getJumpTableEntryAddress(unsigned Index) {
605   const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
606   assert(Index < JT.size() && "Invalid jump table index!");
607   
608   unsigned Offset = 0;
609   unsigned EntrySize = JumpTable->getEntrySize();
610   
611   for (unsigned i = 0; i < Index; ++i)
612     Offset += JT[i].MBBs.size() * EntrySize;
613   
614   return (intptr_t)((char *)JumpTableBase + Offset);
615 }
616
617 // getPointerToNamedFunction - This function is used as a global wrapper to
618 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
619 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
620 // need to resolve function(s) that are being mis-codegenerated, so we need to
621 // resolve their addresses at runtime, and this is the way to do it.
622 extern "C" {
623   void *getPointerToNamedFunction(const char *Name) {
624     Module &M = TheJIT->getModule();
625     if (Function *F = M.getNamedFunction(Name))
626       return TheJIT->getPointerToFunction(F);
627     return TheJIT->getPointerToNamedFunction(Name);
628   }
629 }