4cf4c15d3f9e698fb3aa255117fac7035133ce40
[oota-llvm.git] / lib / ExecutionEngine / JIT / JITEmitter.cpp
1 //===-- Emitter.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 Jello to write
11 // machine code to memory and remember where relocatable values lie.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "jit"
16 #ifndef _POSIX_MAPPED_FILES
17 #define _POSIX_MAPPED_FILES
18 #endif
19 #include "JIT.h"
20 #include "llvm/Constant.h"
21 #include "llvm/Module.h"
22 #include "llvm/CodeGen/MachineCodeEmitter.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/Target/TargetData.h"
26 #include "Support/Debug.h"
27 #include "Support/Statistic.h"
28 #include "Config/unistd.h"
29 #include "Config/sys/mman.h"
30 using namespace llvm;
31
32 namespace {
33   Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
34   JIT *TheJIT = 0;
35
36   /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
37   /// sane way.  This splits a large block of MAP_NORESERVE'd memory into two
38   /// sections, one for function stubs, one for the functions themselves.  We
39   /// have to do this because we may need to emit a function stub while in the
40   /// middle of emitting a function, and we don't know how large the function we
41   /// are emitting is.  This never bothers to release the memory, because when
42   /// we are ready to destroy the JIT, the program exits.
43   class JITMemoryManager {
44     unsigned char *MemBase;      // Base of block of memory, start of stub mem
45     unsigned char *FunctionBase; // Start of the function body area
46     unsigned char *CurStubPtr, *CurFunctionPtr;
47   public:
48     JITMemoryManager();
49     
50     inline unsigned char *allocateStub(unsigned StubSize);
51     inline unsigned char *startFunctionBody();
52     inline void endFunctionBody(unsigned char *FunctionEnd);    
53   };
54 }
55
56 // getMemory - Return a pointer to the specified number of bytes, which is
57 // mapped as executable readable and writable.
58 static void *getMemory(unsigned NumBytes) {
59   if (NumBytes == 0) return 0;
60   static const long pageSize = sysconf(_SC_PAGESIZE);
61   unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
62
63 #if defined(i386) || defined(__i386__) || defined(__x86__)
64   /* Linux and *BSD tend to have these flags named differently. */
65 #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
66 # define MAP_ANONYMOUS MAP_ANON
67 #endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */
68 #elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
69 /* nothing */
70 #else
71   std::cerr << "This architecture is not supported by the JIT!\n";
72   abort();
73 #endif
74
75   int fd = -1;
76 #if defined(__linux__)
77   fd = 0;
78 #endif
79   
80   unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
81 #ifdef MAP_NORESERVE
82   mmapFlags |= MAP_NORESERVE;
83 #endif
84
85   void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
86                   mmapFlags, fd, 0);
87   if (pa == MAP_FAILED) {
88     perror("mmap");
89     abort();
90   }
91   return pa;
92 }
93
94 JITMemoryManager::JITMemoryManager() {
95   // Allocate a 16M block of memory...
96   MemBase = (unsigned char*)getMemory(16 << 20);
97   FunctionBase = MemBase + 512*1024; // Use 512k for stubs
98
99   // Allocate stubs backwards from the function base, allocate functions forward
100   // from the function base.
101   CurStubPtr = CurFunctionPtr = FunctionBase;
102 }
103
104 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
105   CurStubPtr -= StubSize;
106   if (CurStubPtr < MemBase) {
107     std::cerr << "JIT ran out of memory for function stubs!\n";
108     abort();
109   }
110   return CurStubPtr;
111 }
112
113 unsigned char *JITMemoryManager::startFunctionBody() {
114   // Round up to an even multiple of 4 bytes, this should eventually be target
115   // specific.
116   return (unsigned char*)(((intptr_t)CurFunctionPtr + 3) & ~3);
117 }
118
119 void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
120   assert(FunctionEnd > CurFunctionPtr);
121   CurFunctionPtr = FunctionEnd;
122 }
123
124
125
126 namespace {
127   /// Emitter - The JIT implementation of the MachineCodeEmitter, which is used
128   /// to output functions to memory for execution.
129   class Emitter : public MachineCodeEmitter {
130     JITMemoryManager MemMgr;
131
132     // CurBlock - The start of the current block of memory.  CurByte - The
133     // current byte being emitted to.
134     unsigned char *CurBlock, *CurByte;
135
136     // When outputting a function stub in the context of some other function, we
137     // save CurBlock and CurByte here.
138     unsigned char *SavedCurBlock, *SavedCurByte;
139
140     // ConstantPoolAddresses - Contains the location for each entry in the
141     // constant pool.
142     std::vector<void*> ConstantPoolAddresses;
143   public:
144     Emitter(JIT &jit) { TheJIT = &jit; }
145
146     virtual void startFunction(MachineFunction &F);
147     virtual void finishFunction(MachineFunction &F);
148     virtual void emitConstantPool(MachineConstantPool *MCP);
149     virtual void startFunctionStub(const Function &F, unsigned StubSize);
150     virtual void* finishFunctionStub(const Function &F);
151     virtual void emitByte(unsigned char B);
152     virtual void emitWord(unsigned W);
153     virtual void emitWordAt(unsigned W, unsigned *Ptr);
154
155     virtual uint64_t getGlobalValueAddress(GlobalValue *V);
156     virtual uint64_t getGlobalValueAddress(const std::string &Name);
157     virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
158     virtual uint64_t getCurrentPCValue();
159
160     // forceCompilationOf - Force the compilation of the specified function, and
161     // return its address, because we REALLY need the address now.
162     //
163     // FIXME: This is JIT specific!
164     //
165     virtual uint64_t forceCompilationOf(Function *F);
166   };
167 }
168
169 MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
170   return new Emitter(jit);
171 }
172
173 void Emitter::startFunction(MachineFunction &F) {
174   CurByte = CurBlock = MemMgr.startFunctionBody();
175   TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
176 }
177
178 void Emitter::finishFunction(MachineFunction &F) {
179   MemMgr.endFunctionBody(CurByte);
180   ConstantPoolAddresses.clear();
181   NumBytes += CurByte-CurBlock;
182
183   DEBUG(std::cerr << "Finished CodeGen of [" << (void*)CurBlock
184                   << "] Function: " << F.getFunction()->getName()
185                   << ": " << CurByte-CurBlock << " bytes of text\n");
186 }
187
188 void Emitter::emitConstantPool(MachineConstantPool *MCP) {
189   const std::vector<Constant*> &Constants = MCP->getConstants();
190   if (Constants.empty()) return;
191
192   std::vector<unsigned> ConstantOffset;
193   ConstantOffset.reserve(Constants.size());
194
195   // Calculate how much space we will need for all the constants, and the offset
196   // each one will live in.
197   unsigned TotalSize = 0;
198   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
199     const Type *Ty = Constants[i]->getType();
200     unsigned Size      = TheJIT->getTargetData().getTypeSize(Ty);
201     unsigned Alignment = TheJIT->getTargetData().getTypeAlignment(Ty);
202     // Make sure to take into account the alignment requirements of the type.
203     TotalSize = (TotalSize + Alignment-1) & ~(Alignment-1);
204
205     // Remember the offset this element lives at.
206     ConstantOffset.push_back(TotalSize);
207     TotalSize += Size;   // Reserve space for the constant.
208   }
209
210   // Now that we know how much memory to allocate, do so.
211   char *Pool = new char[TotalSize];
212
213   // Actually output all of the constants, and remember their addresses.
214   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
215     void *Addr = Pool + ConstantOffset[i];
216     TheJIT->InitializeMemory(Constants[i], Addr);
217     ConstantPoolAddresses.push_back(Addr);
218   }
219 }
220
221 void Emitter::startFunctionStub(const Function &F, unsigned StubSize) {
222   SavedCurBlock = CurBlock;  SavedCurByte = CurByte;
223   CurByte = CurBlock = MemMgr.allocateStub(StubSize);
224 }
225
226 void *Emitter::finishFunctionStub(const Function &F) {
227   NumBytes += CurByte-CurBlock;
228   DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex
229                   << (unsigned)(intptr_t)CurBlock
230                   << std::dec << "] Function stub for: " << F.getName()
231                   << ": " << CurByte-CurBlock << " bytes of text\n");
232   std::swap(CurBlock, SavedCurBlock);
233   CurByte = SavedCurByte;
234   return SavedCurBlock;
235 }
236
237 void Emitter::emitByte(unsigned char B) {
238   *CurByte++ = B;   // Write the byte to memory
239 }
240
241 void Emitter::emitWord(unsigned W) {
242   // This won't work if the endianness of the host and target don't agree!  (For
243   // a JIT this can't happen though.  :)
244   *(unsigned*)CurByte = W;
245   CurByte += sizeof(unsigned);
246 }
247
248 void Emitter::emitWordAt(unsigned W, unsigned *Ptr) {
249   *Ptr = W;
250 }
251
252 uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) {
253   // Try looking up the function to see if it is already compiled, if not return
254   // 0.
255   if (isa<Function>(V))
256     return (intptr_t)TheJIT->getPointerToGlobalIfAvailable(V);
257   else {
258     return (intptr_t)TheJIT->getOrEmitGlobalVariable(cast<GlobalVariable>(V));
259   }
260 }
261 uint64_t Emitter::getGlobalValueAddress(const std::string &Name) {
262   return (intptr_t)TheJIT->getPointerToNamedFunction(Name);
263 }
264
265 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
266 // in the constant pool that was last emitted with the 'emitConstantPool'
267 // method.
268 //
269 uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
270   assert(ConstantNum < ConstantPoolAddresses.size() &&
271          "Invalid ConstantPoolIndex!");
272   return (intptr_t)ConstantPoolAddresses[ConstantNum];
273 }
274
275 // getCurrentPCValue - This returns the address that the next emitted byte
276 // will be output to.
277 //
278 uint64_t Emitter::getCurrentPCValue() {
279   return (intptr_t)CurByte;
280 }
281
282 uint64_t Emitter::forceCompilationOf(Function *F) {
283   return (intptr_t)TheJIT->getPointerToFunction(F);
284 }
285
286 // getPointerToNamedFunction - This function is used as a global wrapper to
287 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
288 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
289 // need to resolve function(s) that are being mis-codegenerated, so we need to
290 // resolve their addresses at runtime, and this is the way to do it.
291 extern "C" {
292   void *getPointerToNamedFunction(const char *Name) {
293     Module &M = TheJIT->getModule();
294     if (Function *F = M.getNamedFunction(Name))
295       return TheJIT->getPointerToFunction(F);
296     return TheJIT->getPointerToNamedFunction(Name);
297   }
298 }