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 TargetLibraryInfo *unwrap(LLVMTargetLibraryInfoRef P) {
31 return reinterpret_cast<TargetLibraryInfo*>(P);
34 inline LLVMTargetLibraryInfoRef wrap(const TargetLibraryInfo *P) {
35 TargetLibraryInfo *X = const_cast<TargetLibraryInfo*>(P);
36 return reinterpret_cast<LLVMTargetLibraryInfoRef>(X);
39 inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
41 reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
44 /*===-- Operations on generic values --------------------------------------===*/
46 LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
49 GenericValue *GenVal = new GenericValue();
50 GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
54 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
55 GenericValue *GenVal = new GenericValue();
56 GenVal->PointerVal = P;
60 LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
61 GenericValue *GenVal = new GenericValue();
62 switch (unwrap(TyRef)->getTypeID()) {
66 case Type::DoubleTyID:
67 GenVal->DoubleVal = N;
70 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
75 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
76 return unwrap(GenValRef)->IntVal.getBitWidth();
79 unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
81 GenericValue *GenVal = unwrap(GenValRef);
83 return GenVal->IntVal.getSExtValue();
85 return GenVal->IntVal.getZExtValue();
88 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
89 return unwrap(GenVal)->PointerVal;
92 double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
93 switch (unwrap(TyRef)->getTypeID()) {
95 return unwrap(GenVal)->FloatVal;
96 case Type::DoubleTyID:
97 return unwrap(GenVal)->DoubleVal;
99 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
103 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
104 delete unwrap(GenVal);
107 /*===-- Operations on execution engines -----------------------------------===*/
109 LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
113 EngineBuilder builder(unwrap(M));
114 builder.setEngineKind(EngineKind::Either)
115 .setErrorStr(&Error);
116 if (ExecutionEngine *EE = builder.create()){
120 *OutError = strdup(Error.c_str());
124 LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
128 EngineBuilder builder(unwrap(M));
129 builder.setEngineKind(EngineKind::Interpreter)
130 .setErrorStr(&Error);
131 if (ExecutionEngine *Interp = builder.create()) {
132 *OutInterp = wrap(Interp);
135 *OutError = strdup(Error.c_str());
139 LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
144 EngineBuilder builder(unwrap(M));
145 builder.setEngineKind(EngineKind::JIT)
147 .setOptLevel((CodeGenOpt::Level)OptLevel);
148 if (ExecutionEngine *JIT = builder.create()) {
152 *OutError = strdup(Error.c_str());
156 void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
157 size_t SizeOfPassedOptions) {
158 LLVMMCJITCompilerOptions options;
159 memset(&options, 0, sizeof(options)); // Most fields are zero by default.
160 options.CodeModel = LLVMCodeModelJITDefault;
162 memcpy(PassedOptions, &options,
163 std::min(sizeof(options), SizeOfPassedOptions));
166 LLVMBool LLVMCreateMCJITCompilerForModule(
167 LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
168 LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
170 LLVMMCJITCompilerOptions options;
171 // If the user passed a larger sized options struct, then they were compiled
172 // against a newer LLVM. Tell them that something is wrong.
173 if (SizeOfPassedOptions > sizeof(options)) {
175 "Refusing to use options struct that is larger than my own; assuming "
176 "LLVM library mismatch.");
180 // Defend against the user having an old version of the API by ensuring that
181 // any fields they didn't see are cleared. We must defend against fields being
182 // set to the bitwise equivalent of zero, and assume that this means "do the
183 // default" as if that option hadn't been available.
184 LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
185 memcpy(&options, PassedOptions, SizeOfPassedOptions);
187 TargetOptions targetOptions;
188 targetOptions.NoFramePointerElim = options.NoFramePointerElim;
189 targetOptions.EnableFastISel = options.EnableFastISel;
192 EngineBuilder builder(unwrap(M));
193 builder.setEngineKind(EngineKind::JIT)
195 .setOptLevel((CodeGenOpt::Level)options.OptLevel)
196 .setCodeModel(unwrap(options.CodeModel))
197 .setTargetOptions(targetOptions);
199 builder.setMCJITMemoryManager(unwrap(options.MCJMM));
200 if (ExecutionEngine *JIT = builder.create()) {
204 *OutError = strdup(Error.c_str());
208 LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
209 LLVMModuleProviderRef MP,
211 /* The module provider is now actually a module. */
212 return LLVMCreateExecutionEngineForModule(OutEE,
213 reinterpret_cast<LLVMModuleRef>(MP),
217 LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
218 LLVMModuleProviderRef MP,
220 /* The module provider is now actually a module. */
221 return LLVMCreateInterpreterForModule(OutInterp,
222 reinterpret_cast<LLVMModuleRef>(MP),
226 LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
227 LLVMModuleProviderRef MP,
230 /* The module provider is now actually a module. */
231 return LLVMCreateJITCompilerForModule(OutJIT,
232 reinterpret_cast<LLVMModuleRef>(MP),
237 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
241 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
242 unwrap(EE)->runStaticConstructorsDestructors(false);
245 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
246 unwrap(EE)->runStaticConstructorsDestructors(true);
249 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
250 unsigned ArgC, const char * const *ArgV,
251 const char * const *EnvP) {
252 unwrap(EE)->finalizeObject();
254 std::vector<std::string> ArgVec;
255 for (unsigned I = 0; I != ArgC; ++I)
256 ArgVec.push_back(ArgV[I]);
258 return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
261 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
263 LLVMGenericValueRef *Args) {
264 unwrap(EE)->finalizeObject();
266 std::vector<GenericValue> ArgVec;
267 ArgVec.reserve(NumArgs);
268 for (unsigned I = 0; I != NumArgs; ++I)
269 ArgVec.push_back(*unwrap(Args[I]));
271 GenericValue *Result = new GenericValue();
272 *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
276 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
279 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
280 unwrap(EE)->addModule(unwrap(M));
283 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
284 /* The module provider is now actually a module. */
285 LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
288 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
289 LLVMModuleRef *OutMod, char **OutError) {
290 Module *Mod = unwrap(M);
291 unwrap(EE)->removeModule(Mod);
296 LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
297 LLVMModuleProviderRef MP,
298 LLVMModuleRef *OutMod, char **OutError) {
299 /* The module provider is now actually a module. */
300 return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod,
304 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
305 LLVMValueRef *OutFn) {
306 if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
313 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
318 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
319 return wrap(unwrap(EE)->getDataLayout());
323 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
324 return wrap(unwrap(EE)->getTargetMachine());
327 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
329 unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
332 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
333 unwrap(EE)->finalizeObject();
335 return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
338 /*===-- Operations on memory managers -------------------------------------===*/
342 struct SimpleBindingMMFunctions {
343 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
344 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
345 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
346 LLVMMemoryManagerDestroyCallback Destroy;
349 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
351 SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
353 virtual ~SimpleBindingMemoryManager();
355 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
357 StringRef SectionName) override;
359 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
360 unsigned SectionID, StringRef SectionName,
361 bool isReadOnly) override;
363 bool finalizeMemory(std::string *ErrMsg) override;
366 SimpleBindingMMFunctions Functions;
370 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
371 const SimpleBindingMMFunctions& Functions,
373 : Functions(Functions), Opaque(Opaque) {
374 assert(Functions.AllocateCodeSection &&
375 "No AllocateCodeSection function provided!");
376 assert(Functions.AllocateDataSection &&
377 "No AllocateDataSection function provided!");
378 assert(Functions.FinalizeMemory &&
379 "No FinalizeMemory function provided!");
380 assert(Functions.Destroy &&
381 "No Destroy function provided!");
384 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
385 Functions.Destroy(Opaque);
388 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
389 uintptr_t Size, unsigned Alignment, unsigned SectionID,
390 StringRef SectionName) {
391 return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
392 SectionName.str().c_str());
395 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
396 uintptr_t Size, unsigned Alignment, unsigned SectionID,
397 StringRef SectionName, bool isReadOnly) {
398 return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
399 SectionName.str().c_str(),
403 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
404 char *errMsgCString = nullptr;
405 bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
406 assert((result || !errMsgCString) &&
407 "Did not expect an error message if FinalizeMemory succeeded");
410 *ErrMsg = errMsgCString;
416 } // anonymous namespace
418 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
420 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
421 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
422 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
423 LLVMMemoryManagerDestroyCallback Destroy) {
425 if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
429 SimpleBindingMMFunctions functions;
430 functions.AllocateCodeSection = AllocateCodeSection;
431 functions.AllocateDataSection = AllocateDataSection;
432 functions.FinalizeMemory = FinalizeMemory;
433 functions.Destroy = Destroy;
434 return wrap(new SimpleBindingMemoryManager(functions, Opaque));
437 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {