Replace push_back(Constructor(foo)) with emplace_back(foo) for non-trivial types
[oota-llvm.git] / lib / ExecutionEngine / ExecutionEngineBindings.cpp
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.
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
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
46 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
47   GenericValue *GenVal = new GenericValue();
48   GenVal->PointerVal = P;
49   return wrap(GenVal);
50 }
51
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
67 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
68   return unwrap(GenValRef)->IntVal.getBitWidth();
69 }
70
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
80 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
81   return unwrap(GenVal)->PointerVal;
82 }
83
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
95 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
96   delete unwrap(GenVal);
97 }
98
99 /*===-- Operations on execution engines -----------------------------------===*/
100
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
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
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
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
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.EnableFastISel = options.EnableFastISel;
181   std::unique_ptr<Module> Mod(unwrap(M));
182
183   if (Mod)
184     // Set function attribute "no-frame-pointer-elim" based on
185     // NoFramePointerElim.
186     for (auto &F : *Mod) {
187       auto Attrs = F.getAttributes();
188       auto Value = options.NoFramePointerElim ? "true" : "false";
189       Attrs = Attrs.addAttribute(F.getContext(), AttributeSet::FunctionIndex,
190                                  "no-frame-pointer-elim", Value);
191       F.setAttributes(Attrs);
192     }
193
194   std::string Error;
195   EngineBuilder builder(std::move(Mod));
196   builder.setEngineKind(EngineKind::JIT)
197          .setErrorStr(&Error)
198          .setOptLevel((CodeGenOpt::Level)options.OptLevel)
199          .setCodeModel(unwrap(options.CodeModel))
200          .setTargetOptions(targetOptions);
201   if (options.MCJMM)
202     builder.setMCJITMemoryManager(
203       std::unique_ptr<RTDyldMemoryManager>(unwrap(options.MCJMM)));
204   if (ExecutionEngine *JIT = builder.create()) {
205     *OutJIT = wrap(JIT);
206     return 0;
207   }
208   *OutError = strdup(Error.c_str());
209   return 1;
210 }
211
212 LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
213                                    LLVMModuleProviderRef MP,
214                                    char **OutError) {
215   /* The module provider is now actually a module. */
216   return LLVMCreateExecutionEngineForModule(OutEE,
217                                             reinterpret_cast<LLVMModuleRef>(MP),
218                                             OutError);
219 }
220
221 LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
222                                LLVMModuleProviderRef MP,
223                                char **OutError) {
224   /* The module provider is now actually a module. */
225   return LLVMCreateInterpreterForModule(OutInterp,
226                                         reinterpret_cast<LLVMModuleRef>(MP),
227                                         OutError);
228 }
229
230 LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
231                                LLVMModuleProviderRef MP,
232                                unsigned OptLevel,
233                                char **OutError) {
234   /* The module provider is now actually a module. */
235   return LLVMCreateJITCompilerForModule(OutJIT,
236                                         reinterpret_cast<LLVMModuleRef>(MP),
237                                         OptLevel, OutError);
238 }
239
240
241 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
242   delete unwrap(EE);
243 }
244
245 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
246   unwrap(EE)->runStaticConstructorsDestructors(false);
247 }
248
249 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
250   unwrap(EE)->runStaticConstructorsDestructors(true);
251 }
252
253 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
254                           unsigned ArgC, const char * const *ArgV,
255                           const char * const *EnvP) {
256   unwrap(EE)->finalizeObject();
257
258   std::vector<std::string> ArgVec(ArgV, ArgV + ArgC);
259   return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
260 }
261
262 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
263                                     unsigned NumArgs,
264                                     LLVMGenericValueRef *Args) {
265   unwrap(EE)->finalizeObject();
266   
267   std::vector<GenericValue> ArgVec;
268   ArgVec.reserve(NumArgs);
269   for (unsigned I = 0; I != NumArgs; ++I)
270     ArgVec.push_back(*unwrap(Args[I]));
271   
272   GenericValue *Result = new GenericValue();
273   *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
274   return wrap(Result);
275 }
276
277 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
278 }
279
280 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
281   unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
282 }
283
284 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
285   /* The module provider is now actually a module. */
286   LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
287 }
288
289 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
290                           LLVMModuleRef *OutMod, char **OutError) {
291   Module *Mod = unwrap(M);
292   unwrap(EE)->removeModule(Mod);
293   *OutMod = wrap(Mod);
294   return 0;
295 }
296
297 LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
298                                   LLVMModuleProviderRef MP,
299                                   LLVMModuleRef *OutMod, char **OutError) {
300   /* The module provider is now actually a module. */
301   return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod,
302                           OutError);
303 }
304
305 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
306                           LLVMValueRef *OutFn) {
307   if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
308     *OutFn = wrap(F);
309     return 0;
310   }
311   return 1;
312 }
313
314 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
315                                      LLVMValueRef Fn) {
316   return nullptr;
317 }
318
319 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
320   return wrap(unwrap(EE)->getDataLayout());
321 }
322
323 LLVMTargetMachineRef
324 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
325   return wrap(unwrap(EE)->getTargetMachine());
326 }
327
328 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
329                           void* Addr) {
330   unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
331 }
332
333 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
334   unwrap(EE)->finalizeObject();
335   
336   return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
337 }
338
339 uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name) {
340   return unwrap(EE)->getGlobalValueAddress(Name);
341 }
342
343 uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name) {
344   return unwrap(EE)->getFunctionAddress(Name);
345 }
346
347 /*===-- Operations on memory managers -------------------------------------===*/
348
349 namespace {
350
351 struct SimpleBindingMMFunctions {
352   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
353   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
354   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
355   LLVMMemoryManagerDestroyCallback Destroy;
356 };
357
358 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
359 public:
360   SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
361                              void *Opaque);
362   ~SimpleBindingMemoryManager() override;
363
364   uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
365                                unsigned SectionID,
366                                StringRef SectionName) override;
367
368   uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
369                                unsigned SectionID, StringRef SectionName,
370                                bool isReadOnly) override;
371
372   bool finalizeMemory(std::string *ErrMsg) override;
373
374 private:
375   SimpleBindingMMFunctions Functions;
376   void *Opaque;
377 };
378
379 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
380   const SimpleBindingMMFunctions& Functions,
381   void *Opaque)
382   : Functions(Functions), Opaque(Opaque) {
383   assert(Functions.AllocateCodeSection &&
384          "No AllocateCodeSection function provided!");
385   assert(Functions.AllocateDataSection &&
386          "No AllocateDataSection function provided!");
387   assert(Functions.FinalizeMemory &&
388          "No FinalizeMemory function provided!");
389   assert(Functions.Destroy &&
390          "No Destroy function provided!");
391 }
392
393 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
394   Functions.Destroy(Opaque);
395 }
396
397 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
398   uintptr_t Size, unsigned Alignment, unsigned SectionID,
399   StringRef SectionName) {
400   return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
401                                        SectionName.str().c_str());
402 }
403
404 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
405   uintptr_t Size, unsigned Alignment, unsigned SectionID,
406   StringRef SectionName, bool isReadOnly) {
407   return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
408                                        SectionName.str().c_str(),
409                                        isReadOnly);
410 }
411
412 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
413   char *errMsgCString = nullptr;
414   bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
415   assert((result || !errMsgCString) &&
416          "Did not expect an error message if FinalizeMemory succeeded");
417   if (errMsgCString) {
418     if (ErrMsg)
419       *ErrMsg = errMsgCString;
420     free(errMsgCString);
421   }
422   return result;
423 }
424
425 } // anonymous namespace
426
427 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
428   void *Opaque,
429   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
430   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
431   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
432   LLVMMemoryManagerDestroyCallback Destroy) {
433   
434   if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
435       !Destroy)
436     return nullptr;
437   
438   SimpleBindingMMFunctions functions;
439   functions.AllocateCodeSection = AllocateCodeSection;
440   functions.AllocateDataSection = AllocateDataSection;
441   functions.FinalizeMemory = FinalizeMemory;
442   functions.Destroy = Destroy;
443   return wrap(new SimpleBindingMemoryManager(functions, Opaque));
444 }
445
446 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
447   delete unwrap(MM);
448 }
449