LLVM API Documentation

ExecutionEngineBindings.cpp
Go to the documentation of this file.
00001 //===-- ExecutionEngineBindings.cpp - C bindings for EEs ------------------===//
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 // This file defines the C bindings for the ExecutionEngine library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm-c/ExecutionEngine.h"
00015 #include "llvm/ExecutionEngine/ExecutionEngine.h"
00016 #include "llvm/ExecutionEngine/GenericValue.h"
00017 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
00018 #include "llvm/IR/DerivedTypes.h"
00019 #include "llvm/IR/Module.h"
00020 #include "llvm/Support/ErrorHandling.h"
00021 #include <cstring>
00022 
00023 using namespace llvm;
00024 
00025 #define DEBUG_TYPE "jit"
00026 
00027 // Wrapping the C bindings types.
00028 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
00029 
00030 inline TargetLibraryInfo *unwrap(LLVMTargetLibraryInfoRef P) {
00031   return reinterpret_cast<TargetLibraryInfo*>(P);
00032 }
00033 
00034 inline LLVMTargetLibraryInfoRef wrap(const TargetLibraryInfo *P) {
00035   TargetLibraryInfo *X = const_cast<TargetLibraryInfo*>(P);
00036   return reinterpret_cast<LLVMTargetLibraryInfoRef>(X);
00037 }
00038 
00039 inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
00040   return
00041   reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
00042 }
00043 
00044 /*===-- Operations on generic values --------------------------------------===*/
00045 
00046 LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
00047                                                 unsigned long long N,
00048                                                 LLVMBool IsSigned) {
00049   GenericValue *GenVal = new GenericValue();
00050   GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
00051   return wrap(GenVal);
00052 }
00053 
00054 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
00055   GenericValue *GenVal = new GenericValue();
00056   GenVal->PointerVal = P;
00057   return wrap(GenVal);
00058 }
00059 
00060 LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
00061   GenericValue *GenVal = new GenericValue();
00062   switch (unwrap(TyRef)->getTypeID()) {
00063   case Type::FloatTyID:
00064     GenVal->FloatVal = N;
00065     break;
00066   case Type::DoubleTyID:
00067     GenVal->DoubleVal = N;
00068     break;
00069   default:
00070     llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
00071   }
00072   return wrap(GenVal);
00073 }
00074 
00075 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
00076   return unwrap(GenValRef)->IntVal.getBitWidth();
00077 }
00078 
00079 unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
00080                                          LLVMBool IsSigned) {
00081   GenericValue *GenVal = unwrap(GenValRef);
00082   if (IsSigned)
00083     return GenVal->IntVal.getSExtValue();
00084   else
00085     return GenVal->IntVal.getZExtValue();
00086 }
00087 
00088 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
00089   return unwrap(GenVal)->PointerVal;
00090 }
00091 
00092 double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
00093   switch (unwrap(TyRef)->getTypeID()) {
00094   case Type::FloatTyID:
00095     return unwrap(GenVal)->FloatVal;
00096   case Type::DoubleTyID:
00097     return unwrap(GenVal)->DoubleVal;
00098   default:
00099     llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
00100   }
00101 }
00102 
00103 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
00104   delete unwrap(GenVal);
00105 }
00106 
00107 /*===-- Operations on execution engines -----------------------------------===*/
00108 
00109 LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
00110                                             LLVMModuleRef M,
00111                                             char **OutError) {
00112   std::string Error;
00113   EngineBuilder builder(unwrap(M));
00114   builder.setEngineKind(EngineKind::Either)
00115          .setErrorStr(&Error);
00116   if (ExecutionEngine *EE = builder.create()){
00117     *OutEE = wrap(EE);
00118     return 0;
00119   }
00120   *OutError = strdup(Error.c_str());
00121   return 1;
00122 }
00123 
00124 LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
00125                                         LLVMModuleRef M,
00126                                         char **OutError) {
00127   std::string Error;
00128   EngineBuilder builder(unwrap(M));
00129   builder.setEngineKind(EngineKind::Interpreter)
00130          .setErrorStr(&Error);
00131   if (ExecutionEngine *Interp = builder.create()) {
00132     *OutInterp = wrap(Interp);
00133     return 0;
00134   }
00135   *OutError = strdup(Error.c_str());
00136   return 1;
00137 }
00138 
00139 LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
00140                                         LLVMModuleRef M,
00141                                         unsigned OptLevel,
00142                                         char **OutError) {
00143   std::string Error;
00144   EngineBuilder builder(unwrap(M));
00145   builder.setEngineKind(EngineKind::JIT)
00146          .setErrorStr(&Error)
00147          .setOptLevel((CodeGenOpt::Level)OptLevel);
00148   if (ExecutionEngine *JIT = builder.create()) {
00149     *OutJIT = wrap(JIT);
00150     return 0;
00151   }
00152   *OutError = strdup(Error.c_str());
00153   return 1;
00154 }
00155 
00156 void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
00157                                         size_t SizeOfPassedOptions) {
00158   LLVMMCJITCompilerOptions options;
00159   memset(&options, 0, sizeof(options)); // Most fields are zero by default.
00160   options.CodeModel = LLVMCodeModelJITDefault;
00161   
00162   memcpy(PassedOptions, &options,
00163          std::min(sizeof(options), SizeOfPassedOptions));
00164 }
00165 
00166 LLVMBool LLVMCreateMCJITCompilerForModule(
00167     LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
00168     LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
00169     char **OutError) {
00170   LLVMMCJITCompilerOptions options;
00171   // If the user passed a larger sized options struct, then they were compiled
00172   // against a newer LLVM. Tell them that something is wrong.
00173   if (SizeOfPassedOptions > sizeof(options)) {
00174     *OutError = strdup(
00175       "Refusing to use options struct that is larger than my own; assuming "
00176       "LLVM library mismatch.");
00177     return 1;
00178   }
00179   
00180   // Defend against the user having an old version of the API by ensuring that
00181   // any fields they didn't see are cleared. We must defend against fields being
00182   // set to the bitwise equivalent of zero, and assume that this means "do the
00183   // default" as if that option hadn't been available.
00184   LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
00185   memcpy(&options, PassedOptions, SizeOfPassedOptions);
00186   
00187   TargetOptions targetOptions;
00188   targetOptions.NoFramePointerElim = options.NoFramePointerElim;
00189   targetOptions.EnableFastISel = options.EnableFastISel;
00190 
00191   std::string Error;
00192   EngineBuilder builder(unwrap(M));
00193   builder.setEngineKind(EngineKind::JIT)
00194          .setErrorStr(&Error)
00195          .setUseMCJIT(true)
00196          .setOptLevel((CodeGenOpt::Level)options.OptLevel)
00197          .setCodeModel(unwrap(options.CodeModel))
00198          .setTargetOptions(targetOptions);
00199   if (options.MCJMM)
00200     builder.setMCJITMemoryManager(unwrap(options.MCJMM));
00201   if (ExecutionEngine *JIT = builder.create()) {
00202     *OutJIT = wrap(JIT);
00203     return 0;
00204   }
00205   *OutError = strdup(Error.c_str());
00206   return 1;
00207 }
00208 
00209 LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
00210                                    LLVMModuleProviderRef MP,
00211                                    char **OutError) {
00212   /* The module provider is now actually a module. */
00213   return LLVMCreateExecutionEngineForModule(OutEE,
00214                                             reinterpret_cast<LLVMModuleRef>(MP),
00215                                             OutError);
00216 }
00217 
00218 LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
00219                                LLVMModuleProviderRef MP,
00220                                char **OutError) {
00221   /* The module provider is now actually a module. */
00222   return LLVMCreateInterpreterForModule(OutInterp,
00223                                         reinterpret_cast<LLVMModuleRef>(MP),
00224                                         OutError);
00225 }
00226 
00227 LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
00228                                LLVMModuleProviderRef MP,
00229                                unsigned OptLevel,
00230                                char **OutError) {
00231   /* The module provider is now actually a module. */
00232   return LLVMCreateJITCompilerForModule(OutJIT,
00233                                         reinterpret_cast<LLVMModuleRef>(MP),
00234                                         OptLevel, OutError);
00235 }
00236 
00237 
00238 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
00239   delete unwrap(EE);
00240 }
00241 
00242 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
00243   unwrap(EE)->runStaticConstructorsDestructors(false);
00244 }
00245 
00246 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
00247   unwrap(EE)->runStaticConstructorsDestructors(true);
00248 }
00249 
00250 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
00251                           unsigned ArgC, const char * const *ArgV,
00252                           const char * const *EnvP) {
00253   unwrap(EE)->finalizeObject();
00254   
00255   std::vector<std::string> ArgVec;
00256   for (unsigned I = 0; I != ArgC; ++I)
00257     ArgVec.push_back(ArgV[I]);
00258   
00259   return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
00260 }
00261 
00262 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
00263                                     unsigned NumArgs,
00264                                     LLVMGenericValueRef *Args) {
00265   unwrap(EE)->finalizeObject();
00266   
00267   std::vector<GenericValue> ArgVec;
00268   ArgVec.reserve(NumArgs);
00269   for (unsigned I = 0; I != NumArgs; ++I)
00270     ArgVec.push_back(*unwrap(Args[I]));
00271   
00272   GenericValue *Result = new GenericValue();
00273   *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
00274   return wrap(Result);
00275 }
00276 
00277 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
00278   unwrap(EE)->freeMachineCodeForFunction(unwrap<Function>(F));
00279 }
00280 
00281 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
00282   unwrap(EE)->addModule(unwrap(M));
00283 }
00284 
00285 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
00286   /* The module provider is now actually a module. */
00287   LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
00288 }
00289 
00290 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
00291                           LLVMModuleRef *OutMod, char **OutError) {
00292   Module *Mod = unwrap(M);
00293   unwrap(EE)->removeModule(Mod);
00294   *OutMod = wrap(Mod);
00295   return 0;
00296 }
00297 
00298 LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
00299                                   LLVMModuleProviderRef MP,
00300                                   LLVMModuleRef *OutMod, char **OutError) {
00301   /* The module provider is now actually a module. */
00302   return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod,
00303                           OutError);
00304 }
00305 
00306 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
00307                           LLVMValueRef *OutFn) {
00308   if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
00309     *OutFn = wrap(F);
00310     return 0;
00311   }
00312   return 1;
00313 }
00314 
00315 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
00316                                      LLVMValueRef Fn) {
00317   return unwrap(EE)->recompileAndRelinkFunction(unwrap<Function>(Fn));
00318 }
00319 
00320 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
00321   return wrap(unwrap(EE)->getDataLayout());
00322 }
00323 
00324 LLVMTargetMachineRef
00325 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
00326   return wrap(unwrap(EE)->getTargetMachine());
00327 }
00328 
00329 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
00330                           void* Addr) {
00331   unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
00332 }
00333 
00334 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
00335   unwrap(EE)->finalizeObject();
00336   
00337   return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
00338 }
00339 
00340 /*===-- Operations on memory managers -------------------------------------===*/
00341 
00342 namespace {
00343 
00344 struct SimpleBindingMMFunctions {
00345   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
00346   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
00347   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
00348   LLVMMemoryManagerDestroyCallback Destroy;
00349 };
00350 
00351 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
00352 public:
00353   SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
00354                              void *Opaque);
00355   virtual ~SimpleBindingMemoryManager();
00356 
00357   uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
00358                                unsigned SectionID,
00359                                StringRef SectionName) override;
00360 
00361   uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
00362                                unsigned SectionID, StringRef SectionName,
00363                                bool isReadOnly) override;
00364 
00365   bool finalizeMemory(std::string *ErrMsg) override;
00366 
00367 private:
00368   SimpleBindingMMFunctions Functions;
00369   void *Opaque;
00370 };
00371 
00372 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
00373   const SimpleBindingMMFunctions& Functions,
00374   void *Opaque)
00375   : Functions(Functions), Opaque(Opaque) {
00376   assert(Functions.AllocateCodeSection &&
00377          "No AllocateCodeSection function provided!");
00378   assert(Functions.AllocateDataSection &&
00379          "No AllocateDataSection function provided!");
00380   assert(Functions.FinalizeMemory &&
00381          "No FinalizeMemory function provided!");
00382   assert(Functions.Destroy &&
00383          "No Destroy function provided!");
00384 }
00385 
00386 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
00387   Functions.Destroy(Opaque);
00388 }
00389 
00390 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
00391   uintptr_t Size, unsigned Alignment, unsigned SectionID,
00392   StringRef SectionName) {
00393   return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
00394                                        SectionName.str().c_str());
00395 }
00396 
00397 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
00398   uintptr_t Size, unsigned Alignment, unsigned SectionID,
00399   StringRef SectionName, bool isReadOnly) {
00400   return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
00401                                        SectionName.str().c_str(),
00402                                        isReadOnly);
00403 }
00404 
00405 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
00406   char *errMsgCString = nullptr;
00407   bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
00408   assert((result || !errMsgCString) &&
00409          "Did not expect an error message if FinalizeMemory succeeded");
00410   if (errMsgCString) {
00411     if (ErrMsg)
00412       *ErrMsg = errMsgCString;
00413     free(errMsgCString);
00414   }
00415   return result;
00416 }
00417 
00418 } // anonymous namespace
00419 
00420 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
00421   void *Opaque,
00422   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
00423   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
00424   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
00425   LLVMMemoryManagerDestroyCallback Destroy) {
00426   
00427   if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
00428       !Destroy)
00429     return nullptr;
00430   
00431   SimpleBindingMMFunctions functions;
00432   functions.AllocateCodeSection = AllocateCodeSection;
00433   functions.AllocateDataSection = AllocateDataSection;
00434   functions.FinalizeMemory = FinalizeMemory;
00435   functions.Destroy = Destroy;
00436   return wrap(new SimpleBindingMemoryManager(functions, Opaque));
00437 }
00438 
00439 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
00440   delete unwrap(MM);
00441 }
00442