JITEmitter.cpp revision 7a73b80b9052136c8cd2234eb3433a07df7cf38e
1//===-- Emitter.cpp - Write machine code to executable memory -------------===//
2//
3// This file defines a MachineCodeEmitter object that is used by Jello to write
4// machine code to memory and remember where relocatable values lie.
5//
6//===----------------------------------------------------------------------===//
7
8#include "VM.h"
9#include "Config/sys/mman.h"
10#include "llvm/CodeGen/MachineCodeEmitter.h"
11#include "llvm/CodeGen/MachineFunction.h"
12#include "llvm/CodeGen/MachineConstantPool.h"
13#include "llvm/Target/TargetData.h"
14#include "llvm/Function.h"
15#include "Support/Statistic.h"
16#include <stdio.h>
17
18static VM *TheVM = 0;
19
20namespace {
21  Statistic<> NumBytes("jello", "Number of bytes of machine code compiled");
22
23  class Emitter : public MachineCodeEmitter {
24    // CurBlock - The start of the current block of memory.  CurByte - The
25    // current byte being emitted to.
26    unsigned char *CurBlock, *CurByte;
27
28    // When outputting a function stub in the context of some other function, we
29    // save CurBlock and CurByte here.
30    unsigned char *SavedCurBlock, *SavedCurByte;
31
32    // ConstantPoolAddresses - Contains the location for each entry in the
33    // constant pool.
34    std::vector<void*> ConstantPoolAddresses;
35  public:
36    Emitter(VM &vm) { TheVM = &vm; }
37
38    virtual void startFunction(MachineFunction &F);
39    virtual void finishFunction(MachineFunction &F);
40    virtual void emitConstantPool(MachineConstantPool *MCP);
41    virtual void startFunctionStub(const Function &F, unsigned StubSize);
42    virtual void* finishFunctionStub(const Function &F);
43    virtual void emitByte(unsigned char B);
44    virtual void emitWord(unsigned W);
45
46    virtual uint64_t getGlobalValueAddress(GlobalValue *V);
47    virtual uint64_t getGlobalValueAddress(const std::string &Name);
48    virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
49    virtual uint64_t getCurrentPCValue();
50
51    // forceCompilationOf - Force the compilation of the specified function, and
52    // return its address, because we REALLY need the address now.
53    //
54    // FIXME: This is JIT specific!
55    //
56    virtual uint64_t forceCompilationOf(Function *F);
57  };
58}
59
60MachineCodeEmitter *VM::createEmitter(VM &V) {
61  return new Emitter(V);
62}
63
64
65#define _POSIX_MAPPED_FILES
66#include <unistd.h>
67#include <sys/mman.h>
68
69// FIXME: This should be rewritten to support a real memory manager for
70// executable memory pages!
71static void *getMemory(unsigned NumPages) {
72  void *pa;
73  if (NumPages == 0) return 0;
74  static const long pageSize = sysconf(_SC_PAGESIZE);
75
76#if defined(i386) || defined(__i386__) || defined(__x86__)
77#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
78# define MAP_ANONYMOUS MAP_ANON
79#endif
80  pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
81            MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);  /* fd = 0  */
82#elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
83  static unsigned long Counter = 0;
84  pa = mmap((void*)(0x140000000UL+Counter), pageSize*NumPages,
85            PROT_READ|PROT_WRITE|PROT_EXEC,
86            MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0); /* fd = -1 */
87  Counter += pageSize*NumPages;
88#else
89  std::cerr << "This architecture is not supported by the JIT\n";
90  abort();
91#endif
92
93  if (pa == MAP_FAILED) {
94    perror("mmap");
95    abort();
96  }
97  return pa;
98}
99
100
101void Emitter::startFunction(MachineFunction &F) {
102  CurBlock = (unsigned char *)getMemory(16);
103  CurByte = CurBlock;  // Start writing at the beginning of the fn.
104  TheVM->addGlobalMapping(F.getFunction(), CurBlock);
105}
106
107void Emitter::finishFunction(MachineFunction &F) {
108  ConstantPoolAddresses.clear();
109  NumBytes += CurByte-CurBlock;
110
111  DEBUG(std::cerr << "Finished CodeGen of [" << (void*)CurBlock
112                  << "] Function: " << F.getFunction()->getName()
113                  << ": " << CurByte-CurBlock << " bytes of text\n");
114}
115
116void Emitter::emitConstantPool(MachineConstantPool *MCP) {
117  const std::vector<Constant*> &Constants = MCP->getConstants();
118  for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
119    // For now we just allocate some memory on the heap, this can be
120    // dramatically improved.
121    const Type *Ty = ((Value*)Constants[i])->getType();
122    void *Addr = malloc(TheVM->getTargetData().getTypeSize(Ty));
123    TheVM->InitializeMemory(Constants[i], Addr);
124    ConstantPoolAddresses.push_back(Addr);
125  }
126}
127
128void Emitter::startFunctionStub(const Function &F, unsigned StubSize) {
129  static const long pageSize = sysconf(_SC_PAGESIZE);
130  SavedCurBlock = CurBlock;  SavedCurByte = CurByte;
131  // FIXME: this is a huge waste of memory.
132  CurBlock = (unsigned char *)getMemory((StubSize+pageSize-1)/pageSize);
133  CurByte = CurBlock;  // Start writing at the beginning of the fn.
134}
135
136void *Emitter::finishFunctionStub(const Function &F) {
137  NumBytes += CurByte-CurBlock;
138  DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex
139                  << (unsigned)(intptr_t)CurBlock
140                  << std::dec << "] Function stub for: " << F.getName()
141                  << ": " << CurByte-CurBlock << " bytes of text\n");
142  std::swap(CurBlock, SavedCurBlock);
143  CurByte = SavedCurByte;
144  return SavedCurBlock;
145}
146
147void Emitter::emitByte(unsigned char B) {
148  *CurByte++ = B;   // Write the byte to memory
149}
150
151void Emitter::emitWord(unsigned W) {
152  // FIXME: This won't work if the endianness of the host and target don't
153  // agree!  (For a JIT this can't happen though.  :)
154  *(unsigned*)CurByte = W;
155  CurByte += sizeof(unsigned);
156}
157
158
159uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) {
160  // Try looking up the function to see if it is already compiled, if not return
161  // 0.
162  return (intptr_t)TheVM->getPointerToGlobalIfAvailable(V);
163}
164uint64_t Emitter::getGlobalValueAddress(const std::string &Name) {
165  return (intptr_t)TheVM->getPointerToNamedFunction(Name);
166}
167
168// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
169// in the constant pool that was last emitted with the 'emitConstantPool'
170// method.
171//
172uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
173  assert(ConstantNum < ConstantPoolAddresses.size() &&
174	 "Invalid ConstantPoolIndex!");
175  return (intptr_t)ConstantPoolAddresses[ConstantNum];
176}
177
178// getCurrentPCValue - This returns the address that the next emitted byte
179// will be output to.
180//
181uint64_t Emitter::getCurrentPCValue() {
182  return (intptr_t)CurByte;
183}
184
185uint64_t Emitter::forceCompilationOf(Function *F) {
186  return (intptr_t)TheVM->getPointerToFunction(F);
187}
188
189