2009-05-14 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / mini / mini-llvm-cpp.cpp
1 //
2 // mini-llvm-cpp.cpp: C++ support classes for the mono LLVM integration
3 //
4 // (C) 2009 Novell, Inc.
5 //
6
7 //
8 // We need to override some stuff in LLVM, but this cannot be done using the C
9 // interface, so we have to use some C++ code here.
10 // The things which we override are:
11 // - the default JIT code manager used by LLVM doesn't allocate memory using
12 //   MAP_32BIT, we require it.
13 // - add some callbacks so we can obtain the size of methods and their exception
14 //   tables.
15 //
16
17 //
18 // Mono's internal header files are not C++ clean, so avoid including them if 
19 // possible
20 //
21
22 #include <stdint.h>
23
24 #include <llvm/PassManager.h>
25 #include <llvm/ExecutionEngine/ExecutionEngine.h>
26 #include <llvm/ExecutionEngine/JITMemoryManager.h>
27 #include <llvm/Target/TargetOptions.h>
28 #include <llvm/Target/TargetData.h>
29 #include <llvm/Analysis/Verifier.h>
30 #include <llvm/Transforms/Scalar.h>
31 #include <llvm/Support/CommandLine.h>
32 #include "llvm/Support/PassNameParser.h"
33 #include <llvm/CodeGen/Passes.h>
34 #include <llvm/CodeGen/MachineFunctionPass.h>
35 //#include <llvm/LinkAllPasses.h>
36
37 #include "llvm-c/Core.h"
38 #include "llvm-c/ExecutionEngine.h"
39
40 #include "mini-llvm-cpp.h"
41
42 using namespace llvm;
43
44 class MonoJITMemoryManager : public JITMemoryManager
45 {
46 private:
47         JITMemoryManager *mm;
48
49 public:
50         /* Callbacks installed by mono */
51         AllocCodeMemoryCb *alloc_cb;
52         FunctionEmittedCb *emitted_cb;
53
54         MonoJITMemoryManager ();
55         ~MonoJITMemoryManager ();
56
57         void setMemoryWritable (void);
58
59         void setMemoryExecutable (void);
60
61         void AllocateGOT();
62
63     unsigned char *getGOTBase() const {
64                 return mm->getGOTBase ();
65     }
66     
67     void *getDlsymTable() const {
68                 return mm->getDlsymTable ();
69     }
70       
71         void SetDlsymTable(void *ptr);
72   
73         unsigned char *startFunctionBody(const Function *F, 
74                                                                          uintptr_t &ActualSize);
75   
76         unsigned char *allocateStub(const GlobalValue* F, unsigned StubSize,
77                                                                  unsigned Alignment);
78   
79         void endFunctionBody(const Function *F, unsigned char *FunctionStart,
80                                                  unsigned char *FunctionEnd);
81
82         unsigned char *allocateSpace(intptr_t Size, unsigned Alignment);
83   
84         void deallocateMemForFunction(const Function *F);
85   
86         unsigned char*startExceptionTable(const Function* F,
87                                                                           uintptr_t &ActualSize);
88   
89         void endExceptionTable(const Function *F, unsigned char *TableStart,
90                                                    unsigned char *TableEnd, 
91                                                    unsigned char* FrameRegister);
92 };
93
94 MonoJITMemoryManager::MonoJITMemoryManager ()
95 {
96         SizeRequired = true;
97         mm = JITMemoryManager::CreateDefaultMemManager ();
98 }
99
100 MonoJITMemoryManager::~MonoJITMemoryManager ()
101 {
102 }
103
104 void
105 MonoJITMemoryManager::setMemoryWritable (void)
106 {
107 }
108
109 void
110 MonoJITMemoryManager::setMemoryExecutable (void)
111 {
112 }
113
114 void
115 MonoJITMemoryManager::AllocateGOT()
116 {
117         mm->AllocateGOT ();
118 }
119   
120 void
121 MonoJITMemoryManager::SetDlsymTable(void *ptr)
122 {
123         mm->SetDlsymTable (ptr);
124 }
125   
126 unsigned char *
127 MonoJITMemoryManager::startFunctionBody(const Function *F, 
128                                         uintptr_t &ActualSize)
129 {
130         return alloc_cb (wrap (F), ActualSize);
131 }
132   
133 unsigned char *
134 MonoJITMemoryManager::allocateStub(const GlobalValue* F, unsigned StubSize,
135                            unsigned Alignment)
136 {
137         return alloc_cb (wrap (F), StubSize);
138 }
139   
140 void
141 MonoJITMemoryManager::endFunctionBody(const Function *F, unsigned char *FunctionStart,
142                                   unsigned char *FunctionEnd)
143 {
144         emitted_cb (wrap (F), FunctionStart, FunctionEnd);
145 }
146
147 unsigned char *
148 MonoJITMemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
149 {
150         return new unsigned char [Size];
151 }
152   
153 void
154 MonoJITMemoryManager::deallocateMemForFunction(const Function *F)
155 {
156 }
157   
158 unsigned char*
159 MonoJITMemoryManager::startExceptionTable(const Function* F,
160                                           uintptr_t &ActualSize)
161 {
162         return alloc_cb (wrap (F), ActualSize);
163 }
164   
165 void
166 MonoJITMemoryManager::endExceptionTable(const Function *F, unsigned char *TableStart,
167                                         unsigned char *TableEnd, 
168                                         unsigned char* FrameRegister)
169 {
170 }
171
172 static MonoJITMemoryManager *mono_mm;
173
174 static FunctionPassManager *fpm;
175
176 void
177 mono_llvm_optimize_method (LLVMValueRef method)
178 {
179         verifyFunction (*(unwrap<Function> (method)));
180         fpm->run (*unwrap<Function> (method));
181 }
182
183 void
184 mono_llvm_dump_value (LLVMValueRef value)
185 {
186         /* Same as LLVMDumpValue (), but print to stdout */
187         cout << (*unwrap<Value> (value));
188 }
189
190 /* Missing overload for building an alloca with an alignment */
191 LLVMValueRef
192 mono_llvm_build_alloca (LLVMBuilderRef builder, LLVMTypeRef Ty, 
193                                                 LLVMValueRef ArraySize,
194                                                 int alignment, const char *Name)
195 {
196         return wrap (unwrap (builder)->Insert (new AllocaInst(unwrap (Ty), unwrap (ArraySize), alignment), Name));
197 }
198
199 LLVMValueRef 
200 mono_llvm_build_volatile_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
201                                                            const char *Name)
202 {
203         return wrap(unwrap(builder)->CreateLoad(unwrap(PointerVal), true, Name));
204 }
205
206 static cl::list<const PassInfo*, bool, PassNameParser>
207 PassList(cl::desc("Optimizations available:"));
208
209 LLVMExecutionEngineRef
210 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb)
211 {
212   std::string Error;
213
214   llvm::cl::ParseEnvironmentOptions("mono", "MONO_LLVM", "", false);
215
216   mono_mm = new MonoJITMemoryManager ();
217   mono_mm->alloc_cb = alloc_cb;
218   mono_mm->emitted_cb = emitted_cb;
219
220   ExceptionHandling = true;
221
222   ExecutionEngine *EE = ExecutionEngine::createJIT (unwrap (MP), &Error, mono_mm, CodeGenOpt::Default);
223   if (!EE) {
224           cerr << "Unable to create LLVM ExecutionEngine: " << Error << "\n";
225           g_assert_not_reached ();
226   }
227   EE->InstallExceptionTableRegister (exception_cb);
228
229   fpm = new FunctionPassManager (unwrap (MP));
230
231   fpm->add(new TargetData(*EE->getTargetData()));
232   /* Add a random set of passes */
233   /* Make this run-time configurable */
234   fpm->add(createInstructionCombiningPass());
235   fpm->add(createReassociatePass());
236   fpm->add(createGVNPass());
237   fpm->add(createCFGSimplificationPass());
238
239   /* Add passes specified by the env variable */
240   /* FIXME: This can only add passes which are linked in, thus are already used */
241   for (unsigned i = 0; i < PassList.size(); ++i) {
242       const PassInfo *PassInf = PassList[i];
243       Pass *P = 0;
244
245       if (PassInf->getNormalCtor())
246                   P = PassInf->getNormalCtor()();
247           if (dynamic_cast<MachineFunctionPass*>(P) != 0) {
248                   cerr << PassInf->getPassName () << " is a machine function pass.\n";
249           } else {
250                   fpm->add (P);
251           }
252   }
253
254   return wrap(EE);
255 }
256
257 void
258 mono_llvm_dispose_ee (LLVMExecutionEngineRef ee)
259 {
260         delete unwrap (ee);
261
262         delete fpm;
263 }