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