ExecutionEngineBindings.cpp 14 KB

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