1 //===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This tool implements a just-in-time compiler for LLVM, allowing direct
11 // execution of LLVM bytecode in an efficient manner.
13 //===----------------------------------------------------------------------===//
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"
30 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
31 : ExecutionEngine(MP), TM(tm), TJI(tji), PM(MP) {
32 setTargetData(TM.getTargetData());
35 MCE = createEmitter(*this);
38 PM.add (new TargetData (TM.getTargetData ()));
40 // Compile LLVM Code down to machine code in the intermediate representation
41 TJI.addPassesToJITCompile(PM);
43 // Turn the machine code intermediate representation into bytes in memory that
45 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
46 std::cerr << "lli: target '" << TM.getName()
47 << "' doesn't support machine code emission!\n";
57 /// run - Start execution with the specified function and arguments.
59 GenericValue JIT::runFunction(Function *F,
60 const std::vector<GenericValue> &ArgValues) {
61 assert(F && "Function *F was null at entry to run()");
63 void *FPtr = getPointerToFunction(F);
64 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
65 const FunctionType *FTy = F->getFunctionType();
66 const Type *RetTy = FTy->getReturnType();
68 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
69 "Too many arguments passed into function!");
70 assert(FTy->getNumParams() == ArgValues.size() &&
71 "This doesn't support passing arguments through varargs (yet)!");
73 // Handle some common cases first. These cases correspond to common 'main'
75 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
76 switch (ArgValues.size()) {
78 if (FTy->getNumParams() == 3 &&
79 (FTy->getParamType(0) == Type::IntTy ||
80 FTy->getParamType(0) == Type::UIntTy) &&
81 isa<PointerType>(FTy->getParamType(1)) &&
82 isa<PointerType>(FTy->getParamType(2))) {
83 int (*PF)(int, char **, const char **) =
84 (int(*)(int, char **, const char **))FPtr;
88 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
89 (const char **)GVTOP(ArgValues[2]));
94 if (FTy->getNumParams() == 1 &&
95 (FTy->getParamType(0) == Type::IntTy ||
96 FTy->getParamType(0) == Type::UIntTy)) {
98 int (*PF)(int) = (int(*)(int))FPtr;
99 rv.IntVal = PF(ArgValues[0].IntVal);
106 // Handle cases where no arguments are passed first.
107 if (ArgValues.empty()) {
109 switch (RetTy->getTypeID()) {
110 default: assert(0 && "Unknown return type for function call!");
112 rv.BoolVal = ((bool(*)())FPtr)();
114 case Type::SByteTyID:
115 case Type::UByteTyID:
116 rv.SByteVal = ((char(*)())FPtr)();
118 case Type::ShortTyID:
119 case Type::UShortTyID:
120 rv.ShortVal = ((short(*)())FPtr)();
125 rv.IntVal = ((int(*)())FPtr)();
128 case Type::ULongTyID:
129 rv.LongVal = ((int64_t(*)())FPtr)();
131 case Type::FloatTyID:
132 rv.FloatVal = ((float(*)())FPtr)();
134 case Type::DoubleTyID:
135 rv.DoubleVal = ((double(*)())FPtr)();
137 case Type::PointerTyID:
138 return PTOGV(((void*(*)())FPtr)());
142 // FIXME: This code should handle a couple of common cases efficiently, but
143 // it should also implement the general case by code-gening a new anonymous
144 // nullary function to call.
145 std::cerr << "Sorry, unimplemented feature in the LLVM JIT. See LLVM"
146 << " PR#419\n for details.\n";
148 return GenericValue();
151 /// runJITOnFunction - Run the FunctionPassManager full of
152 /// just-in-time compilation passes on F, hopefully filling in
153 /// GlobalAddress[F] with the address of F's machine code.
155 void JIT::runJITOnFunction(Function *F) {
156 static bool isAlreadyCodeGenerating = false;
157 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
160 isAlreadyCodeGenerating = true;
162 isAlreadyCodeGenerating = false;
164 // If the function referred to a global variable that had not yet been
165 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
166 // all of these globals now.
167 while (!PendingGlobals.empty()) {
168 const GlobalVariable *GV = PendingGlobals.back();
169 PendingGlobals.pop_back();
170 EmitGlobalVariable(GV);
174 /// getPointerToFunction - This method is used to get the address of the
175 /// specified function, compiling it if neccesary.
177 void *JIT::getPointerToFunction(Function *F) {
178 if (void *Addr = getPointerToGlobalIfAvailable(F))
179 return Addr; // Check if function already code gen'd
181 // Make sure we read in the function if it exists in this Module
183 MP->materializeFunction(F);
184 } catch ( std::string& errmsg ) {
185 std::cerr << "Error reading bytecode file: " << errmsg << "\n";
188 std::cerr << "Error reading bytecode file!\n";
192 if (F->isExternal()) {
193 void *Addr = getPointerToNamedFunction(F->getName());
194 addGlobalMapping(F, Addr);
200 void *Addr = getPointerToGlobalIfAvailable(F);
201 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
205 // getPointerToFunctionOrStub - If the specified function has been
206 // code-gen'd, return a pointer to the function. If not, compile it, or use
207 // a stub to implement lazy compilation if available.
209 void *JIT::getPointerToFunctionOrStub(Function *F) {
210 // If we have already code generated the function, just return the address.
211 if (void *Addr = getPointerToGlobalIfAvailable(F))
214 // If the target supports "stubs" for functions, get a stub now.
215 if (void *Ptr = TJI.getJITStubForFunction(F, *MCE))
218 // Otherwise, if the target doesn't support it, just codegen the function.
219 return getPointerToFunction(F);
222 /// getOrEmitGlobalVariable - Return the address of the specified global
223 /// variable, possibly emitting it to memory if needed. This is used by the
225 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
226 void *Ptr = getPointerToGlobalIfAvailable(GV);
229 // If the global is external, just remember the address.
230 if (GV->isExternal()) {
231 Ptr = GetAddressOfSymbol(GV->getName().c_str());
233 std::cerr << "Could not resolve external global address: "
234 << GV->getName() << "\n";
238 // If the global hasn't been emitted to memory yet, allocate space. We will
239 // actually initialize the global after current function has finished
241 Ptr =new char[getTargetData().getTypeSize(GV->getType()->getElementType())];
242 PendingGlobals.push_back(GV);
244 addGlobalMapping(GV, Ptr);
249 /// recompileAndRelinkFunction - This method is used to force a function
250 /// which has already been compiled, to be compiled again, possibly
251 /// after it has been modified. Then the entry to the old copy is overwritten
252 /// with a branch to the new copy. If there was no old copy, this acts
253 /// just like JIT::getPointerToFunction().
255 void *JIT::recompileAndRelinkFunction(Function *F) {
256 void *OldAddr = getPointerToGlobalIfAvailable(F);
258 // If it's not already compiled there is no reason to patch it up.
259 if (OldAddr == 0) { return getPointerToFunction(F); }
261 // Delete the old function mapping.
262 addGlobalMapping(F, 0);
264 // Recodegen the function
267 // Update state, forward the old function to the new function.
268 void *Addr = getPointerToGlobalIfAvailable(F);
269 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
270 TJI.replaceMachineCodeForFunction(OldAddr, Addr);