ExecutionEngineBindings.cpp revision 37ed9c199ca639565f6ce88105f9e39e898d82d0
1//===-- ExecutionEngineBindings.cpp - C bindings for EEs ------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the C bindings for the ExecutionEngine library.
11//
12//===----------------------------------------------------------------------===//
13
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 <cstring>
22
23using namespace llvm;
24
25#define DEBUG_TYPE "jit"
26
27// Wrapping the C bindings types.
28DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
29
30
31inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
32  return
33  reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
34}
35
36/*===-- Operations on generic values --------------------------------------===*/
37
38LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
39                                                unsigned long long N,
40                                                LLVMBool IsSigned) {
41  GenericValue *GenVal = new GenericValue();
42  GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
43  return wrap(GenVal);
44}
45
46LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
47  GenericValue *GenVal = new GenericValue();
48  GenVal->PointerVal = P;
49  return wrap(GenVal);
50}
51
52LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
53  GenericValue *GenVal = new GenericValue();
54  switch (unwrap(TyRef)->getTypeID()) {
55  case Type::FloatTyID:
56    GenVal->FloatVal = N;
57    break;
58  case Type::DoubleTyID:
59    GenVal->DoubleVal = N;
60    break;
61  default:
62    llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
63  }
64  return wrap(GenVal);
65}
66
67unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
68  return unwrap(GenValRef)->IntVal.getBitWidth();
69}
70
71unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
72                                         LLVMBool IsSigned) {
73  GenericValue *GenVal = unwrap(GenValRef);
74  if (IsSigned)
75    return GenVal->IntVal.getSExtValue();
76  else
77    return GenVal->IntVal.getZExtValue();
78}
79
80void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
81  return unwrap(GenVal)->PointerVal;
82}
83
84double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
85  switch (unwrap(TyRef)->getTypeID()) {
86  case Type::FloatTyID:
87    return unwrap(GenVal)->FloatVal;
88  case Type::DoubleTyID:
89    return unwrap(GenVal)->DoubleVal;
90  default:
91    llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
92  }
93}
94
95void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
96  delete unwrap(GenVal);
97}
98
99/*===-- Operations on execution engines -----------------------------------===*/
100
101LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
102                                            LLVMModuleRef M,
103                                            char **OutError) {
104  std::string Error;
105  EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
106  builder.setEngineKind(EngineKind::Either)
107         .setErrorStr(&Error);
108  if (ExecutionEngine *EE = builder.create()){
109    *OutEE = wrap(EE);
110    return 0;
111  }
112  *OutError = strdup(Error.c_str());
113  return 1;
114}
115
116LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
117                                        LLVMModuleRef M,
118                                        char **OutError) {
119  std::string Error;
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);
125    return 0;
126  }
127  *OutError = strdup(Error.c_str());
128  return 1;
129}
130
131LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
132                                        LLVMModuleRef M,
133                                        unsigned OptLevel,
134                                        char **OutError) {
135  std::string Error;
136  EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
137  builder.setEngineKind(EngineKind::JIT)
138         .setErrorStr(&Error)
139         .setOptLevel((CodeGenOpt::Level)OptLevel);
140  if (ExecutionEngine *JIT = builder.create()) {
141    *OutJIT = wrap(JIT);
142    return 0;
143  }
144  *OutError = strdup(Error.c_str());
145  return 1;
146}
147
148void 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;
153
154  memcpy(PassedOptions, &options,
155         std::min(sizeof(options), SizeOfPassedOptions));
156}
157
158LLVMBool LLVMCreateMCJITCompilerForModule(
159    LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
160    LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
161    char **OutError) {
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)) {
166    *OutError = strdup(
167      "Refusing to use options struct that is larger than my own; assuming "
168      "LLVM library mismatch.");
169    return 1;
170  }
171
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);
178
179  TargetOptions targetOptions;
180  targetOptions.NoFramePointerElim = options.NoFramePointerElim;
181  targetOptions.EnableFastISel = options.EnableFastISel;
182
183  std::string Error;
184  EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
185  builder.setEngineKind(EngineKind::JIT)
186         .setErrorStr(&Error)
187         .setOptLevel((CodeGenOpt::Level)options.OptLevel)
188         .setCodeModel(unwrap(options.CodeModel))
189         .setTargetOptions(targetOptions);
190  if (options.MCJMM)
191    builder.setMCJITMemoryManager(unwrap(options.MCJMM));
192  if (ExecutionEngine *JIT = builder.create()) {
193    *OutJIT = wrap(JIT);
194    return 0;
195  }
196  *OutError = strdup(Error.c_str());
197  return 1;
198}
199
200LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
201                                   LLVMModuleProviderRef MP,
202                                   char **OutError) {
203  /* The module provider is now actually a module. */
204  return LLVMCreateExecutionEngineForModule(OutEE,
205                                            reinterpret_cast<LLVMModuleRef>(MP),
206                                            OutError);
207}
208
209LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
210                               LLVMModuleProviderRef MP,
211                               char **OutError) {
212  /* The module provider is now actually a module. */
213  return LLVMCreateInterpreterForModule(OutInterp,
214                                        reinterpret_cast<LLVMModuleRef>(MP),
215                                        OutError);
216}
217
218LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
219                               LLVMModuleProviderRef MP,
220                               unsigned OptLevel,
221                               char **OutError) {
222  /* The module provider is now actually a module. */
223  return LLVMCreateJITCompilerForModule(OutJIT,
224                                        reinterpret_cast<LLVMModuleRef>(MP),
225                                        OptLevel, OutError);
226}
227
228
229void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
230  delete unwrap(EE);
231}
232
233void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
234  unwrap(EE)->runStaticConstructorsDestructors(false);
235}
236
237void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
238  unwrap(EE)->runStaticConstructorsDestructors(true);
239}
240
241int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
242                          unsigned ArgC, const char * const *ArgV,
243                          const char * const *EnvP) {
244  unwrap(EE)->finalizeObject();
245
246  std::vector<std::string> ArgVec;
247  for (unsigned I = 0; I != ArgC; ++I)
248    ArgVec.push_back(ArgV[I]);
249
250  return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
251}
252
253LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
254                                    unsigned NumArgs,
255                                    LLVMGenericValueRef *Args) {
256  unwrap(EE)->finalizeObject();
257
258  std::vector<GenericValue> ArgVec;
259  ArgVec.reserve(NumArgs);
260  for (unsigned I = 0; I != NumArgs; ++I)
261    ArgVec.push_back(*unwrap(Args[I]));
262
263  GenericValue *Result = new GenericValue();
264  *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
265  return wrap(Result);
266}
267
268void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
269}
270
271void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
272  unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
273}
274
275void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
276  /* The module provider is now actually a module. */
277  LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
278}
279
280LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
281                          LLVMModuleRef *OutMod, char **OutError) {
282  Module *Mod = unwrap(M);
283  unwrap(EE)->removeModule(Mod);
284  *OutMod = wrap(Mod);
285  return 0;
286}
287
288LLVMBool 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,
293                          OutError);
294}
295
296LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
297                          LLVMValueRef *OutFn) {
298  if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
299    *OutFn = wrap(F);
300    return 0;
301  }
302  return 1;
303}
304
305void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
306                                     LLVMValueRef Fn) {
307  return nullptr;
308}
309
310LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
311  return wrap(unwrap(EE)->getDataLayout());
312}
313
314LLVMTargetMachineRef
315LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
316  return wrap(unwrap(EE)->getTargetMachine());
317}
318
319void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
320                          void* Addr) {
321  unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
322}
323
324void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
325  unwrap(EE)->finalizeObject();
326
327  return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
328}
329
330/*===-- Operations on memory managers -------------------------------------===*/
331
332namespace {
333
334struct SimpleBindingMMFunctions {
335  LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
336  LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
337  LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
338  LLVMMemoryManagerDestroyCallback Destroy;
339};
340
341class SimpleBindingMemoryManager : public RTDyldMemoryManager {
342public:
343  SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
344                             void *Opaque);
345  virtual ~SimpleBindingMemoryManager();
346
347  uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
348                               unsigned SectionID,
349                               StringRef SectionName) override;
350
351  uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
352                               unsigned SectionID, StringRef SectionName,
353                               bool isReadOnly) override;
354
355  bool finalizeMemory(std::string *ErrMsg) override;
356
357private:
358  SimpleBindingMMFunctions Functions;
359  void *Opaque;
360};
361
362SimpleBindingMemoryManager::SimpleBindingMemoryManager(
363  const SimpleBindingMMFunctions& Functions,
364  void *Opaque)
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!");
374}
375
376SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
377  Functions.Destroy(Opaque);
378}
379
380uint8_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());
385}
386
387uint8_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(),
392                                       isReadOnly);
393}
394
395bool 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");
400  if (errMsgCString) {
401    if (ErrMsg)
402      *ErrMsg = errMsgCString;
403    free(errMsgCString);
404  }
405  return result;
406}
407
408} // anonymous namespace
409
410LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
411  void *Opaque,
412  LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
413  LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
414  LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
415  LLVMMemoryManagerDestroyCallback Destroy) {
416
417  if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
418      !Destroy)
419    return nullptr;
420
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));
427}
428
429void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
430  delete unwrap(MM);
431}
432
433