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"
21 #include "llvm/Target/TargetOptions.h"
26 #define DEBUG_TYPE "jit"
28 // Wrapping the C bindings types.
29 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
32 inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
34 reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
37 /*===-- Operations on generic values --------------------------------------===*/
39 LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
42 GenericValue *GenVal = new GenericValue();
43 GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
47 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
48 GenericValue *GenVal = new GenericValue();
49 GenVal->PointerVal = P;
53 LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
54 GenericValue *GenVal = new GenericValue();
55 switch (unwrap(TyRef)->getTypeID()) {
59 case Type::DoubleTyID:
60 GenVal->DoubleVal = N;
63 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
68 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
69 return unwrap(GenValRef)->IntVal.getBitWidth();
72 unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
74 GenericValue *GenVal = unwrap(GenValRef);
76 return GenVal->IntVal.getSExtValue();
78 return GenVal->IntVal.getZExtValue();
81 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
82 return unwrap(GenVal)->PointerVal;
85 double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
86 switch (unwrap(TyRef)->getTypeID()) {
88 return unwrap(GenVal)->FloatVal;
89 case Type::DoubleTyID:
90 return unwrap(GenVal)->DoubleVal;
92 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
96 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
97 delete unwrap(GenVal);
100 /*===-- Operations on execution engines -----------------------------------===*/
102 LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
106 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
107 builder.setEngineKind(EngineKind::Either)
108 .setErrorStr(&Error);
109 if (ExecutionEngine *EE = builder.create()){
113 *OutError = strdup(Error.c_str());
117 LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
121 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
122 builder.setEngineKind(EngineKind::Interpreter)
123 .setErrorStr(&Error);
124 if (ExecutionEngine *Interp = builder.create()) {
125 *OutInterp = wrap(Interp);
128 *OutError = strdup(Error.c_str());
132 LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
137 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
138 builder.setEngineKind(EngineKind::JIT)
140 .setOptLevel((CodeGenOpt::Level)OptLevel);
141 if (ExecutionEngine *JIT = builder.create()) {
145 *OutError = strdup(Error.c_str());
149 void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
150 size_t SizeOfPassedOptions) {
151 LLVMMCJITCompilerOptions options;
152 memset(&options, 0, sizeof(options)); // Most fields are zero by default.
153 options.CodeModel = LLVMCodeModelJITDefault;
155 memcpy(PassedOptions, &options,
156 std::min(sizeof(options), SizeOfPassedOptions));
159 LLVMBool LLVMCreateMCJITCompilerForModule(
160 LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
161 LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
163 LLVMMCJITCompilerOptions options;
164 // If the user passed a larger sized options struct, then they were compiled
165 // against a newer LLVM. Tell them that something is wrong.
166 if (SizeOfPassedOptions > sizeof(options)) {
168 "Refusing to use options struct that is larger than my own; assuming "
169 "LLVM library mismatch.");
173 // Defend against the user having an old version of the API by ensuring that
174 // any fields they didn't see are cleared. We must defend against fields being
175 // set to the bitwise equivalent of zero, and assume that this means "do the
176 // default" as if that option hadn't been available.
177 LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
178 memcpy(&options, PassedOptions, SizeOfPassedOptions);
180 TargetOptions targetOptions;
181 targetOptions.EnableFastISel = options.EnableFastISel;
182 std::unique_ptr<Module> Mod(unwrap(M));
185 // Set function attribute "no-frame-pointer-elim" based on
186 // NoFramePointerElim.
187 for (auto &F : *Mod) {
188 auto Attrs = F.getAttributes();
189 auto Value = options.NoFramePointerElim ? "true" : "false";
190 Attrs = Attrs.addAttribute(F.getContext(), AttributeSet::FunctionIndex,
191 "no-frame-pointer-elim", Value);
192 F.setAttributes(Attrs);
196 EngineBuilder builder(std::move(Mod));
197 builder.setEngineKind(EngineKind::JIT)
199 .setOptLevel((CodeGenOpt::Level)options.OptLevel)
200 .setCodeModel(unwrap(options.CodeModel))
201 .setTargetOptions(targetOptions);
203 builder.setMCJITMemoryManager(
204 std::unique_ptr<RTDyldMemoryManager>(unwrap(options.MCJMM)));
205 if (ExecutionEngine *JIT = builder.create()) {
209 *OutError = strdup(Error.c_str());
213 LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
214 LLVMModuleProviderRef MP,
216 /* The module provider is now actually a module. */
217 return LLVMCreateExecutionEngineForModule(OutEE,
218 reinterpret_cast<LLVMModuleRef>(MP),
222 LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
223 LLVMModuleProviderRef MP,
225 /* The module provider is now actually a module. */
226 return LLVMCreateInterpreterForModule(OutInterp,
227 reinterpret_cast<LLVMModuleRef>(MP),
231 LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
232 LLVMModuleProviderRef MP,
235 /* The module provider is now actually a module. */
236 return LLVMCreateJITCompilerForModule(OutJIT,
237 reinterpret_cast<LLVMModuleRef>(MP),
242 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
246 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
247 unwrap(EE)->runStaticConstructorsDestructors(false);
250 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
251 unwrap(EE)->runStaticConstructorsDestructors(true);
254 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
255 unsigned ArgC, const char * const *ArgV,
256 const char * const *EnvP) {
257 unwrap(EE)->finalizeObject();
259 std::vector<std::string> ArgVec(ArgV, ArgV + ArgC);
260 return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
263 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
265 LLVMGenericValueRef *Args) {
266 unwrap(EE)->finalizeObject();
268 std::vector<GenericValue> ArgVec;
269 ArgVec.reserve(NumArgs);
270 for (unsigned I = 0; I != NumArgs; ++I)
271 ArgVec.push_back(*unwrap(Args[I]));
273 GenericValue *Result = new GenericValue();
274 *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
278 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
281 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
282 unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
285 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
286 /* The module provider is now actually a module. */
287 LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
290 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
291 LLVMModuleRef *OutMod, char **OutError) {
292 Module *Mod = unwrap(M);
293 unwrap(EE)->removeModule(Mod);
298 LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
299 LLVMModuleProviderRef MP,
300 LLVMModuleRef *OutMod, char **OutError) {
301 /* The module provider is now actually a module. */
302 return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod,
306 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
307 LLVMValueRef *OutFn) {
308 if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
315 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
320 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
321 return wrap(unwrap(EE)->getDataLayout());
325 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
326 return wrap(unwrap(EE)->getTargetMachine());
329 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
331 unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
334 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
335 unwrap(EE)->finalizeObject();
337 return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
340 uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name) {
341 return unwrap(EE)->getGlobalValueAddress(Name);
344 uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name) {
345 return unwrap(EE)->getFunctionAddress(Name);
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 ~SimpleBindingMemoryManager() override;
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) {