ExecutionEngineBindings.cpp 15 KB

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