1193323Sed//===-- ExecutionEngineBindings.cpp - C bindings for EEs ------------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file defines the C bindings for the ExecutionEngine library.
11193323Sed//
12193323Sed//===----------------------------------------------------------------------===//
13193323Sed
14193323Sed#define DEBUG_TYPE "jit"
15193323Sed#include "llvm-c/ExecutionEngine.h"
16249423Sdim#include "llvm/ExecutionEngine/ExecutionEngine.h"
17193323Sed#include "llvm/ExecutionEngine/GenericValue.h"
18263508Sdim#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
19251662Sdim#include "llvm/IR/DerivedTypes.h"
20251662Sdim#include "llvm/IR/Module.h"
21198090Srdivacky#include "llvm/Support/ErrorHandling.h"
22193323Sed#include <cstring>
23193323Sed
24193323Sedusing namespace llvm;
25193323Sed
26251662Sdim// Wrapping the C bindings types.
27251662SdimDEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
28251662Sdim
29251662Sdiminline DataLayout *unwrap(LLVMTargetDataRef P) {
30251662Sdim  return reinterpret_cast<DataLayout*>(P);
31251662Sdim}
32251662Sdim
33251662Sdiminline LLVMTargetDataRef wrap(const DataLayout *P) {
34251662Sdim  return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout*>(P));
35251662Sdim}
36251662Sdim
37251662Sdiminline TargetLibraryInfo *unwrap(LLVMTargetLibraryInfoRef P) {
38251662Sdim  return reinterpret_cast<TargetLibraryInfo*>(P);
39251662Sdim}
40251662Sdim
41251662Sdiminline LLVMTargetLibraryInfoRef wrap(const TargetLibraryInfo *P) {
42251662Sdim  TargetLibraryInfo *X = const_cast<TargetLibraryInfo*>(P);
43251662Sdim  return reinterpret_cast<LLVMTargetLibraryInfoRef>(X);
44251662Sdim}
45251662Sdim
46193323Sed/*===-- Operations on generic values --------------------------------------===*/
47193323Sed
48193323SedLLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
49193323Sed                                                unsigned long long N,
50202375Srdivacky                                                LLVMBool IsSigned) {
51193323Sed  GenericValue *GenVal = new GenericValue();
52193323Sed  GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
53193323Sed  return wrap(GenVal);
54193323Sed}
55193323Sed
56193323SedLLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
57193323Sed  GenericValue *GenVal = new GenericValue();
58193323Sed  GenVal->PointerVal = P;
59193323Sed  return wrap(GenVal);
60193323Sed}
61193323Sed
62193323SedLLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
63193323Sed  GenericValue *GenVal = new GenericValue();
64193323Sed  switch (unwrap(TyRef)->getTypeID()) {
65193323Sed  case Type::FloatTyID:
66193323Sed    GenVal->FloatVal = N;
67193323Sed    break;
68193323Sed  case Type::DoubleTyID:
69193323Sed    GenVal->DoubleVal = N;
70193323Sed    break;
71193323Sed  default:
72198090Srdivacky    llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
73193323Sed  }
74193323Sed  return wrap(GenVal);
75193323Sed}
76193323Sed
77193323Sedunsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
78193323Sed  return unwrap(GenValRef)->IntVal.getBitWidth();
79193323Sed}
80193323Sed
81193323Sedunsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
82202375Srdivacky                                         LLVMBool IsSigned) {
83193323Sed  GenericValue *GenVal = unwrap(GenValRef);
84193323Sed  if (IsSigned)
85193323Sed    return GenVal->IntVal.getSExtValue();
86193323Sed  else
87193323Sed    return GenVal->IntVal.getZExtValue();
88193323Sed}
89193323Sed
90193323Sedvoid *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
91193323Sed  return unwrap(GenVal)->PointerVal;
92193323Sed}
93193323Sed
94193323Seddouble LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
95193323Sed  switch (unwrap(TyRef)->getTypeID()) {
96193323Sed  case Type::FloatTyID:
97193323Sed    return unwrap(GenVal)->FloatVal;
98193323Sed  case Type::DoubleTyID:
99193323Sed    return unwrap(GenVal)->DoubleVal;
100193323Sed  default:
101198090Srdivacky    llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
102193323Sed  }
103193323Sed}
104193323Sed
105193323Sedvoid LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
106193323Sed  delete unwrap(GenVal);
107193323Sed}
108193323Sed
109193323Sed/*===-- Operations on execution engines -----------------------------------===*/
110193323Sed
111204642SrdivackyLLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
112204642Srdivacky                                            LLVMModuleRef M,
113204642Srdivacky                                            char **OutError) {
114193323Sed  std::string Error;
115204642Srdivacky  EngineBuilder builder(unwrap(M));
116198090Srdivacky  builder.setEngineKind(EngineKind::Either)
117198090Srdivacky         .setErrorStr(&Error);
118198090Srdivacky  if (ExecutionEngine *EE = builder.create()){
119193323Sed    *OutEE = wrap(EE);
120193323Sed    return 0;
121193323Sed  }
122193323Sed  *OutError = strdup(Error.c_str());
123193323Sed  return 1;
124193323Sed}
125193323Sed
126204642SrdivackyLLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
127204642Srdivacky                                        LLVMModuleRef M,
128204642Srdivacky                                        char **OutError) {
129193323Sed  std::string Error;
130204642Srdivacky  EngineBuilder builder(unwrap(M));
131198090Srdivacky  builder.setEngineKind(EngineKind::Interpreter)
132198090Srdivacky         .setErrorStr(&Error);
133198090Srdivacky  if (ExecutionEngine *Interp = builder.create()) {
134193323Sed    *OutInterp = wrap(Interp);
135193323Sed    return 0;
136193323Sed  }
137193323Sed  *OutError = strdup(Error.c_str());
138193323Sed  return 1;
139193323Sed}
140193323Sed
141204642SrdivackyLLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
142204642Srdivacky                                        LLVMModuleRef M,
143204642Srdivacky                                        unsigned OptLevel,
144204642Srdivacky                                        char **OutError) {
145193323Sed  std::string Error;
146204642Srdivacky  EngineBuilder builder(unwrap(M));
147198090Srdivacky  builder.setEngineKind(EngineKind::JIT)
148198090Srdivacky         .setErrorStr(&Error)
149198090Srdivacky         .setOptLevel((CodeGenOpt::Level)OptLevel);
150198090Srdivacky  if (ExecutionEngine *JIT = builder.create()) {
151193323Sed    *OutJIT = wrap(JIT);
152193323Sed    return 0;
153193323Sed  }
154193323Sed  *OutError = strdup(Error.c_str());
155193323Sed  return 1;
156193323Sed}
157193323Sed
158251662Sdimvoid LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
159251662Sdim                                        size_t SizeOfPassedOptions) {
160251662Sdim  LLVMMCJITCompilerOptions options;
161263508Sdim  memset(&options, 0, sizeof(options)); // Most fields are zero by default.
162251662Sdim  options.CodeModel = LLVMCodeModelJITDefault;
163251662Sdim
164251662Sdim  memcpy(PassedOptions, &options,
165251662Sdim         std::min(sizeof(options), SizeOfPassedOptions));
166251662Sdim}
167251662Sdim
168251662SdimLLVMBool LLVMCreateMCJITCompilerForModule(
169251662Sdim    LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
170251662Sdim    LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
171251662Sdim    char **OutError) {
172251662Sdim  LLVMMCJITCompilerOptions options;
173251662Sdim  // If the user passed a larger sized options struct, then they were compiled
174251662Sdim  // against a newer LLVM. Tell them that something is wrong.
175251662Sdim  if (SizeOfPassedOptions > sizeof(options)) {
176251662Sdim    *OutError = strdup(
177251662Sdim      "Refusing to use options struct that is larger than my own; assuming "
178251662Sdim      "LLVM library mismatch.");
179251662Sdim    return 1;
180251662Sdim  }
181251662Sdim
182251662Sdim  // Defend against the user having an old version of the API by ensuring that
183251662Sdim  // any fields they didn't see are cleared. We must defend against fields being
184251662Sdim  // set to the bitwise equivalent of zero, and assume that this means "do the
185251662Sdim  // default" as if that option hadn't been available.
186251662Sdim  LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
187251662Sdim  memcpy(&options, PassedOptions, SizeOfPassedOptions);
188251662Sdim
189251662Sdim  TargetOptions targetOptions;
190251662Sdim  targetOptions.NoFramePointerElim = options.NoFramePointerElim;
191251662Sdim  targetOptions.EnableFastISel = options.EnableFastISel;
192251662Sdim
193251662Sdim  std::string Error;
194251662Sdim  EngineBuilder builder(unwrap(M));
195251662Sdim  builder.setEngineKind(EngineKind::JIT)
196251662Sdim         .setErrorStr(&Error)
197251662Sdim         .setUseMCJIT(true)
198251662Sdim         .setOptLevel((CodeGenOpt::Level)options.OptLevel)
199251662Sdim         .setCodeModel(unwrap(options.CodeModel))
200251662Sdim         .setTargetOptions(targetOptions);
201263508Sdim  if (options.MCJMM)
202263508Sdim    builder.setMCJITMemoryManager(unwrap(options.MCJMM));
203251662Sdim  if (ExecutionEngine *JIT = builder.create()) {
204251662Sdim    *OutJIT = wrap(JIT);
205251662Sdim    return 0;
206251662Sdim  }
207251662Sdim  *OutError = strdup(Error.c_str());
208251662Sdim  return 1;
209251662Sdim}
210251662Sdim
211204642SrdivackyLLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
212204642Srdivacky                                   LLVMModuleProviderRef MP,
213204642Srdivacky                                   char **OutError) {
214204642Srdivacky  /* The module provider is now actually a module. */
215204642Srdivacky  return LLVMCreateExecutionEngineForModule(OutEE,
216204642Srdivacky                                            reinterpret_cast<LLVMModuleRef>(MP),
217204642Srdivacky                                            OutError);
218204642Srdivacky}
219204642Srdivacky
220204642SrdivackyLLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
221204642Srdivacky                               LLVMModuleProviderRef MP,
222204642Srdivacky                               char **OutError) {
223204642Srdivacky  /* The module provider is now actually a module. */
224204642Srdivacky  return LLVMCreateInterpreterForModule(OutInterp,
225204642Srdivacky                                        reinterpret_cast<LLVMModuleRef>(MP),
226204642Srdivacky                                        OutError);
227204642Srdivacky}
228204642Srdivacky
229204642SrdivackyLLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
230204642Srdivacky                               LLVMModuleProviderRef MP,
231204642Srdivacky                               unsigned OptLevel,
232204642Srdivacky                               char **OutError) {
233204642Srdivacky  /* The module provider is now actually a module. */
234204642Srdivacky  return LLVMCreateJITCompilerForModule(OutJIT,
235204642Srdivacky                                        reinterpret_cast<LLVMModuleRef>(MP),
236204642Srdivacky                                        OptLevel, OutError);
237204642Srdivacky}
238204642Srdivacky
239204642Srdivacky
240193323Sedvoid LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
241193323Sed  delete unwrap(EE);
242193323Sed}
243193323Sed
244193323Sedvoid LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
245193323Sed  unwrap(EE)->runStaticConstructorsDestructors(false);
246193323Sed}
247193323Sed
248193323Sedvoid LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
249193323Sed  unwrap(EE)->runStaticConstructorsDestructors(true);
250193323Sed}
251193323Sed
252193323Sedint LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
253193323Sed                          unsigned ArgC, const char * const *ArgV,
254193323Sed                          const char * const *EnvP) {
255251662Sdim  unwrap(EE)->finalizeObject();
256251662Sdim
257193323Sed  std::vector<std::string> ArgVec;
258193323Sed  for (unsigned I = 0; I != ArgC; ++I)
259193323Sed    ArgVec.push_back(ArgV[I]);
260193323Sed
261193323Sed  return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
262193323Sed}
263193323Sed
264193323SedLLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
265193323Sed                                    unsigned NumArgs,
266193323Sed                                    LLVMGenericValueRef *Args) {
267251662Sdim  unwrap(EE)->finalizeObject();
268251662Sdim
269193323Sed  std::vector<GenericValue> ArgVec;
270193323Sed  ArgVec.reserve(NumArgs);
271193323Sed  for (unsigned I = 0; I != NumArgs; ++I)
272193323Sed    ArgVec.push_back(*unwrap(Args[I]));
273193323Sed
274193323Sed  GenericValue *Result = new GenericValue();
275193323Sed  *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
276193323Sed  return wrap(Result);
277193323Sed}
278193323Sed
279193323Sedvoid LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
280193323Sed  unwrap(EE)->freeMachineCodeForFunction(unwrap<Function>(F));
281193323Sed}
282193323Sed
283204642Srdivackyvoid LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
284204642Srdivacky  unwrap(EE)->addModule(unwrap(M));
285204642Srdivacky}
286204642Srdivacky
287193323Sedvoid LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
288204642Srdivacky  /* The module provider is now actually a module. */
289204642Srdivacky  LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
290193323Sed}
291193323Sed
292204642SrdivackyLLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
293204642Srdivacky                          LLVMModuleRef *OutMod, char **OutError) {
294204642Srdivacky  Module *Mod = unwrap(M);
295204642Srdivacky  unwrap(EE)->removeModule(Mod);
296204642Srdivacky  *OutMod = wrap(Mod);
297204642Srdivacky  return 0;
298204642Srdivacky}
299204642Srdivacky
300202375SrdivackyLLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
301202375Srdivacky                                  LLVMModuleProviderRef MP,
302202375Srdivacky                                  LLVMModuleRef *OutMod, char **OutError) {
303204642Srdivacky  /* The module provider is now actually a module. */
304204642Srdivacky  return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod,
305204642Srdivacky                          OutError);
306193323Sed}
307193323Sed
308202375SrdivackyLLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
309202375Srdivacky                          LLVMValueRef *OutFn) {
310193323Sed  if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
311193323Sed    *OutFn = wrap(F);
312193323Sed    return 0;
313193323Sed  }
314193323Sed  return 1;
315193323Sed}
316193323Sed
317251662Sdimvoid *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
318251662Sdim                                     LLVMValueRef Fn) {
319212904Sdim  return unwrap(EE)->recompileAndRelinkFunction(unwrap<Function>(Fn));
320212904Sdim}
321212904Sdim
322193323SedLLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
323243830Sdim  return wrap(unwrap(EE)->getDataLayout());
324193323Sed}
325193323Sed
326193323Sedvoid LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
327193323Sed                          void* Addr) {
328193323Sed  unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
329193323Sed}
330193323Sed
331193323Sedvoid *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
332251662Sdim  unwrap(EE)->finalizeObject();
333251662Sdim
334193323Sed  return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
335193323Sed}
336263508Sdim
337263508Sdim/*===-- Operations on memory managers -------------------------------------===*/
338263508Sdim
339263508Sdimnamespace {
340263508Sdim
341263508Sdimstruct SimpleBindingMMFunctions {
342263508Sdim  LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
343263508Sdim  LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
344263508Sdim  LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
345263508Sdim  LLVMMemoryManagerDestroyCallback Destroy;
346263508Sdim};
347263508Sdim
348263508Sdimclass SimpleBindingMemoryManager : public RTDyldMemoryManager {
349263508Sdimpublic:
350263508Sdim  SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
351263508Sdim                             void *Opaque);
352263508Sdim  virtual ~SimpleBindingMemoryManager();
353263508Sdim
354263508Sdim  virtual uint8_t *allocateCodeSection(
355263508Sdim    uintptr_t Size, unsigned Alignment, unsigned SectionID,
356263508Sdim    StringRef SectionName);
357263508Sdim
358263508Sdim  virtual uint8_t *allocateDataSection(
359263508Sdim    uintptr_t Size, unsigned Alignment, unsigned SectionID,
360263508Sdim    StringRef SectionName, bool isReadOnly);
361263508Sdim
362263508Sdim  virtual bool finalizeMemory(std::string *ErrMsg);
363263508Sdim
364263508Sdimprivate:
365263508Sdim  SimpleBindingMMFunctions Functions;
366263508Sdim  void *Opaque;
367263508Sdim};
368263508Sdim
369263508SdimSimpleBindingMemoryManager::SimpleBindingMemoryManager(
370263508Sdim  const SimpleBindingMMFunctions& Functions,
371263508Sdim  void *Opaque)
372263508Sdim  : Functions(Functions), Opaque(Opaque) {
373263508Sdim  assert(Functions.AllocateCodeSection &&
374263508Sdim         "No AllocateCodeSection function provided!");
375263508Sdim  assert(Functions.AllocateDataSection &&
376263508Sdim         "No AllocateDataSection function provided!");
377263508Sdim  assert(Functions.FinalizeMemory &&
378263508Sdim         "No FinalizeMemory function provided!");
379263508Sdim  assert(Functions.Destroy &&
380263508Sdim         "No Destroy function provided!");
381263508Sdim}
382263508Sdim
383263508SdimSimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
384263508Sdim  Functions.Destroy(Opaque);
385263508Sdim}
386263508Sdim
387263508Sdimuint8_t *SimpleBindingMemoryManager::allocateCodeSection(
388263508Sdim  uintptr_t Size, unsigned Alignment, unsigned SectionID,
389263508Sdim  StringRef SectionName) {
390263508Sdim  return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
391263508Sdim                                       SectionName.str().c_str());
392263508Sdim}
393263508Sdim
394263508Sdimuint8_t *SimpleBindingMemoryManager::allocateDataSection(
395263508Sdim  uintptr_t Size, unsigned Alignment, unsigned SectionID,
396263508Sdim  StringRef SectionName, bool isReadOnly) {
397263508Sdim  return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
398263508Sdim                                       SectionName.str().c_str(),
399263508Sdim                                       isReadOnly);
400263508Sdim}
401263508Sdim
402263508Sdimbool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
403263508Sdim  char *errMsgCString = 0;
404263508Sdim  bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
405263508Sdim  assert((result || !errMsgCString) &&
406263508Sdim         "Did not expect an error message if FinalizeMemory succeeded");
407263508Sdim  if (errMsgCString) {
408263508Sdim    if (ErrMsg)
409263508Sdim      *ErrMsg = errMsgCString;
410263508Sdim    free(errMsgCString);
411263508Sdim  }
412263508Sdim  return result;
413263508Sdim}
414263508Sdim
415263508Sdim} // anonymous namespace
416263508Sdim
417263508SdimLLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
418263508Sdim  void *Opaque,
419263508Sdim  LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
420263508Sdim  LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
421263508Sdim  LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
422263508Sdim  LLVMMemoryManagerDestroyCallback Destroy) {
423263508Sdim
424263508Sdim  if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
425263508Sdim      !Destroy)
426263508Sdim    return NULL;
427263508Sdim
428263508Sdim  SimpleBindingMMFunctions functions;
429263508Sdim  functions.AllocateCodeSection = AllocateCodeSection;
430263508Sdim  functions.AllocateDataSection = AllocateDataSection;
431263508Sdim  functions.FinalizeMemory = FinalizeMemory;
432263508Sdim  functions.Destroy = Destroy;
433263508Sdim  return wrap(new SimpleBindingMemoryManager(functions, Opaque));
434263508Sdim}
435263508Sdim
436263508Sdimvoid LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
437263508Sdim  delete unwrap(MM);
438263508Sdim}
439263508Sdim
440