blob: fa0a2c10c00fe58cd18cbe657baccdc6b373e7bf [file] [log] [blame]
Chris Lattner4d326fa2003-12-20 01:46:27 +00001//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
Chris Lattnerbd199fb2002-12-24 00:01:05 +00009//
Chris Lattner4d326fa2003-12-20 01:46:27 +000010// This tool implements a just-in-time compiler for LLVM, allowing direct
11// execution of LLVM bytecode in an efficient manner.
Chris Lattnerbd199fb2002-12-24 00:01:05 +000012//
13//===----------------------------------------------------------------------===//
14
Chris Lattner4d326fa2003-12-20 01:46:27 +000015#include "JIT.h"
Chris Lattnerc07ed132003-12-20 03:36:47 +000016#include "llvm/DerivedTypes.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000017#include "llvm/Function.h"
Chris Lattnerc07ed132003-12-20 03:36:47 +000018#include "llvm/GlobalVariable.h"
Misha Brukman0f4f7d92003-10-16 21:19:34 +000019#include "llvm/ModuleProvider.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000020#include "llvm/CodeGen/MachineCodeEmitter.h"
21#include "llvm/CodeGen/MachineFunction.h"
Brian Gaeke97222942003-09-05 19:39:22 +000022#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000023#include "llvm/Target/TargetMachine.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000024#include "llvm/Target/TargetJITInfo.h"
Chris Lattnerc07ed132003-12-20 03:36:47 +000025#include "Support/DynamicLinker.h"
Reid Spencer954da372004-07-04 12:19:56 +000026#include <iostream>
27
Chris Lattnerc19aade2003-12-08 08:06:28 +000028using namespace llvm;
Misha Brukmanabb027c2003-05-27 21:40:39 +000029
Chris Lattner4d326fa2003-12-20 01:46:27 +000030JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
Chris Lattner1e60a912003-12-20 01:22:19 +000031 : ExecutionEngine(MP), TM(tm), TJI(tji), PM(MP) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +000032 setTargetData(TM.getTargetData());
Misha Brukmanabb027c2003-05-27 21:40:39 +000033
34 // Initialize MCE
Misha Brukman906f5fa2003-06-02 03:23:16 +000035 MCE = createEmitter(*this);
Chris Lattner1e60a912003-12-20 01:22:19 +000036
Brian Gaeke50872d52004-04-14 17:45:52 +000037 // Add target data
38 PM.add (new TargetData (TM.getTargetData ()));
39
Chris Lattner4d326fa2003-12-20 01:46:27 +000040 // 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 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +000050}
51
Chris Lattner4d326fa2003-12-20 01:46:27 +000052JIT::~JIT() {
53 delete MCE;
54 delete &TM;
55}
56
Brian Gaeke70975ee2003-09-05 18:42:01 +000057/// run - Start execution with the specified function and arguments.
Chris Lattner05a1a302003-08-21 21:32:12 +000058///
Chris Lattnerff0f1bb2003-12-26 06:13:47 +000059GenericValue JIT::runFunction(Function *F,
60 const std::vector<GenericValue> &ArgValues) {
Chris Lattnerb47130c2004-08-15 23:29:50 +000061 assert(F && "Function *F was null at entry to run()");
Chris Lattnerb47130c2004-08-15 23:29:50 +000062
63 void *FPtr = getPointerToFunction(F);
Chris Lattner7c45d782004-08-15 23:31:43 +000064 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerf7bedf42004-08-15 23:39:59 +000065 const FunctionType *FTy = F->getFunctionType();
Chris Lattnere5eab142004-08-15 23:53:06 +000066 const Type *RetTy = FTy->getReturnType();
Chris Lattnerbd199fb2002-12-24 00:01:05 +000067
Chris Lattnere5eab142004-08-15 23:53:06 +000068 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)!");
72
73 // Handle some common cases first. These cases correspond to common 'main'
74 // prototypes.
Chris Lattnerd297aea2004-08-15 23:34:48 +000075 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
Chris Lattnerf7bedf42004-08-15 23:39:59 +000076 switch (ArgValues.size()) {
77 case 3:
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;
85
86 // Call the function.
Chris Lattnere5eab142004-08-15 23:53:06 +000087 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +000088 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
89 (const char **)GVTOP(ArgValues[2]));
90 return rv;
91 }
92 break;
93 case 1:
94 if (FTy->getNumParams() == 1 &&
95 (FTy->getParamType(0) == Type::IntTy ||
96 FTy->getParamType(0) == Type::UIntTy)) {
Chris Lattnere5eab142004-08-15 23:53:06 +000097 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +000098 int (*PF)(int) = (int(*)(int))FPtr;
99 rv.IntVal = PF(ArgValues[0].IntVal);
100 return rv;
101 }
102 break;
Chris Lattnere5eab142004-08-15 23:53:06 +0000103 }
104 }
105
106 // Handle cases where no arguments are passed first.
107 if (ArgValues.empty()) {
108 GenericValue rv;
109 switch (RetTy->getTypeID()) {
110 default: assert(0 && "Unknown return type for function call!");
111 case Type::BoolTyID:
112 rv.BoolVal = ((bool(*)())FPtr)();
Chris Lattnerd297aea2004-08-15 23:34:48 +0000113 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000114 case Type::SByteTyID:
115 case Type::UByteTyID:
116 rv.SByteVal = ((char(*)())FPtr)();
117 return rv;
118 case Type::ShortTyID:
119 case Type::UShortTyID:
120 rv.ShortVal = ((short(*)())FPtr)();
121 return rv;
122 case Type::VoidTyID:
123 case Type::IntTyID:
124 case Type::UIntTyID:
125 rv.IntVal = ((int(*)())FPtr)();
126 return rv;
127 case Type::LongTyID:
128 case Type::ULongTyID:
129 rv.LongVal = ((int64_t(*)())FPtr)();
130 return rv;
131 case Type::FloatTyID:
132 rv.FloatVal = ((float(*)())FPtr)();
133 return rv;
134 case Type::DoubleTyID:
135 rv.DoubleVal = ((double(*)())FPtr)();
136 return rv;
137 case Type::PointerTyID:
138 return PTOGV(((void*(*)())FPtr)());
Chris Lattnerd297aea2004-08-15 23:34:48 +0000139 }
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000140 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000141
Chris Lattnerb47130c2004-08-15 23:29:50 +0000142 // 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";
147 abort();
Chris Lattnere5eab142004-08-15 23:53:06 +0000148 return GenericValue();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000149}
Chris Lattner4d326fa2003-12-20 01:46:27 +0000150
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.
154///
155void JIT::runJITOnFunction(Function *F) {
156 static bool isAlreadyCodeGenerating = false;
157 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
158
159 // JIT the function
160 isAlreadyCodeGenerating = true;
161 PM.run(*F);
162 isAlreadyCodeGenerating = false;
Chris Lattnerc07ed132003-12-20 03:36:47 +0000163
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);
171 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000172}
173
174/// getPointerToFunction - This method is used to get the address of the
175/// specified function, compiling it if neccesary.
176///
177void *JIT::getPointerToFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000178 if (void *Addr = getPointerToGlobalIfAvailable(F))
179 return Addr; // Check if function already code gen'd
Chris Lattner4d326fa2003-12-20 01:46:27 +0000180
181 // Make sure we read in the function if it exists in this Module
Chris Lattnerda79bd22004-02-01 00:32:35 +0000182 try {
183 MP->materializeFunction(F);
Reid Spencere2947532004-07-07 21:01:38 +0000184 } catch ( std::string& errmsg ) {
Reid Spencerf86cafd2004-07-07 21:20:28 +0000185 std::cerr << "Error reading bytecode file: " << errmsg << "\n";
Reid Spencere2947532004-07-07 21:01:38 +0000186 abort();
Chris Lattnerda79bd22004-02-01 00:32:35 +0000187 } catch (...) {
Reid Spencerf86cafd2004-07-07 21:20:28 +0000188 std::cerr << "Error reading bytecode file!\n";
Chris Lattnerda79bd22004-02-01 00:32:35 +0000189 abort();
190 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000191
Chris Lattnerc07ed132003-12-20 03:36:47 +0000192 if (F->isExternal()) {
193 void *Addr = getPointerToNamedFunction(F->getName());
194 addGlobalMapping(F, Addr);
195 return Addr;
196 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000197
198 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000199
200 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000201 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
202 return Addr;
203}
204
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.
208//
209void *JIT::getPointerToFunctionOrStub(Function *F) {
210 // If we have already code generated the function, just return the address.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000211 if (void *Addr = getPointerToGlobalIfAvailable(F))
212 return Addr;
Chris Lattner4d326fa2003-12-20 01:46:27 +0000213
214 // If the target supports "stubs" for functions, get a stub now.
215 if (void *Ptr = TJI.getJITStubForFunction(F, *MCE))
216 return Ptr;
217
218 // Otherwise, if the target doesn't support it, just codegen the function.
219 return getPointerToFunction(F);
220}
221
Chris Lattnerc07ed132003-12-20 03:36:47 +0000222/// getOrEmitGlobalVariable - Return the address of the specified global
223/// variable, possibly emitting it to memory if needed. This is used by the
224/// Emitter.
225void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
226 void *Ptr = getPointerToGlobalIfAvailable(GV);
227 if (Ptr) return Ptr;
228
229 // If the global is external, just remember the address.
230 if (GV->isExternal()) {
231 Ptr = GetAddressOfSymbol(GV->getName().c_str());
232 if (Ptr == 0) {
233 std::cerr << "Could not resolve external global address: "
234 << GV->getName() << "\n";
235 abort();
236 }
237 } else {
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
240 // compilation.
241 Ptr =new char[getTargetData().getTypeSize(GV->getType()->getElementType())];
242 PendingGlobals.push_back(GV);
243 }
244 addGlobalMapping(GV, Ptr);
245 return Ptr;
246}
247
248
Chris Lattner4d326fa2003-12-20 01:46:27 +0000249/// 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().
254///
255void *JIT::recompileAndRelinkFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000256 void *OldAddr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000257
Chris Lattnerc07ed132003-12-20 03:36:47 +0000258 // If it's not already compiled there is no reason to patch it up.
259 if (OldAddr == 0) { return getPointerToFunction(F); }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000260
Chris Lattnerc07ed132003-12-20 03:36:47 +0000261 // Delete the old function mapping.
262 addGlobalMapping(F, 0);
263
Chris Lattnerc07ed132003-12-20 03:36:47 +0000264 // Recodegen the function
Chris Lattner4d326fa2003-12-20 01:46:27 +0000265 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000266
267 // Update state, forward the old function to the new function.
268 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000269 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
270 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
271 return Addr;
272}