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