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 static 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 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
00214   delete unwrap(EE);
00215 }
00216 
00217 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
00218   unwrap(EE)->finalizeObject();
00219   unwrap(EE)->runStaticConstructorsDestructors(false);
00220 }
00221 
00222 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
00223   unwrap(EE)->finalizeObject();
00224   unwrap(EE)->runStaticConstructorsDestructors(true);
00225 }
00226 
00227 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
00228                           unsigned ArgC, const char * const *ArgV,
00229                           const char * const *EnvP) {
00230   unwrap(EE)->finalizeObject();
00231 
00232   std::vector<std::string> ArgVec(ArgV, ArgV + ArgC);
00233   return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
00234 }
00235 
00236 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
00237                                     unsigned NumArgs,
00238                                     LLVMGenericValueRef *Args) {
00239   unwrap(EE)->finalizeObject();
00240   
00241   std::vector<GenericValue> ArgVec;
00242   ArgVec.reserve(NumArgs);
00243   for (unsigned I = 0; I != NumArgs; ++I)
00244     ArgVec.push_back(*unwrap(Args[I]));
00245   
00246   GenericValue *Result = new GenericValue();
00247   *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
00248   return wrap(Result);
00249 }
00250 
00251 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
00252 }
00253 
00254 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
00255   unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
00256 }
00257 
00258 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
00259                           LLVMModuleRef *OutMod, char **OutError) {
00260   Module *Mod = unwrap(M);
00261   unwrap(EE)->removeModule(Mod);
00262   *OutMod = wrap(Mod);
00263   return 0;
00264 }
00265 
00266 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
00267                           LLVMValueRef *OutFn) {
00268   if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
00269     *OutFn = wrap(F);
00270     return 0;
00271   }
00272   return 1;
00273 }
00274 
00275 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
00276                                      LLVMValueRef Fn) {
00277   return nullptr;
00278 }
00279 
00280 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
00281   return wrap(&unwrap(EE)->getDataLayout());
00282 }
00283 
00284 LLVMTargetMachineRef
00285 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
00286   return wrap(unwrap(EE)->getTargetMachine());
00287 }
00288 
00289 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
00290                           void* Addr) {
00291   unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
00292 }
00293 
00294 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
00295   unwrap(EE)->finalizeObject();
00296   
00297   return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
00298 }
00299 
00300 uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name) {
00301   return unwrap(EE)->getGlobalValueAddress(Name);
00302 }
00303 
00304 uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name) {
00305   return unwrap(EE)->getFunctionAddress(Name);
00306 }
00307 
00308 /*===-- Operations on memory managers -------------------------------------===*/
00309 
00310 namespace {
00311 
00312 struct SimpleBindingMMFunctions {
00313   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
00314   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
00315   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
00316   LLVMMemoryManagerDestroyCallback Destroy;
00317 };
00318 
00319 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
00320 public:
00321   SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
00322                              void *Opaque);
00323   ~SimpleBindingMemoryManager() override;
00324 
00325   uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
00326                                unsigned SectionID,
00327                                StringRef SectionName) override;
00328 
00329   uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
00330                                unsigned SectionID, StringRef SectionName,
00331                                bool isReadOnly) override;
00332 
00333   bool finalizeMemory(std::string *ErrMsg) override;
00334 
00335 private:
00336   SimpleBindingMMFunctions Functions;
00337   void *Opaque;
00338 };
00339 
00340 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
00341   const SimpleBindingMMFunctions& Functions,
00342   void *Opaque)
00343   : Functions(Functions), Opaque(Opaque) {
00344   assert(Functions.AllocateCodeSection &&
00345          "No AllocateCodeSection function provided!");
00346   assert(Functions.AllocateDataSection &&
00347          "No AllocateDataSection function provided!");
00348   assert(Functions.FinalizeMemory &&
00349          "No FinalizeMemory function provided!");
00350   assert(Functions.Destroy &&
00351          "No Destroy function provided!");
00352 }
00353 
00354 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
00355   Functions.Destroy(Opaque);
00356 }
00357 
00358 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
00359   uintptr_t Size, unsigned Alignment, unsigned SectionID,
00360   StringRef SectionName) {
00361   return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
00362                                        SectionName.str().c_str());
00363 }
00364 
00365 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
00366   uintptr_t Size, unsigned Alignment, unsigned SectionID,
00367   StringRef SectionName, bool isReadOnly) {
00368   return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
00369                                        SectionName.str().c_str(),
00370                                        isReadOnly);
00371 }
00372 
00373 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
00374   char *errMsgCString = nullptr;
00375   bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
00376   assert((result || !errMsgCString) &&
00377          "Did not expect an error message if FinalizeMemory succeeded");
00378   if (errMsgCString) {
00379     if (ErrMsg)
00380       *ErrMsg = errMsgCString;
00381     free(errMsgCString);
00382   }
00383   return result;
00384 }
00385 
00386 } // anonymous namespace
00387 
00388 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
00389   void *Opaque,
00390   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
00391   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
00392   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
00393   LLVMMemoryManagerDestroyCallback Destroy) {
00394   
00395   if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
00396       !Destroy)
00397     return nullptr;
00398   
00399   SimpleBindingMMFunctions functions;
00400   functions.AllocateCodeSection = AllocateCodeSection;
00401   functions.AllocateDataSection = AllocateDataSection;
00402   functions.FinalizeMemory = FinalizeMemory;
00403   functions.Destroy = Destroy;
00404   return wrap(new SimpleBindingMemoryManager(functions, Opaque));
00405 }
00406 
00407 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
00408   delete unwrap(MM);
00409 }
00410