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/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/ModuleProvider.h"
22 #include "llvm/CodeGen/MachineCodeEmitter.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/ExecutionEngine/GenericValue.h"
25 #include "llvm/Support/MutexGuard.h"
26 #include "llvm/System/DynamicLibrary.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetJITInfo.h"
33 #include <AvailabilityMacros.h>
34 #if defined(MAC_OS_X_VERSION_10_4) && \
35 ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
36 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
37 __APPLE_CC__ >= 5330))
38 // __dso_handle is resolved by Mac OS X dynamic linker.
39 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
43 static struct RegisterJIT {
44 RegisterJIT() { JIT::Register(); }
52 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
53 : ExecutionEngine(MP), TM(tm), TJI(tji), state(MP) {
54 setTargetData(TM.getTargetData());
57 MCE = createEmitter(*this);
60 MutexGuard locked(lock);
61 FunctionPassManager &PM = state.getPM(locked);
62 PM.add(new TargetData(*TM.getTargetData()));
64 // Turn the machine code intermediate representation into bytes in memory that
66 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
67 cerr << "Target does not support machine code emission!\n";
72 PM.doInitialization();
80 /// run - Start execution with the specified function and arguments.
82 GenericValue JIT::runFunction(Function *F,
83 const std::vector<GenericValue> &ArgValues) {
84 assert(F && "Function *F was null at entry to run()");
86 void *FPtr = getPointerToFunction(F);
87 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
88 const FunctionType *FTy = F->getFunctionType();
89 const Type *RetTy = FTy->getReturnType();
91 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
92 "Too many arguments passed into function!");
93 assert(FTy->getNumParams() == ArgValues.size() &&
94 "This doesn't support passing arguments through varargs (yet)!");
96 // Handle some common cases first. These cases correspond to common `main'
98 if (RetTy == Type::Int32Ty || RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
99 switch (ArgValues.size()) {
101 if ((FTy->getParamType(0) == Type::Int32Ty ||
102 FTy->getParamType(0) == Type::Int32Ty) &&
103 isa<PointerType>(FTy->getParamType(1)) &&
104 isa<PointerType>(FTy->getParamType(2))) {
105 int (*PF)(int, char **, const char **) =
106 (int(*)(int, char **, const char **))(intptr_t)FPtr;
108 // Call the function.
110 rv.Int32Val = PF(ArgValues[0].Int32Val, (char **)GVTOP(ArgValues[1]),
111 (const char **)GVTOP(ArgValues[2]));
116 if ((FTy->getParamType(0) == Type::Int32Ty ||
117 FTy->getParamType(0) == Type::Int32Ty) &&
118 isa<PointerType>(FTy->getParamType(1))) {
119 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
121 // Call the function.
123 rv.Int32Val = PF(ArgValues[0].Int32Val, (char **)GVTOP(ArgValues[1]));
128 if (FTy->getNumParams() == 1 &&
129 (FTy->getParamType(0) == Type::Int32Ty ||
130 FTy->getParamType(0) == Type::Int32Ty)) {
132 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
133 rv.Int32Val = PF(ArgValues[0].Int32Val);
140 // Handle cases where no arguments are passed first.
141 if (ArgValues.empty()) {
143 switch (RetTy->getTypeID()) {
144 default: assert(0 && "Unknown return type for function call!");
145 case Type::IntegerTyID: {
146 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
148 rv.Int1Val = ((bool(*)())(intptr_t)FPtr)();
149 else if (BitWidth <= 8)
150 rv.Int8Val = ((char(*)())(intptr_t)FPtr)();
151 else if (BitWidth <= 16)
152 rv.Int16Val = ((short(*)())(intptr_t)FPtr)();
153 else if (BitWidth <= 32)
154 rv.Int32Val = ((int(*)())(intptr_t)FPtr)();
155 else if (BitWidth <= 64)
156 rv.Int64Val = ((int64_t(*)())(intptr_t)FPtr)();
158 assert(0 && "Integer types > 64 bits not supported");
162 rv.Int32Val = ((int(*)())(intptr_t)FPtr)();
164 case Type::FloatTyID:
165 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
167 case Type::DoubleTyID:
168 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
170 case Type::PointerTyID:
171 return PTOGV(((void*(*)())(intptr_t)FPtr)());
175 // Okay, this is not one of our quick and easy cases. Because we don't have a
176 // full FFI, we have to codegen a nullary stub function that just calls the
177 // function we are interested in, passing in constants for all of the
178 // arguments. Make this function and return.
180 // First, create the function.
181 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
182 Function *Stub = new Function(STy, Function::InternalLinkage, "",
185 // Insert a basic block.
186 BasicBlock *StubBB = new BasicBlock("", Stub);
188 // Convert all of the GenericValue arguments over to constants. Note that we
189 // currently don't support varargs.
190 std::vector<Value*> Args;
191 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
193 const Type *ArgTy = FTy->getParamType(i);
194 const GenericValue &AV = ArgValues[i];
195 switch (ArgTy->getTypeID()) {
196 default: assert(0 && "Unknown argument type for function call!");
197 case Type::IntegerTyID: {
198 unsigned BitWidth = cast<IntegerType>(ArgTy)->getBitWidth();
200 C = ConstantInt::get(ArgTy, AV.Int1Val);
201 else if (BitWidth <= 8)
202 C = ConstantInt::get(ArgTy, AV.Int8Val);
203 else if (BitWidth <= 16)
204 C = ConstantInt::get(ArgTy, AV.Int16Val);
205 else if (BitWidth <= 32)
206 C = ConstantInt::get(ArgTy, AV.Int32Val);
207 else if (BitWidth <= 64)
208 C = ConstantInt::get(ArgTy, AV.Int64Val);
210 assert(0 && "Integer types > 64 bits not supported");
213 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
214 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
215 case Type::PointerTyID:
216 void *ArgPtr = GVTOP(AV);
217 if (sizeof(void*) == 4) {
218 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
220 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
222 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
228 CallInst *TheCall = new CallInst(F, Args, "", StubBB);
229 TheCall->setTailCall();
230 if (TheCall->getType() != Type::VoidTy)
231 new ReturnInst(TheCall, StubBB); // Return result of the call.
233 new ReturnInst(StubBB); // Just return void.
235 // Finally, return the value returned by our nullary stub function.
236 return runFunction(Stub, std::vector<GenericValue>());
239 /// runJITOnFunction - Run the FunctionPassManager full of
240 /// just-in-time compilation passes on F, hopefully filling in
241 /// GlobalAddress[F] with the address of F's machine code.
243 void JIT::runJITOnFunction(Function *F) {
244 static bool isAlreadyCodeGenerating = false;
245 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
247 MutexGuard locked(lock);
250 isAlreadyCodeGenerating = true;
251 state.getPM(locked).run(*F);
252 isAlreadyCodeGenerating = false;
254 // If the function referred to a global variable that had not yet been
255 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
256 // all of these globals now.
257 while (!state.getPendingGlobals(locked).empty()) {
258 const GlobalVariable *GV = state.getPendingGlobals(locked).back();
259 state.getPendingGlobals(locked).pop_back();
260 EmitGlobalVariable(GV);
264 /// getPointerToFunction - This method is used to get the address of the
265 /// specified function, compiling it if neccesary.
267 void *JIT::getPointerToFunction(Function *F) {
268 MutexGuard locked(lock);
270 if (void *Addr = getPointerToGlobalIfAvailable(F))
271 return Addr; // Check if function already code gen'd
273 // Make sure we read in the function if it exists in this Module.
274 if (F->hasNotBeenReadFromBytecode()) {
275 // Determine the module provider this function is provided by.
276 Module *M = F->getParent();
277 ModuleProvider *MP = 0;
278 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
279 if (Modules[i]->getModule() == M) {
284 assert(MP && "Function isn't in a module we know about!");
286 std::string ErrorMsg;
287 if (MP->materializeFunction(F, &ErrorMsg)) {
288 cerr << "Error reading function '" << F->getName()
289 << "' from bytecode file: " << ErrorMsg << "\n";
294 if (F->isDeclaration()) {
295 void *Addr = getPointerToNamedFunction(F->getName());
296 addGlobalMapping(F, Addr);
302 void *Addr = getPointerToGlobalIfAvailable(F);
303 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
307 /// getOrEmitGlobalVariable - Return the address of the specified global
308 /// variable, possibly emitting it to memory if needed. This is used by the
310 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
311 MutexGuard locked(lock);
313 void *Ptr = getPointerToGlobalIfAvailable(GV);
316 // If the global is external, just remember the address.
317 if (GV->isDeclaration()) {
318 #if defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_4) && \
319 ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
320 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
321 __APPLE_CC__ >= 5330))
322 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
323 // of atexit). It passes the address of linker generated symbol __dso_handle
325 // This configuration change happened at version 5330.
326 if (GV->getName() == "__dso_handle")
327 return (void*)&__dso_handle;
329 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
331 cerr << "Could not resolve external global address: "
332 << GV->getName() << "\n";
336 // If the global hasn't been emitted to memory yet, allocate space. We will
337 // actually initialize the global after current function has finished
339 const Type *GlobalType = GV->getType()->getElementType();
340 size_t S = getTargetData()->getTypeSize(GlobalType);
341 size_t A = getTargetData()->getTypeAlignmentPref(GlobalType);
345 // Allocate S+A bytes of memory, then use an aligned pointer within that
348 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
349 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
351 state.getPendingGlobals(locked).push_back(GV);
353 addGlobalMapping(GV, Ptr);
358 /// recompileAndRelinkFunction - This method is used to force a function
359 /// which has already been compiled, to be compiled again, possibly
360 /// after it has been modified. Then the entry to the old copy is overwritten
361 /// with a branch to the new copy. If there was no old copy, this acts
362 /// just like JIT::getPointerToFunction().
364 void *JIT::recompileAndRelinkFunction(Function *F) {
365 void *OldAddr = getPointerToGlobalIfAvailable(F);
367 // If it's not already compiled there is no reason to patch it up.
368 if (OldAddr == 0) { return getPointerToFunction(F); }
370 // Delete the old function mapping.
371 addGlobalMapping(F, 0);
373 // Recodegen the function
376 // Update state, forward the old function to the new function.
377 void *Addr = getPointerToGlobalIfAvailable(F);
378 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
379 TJI.replaceMachineCodeForFunction(OldAddr, Addr);