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 
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "jit"
26 
27 // Wrapping the C bindings types.
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue,LLVMGenericValueRef)28 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
29 
30 
31 inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
32   return
33   reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
34 }
35 
36 /*===-- Operations on generic values --------------------------------------===*/
37 
LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,unsigned long long N,LLVMBool IsSigned)38 LLVMGenericValueRef 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 
LLVMCreateGenericValueOfPointer(void * P)46 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
47   GenericValue *GenVal = new GenericValue();
48   GenVal->PointerVal = P;
49   return wrap(GenVal);
50 }
51 
LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef,double N)52 LLVMGenericValueRef 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 
LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef)67 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
68   return unwrap(GenValRef)->IntVal.getBitWidth();
69 }
70 
LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,LLVMBool IsSigned)71 unsigned 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 
LLVMGenericValueToPointer(LLVMGenericValueRef GenVal)80 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
81   return unwrap(GenVal)->PointerVal;
82 }
83 
LLVMGenericValueToFloat(LLVMTypeRef TyRef,LLVMGenericValueRef GenVal)84 double 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 
LLVMDisposeGenericValue(LLVMGenericValueRef GenVal)95 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
96   delete unwrap(GenVal);
97 }
98 
99 /*===-- Operations on execution engines -----------------------------------===*/
100 
LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef * OutEE,LLVMModuleRef M,char ** OutError)101 LLVMBool 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 
LLVMCreateInterpreterForModule(LLVMExecutionEngineRef * OutInterp,LLVMModuleRef M,char ** OutError)116 LLVMBool 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 
LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef * OutJIT,LLVMModuleRef M,unsigned OptLevel,char ** OutError)131 LLVMBool 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 
LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions * PassedOptions,size_t SizeOfPassedOptions)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;
153 
154   memcpy(PassedOptions, &options,
155          std::min(sizeof(options), SizeOfPassedOptions));
156 }
157 
LLVMCreateMCJITCompilerForModule(LLVMExecutionEngineRef * OutJIT,LLVMModuleRef M,LLVMMCJITCompilerOptions * PassedOptions,size_t SizeOfPassedOptions,char ** OutError)158 LLVMBool 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(
192       std::unique_ptr<RTDyldMemoryManager>(unwrap(options.MCJMM)));
193   if (ExecutionEngine *JIT = builder.create()) {
194     *OutJIT = wrap(JIT);
195     return 0;
196   }
197   *OutError = strdup(Error.c_str());
198   return 1;
199 }
200 
LLVMCreateExecutionEngine(LLVMExecutionEngineRef * OutEE,LLVMModuleProviderRef MP,char ** OutError)201 LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
202                                    LLVMModuleProviderRef MP,
203                                    char **OutError) {
204   /* The module provider is now actually a module. */
205   return LLVMCreateExecutionEngineForModule(OutEE,
206                                             reinterpret_cast<LLVMModuleRef>(MP),
207                                             OutError);
208 }
209 
LLVMCreateInterpreter(LLVMExecutionEngineRef * OutInterp,LLVMModuleProviderRef MP,char ** OutError)210 LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
211                                LLVMModuleProviderRef MP,
212                                char **OutError) {
213   /* The module provider is now actually a module. */
214   return LLVMCreateInterpreterForModule(OutInterp,
215                                         reinterpret_cast<LLVMModuleRef>(MP),
216                                         OutError);
217 }
218 
LLVMCreateJITCompiler(LLVMExecutionEngineRef * OutJIT,LLVMModuleProviderRef MP,unsigned OptLevel,char ** OutError)219 LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
220                                LLVMModuleProviderRef MP,
221                                unsigned OptLevel,
222                                char **OutError) {
223   /* The module provider is now actually a module. */
224   return LLVMCreateJITCompilerForModule(OutJIT,
225                                         reinterpret_cast<LLVMModuleRef>(MP),
226                                         OptLevel, OutError);
227 }
228 
229 
LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE)230 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
231   delete unwrap(EE);
232 }
233 
LLVMRunStaticConstructors(LLVMExecutionEngineRef EE)234 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
235   unwrap(EE)->runStaticConstructorsDestructors(false);
236 }
237 
LLVMRunStaticDestructors(LLVMExecutionEngineRef EE)238 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
239   unwrap(EE)->runStaticConstructorsDestructors(true);
240 }
241 
LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE,LLVMValueRef F,unsigned ArgC,const char * const * ArgV,const char * const * EnvP)242 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
243                           unsigned ArgC, const char * const *ArgV,
244                           const char * const *EnvP) {
245   unwrap(EE)->finalizeObject();
246 
247   std::vector<std::string> ArgVec;
248   for (unsigned I = 0; I != ArgC; ++I)
249     ArgVec.push_back(ArgV[I]);
250 
251   return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
252 }
253 
LLVMRunFunction(LLVMExecutionEngineRef EE,LLVMValueRef F,unsigned NumArgs,LLVMGenericValueRef * Args)254 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
255                                     unsigned NumArgs,
256                                     LLVMGenericValueRef *Args) {
257   unwrap(EE)->finalizeObject();
258 
259   std::vector<GenericValue> ArgVec;
260   ArgVec.reserve(NumArgs);
261   for (unsigned I = 0; I != NumArgs; ++I)
262     ArgVec.push_back(*unwrap(Args[I]));
263 
264   GenericValue *Result = new GenericValue();
265   *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
266   return wrap(Result);
267 }
268 
LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE,LLVMValueRef F)269 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
270 }
271 
LLVMAddModule(LLVMExecutionEngineRef EE,LLVMModuleRef M)272 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
273   unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
274 }
275 
LLVMAddModuleProvider(LLVMExecutionEngineRef EE,LLVMModuleProviderRef MP)276 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
277   /* The module provider is now actually a module. */
278   LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
279 }
280 
LLVMRemoveModule(LLVMExecutionEngineRef EE,LLVMModuleRef M,LLVMModuleRef * OutMod,char ** OutError)281 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
282                           LLVMModuleRef *OutMod, char **OutError) {
283   Module *Mod = unwrap(M);
284   unwrap(EE)->removeModule(Mod);
285   *OutMod = wrap(Mod);
286   return 0;
287 }
288 
LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,LLVMModuleProviderRef MP,LLVMModuleRef * OutMod,char ** OutError)289 LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
290                                   LLVMModuleProviderRef MP,
291                                   LLVMModuleRef *OutMod, char **OutError) {
292   /* The module provider is now actually a module. */
293   return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod,
294                           OutError);
295 }
296 
LLVMFindFunction(LLVMExecutionEngineRef EE,const char * Name,LLVMValueRef * OutFn)297 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
298                           LLVMValueRef *OutFn) {
299   if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
300     *OutFn = wrap(F);
301     return 0;
302   }
303   return 1;
304 }
305 
LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,LLVMValueRef Fn)306 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
307                                      LLVMValueRef Fn) {
308   return nullptr;
309 }
310 
LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE)311 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
312   return wrap(unwrap(EE)->getDataLayout());
313 }
314 
315 LLVMTargetMachineRef
LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE)316 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
317   return wrap(unwrap(EE)->getTargetMachine());
318 }
319 
LLVMAddGlobalMapping(LLVMExecutionEngineRef EE,LLVMValueRef Global,void * Addr)320 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
321                           void* Addr) {
322   unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
323 }
324 
LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE,LLVMValueRef Global)325 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
326   unwrap(EE)->finalizeObject();
327 
328   return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
329 }
330 
LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE,const char * Name)331 uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name) {
332   return unwrap(EE)->getGlobalValueAddress(Name);
333 }
334 
LLVMGetFunctionAddress(LLVMExecutionEngineRef EE,const char * Name)335 uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name) {
336   return unwrap(EE)->getFunctionAddress(Name);
337 }
338 
339 /*===-- Operations on memory managers -------------------------------------===*/
340 
341 namespace {
342 
343 struct SimpleBindingMMFunctions {
344   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
345   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
346   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
347   LLVMMemoryManagerDestroyCallback Destroy;
348 };
349 
350 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
351 public:
352   SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
353                              void *Opaque);
354   ~SimpleBindingMemoryManager() override;
355 
356   uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
357                                unsigned SectionID,
358                                StringRef SectionName) override;
359 
360   uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
361                                unsigned SectionID, StringRef SectionName,
362                                bool isReadOnly) override;
363 
364   bool finalizeMemory(std::string *ErrMsg) override;
365 
366 private:
367   SimpleBindingMMFunctions Functions;
368   void *Opaque;
369 };
370 
SimpleBindingMemoryManager(const SimpleBindingMMFunctions & Functions,void * Opaque)371 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
372   const SimpleBindingMMFunctions& Functions,
373   void *Opaque)
374   : Functions(Functions), Opaque(Opaque) {
375   assert(Functions.AllocateCodeSection &&
376          "No AllocateCodeSection function provided!");
377   assert(Functions.AllocateDataSection &&
378          "No AllocateDataSection function provided!");
379   assert(Functions.FinalizeMemory &&
380          "No FinalizeMemory function provided!");
381   assert(Functions.Destroy &&
382          "No Destroy function provided!");
383 }
384 
~SimpleBindingMemoryManager()385 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
386   Functions.Destroy(Opaque);
387 }
388 
allocateCodeSection(uintptr_t Size,unsigned Alignment,unsigned SectionID,StringRef SectionName)389 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
390   uintptr_t Size, unsigned Alignment, unsigned SectionID,
391   StringRef SectionName) {
392   return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
393                                        SectionName.str().c_str());
394 }
395 
allocateDataSection(uintptr_t Size,unsigned Alignment,unsigned SectionID,StringRef SectionName,bool isReadOnly)396 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
397   uintptr_t Size, unsigned Alignment, unsigned SectionID,
398   StringRef SectionName, bool isReadOnly) {
399   return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
400                                        SectionName.str().c_str(),
401                                        isReadOnly);
402 }
403 
finalizeMemory(std::string * ErrMsg)404 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
405   char *errMsgCString = nullptr;
406   bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
407   assert((result || !errMsgCString) &&
408          "Did not expect an error message if FinalizeMemory succeeded");
409   if (errMsgCString) {
410     if (ErrMsg)
411       *ErrMsg = errMsgCString;
412     free(errMsgCString);
413   }
414   return result;
415 }
416 
417 } // anonymous namespace
418 
LLVMCreateSimpleMCJITMemoryManager(void * Opaque,LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,LLVMMemoryManagerDestroyCallback Destroy)419 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
420   void *Opaque,
421   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
422   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
423   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
424   LLVMMemoryManagerDestroyCallback Destroy) {
425 
426   if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
427       !Destroy)
428     return nullptr;
429 
430   SimpleBindingMMFunctions functions;
431   functions.AllocateCodeSection = AllocateCodeSection;
432   functions.AllocateDataSection = AllocateDataSection;
433   functions.FinalizeMemory = FinalizeMemory;
434   functions.Destroy = Destroy;
435   return wrap(new SimpleBindingMemoryManager(functions, Opaque));
436 }
437 
LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM)438 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
439   delete unwrap(MM);
440 }
441 
442