LLVM API Documentation

MCJIT.cpp
Go to the documentation of this file.
00001 //===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "MCJIT.h"
00011 #include "MCJITMemoryManager.h"
00012 #include "llvm/DerivedTypes.h"
00013 #include "llvm/Function.h"
00014 #include "llvm/ExecutionEngine/GenericValue.h"
00015 #include "llvm/ExecutionEngine/MCJIT.h"
00016 #include "llvm/ExecutionEngine/JITMemoryManager.h"
00017 #include "llvm/MC/MCAsmInfo.h"
00018 #include "llvm/Support/ErrorHandling.h"
00019 #include "llvm/Support/DynamicLibrary.h"
00020 #include "llvm/Support/MemoryBuffer.h"
00021 #include "llvm/Target/TargetData.h"
00022 
00023 using namespace llvm;
00024 
00025 namespace {
00026 
00027 static struct RegisterJIT {
00028   RegisterJIT() { MCJIT::Register(); }
00029 } JITRegistrator;
00030 
00031 }
00032 
00033 extern "C" void LLVMLinkInMCJIT() {
00034 }
00035 
00036 ExecutionEngine *MCJIT::createJIT(Module *M,
00037                                   std::string *ErrorStr,
00038                                   JITMemoryManager *JMM,
00039                                   bool GVsWithCode,
00040                                   TargetMachine *TM) {
00041   // Try to register the program as a source of symbols to resolve against.
00042   //
00043   // FIXME: Don't do this here.
00044   sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
00045 
00046   // If the target supports JIT code generation, create the JIT.
00047   if (TargetJITInfo *TJ = TM->getJITInfo())
00048     return new MCJIT(M, TM, *TJ, new MCJITMemoryManager(JMM, M), GVsWithCode);
00049 
00050   if (ErrorStr)
00051     *ErrorStr = "target does not support JIT code generation";
00052   return 0;
00053 }
00054 
00055 MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji,
00056              RTDyldMemoryManager *MM, bool AllocateGVsWithCode)
00057   : ExecutionEngine(m), TM(tm), MemMgr(MM), M(m), OS(Buffer), Dyld(MM) {
00058 
00059   setTargetData(TM->getTargetData());
00060   PM.add(new TargetData(*TM->getTargetData()));
00061 
00062   // Turn the machine code intermediate representation into bytes in memory
00063   // that may be executed.
00064   if (TM->addPassesToEmitMC(PM, Ctx, OS, false)) {
00065     report_fatal_error("Target does not support MC emission!");
00066   }
00067 
00068   // Initialize passes.
00069   // FIXME: When we support multiple modules, we'll want to move the code
00070   // gen and finalization out of the constructor here and do it more
00071   // on-demand as part of getPointerToFunction().
00072   PM.run(*M);
00073   // Flush the output buffer so the SmallVector gets its data.
00074   OS.flush();
00075 
00076   // Load the object into the dynamic linker.
00077   MemoryBuffer *MB = MemoryBuffer::getMemBuffer(StringRef(Buffer.data(),
00078                                                           Buffer.size()),
00079                                                 "", false);
00080   if (Dyld.loadObject(MB))
00081     report_fatal_error(Dyld.getErrorString());
00082   // Resolve any relocations.
00083   Dyld.resolveRelocations();
00084 }
00085 
00086 MCJIT::~MCJIT() {
00087   delete MemMgr;
00088   delete TM;
00089 }
00090 
00091 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
00092   report_fatal_error("not yet implemented");
00093 }
00094 
00095 void *MCJIT::getPointerToFunction(Function *F) {
00096   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
00097     bool AbortOnFailure = !F->hasExternalWeakLinkage();
00098     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
00099     addGlobalMapping(F, Addr);
00100     return Addr;
00101   }
00102 
00103   // FIXME: Should we be using the mangler for this? Probably.
00104   StringRef BaseName = F->getName();
00105   if (BaseName[0] == '\1')
00106     return (void*)Dyld.getSymbolAddress(BaseName.substr(1));
00107   return (void*)Dyld.getSymbolAddress((TM->getMCAsmInfo()->getGlobalPrefix()
00108                                        + BaseName).str());
00109 }
00110 
00111 void *MCJIT::recompileAndRelinkFunction(Function *F) {
00112   report_fatal_error("not yet implemented");
00113 }
00114 
00115 void MCJIT::freeMachineCodeForFunction(Function *F) {
00116   report_fatal_error("not yet implemented");
00117 }
00118 
00119 GenericValue MCJIT::runFunction(Function *F,
00120                                 const std::vector<GenericValue> &ArgValues) {
00121   assert(F && "Function *F was null at entry to run()");
00122 
00123   void *FPtr = getPointerToFunction(F);
00124   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
00125   FunctionType *FTy = F->getFunctionType();
00126   Type *RetTy = FTy->getReturnType();
00127 
00128   assert((FTy->getNumParams() == ArgValues.size() ||
00129           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
00130          "Wrong number of arguments passed into function!");
00131   assert(FTy->getNumParams() == ArgValues.size() &&
00132          "This doesn't support passing arguments through varargs (yet)!");
00133 
00134   // Handle some common cases first.  These cases correspond to common `main'
00135   // prototypes.
00136   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
00137     switch (ArgValues.size()) {
00138     case 3:
00139       if (FTy->getParamType(0)->isIntegerTy(32) &&
00140           FTy->getParamType(1)->isPointerTy() &&
00141           FTy->getParamType(2)->isPointerTy()) {
00142         int (*PF)(int, char **, const char **) =
00143           (int(*)(int, char **, const char **))(intptr_t)FPtr;
00144 
00145         // Call the function.
00146         GenericValue rv;
00147         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
00148                                  (char **)GVTOP(ArgValues[1]),
00149                                  (const char **)GVTOP(ArgValues[2])));
00150         return rv;
00151       }
00152       break;
00153     case 2:
00154       if (FTy->getParamType(0)->isIntegerTy(32) &&
00155           FTy->getParamType(1)->isPointerTy()) {
00156         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
00157 
00158         // Call the function.
00159         GenericValue rv;
00160         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
00161                                  (char **)GVTOP(ArgValues[1])));
00162         return rv;
00163       }
00164       break;
00165     case 1:
00166       if (FTy->getNumParams() == 1 &&
00167           FTy->getParamType(0)->isIntegerTy(32)) {
00168         GenericValue rv;
00169         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
00170         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
00171         return rv;
00172       }
00173       break;
00174     }
00175   }
00176 
00177   // Handle cases where no arguments are passed first.
00178   if (ArgValues.empty()) {
00179     GenericValue rv;
00180     switch (RetTy->getTypeID()) {
00181     default: llvm_unreachable("Unknown return type for function call!");
00182     case Type::IntegerTyID: {
00183       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
00184       if (BitWidth == 1)
00185         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
00186       else if (BitWidth <= 8)
00187         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
00188       else if (BitWidth <= 16)
00189         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
00190       else if (BitWidth <= 32)
00191         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
00192       else if (BitWidth <= 64)
00193         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
00194       else
00195         llvm_unreachable("Integer types > 64 bits not supported");
00196       return rv;
00197     }
00198     case Type::VoidTyID:
00199       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
00200       return rv;
00201     case Type::FloatTyID:
00202       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
00203       return rv;
00204     case Type::DoubleTyID:
00205       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
00206       return rv;
00207     case Type::X86_FP80TyID:
00208     case Type::FP128TyID:
00209     case Type::PPC_FP128TyID:
00210       llvm_unreachable("long double not supported yet");
00211     case Type::PointerTyID:
00212       return PTOGV(((void*(*)())(intptr_t)FPtr)());
00213     }
00214   }
00215 
00216   llvm_unreachable("Full-featured argument passing not supported yet!");
00217 }
00218 
00219 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
00220                                        bool AbortOnFailure) {
00221   if (!isSymbolSearchingDisabled() && MemMgr) {
00222     void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
00223     if (ptr)
00224       return ptr;
00225   }
00226 
00227   /// If a LazyFunctionCreator is installed, use it to get/create the function.
00228   if (LazyFunctionCreator)
00229     if (void *RP = LazyFunctionCreator(Name))
00230       return RP;
00231 
00232   if (AbortOnFailure) {
00233     report_fatal_error("Program used external function '"+Name+
00234                        "' which could not be resolved!");
00235   }
00236   return 0;
00237 }