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)
31 inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
33 reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
36 /*===-- Operations on generic values --------------------------------------===*/
38 LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
41 GenericValue *GenVal = new GenericValue();
42 GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
46 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
47 GenericValue *GenVal = new GenericValue();
48 GenVal->PointerVal = P;
52 LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
53 GenericValue *GenVal = new GenericValue();
54 switch (unwrap(TyRef)->getTypeID()) {
58 case Type::DoubleTyID:
59 GenVal->DoubleVal = N;
62 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
67 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
68 return unwrap(GenValRef)->IntVal.getBitWidth();
71 unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
73 GenericValue *GenVal = unwrap(GenValRef);
75 return GenVal->IntVal.getSExtValue();
77 return GenVal->IntVal.getZExtValue();
80 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
81 return unwrap(GenVal)->PointerVal;
84 double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
85 switch (unwrap(TyRef)->getTypeID()) {
87 return unwrap(GenVal)->FloatVal;
88 case Type::DoubleTyID:
89 return unwrap(GenVal)->DoubleVal;
91 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
95 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
96 delete unwrap(GenVal);
99 /*===-- Operations on execution engines -----------------------------------===*/
101 LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
105 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
106 builder.setEngineKind(EngineKind::Either)
107 .setErrorStr(&Error);
108 if (ExecutionEngine *EE = builder.create()){
112 *OutError = strdup(Error.c_str());
116 LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
120 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
121 builder.setEngineKind(EngineKind::Interpreter)
122 .setErrorStr(&Error);
123 if (ExecutionEngine *Interp = builder.create()) {
124 *OutInterp = wrap(Interp);
127 *OutError = strdup(Error.c_str());
131 LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
136 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
137 builder.setEngineKind(EngineKind::JIT)
139 .setOptLevel((CodeGenOpt::Level)OptLevel);
140 if (ExecutionEngine *JIT = builder.create()) {
144 *OutError = strdup(Error.c_str());
148 void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
149 size_t SizeOfPassedOptions) {
150 LLVMMCJITCompilerOptions options;
151 memset(&options, 0, sizeof(options)); // Most fields are zero by default.
152 options.CodeModel = LLVMCodeModelJITDefault;
154 memcpy(PassedOptions, &options,
155 std::min(sizeof(options), SizeOfPassedOptions));
158 LLVMBool LLVMCreateMCJITCompilerForModule(
159 LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
160 LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
162 LLVMMCJITCompilerOptions options;
163 // If the user passed a larger sized options struct, then they were compiled
164 // against a newer LLVM. Tell them that something is wrong.
165 if (SizeOfPassedOptions > sizeof(options)) {
167 "Refusing to use options struct that is larger than my own; assuming "
168 "LLVM library mismatch.");
172 // Defend against the user having an old version of the API by ensuring that
173 // any fields they didn't see are cleared. We must defend against fields being
174 // set to the bitwise equivalent of zero, and assume that this means "do the
175 // default" as if that option hadn't been available.
176 LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
177 memcpy(&options, PassedOptions, SizeOfPassedOptions);
179 TargetOptions targetOptions;
180 targetOptions.NoFramePointerElim = options.NoFramePointerElim;
181 targetOptions.EnableFastISel = options.EnableFastISel;
184 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
185 builder.setEngineKind(EngineKind::JIT)
187 .setOptLevel((CodeGenOpt::Level)options.OptLevel)
188 .setCodeModel(unwrap(options.CodeModel))
189 .setTargetOptions(targetOptions);
191 builder.setMCJITMemoryManager(unwrap(options.MCJMM));
192 if (ExecutionEngine *JIT = builder.create()) {
196 *OutError = strdup(Error.c_str());
200 LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
201 LLVMModuleProviderRef MP,
203 /* The module provider is now actually a module. */
204 return LLVMCreateExecutionEngineForModule(OutEE,
205 reinterpret_cast<LLVMModuleRef>(MP),
209 LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
210 LLVMModuleProviderRef MP,
212 /* The module provider is now actually a module. */
213 return LLVMCreateInterpreterForModule(OutInterp,
214 reinterpret_cast<LLVMModuleRef>(MP),
218 LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
219 LLVMModuleProviderRef MP,
222 /* The module provider is now actually a module. */
223 return LLVMCreateJITCompilerForModule(OutJIT,
224 reinterpret_cast<LLVMModuleRef>(MP),
229 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
233 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
234 unwrap(EE)->runStaticConstructorsDestructors(false);
237 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
238 unwrap(EE)->runStaticConstructorsDestructors(true);
241 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
242 unsigned ArgC, const char * const *ArgV,
243 const char * const *EnvP) {
244 unwrap(EE)->finalizeObject();
246 std::vector<std::string> ArgVec;
247 for (unsigned I = 0; I != ArgC; ++I)
248 ArgVec.push_back(ArgV[I]);
250 return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
253 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
255 LLVMGenericValueRef *Args) {
256 unwrap(EE)->finalizeObject();
258 std::vector<GenericValue> ArgVec;
259 ArgVec.reserve(NumArgs);
260 for (unsigned I = 0; I != NumArgs; ++I)
261 ArgVec.push_back(*unwrap(Args[I]));
263 GenericValue *Result = new GenericValue();
264 *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
268 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
271 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
272 unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
275 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
276 /* The module provider is now actually a module. */
277 LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
280 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
281 LLVMModuleRef *OutMod, char **OutError) {
282 Module *Mod = unwrap(M);
283 unwrap(EE)->removeModule(Mod);
288 LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
289 LLVMModuleProviderRef MP,
290 LLVMModuleRef *OutMod, char **OutError) {
291 /* The module provider is now actually a module. */
292 return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod,
296 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
297 LLVMValueRef *OutFn) {
298 if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
305 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
310 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
311 return wrap(unwrap(EE)->getDataLayout());
315 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
316 return wrap(unwrap(EE)->getTargetMachine());
319 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
321 unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
324 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
325 unwrap(EE)->finalizeObject();
327 return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
330 /*===-- Operations on memory managers -------------------------------------===*/
334 struct SimpleBindingMMFunctions {
335 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
336 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
337 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
338 LLVMMemoryManagerDestroyCallback Destroy;
341 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
343 SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
345 virtual ~SimpleBindingMemoryManager();
347 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
349 StringRef SectionName) override;
351 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
352 unsigned SectionID, StringRef SectionName,
353 bool isReadOnly) override;
355 bool finalizeMemory(std::string *ErrMsg) override;
358 SimpleBindingMMFunctions Functions;
362 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
363 const SimpleBindingMMFunctions& Functions,
365 : Functions(Functions), Opaque(Opaque) {
366 assert(Functions.AllocateCodeSection &&
367 "No AllocateCodeSection function provided!");
368 assert(Functions.AllocateDataSection &&
369 "No AllocateDataSection function provided!");
370 assert(Functions.FinalizeMemory &&
371 "No FinalizeMemory function provided!");
372 assert(Functions.Destroy &&
373 "No Destroy function provided!");
376 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
377 Functions.Destroy(Opaque);
380 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
381 uintptr_t Size, unsigned Alignment, unsigned SectionID,
382 StringRef SectionName) {
383 return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
384 SectionName.str().c_str());
387 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
388 uintptr_t Size, unsigned Alignment, unsigned SectionID,
389 StringRef SectionName, bool isReadOnly) {
390 return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
391 SectionName.str().c_str(),
395 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
396 char *errMsgCString = nullptr;
397 bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
398 assert((result || !errMsgCString) &&
399 "Did not expect an error message if FinalizeMemory succeeded");
402 *ErrMsg = errMsgCString;
408 } // anonymous namespace
410 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
412 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
413 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
414 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
415 LLVMMemoryManagerDestroyCallback Destroy) {
417 if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
421 SimpleBindingMMFunctions functions;
422 functions.AllocateCodeSection = AllocateCodeSection;
423 functions.AllocateDataSection = AllocateDataSection;
424 functions.FinalizeMemory = FinalizeMemory;
425 functions.Destroy = Destroy;
426 return wrap(new SimpleBindingMemoryManager(functions, Opaque));
429 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {