32d0651f22675c111711e54e4b29439cf3c7b871
[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 "VM.h"
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Module.h"
25 #include "Support/Debug.h"
26 #include "Support/Statistic.h"
27 #include "Config/unistd.h"
28 #include "Config/sys/mman.h"
29
30 namespace llvm {
31
32 namespace {
33   Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
34   VM *TheVM = 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 #if defined(__linux__)
76 #define fd 0
77 #else
78 #define fd -1
79 #endif
80   
81   unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
82 #ifdef MAP_NORESERVE
83   mmapFlags |= MAP_NORESERVE;
84 #endif
85
86   void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
87                   mmapFlags, fd, 0);
88   if (pa == MAP_FAILED) {
89     perror("mmap");
90     abort();
91   }
92   return pa;
93 }
94
95 JITMemoryManager::JITMemoryManager() {
96   // Allocate a 16M block of memory...
97   MemBase = (unsigned char*)getMemory(16 << 20);
98   FunctionBase = MemBase + 512*1024; // Use 512k for stubs
99
100   // Allocate stubs backwards from the function base, allocate functions forward
101   // from the function base.
102   CurStubPtr = CurFunctionPtr = FunctionBase;
103 }
104
105 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
106   CurStubPtr -= StubSize;
107   if (CurStubPtr < MemBase) {
108     std::cerr << "JIT ran out of memory for function stubs!\n";
109     abort();
110   }
111   return CurStubPtr;
112 }
113
114 unsigned char *JITMemoryManager::startFunctionBody() {
115   // Round up to an even multiple of 4 bytes, this should eventually be target
116   // specific.
117   return (unsigned char*)(((intptr_t)CurFunctionPtr + 3) & ~3);
118 }
119
120 void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
121   assert(FunctionEnd > CurFunctionPtr);
122   CurFunctionPtr = FunctionEnd;
123 }
124
125
126
127 namespace {
128   /// Emitter - The JIT implementation of the MachineCodeEmitter, which is used
129   /// to output functions to memory for execution.
130   class Emitter : public MachineCodeEmitter {
131     JITMemoryManager MemMgr;
132
133     // CurBlock - The start of the current block of memory.  CurByte - The
134     // current byte being emitted to.
135     unsigned char *CurBlock, *CurByte;
136
137     // When outputting a function stub in the context of some other function, we
138     // save CurBlock and CurByte here.
139     unsigned char *SavedCurBlock, *SavedCurByte;
140
141     // ConstantPoolAddresses - Contains the location for each entry in the
142     // constant pool.
143     std::vector<void*> ConstantPoolAddresses;
144   public:
145     Emitter(VM &vm) { TheVM = &vm; }
146
147     virtual void startFunction(MachineFunction &F);
148     virtual void finishFunction(MachineFunction &F);
149     virtual void emitConstantPool(MachineConstantPool *MCP);
150     virtual void startFunctionStub(const Function &F, unsigned StubSize);
151     virtual void* finishFunctionStub(const Function &F);
152     virtual void emitByte(unsigned char B);
153     virtual void emitWord(unsigned W);
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 *VM::createEmitter(VM &V) {
170   return new Emitter(V);
171 }
172
173 void Emitter::startFunction(MachineFunction &F) {
174   CurByte = CurBlock = MemMgr.startFunctionBody();
175   TheVM->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   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
191     // For now we just allocate some memory on the heap, this can be
192     // dramatically improved.
193     const Type *Ty = ((Value*)Constants[i])->getType();
194     void *Addr = malloc(TheVM->getTargetData().getTypeSize(Ty));
195     TheVM->InitializeMemory(Constants[i], Addr);
196     ConstantPoolAddresses.push_back(Addr);
197   }
198 }
199
200 void Emitter::startFunctionStub(const Function &F, unsigned StubSize) {
201   SavedCurBlock = CurBlock;  SavedCurByte = CurByte;
202   CurByte = CurBlock = MemMgr.allocateStub(StubSize);
203 }
204
205 void *Emitter::finishFunctionStub(const Function &F) {
206   NumBytes += CurByte-CurBlock;
207   DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex
208                   << (unsigned)(intptr_t)CurBlock
209                   << std::dec << "] Function stub for: " << F.getName()
210                   << ": " << CurByte-CurBlock << " bytes of text\n");
211   std::swap(CurBlock, SavedCurBlock);
212   CurByte = SavedCurByte;
213   return SavedCurBlock;
214 }
215
216 void Emitter::emitByte(unsigned char B) {
217   *CurByte++ = B;   // Write the byte to memory
218 }
219
220 void Emitter::emitWord(unsigned W) {
221   // This won't work if the endianness of the host and target don't agree!  (For
222   // a JIT this can't happen though.  :)
223   *(unsigned*)CurByte = W;
224   CurByte += sizeof(unsigned);
225 }
226
227 uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) {
228   // Try looking up the function to see if it is already compiled, if not return
229   // 0.
230   return (intptr_t)TheVM->getPointerToGlobalIfAvailable(V);
231 }
232 uint64_t Emitter::getGlobalValueAddress(const std::string &Name) {
233   return (intptr_t)TheVM->getPointerToNamedFunction(Name);
234 }
235
236 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
237 // in the constant pool that was last emitted with the 'emitConstantPool'
238 // method.
239 //
240 uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
241   assert(ConstantNum < ConstantPoolAddresses.size() &&
242          "Invalid ConstantPoolIndex!");
243   return (intptr_t)ConstantPoolAddresses[ConstantNum];
244 }
245
246 // getCurrentPCValue - This returns the address that the next emitted byte
247 // will be output to.
248 //
249 uint64_t Emitter::getCurrentPCValue() {
250   return (intptr_t)CurByte;
251 }
252
253 uint64_t Emitter::forceCompilationOf(Function *F) {
254   return (intptr_t)TheVM->getPointerToFunction(F);
255 }
256
257 // getPointerToNamedFunction - This function is used as a global wrapper to
258 // VM::getPointerToNamedFunction for the purpose of resolving symbols when
259 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
260 // need to resolve function(s) that are being mis-codegenerated, so we need to
261 // resolve their addresses at runtime, and this is the way to do it.
262 extern "C" {
263   void *getPointerToNamedFunction(const char *Name) {
264     Module &M = TheVM->getModule();
265     if (Function *F = M.getNamedFunction(Name))
266       return TheVM->getPointerToFunction(F);
267     return TheVM->getPointerToNamedFunction(Name);
268   }
269 }
270
271 } // End llvm namespace