1 //===-- ExecutionEngineBindings.cpp - C bindings for EEs ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the C bindings for the ExecutionEngine library.
12 //===----------------------------------------------------------------------===//
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"
25 #define DEBUG_TYPE "jit"
27 // Wrapping the C bindings types.
28 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
30 inline DataLayout *unwrap(LLVMTargetDataRef P) {
31 return reinterpret_cast<DataLayout*>(P);
34 inline LLVMTargetDataRef wrap(const DataLayout *P) {
35 return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout*>(P));
38 inline TargetLibraryInfo *unwrap(LLVMTargetLibraryInfoRef P) {
39 return reinterpret_cast<TargetLibraryInfo*>(P);
42 inline LLVMTargetLibraryInfoRef wrap(const TargetLibraryInfo *P) {
43 TargetLibraryInfo *X = const_cast<TargetLibraryInfo*>(P);
44 return reinterpret_cast<LLVMTargetLibraryInfoRef>(X);
47 inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
49 reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
52 /*===-- Operations on generic values --------------------------------------===*/
54 LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
57 GenericValue *GenVal = new GenericValue();
58 GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
62 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
63 GenericValue *GenVal = new GenericValue();
64 GenVal->PointerVal = P;
68 LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
69 GenericValue *GenVal = new GenericValue();
70 switch (unwrap(TyRef)->getTypeID()) {
74 case Type::DoubleTyID:
75 GenVal->DoubleVal = N;
78 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
83 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
84 return unwrap(GenValRef)->IntVal.getBitWidth();
87 unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
89 GenericValue *GenVal = unwrap(GenValRef);
91 return GenVal->IntVal.getSExtValue();
93 return GenVal->IntVal.getZExtValue();
96 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
97 return unwrap(GenVal)->PointerVal;
100 double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
101 switch (unwrap(TyRef)->getTypeID()) {
102 case Type::FloatTyID:
103 return unwrap(GenVal)->FloatVal;
104 case Type::DoubleTyID:
105 return unwrap(GenVal)->DoubleVal;
107 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
111 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
112 delete unwrap(GenVal);
115 /*===-- Operations on execution engines -----------------------------------===*/
117 LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
121 EngineBuilder builder(unwrap(M));
122 builder.setEngineKind(EngineKind::Either)
123 .setErrorStr(&Error);
124 if (ExecutionEngine *EE = builder.create()){
128 *OutError = strdup(Error.c_str());
132 LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
136 EngineBuilder builder(unwrap(M));
137 builder.setEngineKind(EngineKind::Interpreter)
138 .setErrorStr(&Error);
139 if (ExecutionEngine *Interp = builder.create()) {
140 *OutInterp = wrap(Interp);
143 *OutError = strdup(Error.c_str());
147 LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
152 EngineBuilder builder(unwrap(M));
153 builder.setEngineKind(EngineKind::JIT)
155 .setOptLevel((CodeGenOpt::Level)OptLevel);
156 if (ExecutionEngine *JIT = builder.create()) {
160 *OutError = strdup(Error.c_str());
164 void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
165 size_t SizeOfPassedOptions) {
166 LLVMMCJITCompilerOptions options;
167 memset(&options, 0, sizeof(options)); // Most fields are zero by default.
168 options.CodeModel = LLVMCodeModelJITDefault;
170 memcpy(PassedOptions, &options,
171 std::min(sizeof(options), SizeOfPassedOptions));
174 LLVMBool LLVMCreateMCJITCompilerForModule(
175 LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
176 LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
178 LLVMMCJITCompilerOptions options;
179 // If the user passed a larger sized options struct, then they were compiled
180 // against a newer LLVM. Tell them that something is wrong.
181 if (SizeOfPassedOptions > sizeof(options)) {
183 "Refusing to use options struct that is larger than my own; assuming "
184 "LLVM library mismatch.");
188 // Defend against the user having an old version of the API by ensuring that
189 // any fields they didn't see are cleared. We must defend against fields being
190 // set to the bitwise equivalent of zero, and assume that this means "do the
191 // default" as if that option hadn't been available.
192 LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
193 memcpy(&options, PassedOptions, SizeOfPassedOptions);
195 TargetOptions targetOptions;
196 targetOptions.NoFramePointerElim = options.NoFramePointerElim;
197 targetOptions.EnableFastISel = options.EnableFastISel;
200 EngineBuilder builder(unwrap(M));
201 builder.setEngineKind(EngineKind::JIT)
204 .setOptLevel((CodeGenOpt::Level)options.OptLevel)
205 .setCodeModel(unwrap(options.CodeModel))
206 .setTargetOptions(targetOptions);
208 builder.setMCJITMemoryManager(unwrap(options.MCJMM));
209 if (ExecutionEngine *JIT = builder.create()) {
213 *OutError = strdup(Error.c_str());
217 LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
218 LLVMModuleProviderRef MP,
220 /* The module provider is now actually a module. */
221 return LLVMCreateExecutionEngineForModule(OutEE,
222 reinterpret_cast<LLVMModuleRef>(MP),
226 LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
227 LLVMModuleProviderRef MP,
229 /* The module provider is now actually a module. */
230 return LLVMCreateInterpreterForModule(OutInterp,
231 reinterpret_cast<LLVMModuleRef>(MP),
235 LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
236 LLVMModuleProviderRef MP,
239 /* The module provider is now actually a module. */
240 return LLVMCreateJITCompilerForModule(OutJIT,
241 reinterpret_cast<LLVMModuleRef>(MP),
246 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
250 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
251 unwrap(EE)->runStaticConstructorsDestructors(false);
254 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
255 unwrap(EE)->runStaticConstructorsDestructors(true);
258 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
259 unsigned ArgC, const char * const *ArgV,
260 const char * const *EnvP) {
261 unwrap(EE)->finalizeObject();
263 std::vector<std::string> ArgVec;
264 for (unsigned I = 0; I != ArgC; ++I)
265 ArgVec.push_back(ArgV[I]);
267 return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
270 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
272 LLVMGenericValueRef *Args) {
273 unwrap(EE)->finalizeObject();
275 std::vector<GenericValue> ArgVec;
276 ArgVec.reserve(NumArgs);
277 for (unsigned I = 0; I != NumArgs; ++I)
278 ArgVec.push_back(*unwrap(Args[I]));
280 GenericValue *Result = new GenericValue();
281 *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
285 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
286 unwrap(EE)->freeMachineCodeForFunction(unwrap<Function>(F));
289 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
290 unwrap(EE)->addModule(unwrap(M));
293 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
294 /* The module provider is now actually a module. */
295 LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
298 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
299 LLVMModuleRef *OutMod, char **OutError) {
300 Module *Mod = unwrap(M);
301 unwrap(EE)->removeModule(Mod);
306 LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
307 LLVMModuleProviderRef MP,
308 LLVMModuleRef *OutMod, char **OutError) {
309 /* The module provider is now actually a module. */
310 return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod,
314 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
315 LLVMValueRef *OutFn) {
316 if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
323 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
325 return unwrap(EE)->recompileAndRelinkFunction(unwrap<Function>(Fn));
328 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
329 return wrap(unwrap(EE)->getDataLayout());
333 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
334 return wrap(unwrap(EE)->getTargetMachine());
337 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
339 unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
342 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
343 unwrap(EE)->finalizeObject();
345 return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
348 /*===-- Operations on memory managers -------------------------------------===*/
352 struct SimpleBindingMMFunctions {
353 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
354 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
355 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
356 LLVMMemoryManagerDestroyCallback Destroy;
359 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
361 SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
363 virtual ~SimpleBindingMemoryManager();
365 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
367 StringRef SectionName) override;
369 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
370 unsigned SectionID, StringRef SectionName,
371 bool isReadOnly) override;
373 bool finalizeMemory(std::string *ErrMsg) override;
376 SimpleBindingMMFunctions Functions;
380 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
381 const SimpleBindingMMFunctions& Functions,
383 : Functions(Functions), Opaque(Opaque) {
384 assert(Functions.AllocateCodeSection &&
385 "No AllocateCodeSection function provided!");
386 assert(Functions.AllocateDataSection &&
387 "No AllocateDataSection function provided!");
388 assert(Functions.FinalizeMemory &&
389 "No FinalizeMemory function provided!");
390 assert(Functions.Destroy &&
391 "No Destroy function provided!");
394 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
395 Functions.Destroy(Opaque);
398 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
399 uintptr_t Size, unsigned Alignment, unsigned SectionID,
400 StringRef SectionName) {
401 return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
402 SectionName.str().c_str());
405 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
406 uintptr_t Size, unsigned Alignment, unsigned SectionID,
407 StringRef SectionName, bool isReadOnly) {
408 return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
409 SectionName.str().c_str(),
413 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
414 char *errMsgCString = nullptr;
415 bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
416 assert((result || !errMsgCString) &&
417 "Did not expect an error message if FinalizeMemory succeeded");
420 *ErrMsg = errMsgCString;
426 } // anonymous namespace
428 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
430 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
431 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
432 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
433 LLVMMemoryManagerDestroyCallback Destroy) {
435 if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
439 SimpleBindingMMFunctions functions;
440 functions.AllocateCodeSection = AllocateCodeSection;
441 functions.AllocateDataSection = AllocateDataSection;
442 functions.FinalizeMemory = FinalizeMemory;
443 functions.Destroy = Destroy;
444 return wrap(new SimpleBindingMemoryManager(functions, Opaque));
447 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {