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