Clean up DEBUG output
[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 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 "llvm/Constant.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/MachineCodeEmitter.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineRelocation.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetJITInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/System/Memory.h"
28 using namespace llvm;
29
30 namespace {
31   Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
32   JIT *TheJIT = 0;
33 }
34
35
36 //===----------------------------------------------------------------------===//
37 // JITMemoryManager code.
38 //
39 namespace {
40   /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
41   /// sane way.  This splits a large block of MAP_NORESERVE'd memory into two
42   /// sections, one for function stubs, one for the functions themselves.  We
43   /// have to do this because we may need to emit a function stub while in the
44   /// middle of emitting a function, and we don't know how large the function we
45   /// are emitting is.  This never bothers to release the memory, because when
46   /// we are ready to destroy the JIT, the program exits.
47   class JITMemoryManager {
48     sys::MemoryBlock  MemBlock;  // Virtual memory block allocated RWX
49     unsigned char *MemBase;      // Base of block of memory, start of stub mem
50     unsigned char *FunctionBase; // Start of the function body area
51     unsigned char *CurStubPtr, *CurFunctionPtr;
52   public:
53     JITMemoryManager();
54     
55     inline unsigned char *allocateStub(unsigned StubSize);
56     inline unsigned char *startFunctionBody();
57     inline void endFunctionBody(unsigned char *FunctionEnd);    
58   };
59 }
60
61 JITMemoryManager::JITMemoryManager() {
62   // Allocate a 16M block of memory...
63   MemBlock = sys::Memory::AllocateRWX((16 << 20));
64   MemBase = reinterpret_cast<unsigned char*>(MemBlock.base());
65   FunctionBase = MemBase + 512*1024; // Use 512k for stubs
66
67   // Allocate stubs backwards from the function base, allocate functions forward
68   // from the function base.
69   CurStubPtr = CurFunctionPtr = FunctionBase;
70 }
71
72 unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
73   CurStubPtr -= StubSize;
74   if (CurStubPtr < MemBase) {
75     std::cerr << "JIT ran out of memory for function stubs!\n";
76     abort();
77   }
78   return CurStubPtr;
79 }
80
81 unsigned char *JITMemoryManager::startFunctionBody() {
82   // Round up to an even multiple of 8 bytes, this should eventually be target
83   // specific.
84   return (unsigned char*)(((intptr_t)CurFunctionPtr + 7) & ~7);
85 }
86
87 void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
88   assert(FunctionEnd > CurFunctionPtr);
89   CurFunctionPtr = FunctionEnd;
90 }
91
92 //===----------------------------------------------------------------------===//
93 // JIT lazy compilation code.
94 //
95 namespace {
96   /// JITResolver - Keep track of, and resolve, call sites for functions that
97   /// have not yet been compiled.
98   class JITResolver {
99     /// MCE - The MachineCodeEmitter to use to emit stubs with.
100     MachineCodeEmitter &MCE;
101
102     /// LazyResolverFn - The target lazy resolver function that we actually
103     /// rewrite instructions to use.
104     TargetJITInfo::LazyResolverFn LazyResolverFn;
105
106     // FunctionToStubMap - Keep track of the stub created for a particular
107     // function so that we can reuse them if necessary.
108     std::map<Function*, void*> FunctionToStubMap;
109
110     // StubToFunctionMap - Keep track of the function that each stub corresponds
111     // to.
112     std::map<void*, Function*> StubToFunctionMap;
113
114   public:
115     JITResolver(MachineCodeEmitter &mce) : MCE(mce) {
116       LazyResolverFn =
117         TheJIT->getJITInfo().getLazyResolverFunction(JITCompilerFn);
118     }
119
120     /// getFunctionStub - This returns a pointer to a function stub, creating
121     /// one on demand as needed.
122     void *getFunctionStub(Function *F);
123
124     /// AddCallbackAtLocation - If the target is capable of rewriting an
125     /// instruction without the use of a stub, record the location of the use so
126     /// we know which function is being used at the location.
127     void *AddCallbackAtLocation(Function *F, void *Location) {
128       /// Get the target-specific JIT resolver function.
129       StubToFunctionMap[Location] = F;
130       return (void*)LazyResolverFn;
131     }
132
133     /// JITCompilerFn - This function is called to resolve a stub to a compiled
134     /// address.  If the LLVM Function corresponding to the stub has not yet
135     /// been compiled, this function compiles it first.
136     static void *JITCompilerFn(void *Stub);
137   };
138 }
139
140 /// getJITResolver - This function returns the one instance of the JIT resolver.
141 ///
142 static JITResolver &getJITResolver(MachineCodeEmitter *MCE = 0) {
143   static JITResolver TheJITResolver(*MCE);
144   return TheJITResolver;
145 }
146
147 /// getFunctionStub - This returns a pointer to a function stub, creating
148 /// one on demand as needed.
149 void *JITResolver::getFunctionStub(Function *F) {
150   // If we already have a stub for this function, recycle it.
151   void *&Stub = FunctionToStubMap[F];
152   if (Stub) return Stub;
153
154   // Otherwise, codegen a new stub.  For now, the stub will call the lazy
155   // resolver function.
156   Stub = TheJIT->getJITInfo().emitFunctionStub((void*)LazyResolverFn, MCE);
157
158   DEBUG(std::cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
159                   << F->getName() << "\n");
160
161   // Finally, keep track of the stub-to-Function mapping so that the
162   // JITCompilerFn knows which function to compile!
163   StubToFunctionMap[Stub] = F;
164   return Stub;
165 }
166
167 /// JITCompilerFn - This function is called when a lazy compilation stub has
168 /// been entered.  It looks up which function this stub corresponds to, compiles
169 /// it if necessary, then returns the resultant function pointer.
170 void *JITResolver::JITCompilerFn(void *Stub) {
171   JITResolver &JR = getJITResolver();
172   
173   // The address given to us for the stub may not be exactly right, it might be
174   // a little bit after the stub.  As such, use upper_bound to find it.
175   std::map<void*, Function*>::iterator I =
176     JR.StubToFunctionMap.upper_bound(Stub);
177   assert(I != JR.StubToFunctionMap.begin() && "This is not a known stub!");
178   Function *F = (--I)->second;
179
180   // The target function will rewrite the stub so that the compilation callback
181   // function is no longer called from this stub.
182   JR.StubToFunctionMap.erase(I);
183
184   DEBUG(std::cerr << "JIT: Lazily resolving function '" << F->getName()
185                   << "' In stub ptr = " << Stub << " actual ptr = "
186                   << I->first << "\n");
187
188   void *Result = TheJIT->getPointerToFunction(F);
189
190   // We don't need to reuse this stub in the future, as F is now compiled.
191   JR.FunctionToStubMap.erase(F);
192
193   // FIXME: We could rewrite all references to this stub if we knew them.
194   return Result;
195 }
196
197
198 //===----------------------------------------------------------------------===//
199 // JIT MachineCodeEmitter code.
200 //
201 namespace {
202   /// Emitter - The JIT implementation of the MachineCodeEmitter, which is used
203   /// to output functions to memory for execution.
204   class Emitter : public MachineCodeEmitter {
205     JITMemoryManager MemMgr;
206
207     // CurBlock - The start of the current block of memory.  CurByte - The
208     // current byte being emitted to.
209     unsigned char *CurBlock, *CurByte;
210
211     // When outputting a function stub in the context of some other function, we
212     // save CurBlock and CurByte here.
213     unsigned char *SavedCurBlock, *SavedCurByte;
214
215     // ConstantPoolAddresses - Contains the location for each entry in the
216     // constant pool.
217     std::vector<void*> ConstantPoolAddresses;
218
219     /// Relocations - These are the relocations that the function needs, as
220     /// emitted.
221     std::vector<MachineRelocation> Relocations;
222   public:
223     Emitter(JIT &jit) { TheJIT = &jit; }
224
225     virtual void startFunction(MachineFunction &F);
226     virtual void finishFunction(MachineFunction &F);
227     virtual void emitConstantPool(MachineConstantPool *MCP);
228     virtual void startFunctionStub(unsigned StubSize);
229     virtual void* finishFunctionStub(const Function *F);
230     virtual void emitByte(unsigned char B);
231     virtual void emitWord(unsigned W);
232     virtual void emitWordAt(unsigned W, unsigned *Ptr);
233
234     virtual void addRelocation(const MachineRelocation &MR) {
235       Relocations.push_back(MR);
236     }
237
238     virtual uint64_t getCurrentPCValue();
239     virtual uint64_t getCurrentPCOffset();
240     virtual uint64_t getGlobalValueAddress(GlobalValue *V);
241     virtual uint64_t getGlobalValueAddress(const char *Name);
242     virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
243
244     // forceCompilationOf - Force the compilation of the specified function, and
245     // return its address, because we REALLY need the address now.
246     //
247     // FIXME: This is JIT specific!
248     //
249     virtual uint64_t forceCompilationOf(Function *F);
250
251   private:
252     void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
253   };
254 }
255
256 MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
257   return new Emitter(jit);
258 }
259
260 void *Emitter::getPointerToGlobal(GlobalValue *V, void *Reference,
261                                   bool DoesntNeedStub) {
262   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
263     /// FIXME: If we straightened things out, this could actually emit the
264     /// global immediately instead of queuing it for codegen later!
265     GlobalVariable *GV = cast<GlobalVariable>(V);
266     return TheJIT->getOrEmitGlobalVariable(GV);
267   }
268
269   // If we have already compiled the function, return a pointer to its body.
270   Function *F = cast<Function>(V);
271   void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
272   if (ResultPtr) return ResultPtr;
273
274   if (F->hasExternalLinkage()) {
275     // If this is an external function pointer, we can force the JIT to
276     // 'compile' it, which really just adds it to the map.
277     return TheJIT->getPointerToFunction(F);
278   }
279
280   // Okay, the function has not been compiled yet, if the target callback
281   // mechanism is capable of rewriting the instruction directly, prefer to do
282   // that instead of emitting a stub.
283   if (DoesntNeedStub)
284     return getJITResolver(this).AddCallbackAtLocation(F, Reference);
285
286   // Otherwise, we have to emit a lazy resolving stub.
287   return getJITResolver(this).getFunctionStub(F);
288 }
289
290 void Emitter::startFunction(MachineFunction &F) {
291   CurByte = CurBlock = MemMgr.startFunctionBody();
292   TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
293 }
294
295 void Emitter::finishFunction(MachineFunction &F) {
296   MemMgr.endFunctionBody(CurByte);
297   ConstantPoolAddresses.clear();
298   NumBytes += CurByte-CurBlock;
299
300   if (!Relocations.empty()) {
301     // Resolve the relocations to concrete pointers.
302     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
303       MachineRelocation &MR = Relocations[i];
304       void *ResultPtr;
305       if (MR.isString())
306         ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
307       else
308         ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
309                                        CurBlock+MR.getMachineCodeOffset(),
310                                        MR.doesntNeedFunctionStub());
311       MR.setResultPointer(ResultPtr);
312     }
313
314     TheJIT->getJITInfo().relocate(CurBlock, &Relocations[0],
315                                   Relocations.size());
316   }
317
318   DEBUG(std::cerr << "JIT: Finished CodeGen of [" << (void*)CurBlock
319                   << "] Function: " << F.getFunction()->getName()
320                   << ": " << CurByte-CurBlock << " bytes of text, "
321                   << Relocations.size() << " relocations\n");
322   Relocations.clear();
323 }
324
325 void Emitter::emitConstantPool(MachineConstantPool *MCP) {
326   const std::vector<Constant*> &Constants = MCP->getConstants();
327   if (Constants.empty()) return;
328
329   std::vector<unsigned> ConstantOffset;
330   ConstantOffset.reserve(Constants.size());
331
332   // Calculate how much space we will need for all the constants, and the offset
333   // each one will live in.
334   unsigned TotalSize = 0;
335   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
336     const Type *Ty = Constants[i]->getType();
337     unsigned Size      = TheJIT->getTargetData().getTypeSize(Ty);
338     unsigned Alignment = TheJIT->getTargetData().getTypeAlignment(Ty);
339     // Make sure to take into account the alignment requirements of the type.
340     TotalSize = (TotalSize + Alignment-1) & ~(Alignment-1);
341
342     // Remember the offset this element lives at.
343     ConstantOffset.push_back(TotalSize);
344     TotalSize += Size;   // Reserve space for the constant.
345   }
346
347   // Now that we know how much memory to allocate, do so.
348   char *Pool = new char[TotalSize];
349
350   // Actually output all of the constants, and remember their addresses.
351   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
352     void *Addr = Pool + ConstantOffset[i];
353     TheJIT->InitializeMemory(Constants[i], Addr);
354     ConstantPoolAddresses.push_back(Addr);
355   }
356 }
357
358 void Emitter::startFunctionStub(unsigned StubSize) {
359   SavedCurBlock = CurBlock;  SavedCurByte = CurByte;
360   CurByte = CurBlock = MemMgr.allocateStub(StubSize);
361 }
362
363 void *Emitter::finishFunctionStub(const Function *F) {
364   NumBytes += CurByte-CurBlock;
365   std::swap(CurBlock, SavedCurBlock);
366   CurByte = SavedCurByte;
367   return SavedCurBlock;
368 }
369
370 void Emitter::emitByte(unsigned char B) {
371   *CurByte++ = B;   // Write the byte to memory
372 }
373
374 void Emitter::emitWord(unsigned W) {
375   // This won't work if the endianness of the host and target don't agree!  (For
376   // a JIT this can't happen though.  :)
377   *(unsigned*)CurByte = W;
378   CurByte += sizeof(unsigned);
379 }
380
381 void Emitter::emitWordAt(unsigned W, unsigned *Ptr) {
382   *Ptr = W;
383 }
384
385 uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) {
386   // Try looking up the function to see if it is already compiled, if not return
387   // 0.
388   if (Function *F = dyn_cast<Function>(V)) {
389     void *Addr = TheJIT->getPointerToGlobalIfAvailable(F);
390     if (Addr == 0 && F->hasExternalLinkage()) {
391       // Do not output stubs for external functions.
392       Addr = TheJIT->getPointerToFunction(F);
393     }
394     return (intptr_t)Addr;
395   } else {
396     return (intptr_t)TheJIT->getOrEmitGlobalVariable(cast<GlobalVariable>(V));
397   }
398 }
399 uint64_t Emitter::getGlobalValueAddress(const char *Name) {
400   return (intptr_t)TheJIT->getPointerToNamedFunction(Name);
401 }
402
403 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
404 // in the constant pool that was last emitted with the 'emitConstantPool'
405 // method.
406 //
407 uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
408   assert(ConstantNum < ConstantPoolAddresses.size() &&
409          "Invalid ConstantPoolIndex!");
410   return (intptr_t)ConstantPoolAddresses[ConstantNum];
411 }
412
413 // getCurrentPCValue - This returns the address that the next emitted byte
414 // will be output to.
415 //
416 uint64_t Emitter::getCurrentPCValue() {
417   return (intptr_t)CurByte;
418 }
419
420 uint64_t Emitter::getCurrentPCOffset() {
421   return (intptr_t)CurByte-(intptr_t)CurBlock;
422 }
423
424 uint64_t Emitter::forceCompilationOf(Function *F) {
425   return (intptr_t)TheJIT->getPointerToFunction(F);
426 }
427
428 // getPointerToNamedFunction - This function is used as a global wrapper to
429 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
430 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
431 // need to resolve function(s) that are being mis-codegenerated, so we need to
432 // resolve their addresses at runtime, and this is the way to do it.
433 extern "C" {
434   void *getPointerToNamedFunction(const char *Name) {
435     Module &M = TheJIT->getModule();
436     if (Function *F = M.getNamedFunction(Name))
437       return TheJIT->getPointerToFunction(F);
438     return TheJIT->getPointerToNamedFunction(Name);
439   }
440 }