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