1 //===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tool implements a just-in-time compiler for LLVM, allowing direct
11 // execution of LLVM bitcode 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"
31 #include "llvm/Config/config.h"
36 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
37 // of atexit). It passes the address of linker generated symbol __dso_handle
39 // This configuration change happened at version 5330.
40 # include <AvailabilityMacros.h>
41 # if defined(MAC_OS_X_VERSION_10_4) && \
42 ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
43 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
44 __APPLE_CC__ >= 5330))
45 # ifndef HAVE___DSO_HANDLE
46 # define HAVE___DSO_HANDLE 1
52 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
57 static struct RegisterJIT {
58 RegisterJIT() { JIT::Register(); }
68 #if defined (__GNUC__)
69 extern "C" void __register_frame(void*);
72 /// createJIT - This is the factory method for creating a JIT for the current
73 /// machine, it does not fall back to the interpreter. This takes ownership
74 /// of the module provider.
75 ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
76 std::string *ErrorStr,
77 JITMemoryManager *JMM) {
78 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM);
81 // Register routine for informing unwinding runtime about new EH frames
83 EE->InstallExceptionTableRegister(__register_frame);
86 // Make sure we can resolve symbols in the program as well. The zero arg
87 // to the function tells DynamicLibrary to load the program, not a library.
88 sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
92 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
93 JITMemoryManager *JMM)
94 : ExecutionEngine(MP), TM(tm), TJI(tji) {
95 setTargetData(TM.getTargetData());
97 jitstate = new JITState(MP);
100 MCE = createEmitter(*this, JMM);
103 MutexGuard locked(lock);
104 FunctionPassManager &PM = jitstate->getPM(locked);
105 PM.add(new TargetData(*TM.getTargetData()));
107 // Turn the machine code intermediate representation into bytes in memory that
109 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
110 cerr << "Target does not support machine code emission!\n";
114 // Initialize passes.
115 PM.doInitialization();
124 /// addModuleProvider - Add a new ModuleProvider to the JIT. If we previously
125 /// removed the last ModuleProvider, we need re-initialize jitstate with a valid
127 void JIT::addModuleProvider(ModuleProvider *MP) {
128 MutexGuard locked(lock);
130 if (Modules.empty()) {
131 assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
133 jitstate = new JITState(MP);
135 FunctionPassManager &PM = jitstate->getPM(locked);
136 PM.add(new TargetData(*TM.getTargetData()));
138 // Turn the machine code intermediate representation into bytes in memory
139 // that may be executed.
140 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
141 cerr << "Target does not support machine code emission!\n";
145 // Initialize passes.
146 PM.doInitialization();
149 ExecutionEngine::addModuleProvider(MP);
152 /// removeModuleProvider - If we are removing the last ModuleProvider,
153 /// invalidate the jitstate since the PassManager it contains references a
154 /// released ModuleProvider.
155 Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
156 Module *result = ExecutionEngine::removeModuleProvider(MP, E);
158 MutexGuard locked(lock);
159 if (Modules.empty()) {
167 /// run - Start execution with the specified function and arguments.
169 GenericValue JIT::runFunction(Function *F,
170 const std::vector<GenericValue> &ArgValues) {
171 assert(F && "Function *F was null at entry to run()");
173 void *FPtr = getPointerToFunction(F);
174 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
175 const FunctionType *FTy = F->getFunctionType();
176 const Type *RetTy = FTy->getReturnType();
178 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
179 "Too many arguments passed into function!");
180 assert(FTy->getNumParams() == ArgValues.size() &&
181 "This doesn't support passing arguments through varargs (yet)!");
183 // Handle some common cases first. These cases correspond to common `main'
185 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
186 switch (ArgValues.size()) {
188 if (FTy->getParamType(0) == Type::Int32Ty &&
189 isa<PointerType>(FTy->getParamType(1)) &&
190 isa<PointerType>(FTy->getParamType(2))) {
191 int (*PF)(int, char **, const char **) =
192 (int(*)(int, char **, const char **))(intptr_t)FPtr;
194 // Call the function.
196 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
197 (char **)GVTOP(ArgValues[1]),
198 (const char **)GVTOP(ArgValues[2])));
203 if (FTy->getParamType(0) == Type::Int32Ty &&
204 isa<PointerType>(FTy->getParamType(1))) {
205 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
207 // Call the function.
209 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
210 (char **)GVTOP(ArgValues[1])));
215 if (FTy->getNumParams() == 1 &&
216 FTy->getParamType(0) == Type::Int32Ty) {
218 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
219 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
226 // Handle cases where no arguments are passed first.
227 if (ArgValues.empty()) {
229 switch (RetTy->getTypeID()) {
230 default: assert(0 && "Unknown return type for function call!");
231 case Type::IntegerTyID: {
232 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
234 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
235 else if (BitWidth <= 8)
236 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
237 else if (BitWidth <= 16)
238 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
239 else if (BitWidth <= 32)
240 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
241 else if (BitWidth <= 64)
242 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
244 assert(0 && "Integer types > 64 bits not supported");
248 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
250 case Type::FloatTyID:
251 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
253 case Type::DoubleTyID:
254 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
256 case Type::X86_FP80TyID:
257 case Type::FP128TyID:
258 case Type::PPC_FP128TyID:
259 assert(0 && "long double not supported yet");
261 case Type::PointerTyID:
262 return PTOGV(((void*(*)())(intptr_t)FPtr)());
266 // Okay, this is not one of our quick and easy cases. Because we don't have a
267 // full FFI, we have to codegen a nullary stub function that just calls the
268 // function we are interested in, passing in constants for all of the
269 // arguments. Make this function and return.
271 // First, create the function.
272 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
273 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
276 // Insert a basic block.
277 BasicBlock *StubBB = BasicBlock::Create("", Stub);
279 // Convert all of the GenericValue arguments over to constants. Note that we
280 // currently don't support varargs.
281 SmallVector<Value*, 8> Args;
282 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
284 const Type *ArgTy = FTy->getParamType(i);
285 const GenericValue &AV = ArgValues[i];
286 switch (ArgTy->getTypeID()) {
287 default: assert(0 && "Unknown argument type for function call!");
288 case Type::IntegerTyID:
289 C = ConstantInt::get(AV.IntVal);
291 case Type::FloatTyID:
292 C = ConstantFP::get(APFloat(AV.FloatVal));
294 case Type::DoubleTyID:
295 C = ConstantFP::get(APFloat(AV.DoubleVal));
297 case Type::PPC_FP128TyID:
298 case Type::X86_FP80TyID:
299 case Type::FP128TyID:
300 C = ConstantFP::get(APFloat(AV.IntVal));
302 case Type::PointerTyID:
303 void *ArgPtr = GVTOP(AV);
304 if (sizeof(void*) == 4)
305 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
307 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
308 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
314 CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
316 TheCall->setTailCall();
317 if (TheCall->getType() != Type::VoidTy)
318 ReturnInst::Create(TheCall, StubBB); // Return result of the call.
320 ReturnInst::Create(StubBB); // Just return void.
322 // Finally, return the value returned by our nullary stub function.
323 return runFunction(Stub, std::vector<GenericValue>());
326 /// runJITOnFunction - Run the FunctionPassManager full of
327 /// just-in-time compilation passes on F, hopefully filling in
328 /// GlobalAddress[F] with the address of F's machine code.
330 void JIT::runJITOnFunction(Function *F) {
331 static bool isAlreadyCodeGenerating = false;
333 MutexGuard locked(lock);
334 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
337 isAlreadyCodeGenerating = true;
338 jitstate->getPM(locked).run(*F);
339 isAlreadyCodeGenerating = false;
341 // If the function referred to a global variable that had not yet been
342 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
343 // all of these globals now.
344 while (!jitstate->getPendingGlobals(locked).empty()) {
345 const GlobalVariable *GV = jitstate->getPendingGlobals(locked).back();
346 jitstate->getPendingGlobals(locked).pop_back();
347 EmitGlobalVariable(GV);
351 /// getPointerToFunction - This method is used to get the address of the
352 /// specified function, compiling it if neccesary.
354 void *JIT::getPointerToFunction(Function *F) {
356 if (void *Addr = getPointerToGlobalIfAvailable(F))
357 return Addr; // Check if function already code gen'd
359 // Make sure we read in the function if it exists in this Module.
360 if (F->hasNotBeenReadFromBitcode()) {
361 // Determine the module provider this function is provided by.
362 Module *M = F->getParent();
363 ModuleProvider *MP = 0;
364 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
365 if (Modules[i]->getModule() == M) {
370 assert(MP && "Function isn't in a module we know about!");
372 std::string ErrorMsg;
373 if (MP->materializeFunction(F, &ErrorMsg)) {
374 cerr << "Error reading function '" << F->getName()
375 << "' from bitcode file: " << ErrorMsg << "\n";
380 if (void *Addr = getPointerToGlobalIfAvailable(F)) {
384 MutexGuard locked(lock);
386 if (F->isDeclaration()) {
387 void *Addr = getPointerToNamedFunction(F->getName());
388 addGlobalMapping(F, Addr);
394 void *Addr = getPointerToGlobalIfAvailable(F);
395 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
399 /// getOrEmitGlobalVariable - Return the address of the specified global
400 /// variable, possibly emitting it to memory if needed. This is used by the
402 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
403 MutexGuard locked(lock);
405 void *Ptr = getPointerToGlobalIfAvailable(GV);
408 // If the global is external, just remember the address.
409 if (GV->isDeclaration()) {
410 #if HAVE___DSO_HANDLE
411 if (GV->getName() == "__dso_handle")
412 return (void*)&__dso_handle;
414 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
416 cerr << "Could not resolve external global address: "
417 << GV->getName() << "\n";
421 // If the global hasn't been emitted to memory yet, allocate space. We will
422 // actually initialize the global after current function has finished
424 const Type *GlobalType = GV->getType()->getElementType();
425 size_t S = getTargetData()->getABITypeSize(GlobalType);
426 size_t A = getTargetData()->getPreferredAlignment(GV);
430 // Allocate S+A bytes of memory, then use an aligned pointer within that
433 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
434 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
436 jitstate->getPendingGlobals(locked).push_back(GV);
438 addGlobalMapping(GV, Ptr);
443 /// recompileAndRelinkFunction - This method is used to force a function
444 /// which has already been compiled, to be compiled again, possibly
445 /// after it has been modified. Then the entry to the old copy is overwritten
446 /// with a branch to the new copy. If there was no old copy, this acts
447 /// just like JIT::getPointerToFunction().
449 void *JIT::recompileAndRelinkFunction(Function *F) {
450 void *OldAddr = getPointerToGlobalIfAvailable(F);
452 // If it's not already compiled there is no reason to patch it up.
453 if (OldAddr == 0) { return getPointerToFunction(F); }
455 // Delete the old function mapping.
456 addGlobalMapping(F, 0);
458 // Recodegen the function
461 // Update state, forward the old function to the new function.
462 void *Addr = getPointerToGlobalIfAvailable(F);
463 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
464 TJI.replaceMachineCodeForFunction(OldAddr, Addr);