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/CodeGenCWrappers.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Target/TargetOptions.h"
27 #define DEBUG_TYPE "jit"
29 // Wrapping the C bindings types.
30 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
33 static LLVMTargetMachineRef wrap(const TargetMachine *P) {
35 reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
38 /*===-- Operations on generic values --------------------------------------===*/
40 LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
43 GenericValue *GenVal = new GenericValue();
44 GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
48 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
49 GenericValue *GenVal = new GenericValue();
50 GenVal->PointerVal = P;
54 LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
55 GenericValue *GenVal = new GenericValue();
56 switch (unwrap(TyRef)->getTypeID()) {
60 case Type::DoubleTyID:
61 GenVal->DoubleVal = N;
64 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
69 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
70 return unwrap(GenValRef)->IntVal.getBitWidth();
73 unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
75 GenericValue *GenVal = unwrap(GenValRef);
77 return GenVal->IntVal.getSExtValue();
79 return GenVal->IntVal.getZExtValue();
82 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
83 return unwrap(GenVal)->PointerVal;
86 double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
87 switch (unwrap(TyRef)->getTypeID()) {
89 return unwrap(GenVal)->FloatVal;
90 case Type::DoubleTyID:
91 return unwrap(GenVal)->DoubleVal;
93 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
97 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
98 delete unwrap(GenVal);
101 /*===-- Operations on execution engines -----------------------------------===*/
103 LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
107 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
108 builder.setEngineKind(EngineKind::Either)
109 .setErrorStr(&Error);
110 if (ExecutionEngine *EE = builder.create()){
114 *OutError = strdup(Error.c_str());
118 LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
122 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
123 builder.setEngineKind(EngineKind::Interpreter)
124 .setErrorStr(&Error);
125 if (ExecutionEngine *Interp = builder.create()) {
126 *OutInterp = wrap(Interp);
129 *OutError = strdup(Error.c_str());
133 LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
138 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
139 builder.setEngineKind(EngineKind::JIT)
141 .setOptLevel((CodeGenOpt::Level)OptLevel);
142 if (ExecutionEngine *JIT = builder.create()) {
146 *OutError = strdup(Error.c_str());
150 void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
151 size_t SizeOfPassedOptions) {
152 LLVMMCJITCompilerOptions options;
153 memset(&options, 0, sizeof(options)); // Most fields are zero by default.
154 options.CodeModel = LLVMCodeModelJITDefault;
156 memcpy(PassedOptions, &options,
157 std::min(sizeof(options), SizeOfPassedOptions));
160 LLVMBool LLVMCreateMCJITCompilerForModule(
161 LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
162 LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
164 LLVMMCJITCompilerOptions options;
165 // If the user passed a larger sized options struct, then they were compiled
166 // against a newer LLVM. Tell them that something is wrong.
167 if (SizeOfPassedOptions > sizeof(options)) {
169 "Refusing to use options struct that is larger than my own; assuming "
170 "LLVM library mismatch.");
174 // Defend against the user having an old version of the API by ensuring that
175 // any fields they didn't see are cleared. We must defend against fields being
176 // set to the bitwise equivalent of zero, and assume that this means "do the
177 // default" as if that option hadn't been available.
178 LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
179 memcpy(&options, PassedOptions, SizeOfPassedOptions);
181 TargetOptions targetOptions;
182 targetOptions.EnableFastISel = options.EnableFastISel;
183 std::unique_ptr<Module> Mod(unwrap(M));
186 // Set function attribute "no-frame-pointer-elim" based on
187 // NoFramePointerElim.
188 for (auto &F : *Mod) {
189 auto Attrs = F.getAttributes();
190 StringRef Value(options.NoFramePointerElim ? "true" : "false");
191 Attrs = Attrs.addAttribute(F.getContext(), AttributeSet::FunctionIndex,
192 "no-frame-pointer-elim", Value);
193 F.setAttributes(Attrs);
197 EngineBuilder builder(std::move(Mod));
198 builder.setEngineKind(EngineKind::JIT)
200 .setOptLevel((CodeGenOpt::Level)options.OptLevel)
201 .setCodeModel(unwrap(options.CodeModel))
202 .setTargetOptions(targetOptions);
204 builder.setMCJITMemoryManager(
205 std::unique_ptr<RTDyldMemoryManager>(unwrap(options.MCJMM)));
206 if (ExecutionEngine *JIT = builder.create()) {
210 *OutError = strdup(Error.c_str());
214 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
218 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
219 unwrap(EE)->finalizeObject();
220 unwrap(EE)->runStaticConstructorsDestructors(false);
223 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
224 unwrap(EE)->finalizeObject();
225 unwrap(EE)->runStaticConstructorsDestructors(true);
228 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
229 unsigned ArgC, const char * const *ArgV,
230 const char * const *EnvP) {
231 unwrap(EE)->finalizeObject();
233 std::vector<std::string> ArgVec(ArgV, ArgV + ArgC);
234 return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
237 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
239 LLVMGenericValueRef *Args) {
240 unwrap(EE)->finalizeObject();
242 std::vector<GenericValue> ArgVec;
243 ArgVec.reserve(NumArgs);
244 for (unsigned I = 0; I != NumArgs; ++I)
245 ArgVec.push_back(*unwrap(Args[I]));
247 GenericValue *Result = new GenericValue();
248 *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
252 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
255 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
256 unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
259 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
260 LLVMModuleRef *OutMod, char **OutError) {
261 Module *Mod = unwrap(M);
262 unwrap(EE)->removeModule(Mod);
267 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
268 LLVMValueRef *OutFn) {
269 if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
276 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
281 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
282 return wrap(&unwrap(EE)->getDataLayout());
286 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
287 return wrap(unwrap(EE)->getTargetMachine());
290 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
292 unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
295 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
296 unwrap(EE)->finalizeObject();
298 return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
301 uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name) {
302 return unwrap(EE)->getGlobalValueAddress(Name);
305 uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name) {
306 return unwrap(EE)->getFunctionAddress(Name);
309 /*===-- Operations on memory managers -------------------------------------===*/
313 struct SimpleBindingMMFunctions {
314 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
315 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
316 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
317 LLVMMemoryManagerDestroyCallback Destroy;
320 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
322 SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
324 ~SimpleBindingMemoryManager() override;
326 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
328 StringRef SectionName) override;
330 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
331 unsigned SectionID, StringRef SectionName,
332 bool isReadOnly) override;
334 bool finalizeMemory(std::string *ErrMsg) override;
337 SimpleBindingMMFunctions Functions;
341 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
342 const SimpleBindingMMFunctions& Functions,
344 : Functions(Functions), Opaque(Opaque) {
345 assert(Functions.AllocateCodeSection &&
346 "No AllocateCodeSection function provided!");
347 assert(Functions.AllocateDataSection &&
348 "No AllocateDataSection function provided!");
349 assert(Functions.FinalizeMemory &&
350 "No FinalizeMemory function provided!");
351 assert(Functions.Destroy &&
352 "No Destroy function provided!");
355 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
356 Functions.Destroy(Opaque);
359 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
360 uintptr_t Size, unsigned Alignment, unsigned SectionID,
361 StringRef SectionName) {
362 return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
363 SectionName.str().c_str());
366 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
367 uintptr_t Size, unsigned Alignment, unsigned SectionID,
368 StringRef SectionName, bool isReadOnly) {
369 return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
370 SectionName.str().c_str(),
374 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
375 char *errMsgCString = nullptr;
376 bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
377 assert((result || !errMsgCString) &&
378 "Did not expect an error message if FinalizeMemory succeeded");
381 *ErrMsg = errMsgCString;
387 } // anonymous namespace
389 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
391 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
392 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
393 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
394 LLVMMemoryManagerDestroyCallback Destroy) {
396 if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
400 SimpleBindingMMFunctions functions;
401 functions.AllocateCodeSection = AllocateCodeSection;
402 functions.AllocateDataSection = AllocateDataSection;
403 functions.FinalizeMemory = FinalizeMemory;
404 functions.Destroy = Destroy;
405 return wrap(new SimpleBindingMemoryManager(functions, Opaque));
408 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {