2010-06-21 Rodrigo Kumpera <rkumpera@novell.com>
[mono.git] / mono / mini / mini-llvm-cpp.cpp
blob13fe73a37564637af26dc180f683db6a3a656872
1 //
2 // mini-llvm-cpp.cpp: C++ support classes for the mono LLVM integration
3 //
4 // (C) 2009 Novell, Inc.
5 //
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.
18 // Mono's internal header files are not C++ clean, so avoid including them if
19 // possible
22 #include <stdint.h>
24 #include <llvm/Support/raw_ostream.h>
25 #include <llvm/PassManager.h>
26 #include <llvm/ExecutionEngine/ExecutionEngine.h>
27 #include <llvm/ExecutionEngine/JITMemoryManager.h>
28 #include <llvm/ExecutionEngine/JITEventListener.h>
29 #include <llvm/Target/TargetOptions.h>
30 #include <llvm/Target/TargetData.h>
31 #include <llvm/Target/TargetRegisterInfo.h>
32 #include <llvm/Analysis/Verifier.h>
33 #include <llvm/Transforms/Scalar.h>
34 #include <llvm/Support/CommandLine.h>
35 #include "llvm/Support/PassNameParser.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include <llvm/CodeGen/Passes.h>
38 #include <llvm/CodeGen/MachineFunctionPass.h>
39 #include <llvm/CodeGen/MachineFunction.h>
40 #include <llvm/CodeGen/MachineFrameInfo.h>
41 //#include <llvm/LinkAllPasses.h>
43 #include "llvm-c/Core.h"
44 #include "llvm-c/ExecutionEngine.h"
46 #include "mini-llvm-cpp.h"
48 extern "C" void LLVMInitializeX86TargetInfo();
50 using namespace llvm;
52 class MonoJITMemoryManager : public JITMemoryManager
54 private:
55 JITMemoryManager *mm;
57 public:
58 /* Callbacks installed by mono */
59 AllocCodeMemoryCb *alloc_cb;
61 MonoJITMemoryManager ();
62 ~MonoJITMemoryManager ();
64 void setMemoryWritable (void);
66 void setMemoryExecutable (void);
68 void AllocateGOT();
70 unsigned char *getGOTBase() const {
71 return mm->getGOTBase ();
74 #if LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION < 7
75 void *getDlsymTable() const {
76 return mm->getDlsymTable ();
79 void SetDlsymTable(void *ptr);
80 #endif
82 void setPoisonMemory(bool) {
85 unsigned char *startFunctionBody(const Function *F,
86 uintptr_t &ActualSize);
88 unsigned char *allocateStub(const GlobalValue* F, unsigned StubSize,
89 unsigned Alignment);
91 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
92 unsigned char *FunctionEnd);
94 unsigned char *allocateSpace(intptr_t Size, unsigned Alignment);
96 uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment);
98 void deallocateMemForFunction(const Function *F);
100 unsigned char*startExceptionTable(const Function* F,
101 uintptr_t &ActualSize);
103 void endExceptionTable(const Function *F, unsigned char *TableStart,
104 unsigned char *TableEnd,
105 unsigned char* FrameRegister);
107 #if LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION >= 7
108 virtual void deallocateFunctionBody(void*) {
111 virtual void deallocateExceptionTable(void*) {
113 #endif
116 MonoJITMemoryManager::MonoJITMemoryManager ()
118 SizeRequired = true;
119 mm = JITMemoryManager::CreateDefaultMemManager ();
122 MonoJITMemoryManager::~MonoJITMemoryManager ()
126 void
127 MonoJITMemoryManager::setMemoryWritable (void)
131 void
132 MonoJITMemoryManager::setMemoryExecutable (void)
136 void
137 MonoJITMemoryManager::AllocateGOT()
139 mm->AllocateGOT ();
142 #if LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION < 7
143 void
144 MonoJITMemoryManager::SetDlsymTable(void *ptr)
146 mm->SetDlsymTable (ptr);
148 #endif
150 unsigned char *
151 MonoJITMemoryManager::startFunctionBody(const Function *F,
152 uintptr_t &ActualSize)
154 return alloc_cb (wrap (F), ActualSize);
157 unsigned char *
158 MonoJITMemoryManager::allocateStub(const GlobalValue* F, unsigned StubSize,
159 unsigned Alignment)
161 return alloc_cb (wrap (F), StubSize);
164 void
165 MonoJITMemoryManager::endFunctionBody(const Function *F, unsigned char *FunctionStart,
166 unsigned char *FunctionEnd)
170 unsigned char *
171 MonoJITMemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
173 return new unsigned char [Size];
176 uint8_t *
177 MonoJITMemoryManager::allocateGlobal(uintptr_t Size, unsigned Alignment)
179 return new unsigned char [Size];
182 void
183 MonoJITMemoryManager::deallocateMemForFunction(const Function *F)
187 unsigned char*
188 MonoJITMemoryManager::startExceptionTable(const Function* F,
189 uintptr_t &ActualSize)
191 return alloc_cb (wrap (F), ActualSize);
194 void
195 MonoJITMemoryManager::endExceptionTable(const Function *F, unsigned char *TableStart,
196 unsigned char *TableEnd,
197 unsigned char* FrameRegister)
201 static MonoJITMemoryManager *mono_mm;
203 static FunctionPassManager *fpm;
205 void
206 mono_llvm_optimize_method (LLVMValueRef method)
208 verifyFunction (*(unwrap<Function> (method)));
209 fpm->run (*unwrap<Function> (method));
212 void
213 mono_llvm_dump_value (LLVMValueRef value)
215 /* Same as LLVMDumpValue (), but print to stdout */
216 outs () << (*unwrap<Value> (value));
219 /* Missing overload for building an alloca with an alignment */
220 LLVMValueRef
221 mono_llvm_build_alloca (LLVMBuilderRef builder, LLVMTypeRef Ty,
222 LLVMValueRef ArraySize,
223 int alignment, const char *Name)
225 return wrap (unwrap (builder)->Insert (new AllocaInst (unwrap (Ty), unwrap (ArraySize), alignment), Name));
228 LLVMValueRef
229 mono_llvm_build_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
230 const char *Name, gboolean is_volatile)
232 return wrap(unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name));
235 LLVMValueRef
236 mono_llvm_build_aligned_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
237 const char *Name, gboolean is_volatile, int alignment)
239 LoadInst *ins;
241 ins = unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name);
242 ins->setAlignment (alignment);
244 return wrap(ins);
247 LLVMValueRef
248 mono_llvm_build_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
249 gboolean is_volatile)
251 return wrap(unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile));
254 void
255 mono_llvm_replace_uses_of (LLVMValueRef var, LLVMValueRef v)
257 Value *V = ConstantExpr::getTruncOrBitCast (unwrap<Constant> (v), unwrap (var)->getType ());
258 unwrap (var)->replaceAllUsesWith (V);
261 static cl::list<const PassInfo*, bool, PassNameParser>
262 PassList(cl::desc("Optimizations available:"));
264 class MonoJITEventListener : public JITEventListener {
266 public:
267 FunctionEmittedCb *emitted_cb;
269 MonoJITEventListener (FunctionEmittedCb *cb) {
270 emitted_cb = cb;
273 virtual void NotifyFunctionEmitted(const Function &F,
274 void *Code, size_t Size,
275 const EmittedFunctionDetails &Details) {
277 * X86TargetMachine::setCodeModelForJIT() sets the code model to Large on amd64,
278 * which means the JIT will generate calls of the form
279 * mov reg, <imm>
280 * call *reg
281 * Our trampoline code can't patch this. Passing CodeModel::Small to createJIT
282 * doesn't seem to work, we need Default. A discussion is here:
283 * http://lists.cs.uiuc.edu/pipermail/llvmdev/2009-December/027999.html
284 * There seems to no way to get the TargeMachine used by an EE either, so we
285 * install a profiler hook and reset the code model here.
286 * This should be inside an ifdef, but we can't include our config.h either,
287 * since its definitions conflict with LLVM's config.h.
290 //#if defined(TARGET_X86) || defined(TARGET_AMD64)
291 #ifndef LLVM_MONO_BRANCH
292 /* The LLVM mono branch contains a workaround, so this is not needed */
293 if (Details.MF->getTarget ().getCodeModel () == CodeModel::Large) {
294 Details.MF->getTarget ().setCodeModel (CodeModel::Default);
296 #endif
297 //#endif
299 emitted_cb (wrap (&F), Code, (char*)Code + Size);
303 LLVMExecutionEngineRef
304 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb)
306 std::string Error;
308 LLVMInitializeX86Target ();
309 LLVMInitializeX86TargetInfo ();
311 llvm::cl::ParseEnvironmentOptions("mono", "MONO_LLVM", "", false);
313 mono_mm = new MonoJITMemoryManager ();
314 mono_mm->alloc_cb = alloc_cb;
316 #if LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION < 8
317 DwarfExceptionHandling = true;
318 #else
319 JITExceptionHandling = true;
320 #endif
321 // PrettyStackTrace installs signal handlers which trip up libgc
322 DisablePrettyStackTrace = true;
324 ExecutionEngine *EE = ExecutionEngine::createJIT (unwrap (MP), &Error, mono_mm, CodeGenOpt::Default);
325 if (!EE) {
326 errs () << "Unable to create LLVM ExecutionEngine: " << Error << "\n";
327 g_assert_not_reached ();
329 EE->InstallExceptionTableRegister (exception_cb);
330 EE->RegisterJITEventListener (new MonoJITEventListener (emitted_cb));
332 fpm = new FunctionPassManager (unwrap (MP));
334 fpm->add(new TargetData(*EE->getTargetData()));
335 /* Add a random set of passes */
336 /* Make this run-time configurable */
337 fpm->add(createInstructionCombiningPass());
338 fpm->add(createReassociatePass());
339 fpm->add(createGVNPass());
340 fpm->add(createCFGSimplificationPass());
342 /* Add passes specified by the env variable */
343 /* FIXME: This can only add passes which are linked in, thus are already used */
344 for (unsigned i = 0; i < PassList.size(); ++i) {
345 const PassInfo *PassInf = PassList[i];
346 Pass *P = 0;
348 if (PassInf->getNormalCtor())
349 P = PassInf->getNormalCtor()();
350 fpm->add (P);
353 return wrap(EE);
356 void
357 mono_llvm_dispose_ee (LLVMExecutionEngineRef ee)
359 delete unwrap (ee);
361 delete fpm;