JITEmitter.cpp revision 3b374489041ac28153c84194dda45e182d8939fc
1//===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a MachineCodeEmitter object that is used by the JIT to
11// write machine code to memory and remember where relocatable values are.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "jit"
16#include "JIT.h"
17#include "JITDwarfEmitter.h"
18#include "llvm/Constant.h"
19#include "llvm/Module.h"
20#include "llvm/Type.h"
21#include "llvm/CodeGen/MachineCodeEmitter.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineJumpTableInfo.h"
25#include "llvm/CodeGen/MachineModuleInfo.h"
26#include "llvm/CodeGen/MachineRelocation.h"
27#include "llvm/ExecutionEngine/JITMemoryManager.h"
28#include "llvm/Target/TargetData.h"
29#include "llvm/Target/TargetJITInfo.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetOptions.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/MutexGuard.h"
34#include "llvm/System/Disassembler.h"
35#include "llvm/ADT/Statistic.h"
36#include <algorithm>
37using namespace llvm;
38
39STATISTIC(NumBytes, "Number of bytes of machine code compiled");
40STATISTIC(NumRelos, "Number of relocations applied");
41static JIT *TheJIT = 0;
42
43
44//===----------------------------------------------------------------------===//
45// JIT lazy compilation code.
46//
47namespace {
48  class JITResolverState {
49  private:
50    /// FunctionToStubMap - Keep track of the stub created for a particular
51    /// function so that we can reuse them if necessary.
52    std::map<Function*, void*> FunctionToStubMap;
53
54    /// StubToFunctionMap - Keep track of the function that each stub
55    /// corresponds to.
56    std::map<void*, Function*> StubToFunctionMap;
57
58    /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a
59    /// particular GlobalVariable so that we can reuse them if necessary.
60    std::map<GlobalValue*, void*> GlobalToLazyPtrMap;
61
62  public:
63    std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
64      assert(locked.holds(TheJIT->lock));
65      return FunctionToStubMap;
66    }
67
68    std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
69      assert(locked.holds(TheJIT->lock));
70      return StubToFunctionMap;
71    }
72
73    std::map<GlobalValue*, void*>&
74    getGlobalToLazyPtrMap(const MutexGuard& locked) {
75      assert(locked.holds(TheJIT->lock));
76      return GlobalToLazyPtrMap;
77    }
78  };
79
80  /// JITResolver - Keep track of, and resolve, call sites for functions that
81  /// have not yet been compiled.
82  class JITResolver {
83    /// LazyResolverFn - The target lazy resolver function that we actually
84    /// rewrite instructions to use.
85    TargetJITInfo::LazyResolverFn LazyResolverFn;
86
87    JITResolverState state;
88
89    /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
90    /// external functions.
91    std::map<void*, void*> ExternalFnToStubMap;
92
93    //map addresses to indexes in the GOT
94    std::map<void*, unsigned> revGOTMap;
95    unsigned nextGOTIndex;
96
97    static JITResolver *TheJITResolver;
98  public:
99    explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
100      TheJIT = &jit;
101
102      LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
103      assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
104      TheJITResolver = this;
105    }
106
107    ~JITResolver() {
108      TheJITResolver = 0;
109    }
110
111    /// getFunctionStub - This returns a pointer to a function stub, creating
112    /// one on demand as needed.
113    void *getFunctionStub(Function *F);
114
115    /// getExternalFunctionStub - Return a stub for the function at the
116    /// specified address, created lazily on demand.
117    void *getExternalFunctionStub(void *FnAddr);
118
119    /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
120    /// GV address.
121    void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress);
122
123    /// AddCallbackAtLocation - If the target is capable of rewriting an
124    /// instruction without the use of a stub, record the location of the use so
125    /// we know which function is being used at the location.
126    void *AddCallbackAtLocation(Function *F, void *Location) {
127      MutexGuard locked(TheJIT->lock);
128      /// Get the target-specific JIT resolver function.
129      state.getStubToFunctionMap(locked)[Location] = F;
130      return (void*)(intptr_t)LazyResolverFn;
131    }
132
133    /// getGOTIndexForAddress - Return a new or existing index in the GOT for
134    /// an address.  This function only manages slots, it does not manage the
135    /// contents of the slots or the memory associated with the GOT.
136    unsigned getGOTIndexForAddr(void *addr);
137
138    /// JITCompilerFn - This function is called to resolve a stub to a compiled
139    /// address.  If the LLVM Function corresponding to the stub has not yet
140    /// been compiled, this function compiles it first.
141    static void *JITCompilerFn(void *Stub);
142  };
143}
144
145JITResolver *JITResolver::TheJITResolver = 0;
146
147#if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
148    defined(__APPLE__)
149extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
150#endif
151
152/// synchronizeICache - On some targets, the JIT emitted code must be
153/// explicitly refetched to ensure correct execution.
154static void synchronizeICache(const void *Addr, size_t len) {
155#if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
156    defined(__APPLE__)
157  sys_icache_invalidate(Addr, len);
158#endif
159}
160
161/// getFunctionStub - This returns a pointer to a function stub, creating
162/// one on demand as needed.
163void *JITResolver::getFunctionStub(Function *F) {
164  MutexGuard locked(TheJIT->lock);
165
166  // If we already have a stub for this function, recycle it.
167  void *&Stub = state.getFunctionToStubMap(locked)[F];
168  if (Stub) return Stub;
169
170  // Call the lazy resolver function unless we already KNOW it is an external
171  // function, in which case we just skip the lazy resolution step.
172  void *Actual = (void*)(intptr_t)LazyResolverFn;
173  if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
174    Actual = TheJIT->getPointerToFunction(F);
175
176  // Otherwise, codegen a new stub.  For now, the stub will call the lazy
177  // resolver function.
178  Stub = TheJIT->getJITInfo().emitFunctionStub(Actual,
179                                               *TheJIT->getCodeEmitter());
180
181  if (Actual != (void*)(intptr_t)LazyResolverFn) {
182    // If we are getting the stub for an external function, we really want the
183    // address of the stub in the GlobalAddressMap for the JIT, not the address
184    // of the external function.
185    TheJIT->updateGlobalMapping(F, Stub);
186  }
187
188  DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
189       << F->getName() << "'\n";
190
191  // Finally, keep track of the stub-to-Function mapping so that the
192  // JITCompilerFn knows which function to compile!
193  state.getStubToFunctionMap(locked)[Stub] = F;
194  return Stub;
195}
196
197/// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
198/// GV address.
199void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) {
200  MutexGuard locked(TheJIT->lock);
201
202  // If we already have a stub for this global variable, recycle it.
203  void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV];
204  if (LazyPtr) return LazyPtr;
205
206  // Otherwise, codegen a new lazy pointer.
207  LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GVAddress,
208                                                    *TheJIT->getCodeEmitter());
209
210  DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '"
211       << GV->getName() << "'\n";
212
213  return LazyPtr;
214}
215
216/// getExternalFunctionStub - Return a stub for the function at the
217/// specified address, created lazily on demand.
218void *JITResolver::getExternalFunctionStub(void *FnAddr) {
219  // If we already have a stub for this function, recycle it.
220  void *&Stub = ExternalFnToStubMap[FnAddr];
221  if (Stub) return Stub;
222
223  Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr,
224                                               *TheJIT->getCodeEmitter());
225
226  DOUT << "JIT: Stub emitted at [" << Stub
227       << "] for external function at '" << FnAddr << "'\n";
228  return Stub;
229}
230
231unsigned JITResolver::getGOTIndexForAddr(void* addr) {
232  unsigned idx = revGOTMap[addr];
233  if (!idx) {
234    idx = ++nextGOTIndex;
235    revGOTMap[addr] = idx;
236    DOUT << "Adding GOT entry " << idx << " for addr " << addr << "\n";
237  }
238  return idx;
239}
240
241/// JITCompilerFn - This function is called when a lazy compilation stub has
242/// been entered.  It looks up which function this stub corresponds to, compiles
243/// it if necessary, then returns the resultant function pointer.
244void *JITResolver::JITCompilerFn(void *Stub) {
245  JITResolver &JR = *TheJITResolver;
246
247  MutexGuard locked(TheJIT->lock);
248
249  // The address given to us for the stub may not be exactly right, it might be
250  // a little bit after the stub.  As such, use upper_bound to find it.
251  std::map<void*, Function*>::iterator I =
252    JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
253  assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
254         "This is not a known stub!");
255  Function *F = (--I)->second;
256
257  // If we have already code generated the function, just return the address.
258  void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
259
260  if (!Result) {
261    // Otherwise we don't have it, do lazy compilation now.
262
263    // If lazy compilation is disabled, emit a useful error message and abort.
264    if (TheJIT->isLazyCompilationDisabled()) {
265      cerr << "LLVM JIT requested to do lazy compilation of function '"
266      << F->getName() << "' when lazy compiles are disabled!\n";
267      abort();
268    }
269
270    // We might like to remove the stub from the StubToFunction map.
271    // We can't do that! Multiple threads could be stuck, waiting to acquire the
272    // lock above. As soon as the 1st function finishes compiling the function,
273    // the next one will be released, and needs to be able to find the function
274    // it needs to call.
275    //JR.state.getStubToFunctionMap(locked).erase(I);
276
277    DOUT << "JIT: Lazily resolving function '" << F->getName()
278         << "' In stub ptr = " << Stub << " actual ptr = "
279         << I->first << "\n";
280
281    Result = TheJIT->getPointerToFunction(F);
282  }
283
284  // We don't need to reuse this stub in the future, as F is now compiled.
285  JR.state.getFunctionToStubMap(locked).erase(F);
286
287  // FIXME: We could rewrite all references to this stub if we knew them.
288
289  // What we will do is set the compiled function address to map to the
290  // same GOT entry as the stub so that later clients may update the GOT
291  // if they see it still using the stub address.
292  // Note: this is done so the Resolver doesn't have to manage GOT memory
293  // Do this without allocating map space if the target isn't using a GOT
294  if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
295    JR.revGOTMap[Result] = JR.revGOTMap[Stub];
296
297  return Result;
298}
299
300//===----------------------------------------------------------------------===//
301// Function Index Support
302
303// On MacOS we generate an index of currently JIT'd functions so that
304// performance tools can determine a symbol name and accurate code range for a
305// PC value.  Because performance tools are generally asynchronous, the code
306// below is written with the hope that it could be interrupted at any time and
307// have useful answers.  However, we don't go crazy with atomic operations, we
308// just do a "reasonable effort".
309#ifdef __APPLE__
310#define ENABLE_JIT_SYMBOL_TABLE 1
311#endif
312
313/// JitSymbolEntry - Each function that is JIT compiled results in one of these
314/// being added to an array of symbols.  This indicates the name of the function
315/// as well as the address range it occupies.  This allows the client to map
316/// from a PC value to the name of the function.
317struct JitSymbolEntry {
318  const char *FnName;   // FnName - a strdup'd string.
319  void *FnStart;
320  intptr_t FnSize;
321};
322
323
324struct JitSymbolTable {
325  /// NextPtr - This forms a linked list of JitSymbolTable entries.  This
326  /// pointer is not used right now, but might be used in the future.  Consider
327  /// it reserved for future use.
328  JitSymbolTable *NextPtr;
329
330  /// Symbols - This is an array of JitSymbolEntry entries.  Only the first
331  /// 'NumSymbols' symbols are valid.
332  JitSymbolEntry *Symbols;
333
334  /// NumSymbols - This indicates the number entries in the Symbols array that
335  /// are valid.
336  unsigned NumSymbols;
337
338  /// NumAllocated - This indicates the amount of space we have in the Symbols
339  /// array.  This is a private field that should not be read by external tools.
340  unsigned NumAllocated;
341};
342
343#if ENABLE_JIT_SYMBOL_TABLE
344JitSymbolTable *__jitSymbolTable;
345#endif
346
347static void AddFunctionToSymbolTable(const char *FnName,
348                                     void *FnStart, intptr_t FnSize) {
349  assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
350  JitSymbolTable **SymTabPtrPtr = 0;
351#if !ENABLE_JIT_SYMBOL_TABLE
352  return;
353#else
354  SymTabPtrPtr = &__jitSymbolTable;
355#endif
356
357  // If this is the first entry in the symbol table, add the JitSymbolTable
358  // index.
359  if (*SymTabPtrPtr == 0) {
360    JitSymbolTable *New = new JitSymbolTable();
361    New->NextPtr = 0;
362    New->Symbols = 0;
363    New->NumSymbols = 0;
364    New->NumAllocated = 0;
365    *SymTabPtrPtr = New;
366  }
367
368  JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
369
370  // If we have space in the table, reallocate the table.
371  if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
372    // If we don't have space, reallocate the table.
373    unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
374    JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
375    JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
376
377    // Copy the old entries over.
378    memcpy(NewSymbols, OldSymbols,
379           SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
380
381    // Swap the new symbols in, delete the old ones.
382    SymTabPtr->Symbols = NewSymbols;
383    SymTabPtr->NumAllocated = NewSize;
384    delete [] OldSymbols;
385  }
386
387  // Otherwise, we have enough space, just tack it onto the end of the array.
388  JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
389  Entry.FnName = strdup(FnName);
390  Entry.FnStart = FnStart;
391  Entry.FnSize = FnSize;
392  ++SymTabPtr->NumSymbols;
393}
394
395static void RemoveFunctionFromSymbolTable(void *FnStart) {
396  assert(FnStart && "Invalid function pointer");
397  JitSymbolTable **SymTabPtrPtr = 0;
398#if !ENABLE_JIT_SYMBOL_TABLE
399  return;
400#else
401  SymTabPtrPtr = &__jitSymbolTable;
402#endif
403
404  JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
405  JitSymbolEntry *Symbols = SymTabPtr->Symbols;
406
407  // Scan the table to find its index.  The table is not sorted, so do a linear
408  // scan.
409  unsigned Index;
410  for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
411    assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
412
413  // Once we have an index, we know to nuke this entry, overwrite it with the
414  // entry at the end of the array, making the last entry redundant.
415  const char *OldName = Symbols[Index].FnName;
416  Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
417  free((void*)OldName);
418
419  // Drop the number of symbols in the table.
420  --SymTabPtr->NumSymbols;
421
422  // Finally, if we deleted the final symbol, deallocate the table itself.
423  if (SymTabPtr->NumSymbols == 0)
424    return;
425
426  *SymTabPtrPtr = 0;
427  delete [] Symbols;
428  delete SymTabPtr;
429}
430
431//===----------------------------------------------------------------------===//
432// JITEmitter code.
433//
434namespace {
435  /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
436  /// used to output functions to memory for execution.
437  class JITEmitter : public MachineCodeEmitter {
438    JITMemoryManager *MemMgr;
439
440    // When outputting a function stub in the context of some other function, we
441    // save BufferBegin/BufferEnd/CurBufferPtr here.
442    unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
443
444    /// Relocations - These are the relocations that the function needs, as
445    /// emitted.
446    std::vector<MachineRelocation> Relocations;
447
448    /// MBBLocations - This vector is a mapping from MBB ID's to their address.
449    /// It is filled in by the StartMachineBasicBlock callback and queried by
450    /// the getMachineBasicBlockAddress callback.
451    std::vector<intptr_t> MBBLocations;
452
453    /// ConstantPool - The constant pool for the current function.
454    ///
455    MachineConstantPool *ConstantPool;
456
457    /// ConstantPoolBase - A pointer to the first entry in the constant pool.
458    ///
459    void *ConstantPoolBase;
460
461    /// JumpTable - The jump tables for the current function.
462    ///
463    MachineJumpTableInfo *JumpTable;
464
465    /// JumpTableBase - A pointer to the first entry in the jump table.
466    ///
467    void *JumpTableBase;
468
469    /// Resolver - This contains info about the currently resolved functions.
470    JITResolver Resolver;
471
472    /// DE - The dwarf emitter for the jit.
473    JITDwarfEmitter *DE;
474
475    /// LabelLocations - This vector is a mapping from Label ID's to their
476    /// address.
477    std::vector<intptr_t> LabelLocations;
478
479    /// MMI - Machine module info for exception informations
480    MachineModuleInfo* MMI;
481
482  public:
483    JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
484      MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
485      if (jit.getJITInfo().needsGOT()) {
486        MemMgr->AllocateGOT();
487        DOUT << "JIT is managing a GOT\n";
488      }
489
490      if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
491    }
492    ~JITEmitter() {
493      delete MemMgr;
494      if (ExceptionHandling) delete DE;
495    }
496
497    JITResolver &getJITResolver() { return Resolver; }
498
499    virtual void startFunction(MachineFunction &F);
500    virtual bool finishFunction(MachineFunction &F);
501
502    void emitConstantPool(MachineConstantPool *MCP);
503    void initJumpTableInfo(MachineJumpTableInfo *MJTI);
504    void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
505
506    virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1);
507    virtual void* finishFunctionStub(const Function *F);
508
509    virtual void addRelocation(const MachineRelocation &MR) {
510      Relocations.push_back(MR);
511    }
512
513    virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
514      if (MBBLocations.size() <= (unsigned)MBB->getNumber())
515        MBBLocations.resize((MBB->getNumber()+1)*2);
516      MBBLocations[MBB->getNumber()] = getCurrentPCValue();
517    }
518
519    virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
520    virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
521
522    virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
523      assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
524             MBBLocations[MBB->getNumber()] && "MBB not emitted!");
525      return MBBLocations[MBB->getNumber()];
526    }
527
528    /// deallocateMemForFunction - Deallocate all memory for the specified
529    /// function body.
530    void deallocateMemForFunction(Function *F) {
531      MemMgr->deallocateMemForFunction(F);
532    }
533
534    virtual void emitLabel(uint64_t LabelID) {
535      if (LabelLocations.size() <= LabelID)
536        LabelLocations.resize((LabelID+1)*2);
537      LabelLocations[LabelID] = getCurrentPCValue();
538    }
539
540    virtual intptr_t getLabelAddress(uint64_t LabelID) const {
541      assert(LabelLocations.size() > (unsigned)LabelID &&
542             LabelLocations[LabelID] && "Label not emitted!");
543      return LabelLocations[LabelID];
544    }
545
546    virtual void setModuleInfo(MachineModuleInfo* Info) {
547      MMI = Info;
548      if (ExceptionHandling) DE->setModuleInfo(Info);
549    }
550
551  private:
552    void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
553    void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
554                                bool NoNeedStub);
555  };
556}
557
558void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
559                                     bool DoesntNeedStub) {
560  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
561    /// FIXME: If we straightened things out, this could actually emit the
562    /// global immediately instead of queuing it for codegen later!
563    return TheJIT->getOrEmitGlobalVariable(GV);
564  }
565
566  // If we have already compiled the function, return a pointer to its body.
567  Function *F = cast<Function>(V);
568  void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
569  if (ResultPtr) return ResultPtr;
570
571  if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
572    // If this is an external function pointer, we can force the JIT to
573    // 'compile' it, which really just adds it to the map.
574    if (DoesntNeedStub)
575      return TheJIT->getPointerToFunction(F);
576
577    return Resolver.getFunctionStub(F);
578  }
579
580  // Okay, the function has not been compiled yet, if the target callback
581  // mechanism is capable of rewriting the instruction directly, prefer to do
582  // that instead of emitting a stub.
583  if (DoesntNeedStub)
584    return Resolver.AddCallbackAtLocation(F, Reference);
585
586  // Otherwise, we have to emit a lazy resolving stub.
587  return Resolver.getFunctionStub(F);
588}
589
590void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
591                                        bool DoesntNeedStub) {
592  // Make sure GV is emitted first.
593  // FIXME: For now, if the GV is an external function we force the JIT to
594  // compile it so the lazy pointer will contain the fully resolved address.
595  void *GVAddress = getPointerToGlobal(V, Reference, true);
596  return Resolver.getGlobalValueLazyPtr(V, GVAddress);
597}
598
599
600void JITEmitter::startFunction(MachineFunction &F) {
601  uintptr_t ActualSize;
602  BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
603                                                         ActualSize);
604  BufferEnd = BufferBegin+ActualSize;
605
606  // Ensure the constant pool/jump table info is at least 4-byte aligned.
607  emitAlignment(16);
608
609  emitConstantPool(F.getConstantPool());
610  initJumpTableInfo(F.getJumpTableInfo());
611
612  // About to start emitting the machine code for the function.
613  emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
614  TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
615
616  MBBLocations.clear();
617}
618
619bool JITEmitter::finishFunction(MachineFunction &F) {
620  if (CurBufferPtr == BufferEnd) {
621    // FIXME: Allocate more space, then try again.
622    cerr << "JIT: Ran out of space for generated machine code!\n";
623    abort();
624  }
625
626  emitJumpTableInfo(F.getJumpTableInfo());
627
628  // FnStart is the start of the text, not the start of the constant pool and
629  // other per-function data.
630  unsigned char *FnStart =
631    (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
632  unsigned char *FnEnd   = CurBufferPtr;
633
634  MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
635  NumBytes += FnEnd-FnStart;
636
637  if (!Relocations.empty()) {
638    NumRelos += Relocations.size();
639
640    // Resolve the relocations to concrete pointers.
641    for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
642      MachineRelocation &MR = Relocations[i];
643      void *ResultPtr;
644      if (MR.isString()) {
645        ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
646
647        // If the target REALLY wants a stub for this function, emit it now.
648        if (!MR.doesntNeedStub())
649          ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
650      } else if (MR.isGlobalValue()) {
651        ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
652                                       BufferBegin+MR.getMachineCodeOffset(),
653                                       MR.doesntNeedStub());
654      } else if (MR.isGlobalValueLazyPtr()) {
655        ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(),
656                                          BufferBegin+MR.getMachineCodeOffset(),
657                                          MR.doesntNeedStub());
658      } else if (MR.isBasicBlock()) {
659        ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
660      } else if (MR.isConstantPoolIndex()) {
661        ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
662      } else {
663        assert(MR.isJumpTableIndex());
664        ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
665      }
666
667      MR.setResultPointer(ResultPtr);
668
669      // if we are managing the GOT and the relocation wants an index,
670      // give it one
671      if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
672        unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
673        MR.setGOTIndex(idx);
674        if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
675          DOUT << "GOT was out of date for " << ResultPtr
676               << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
677               << "\n";
678          ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
679        }
680      }
681    }
682
683    TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
684                                  Relocations.size(), MemMgr->getGOTBase());
685  }
686
687  // Update the GOT entry for F to point to the new code.
688  if (MemMgr->isManagingGOT()) {
689    unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
690    if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
691      DOUT << "GOT was out of date for " << (void*)BufferBegin
692           << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
693      ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
694    }
695  }
696
697  // Invalidate the icache if necessary.
698  synchronizeICache(FnStart, FnEnd-FnStart);
699
700  // Add it to the JIT symbol table if the host wants it.
701  AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
702                           FnStart, FnEnd-FnStart);
703
704  DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
705       << "] Function: " << F.getFunction()->getName()
706       << ": " << (FnEnd-FnStart) << " bytes of text, "
707       << Relocations.size() << " relocations\n";
708  Relocations.clear();
709
710#ifndef NDEBUG
711  if (sys::hasDisassembler())
712    DOUT << "Disassembled code:\n"
713         << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
714#endif
715  if (ExceptionHandling) {
716    uintptr_t ActualSize;
717    SavedBufferBegin = BufferBegin;
718    SavedBufferEnd = BufferEnd;
719    SavedCurBufferPtr = CurBufferPtr;
720
721    BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
722                                                             ActualSize);
723    BufferEnd = BufferBegin+ActualSize;
724    unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
725    MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
726                              FrameRegister);
727    BufferBegin = SavedBufferBegin;
728    BufferEnd = SavedBufferEnd;
729    CurBufferPtr = SavedCurBufferPtr;
730
731    TheJIT->RegisterTable(FrameRegister);
732  }
733  MMI->EndFunction();
734
735  return false;
736}
737
738void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
739  const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
740  if (Constants.empty()) return;
741
742  MachineConstantPoolEntry CPE = Constants.back();
743  unsigned Size = CPE.Offset;
744  const Type *Ty = CPE.isMachineConstantPoolEntry()
745    ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
746  Size += TheJIT->getTargetData()->getABITypeSize(Ty);
747
748  unsigned Align = 1 << MCP->getConstantPoolAlignment();
749  ConstantPoolBase = allocateSpace(Size, Align);
750  ConstantPool = MCP;
751
752  if (ConstantPoolBase == 0) return;  // Buffer overflow.
753
754  DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
755       << "] (size: " << Size << ", alignment: " << Align << ")\n";
756
757  // Initialize the memory for all of the constant pool entries.
758  for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
759    void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
760    if (Constants[i].isMachineConstantPoolEntry()) {
761      // FIXME: add support to lower machine constant pool values into bytes!
762      cerr << "Initialize memory with machine specific constant pool entry"
763           << " has not been implemented!\n";
764      abort();
765    }
766    TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
767    DOUT << "JIT:   CP" << i << " at [" << CAddr << "]\n";
768  }
769}
770
771void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
772  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
773  if (JT.empty()) return;
774
775  unsigned NumEntries = 0;
776  for (unsigned i = 0, e = JT.size(); i != e; ++i)
777    NumEntries += JT[i].MBBs.size();
778
779  unsigned EntrySize = MJTI->getEntrySize();
780
781  // Just allocate space for all the jump tables now.  We will fix up the actual
782  // MBB entries in the tables after we emit the code for each block, since then
783  // we will know the final locations of the MBBs in memory.
784  JumpTable = MJTI;
785  JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
786}
787
788void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
789  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
790  if (JT.empty() || JumpTableBase == 0) return;
791
792  if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
793    assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
794    // For each jump table, place the offset from the beginning of the table
795    // to the target address.
796    int *SlotPtr = (int*)JumpTableBase;
797
798    for (unsigned i = 0, e = JT.size(); i != e; ++i) {
799      const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
800      // Store the offset of the basic block for this jump table slot in the
801      // memory we allocated for the jump table in 'initJumpTableInfo'
802      intptr_t Base = (intptr_t)SlotPtr;
803      for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
804        intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
805        *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
806      }
807    }
808  } else {
809    assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
810
811    // For each jump table, map each target in the jump table to the address of
812    // an emitted MachineBasicBlock.
813    intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
814
815    for (unsigned i = 0, e = JT.size(); i != e; ++i) {
816      const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
817      // Store the address of the basic block for this jump table slot in the
818      // memory we allocated for the jump table in 'initJumpTableInfo'
819      for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
820        *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
821    }
822  }
823}
824
825void JITEmitter::startFunctionStub(unsigned StubSize, unsigned Alignment) {
826  SavedBufferBegin = BufferBegin;
827  SavedBufferEnd = BufferEnd;
828  SavedCurBufferPtr = CurBufferPtr;
829
830  BufferBegin = CurBufferPtr = MemMgr->allocateStub(StubSize, Alignment);
831  BufferEnd = BufferBegin+StubSize+1;
832}
833
834void *JITEmitter::finishFunctionStub(const Function *F) {
835  NumBytes += getCurrentPCOffset();
836  std::swap(SavedBufferBegin, BufferBegin);
837  BufferEnd = SavedBufferEnd;
838  CurBufferPtr = SavedCurBufferPtr;
839  return SavedBufferBegin;
840}
841
842// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
843// in the constant pool that was last emitted with the 'emitConstantPool'
844// method.
845//
846intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
847  assert(ConstantNum < ConstantPool->getConstants().size() &&
848         "Invalid ConstantPoolIndex!");
849  return (intptr_t)ConstantPoolBase +
850         ConstantPool->getConstants()[ConstantNum].Offset;
851}
852
853// getJumpTableEntryAddress - Return the address of the JumpTable with index
854// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
855//
856intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
857  const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
858  assert(Index < JT.size() && "Invalid jump table index!");
859
860  unsigned Offset = 0;
861  unsigned EntrySize = JumpTable->getEntrySize();
862
863  for (unsigned i = 0; i < Index; ++i)
864    Offset += JT[i].MBBs.size();
865
866   Offset *= EntrySize;
867
868  return (intptr_t)((char *)JumpTableBase + Offset);
869}
870
871//===----------------------------------------------------------------------===//
872//  Public interface to this file
873//===----------------------------------------------------------------------===//
874
875MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
876  return new JITEmitter(jit, JMM);
877}
878
879// getPointerToNamedFunction - This function is used as a global wrapper to
880// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
881// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
882// need to resolve function(s) that are being mis-codegenerated, so we need to
883// resolve their addresses at runtime, and this is the way to do it.
884extern "C" {
885  void *getPointerToNamedFunction(const char *Name) {
886    if (Function *F = TheJIT->FindFunctionNamed(Name))
887      return TheJIT->getPointerToFunction(F);
888    return TheJIT->getPointerToNamedFunction(Name);
889  }
890}
891
892// getPointerToFunctionOrStub - If the specified function has been
893// code-gen'd, return a pointer to the function.  If not, compile it, or use
894// a stub to implement lazy compilation if available.
895//
896void *JIT::getPointerToFunctionOrStub(Function *F) {
897  // If we have already code generated the function, just return the address.
898  if (void *Addr = getPointerToGlobalIfAvailable(F))
899    return Addr;
900
901  // Get a stub if the target supports it.
902  assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
903  JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
904  return JE->getJITResolver().getFunctionStub(F);
905}
906
907/// freeMachineCodeForFunction - release machine code memory for given Function.
908///
909void JIT::freeMachineCodeForFunction(Function *F) {
910
911  // Delete translation for this from the ExecutionEngine, so it will get
912  // retranslated next time it is used.
913  void *OldPtr = updateGlobalMapping(F, 0);
914
915  if (OldPtr)
916    RemoveFunctionFromSymbolTable(OldPtr);
917
918  // Free the actual memory for the function body and related stuff.
919  assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
920  static_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);
921}
922
923