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