ExecutionEngineBindings.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. //===-- ExecutionEngineBindings.cpp - C bindings for EEs ------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the C bindings for the ExecutionEngine library.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm-c/ExecutionEngine.h"
  14. #include "llvm/ExecutionEngine/ExecutionEngine.h"
  15. #include "llvm/ExecutionEngine/GenericValue.h"
  16. #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
  17. #include "llvm/IR/DerivedTypes.h"
  18. #include "llvm/IR/Module.h"
  19. #include "llvm/Support/ErrorHandling.h"
  20. #include <cstring>
  21. using namespace llvm;
  22. #define DEBUG_TYPE "jit"
  23. // Wrapping the C bindings types.
  24. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
  25. inline DataLayout *unwrap(LLVMTargetDataRef P) {
  26. return reinterpret_cast<DataLayout*>(P);
  27. }
  28. inline LLVMTargetDataRef wrap(const DataLayout *P) {
  29. return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout*>(P));
  30. }
  31. inline TargetLibraryInfo *unwrap(LLVMTargetLibraryInfoRef P) {
  32. return reinterpret_cast<TargetLibraryInfo*>(P);
  33. }
  34. inline LLVMTargetLibraryInfoRef wrap(const TargetLibraryInfo *P) {
  35. TargetLibraryInfo *X = const_cast<TargetLibraryInfo*>(P);
  36. return reinterpret_cast<LLVMTargetLibraryInfoRef>(X);
  37. }
  38. inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
  39. return
  40. reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
  41. }
  42. /*===-- Operations on generic values --------------------------------------===*/
  43. LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
  44. unsigned long long N,
  45. LLVMBool IsSigned) {
  46. GenericValue *GenVal = new GenericValue();
  47. GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
  48. return wrap(GenVal);
  49. }
  50. LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
  51. GenericValue *GenVal = new GenericValue();
  52. GenVal->PointerVal = P;
  53. return wrap(GenVal);
  54. }
  55. LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
  56. GenericValue *GenVal = new GenericValue();
  57. switch (unwrap(TyRef)->getTypeID()) {
  58. case Type::FloatTyID:
  59. GenVal->FloatVal = N;
  60. break;
  61. case Type::DoubleTyID:
  62. GenVal->DoubleVal = N;
  63. break;
  64. default:
  65. llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
  66. }
  67. return wrap(GenVal);
  68. }
  69. unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
  70. return unwrap(GenValRef)->IntVal.getBitWidth();
  71. }
  72. unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
  73. LLVMBool IsSigned) {
  74. GenericValue *GenVal = unwrap(GenValRef);
  75. if (IsSigned)
  76. return GenVal->IntVal.getSExtValue();
  77. else
  78. return GenVal->IntVal.getZExtValue();
  79. }
  80. void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
  81. return unwrap(GenVal)->PointerVal;
  82. }
  83. double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
  84. switch (unwrap(TyRef)->getTypeID()) {
  85. case Type::FloatTyID:
  86. return unwrap(GenVal)->FloatVal;
  87. case Type::DoubleTyID:
  88. return unwrap(GenVal)->DoubleVal;
  89. default:
  90. llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
  91. }
  92. }
  93. void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
  94. delete unwrap(GenVal);
  95. }
  96. /*===-- Operations on execution engines -----------------------------------===*/
  97. LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
  98. LLVMModuleRef M,
  99. char **OutError) {
  100. std::string Error;
  101. EngineBuilder builder(unwrap(M));
  102. builder.setEngineKind(EngineKind::Either)
  103. .setErrorStr(&Error);
  104. if (ExecutionEngine *EE = builder.create()){
  105. *OutEE = wrap(EE);
  106. return 0;
  107. }
  108. *OutError = strdup(Error.c_str());
  109. return 1;
  110. }
  111. LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
  112. LLVMModuleRef M,
  113. char **OutError) {
  114. std::string Error;
  115. EngineBuilder builder(unwrap(M));
  116. builder.setEngineKind(EngineKind::Interpreter)
  117. .setErrorStr(&Error);
  118. if (ExecutionEngine *Interp = builder.create()) {
  119. *OutInterp = wrap(Interp);
  120. return 0;
  121. }
  122. *OutError = strdup(Error.c_str());
  123. return 1;
  124. }
  125. LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
  126. LLVMModuleRef M,
  127. unsigned OptLevel,
  128. char **OutError) {
  129. std::string Error;
  130. EngineBuilder builder(unwrap(M));
  131. builder.setEngineKind(EngineKind::JIT)
  132. .setErrorStr(&Error)
  133. .setOptLevel((CodeGenOpt::Level)OptLevel);
  134. if (ExecutionEngine *JIT = builder.create()) {
  135. *OutJIT = wrap(JIT);
  136. return 0;
  137. }
  138. *OutError = strdup(Error.c_str());
  139. return 1;
  140. }
  141. void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
  142. size_t SizeOfPassedOptions) {
  143. LLVMMCJITCompilerOptions options;
  144. memset(&options, 0, sizeof(options)); // Most fields are zero by default.
  145. options.CodeModel = LLVMCodeModelJITDefault;
  146. memcpy(PassedOptions, &options,
  147. std::min(sizeof(options), SizeOfPassedOptions));
  148. }
  149. LLVMBool LLVMCreateMCJITCompilerForModule(
  150. LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
  151. LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
  152. char **OutError) {
  153. LLVMMCJITCompilerOptions options;
  154. // If the user passed a larger sized options struct, then they were compiled
  155. // against a newer LLVM. Tell them that something is wrong.
  156. if (SizeOfPassedOptions > sizeof(options)) {
  157. *OutError = strdup(
  158. "Refusing to use options struct that is larger than my own; assuming "
  159. "LLVM library mismatch.");
  160. return 1;
  161. }
  162. // Defend against the user having an old version of the API by ensuring that
  163. // any fields they didn't see are cleared. We must defend against fields being
  164. // set to the bitwise equivalent of zero, and assume that this means "do the
  165. // default" as if that option hadn't been available.
  166. LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
  167. memcpy(&options, PassedOptions, SizeOfPassedOptions);
  168. TargetOptions targetOptions;
  169. targetOptions.NoFramePointerElim = options.NoFramePointerElim;
  170. targetOptions.EnableFastISel = options.EnableFastISel;
  171. std::string Error;
  172. EngineBuilder builder(unwrap(M));
  173. builder.setEngineKind(EngineKind::JIT)
  174. .setErrorStr(&Error)
  175. .setUseMCJIT(true)
  176. .setOptLevel((CodeGenOpt::Level)options.OptLevel)
  177. .setCodeModel(unwrap(options.CodeModel))
  178. .setTargetOptions(targetOptions);
  179. if (options.MCJMM)
  180. builder.setMCJITMemoryManager(unwrap(options.MCJMM));
  181. if (ExecutionEngine *JIT = builder.create()) {
  182. *OutJIT = wrap(JIT);
  183. return 0;
  184. }
  185. *OutError = strdup(Error.c_str());
  186. return 1;
  187. }
  188. LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
  189. LLVMModuleProviderRef MP,
  190. char **OutError) {
  191. /* The module provider is now actually a module. */
  192. return LLVMCreateExecutionEngineForModule(OutEE,
  193. reinterpret_cast<LLVMModuleRef>(MP),
  194. OutError);
  195. }
  196. LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
  197. LLVMModuleProviderRef MP,
  198. char **OutError) {
  199. /* The module provider is now actually a module. */
  200. return LLVMCreateInterpreterForModule(OutInterp,
  201. reinterpret_cast<LLVMModuleRef>(MP),
  202. OutError);
  203. }
  204. LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
  205. LLVMModuleProviderRef MP,
  206. unsigned OptLevel,
  207. char **OutError) {
  208. /* The module provider is now actually a module. */
  209. return LLVMCreateJITCompilerForModule(OutJIT,
  210. reinterpret_cast<LLVMModuleRef>(MP),
  211. OptLevel, OutError);
  212. }
  213. void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
  214. delete unwrap(EE);
  215. }
  216. void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
  217. unwrap(EE)->runStaticConstructorsDestructors(false);
  218. }
  219. void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
  220. unwrap(EE)->runStaticConstructorsDestructors(true);
  221. }
  222. int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
  223. unsigned ArgC, const char * const *ArgV,
  224. const char * const *EnvP) {
  225. unwrap(EE)->finalizeObject();
  226. std::vector<std::string> ArgVec;
  227. for (unsigned I = 0; I != ArgC; ++I)
  228. ArgVec.push_back(ArgV[I]);
  229. return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
  230. }
  231. LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
  232. unsigned NumArgs,
  233. LLVMGenericValueRef *Args) {
  234. unwrap(EE)->finalizeObject();
  235. std::vector<GenericValue> ArgVec;
  236. ArgVec.reserve(NumArgs);
  237. for (unsigned I = 0; I != NumArgs; ++I)
  238. ArgVec.push_back(*unwrap(Args[I]));
  239. GenericValue *Result = new GenericValue();
  240. *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
  241. return wrap(Result);
  242. }
  243. void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
  244. unwrap(EE)->freeMachineCodeForFunction(unwrap<Function>(F));
  245. }
  246. void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
  247. unwrap(EE)->addModule(unwrap(M));
  248. }
  249. void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
  250. /* The module provider is now actually a module. */
  251. LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
  252. }
  253. LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
  254. LLVMModuleRef *OutMod, char **OutError) {
  255. Module *Mod = unwrap(M);
  256. unwrap(EE)->removeModule(Mod);
  257. *OutMod = wrap(Mod);
  258. return 0;
  259. }
  260. LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
  261. LLVMModuleProviderRef MP,
  262. LLVMModuleRef *OutMod, char **OutError) {
  263. /* The module provider is now actually a module. */
  264. return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod,
  265. OutError);
  266. }
  267. LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
  268. LLVMValueRef *OutFn) {
  269. if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
  270. *OutFn = wrap(F);
  271. return 0;
  272. }
  273. return 1;
  274. }
  275. void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
  276. LLVMValueRef Fn) {
  277. return unwrap(EE)->recompileAndRelinkFunction(unwrap<Function>(Fn));
  278. }
  279. LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
  280. return wrap(unwrap(EE)->getDataLayout());
  281. }
  282. LLVMTargetMachineRef
  283. LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
  284. return wrap(unwrap(EE)->getTargetMachine());
  285. }
  286. void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
  287. void* Addr) {
  288. unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
  289. }
  290. void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
  291. unwrap(EE)->finalizeObject();
  292. return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
  293. }
  294. /*===-- Operations on memory managers -------------------------------------===*/
  295. namespace {
  296. struct SimpleBindingMMFunctions {
  297. LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
  298. LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
  299. LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
  300. LLVMMemoryManagerDestroyCallback Destroy;
  301. };
  302. class SimpleBindingMemoryManager : public RTDyldMemoryManager {
  303. public:
  304. SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
  305. void *Opaque);
  306. virtual ~SimpleBindingMemoryManager();
  307. uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
  308. unsigned SectionID,
  309. StringRef SectionName) override;
  310. uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
  311. unsigned SectionID, StringRef SectionName,
  312. bool isReadOnly) override;
  313. bool finalizeMemory(std::string *ErrMsg) override;
  314. private:
  315. SimpleBindingMMFunctions Functions;
  316. void *Opaque;
  317. };
  318. SimpleBindingMemoryManager::SimpleBindingMemoryManager(
  319. const SimpleBindingMMFunctions& Functions,
  320. void *Opaque)
  321. : Functions(Functions), Opaque(Opaque) {
  322. assert(Functions.AllocateCodeSection &&
  323. "No AllocateCodeSection function provided!");
  324. assert(Functions.AllocateDataSection &&
  325. "No AllocateDataSection function provided!");
  326. assert(Functions.FinalizeMemory &&
  327. "No FinalizeMemory function provided!");
  328. assert(Functions.Destroy &&
  329. "No Destroy function provided!");
  330. }
  331. SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
  332. Functions.Destroy(Opaque);
  333. }
  334. uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
  335. uintptr_t Size, unsigned Alignment, unsigned SectionID,
  336. StringRef SectionName) {
  337. return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
  338. SectionName.str().c_str());
  339. }
  340. uint8_t *SimpleBindingMemoryManager::allocateDataSection(
  341. uintptr_t Size, unsigned Alignment, unsigned SectionID,
  342. StringRef SectionName, bool isReadOnly) {
  343. return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
  344. SectionName.str().c_str(),
  345. isReadOnly);
  346. }
  347. bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
  348. char *errMsgCString = nullptr;
  349. bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
  350. assert((result || !errMsgCString) &&
  351. "Did not expect an error message if FinalizeMemory succeeded");
  352. if (errMsgCString) {
  353. if (ErrMsg)
  354. *ErrMsg = errMsgCString;
  355. free(errMsgCString);
  356. }
  357. return result;
  358. }
  359. } // anonymous namespace
  360. LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
  361. void *Opaque,
  362. LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
  363. LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
  364. LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
  365. LLVMMemoryManagerDestroyCallback Destroy) {
  366. if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
  367. !Destroy)
  368. return nullptr;
  369. SimpleBindingMMFunctions functions;
  370. functions.AllocateCodeSection = AllocateCodeSection;
  371. functions.AllocateDataSection = AllocateDataSection;
  372. functions.FinalizeMemory = FinalizeMemory;
  373. functions.Destroy = Destroy;
  374. return wrap(new SimpleBindingMemoryManager(functions, Opaque));
  375. }
  376. void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
  377. delete unwrap(MM);
  378. }