e6fd470d3428d7ea67bf45f307196e247d050212
[oota-llvm.git] / lib / ExecutionEngine / JIT / JIT.cpp
1 //===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
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 tool implements a just-in-time compiler for LLVM, allowing direct
11 // execution of LLVM bytecode in an efficient manner.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "JIT.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetJITInfo.h"
25 #include "Support/DynamicLinker.h"
26 #include <iostream>
27
28 using namespace llvm;
29
30 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
31   : ExecutionEngine(MP), TM(tm), TJI(tji), PM(MP) {
32   setTargetData(TM.getTargetData());
33
34   // Initialize MCE
35   MCE = createEmitter(*this);
36   
37   // Add target data
38   PM.add (new TargetData (TM.getTargetData ()));
39
40   // Compile LLVM Code down to machine code in the intermediate representation
41   TJI.addPassesToJITCompile(PM);
42
43   // Turn the machine code intermediate representation into bytes in memory that
44   // may be executed.
45   if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
46     std::cerr << "lli: target '" << TM.getName()
47               << "' doesn't support machine code emission!\n";
48     abort();
49   }
50 }
51
52 JIT::~JIT() {
53   delete MCE;
54   delete &TM;
55 }
56
57 /// run - Start execution with the specified function and arguments.
58 ///
59 GenericValue JIT::runFunction(Function *F,
60                               const std::vector<GenericValue> &ArgValues) {
61   assert(F && "Function *F was null at entry to run()");
62   GenericValue rv;
63
64   void *FPtr = getPointerToFunction(F);
65   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
66   const Type *RetTy = F->getReturnType();
67   const FunctionType *FTy = F->getFunctionType();
68
69   // Handle some common cases first.
70   if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
71     switch (ArgValues.size()) {
72     case 3:
73       if (FTy->getNumParams() == 3 && 
74           (FTy->getParamType(0) == Type::IntTy || 
75            FTy->getParamType(0) == Type::UIntTy) &&
76           isa<PointerType>(FTy->getParamType(1)) &&
77           isa<PointerType>(FTy->getParamType(2))) {
78         int (*PF)(int, char **, const char **) =
79           (int(*)(int, char **, const char **))FPtr;
80         
81         // Call the function.
82         rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
83                        (const char **)GVTOP(ArgValues[2]));
84         return rv;
85       }
86       break;
87     case 1:
88       if (FTy->getNumParams() == 1 &&
89           (FTy->getParamType(0) == Type::IntTy || 
90            FTy->getParamType(0) == Type::UIntTy)) {
91         int (*PF)(int) = (int(*)(int))FPtr;
92         rv.IntVal = PF(ArgValues[0].IntVal);
93         return rv;
94       }
95       break;
96     case 0:
97       int (*PF)() = (int(*)())FPtr;
98       rv.IntVal = PF();
99       return rv;
100     }
101   }
102
103   // FIXME: This code should handle a couple of common cases efficiently, but
104   // it should also implement the general case by code-gening a new anonymous
105   // nullary function to call.
106   std::cerr << "Sorry, unimplemented feature in the LLVM JIT.  See LLVM"
107             << " PR#419\n for details.\n";
108   abort();
109   return rv;
110 }
111
112 /// runJITOnFunction - Run the FunctionPassManager full of
113 /// just-in-time compilation passes on F, hopefully filling in
114 /// GlobalAddress[F] with the address of F's machine code.
115 ///
116 void JIT::runJITOnFunction(Function *F) {
117   static bool isAlreadyCodeGenerating = false;
118   assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
119
120   // JIT the function
121   isAlreadyCodeGenerating = true;
122   PM.run(*F);
123   isAlreadyCodeGenerating = false;
124
125   // If the function referred to a global variable that had not yet been
126   // emitted, it allocates memory for the global, but doesn't emit it yet.  Emit
127   // all of these globals now.
128   while (!PendingGlobals.empty()) {
129     const GlobalVariable *GV = PendingGlobals.back();
130     PendingGlobals.pop_back();
131     EmitGlobalVariable(GV);
132   }
133 }
134
135 /// getPointerToFunction - This method is used to get the address of the
136 /// specified function, compiling it if neccesary.
137 ///
138 void *JIT::getPointerToFunction(Function *F) {
139   if (void *Addr = getPointerToGlobalIfAvailable(F))
140     return Addr;   // Check if function already code gen'd
141
142   // Make sure we read in the function if it exists in this Module
143   try {
144     MP->materializeFunction(F);
145   } catch ( std::string& errmsg ) {
146     std::cerr << "Error reading bytecode file: " << errmsg << "\n";
147     abort();
148   } catch (...) {
149     std::cerr << "Error reading bytecode file!\n";
150     abort();
151   }
152
153   if (F->isExternal()) {
154     void *Addr = getPointerToNamedFunction(F->getName());
155     addGlobalMapping(F, Addr);
156     return Addr;
157   }
158
159   runJITOnFunction(F);
160
161   void *Addr = getPointerToGlobalIfAvailable(F);
162   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
163   return Addr;
164 }
165
166 // getPointerToFunctionOrStub - If the specified function has been
167 // code-gen'd, return a pointer to the function.  If not, compile it, or use
168 // a stub to implement lazy compilation if available.
169 //
170 void *JIT::getPointerToFunctionOrStub(Function *F) {
171   // If we have already code generated the function, just return the address.
172   if (void *Addr = getPointerToGlobalIfAvailable(F))
173     return Addr;
174
175   // If the target supports "stubs" for functions, get a stub now.
176   if (void *Ptr = TJI.getJITStubForFunction(F, *MCE))
177     return Ptr;
178
179   // Otherwise, if the target doesn't support it, just codegen the function.
180   return getPointerToFunction(F);
181 }
182
183 /// getOrEmitGlobalVariable - Return the address of the specified global
184 /// variable, possibly emitting it to memory if needed.  This is used by the
185 /// Emitter.
186 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
187   void *Ptr = getPointerToGlobalIfAvailable(GV);
188   if (Ptr) return Ptr;
189
190   // If the global is external, just remember the address.
191   if (GV->isExternal()) {
192     Ptr = GetAddressOfSymbol(GV->getName().c_str());
193     if (Ptr == 0) {
194       std::cerr << "Could not resolve external global address: "
195                 << GV->getName() << "\n";
196       abort();
197     }
198   } else {
199     // If the global hasn't been emitted to memory yet, allocate space.  We will
200     // actually initialize the global after current function has finished
201     // compilation.
202     Ptr =new char[getTargetData().getTypeSize(GV->getType()->getElementType())];
203     PendingGlobals.push_back(GV);
204   }
205   addGlobalMapping(GV, Ptr);
206   return Ptr;
207 }
208
209
210 /// recompileAndRelinkFunction - This method is used to force a function
211 /// which has already been compiled, to be compiled again, possibly
212 /// after it has been modified. Then the entry to the old copy is overwritten
213 /// with a branch to the new copy. If there was no old copy, this acts
214 /// just like JIT::getPointerToFunction().
215 ///
216 void *JIT::recompileAndRelinkFunction(Function *F) {
217   void *OldAddr = getPointerToGlobalIfAvailable(F);
218
219   // If it's not already compiled there is no reason to patch it up.
220   if (OldAddr == 0) { return getPointerToFunction(F); }
221
222   // Delete the old function mapping.
223   addGlobalMapping(F, 0);
224
225   // Recodegen the function
226   runJITOnFunction(F);
227
228   // Update state, forward the old function to the new function.
229   void *Addr = getPointerToGlobalIfAvailable(F);
230   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
231   TJI.replaceMachineCodeForFunction(OldAddr, Addr);
232   return Addr;
233 }