2 // mini-llvm-cpp.cpp: C++ support classes for the mono LLVM integration
4 // (C) 2009-2011 Novell, Inc.
5 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
9 // We need to override some stuff in LLVM, but this cannot be done using the C
10 // interface, so we have to use some C++ code here.
11 // The things which we override are:
12 // - the default JIT code manager used by LLVM doesn't allocate memory using
13 // MAP_32BIT, we require it.
14 // - add some callbacks so we can obtain the size of methods and their exception
19 // Mono's internal header files are not C++ clean, so avoid including them if
24 //undef those as llvm defines them on its own config.h as well.
25 #undef PACKAGE_BUGREPORT
28 #undef PACKAGE_TARNAME
29 #undef PACKAGE_VERSION
33 #include <llvm/Support/raw_ostream.h>
34 #include <llvm/PassManager.h>
35 #include <llvm/ExecutionEngine/ExecutionEngine.h>
36 #include <llvm/ExecutionEngine/JITMemoryManager.h>
37 #include <llvm/ExecutionEngine/JITEventListener.h>
38 #include <llvm/Target/TargetOptions.h>
39 #include <llvm/Target/TargetRegisterInfo.h>
40 #if LLVM_API_VERSION >= 1
41 #include <llvm/IR/Verifier.h>
43 #include <llvm/Analysis/Verifier.h>
45 #include <llvm/Analysis/Passes.h>
46 #include <llvm/Transforms/Scalar.h>
47 #include <llvm/Support/CommandLine.h>
48 #if LLVM_API_VERSION >= 1
49 #include "llvm/IR/LegacyPassNameParser.h"
51 #include "llvm/Support/PassNameParser.h"
53 #include "llvm/Support/PrettyStackTrace.h"
54 #include <llvm/CodeGen/Passes.h>
55 #include <llvm/CodeGen/MachineFunctionPass.h>
56 #include <llvm/CodeGen/MachineFunction.h>
57 #include <llvm/CodeGen/MachineFrameInfo.h>
58 #include <llvm/IR/Function.h>
59 #include <llvm/IR/IRBuilder.h>
60 #include <llvm/IR/Module.h>
61 //#include <llvm/LinkAllPasses.h>
63 #include "llvm-c/Core.h"
64 #include "llvm-c/ExecutionEngine.h"
66 #include "mini-llvm-cpp.h"
68 #define LLVM_CHECK_VERSION(major,minor) \
69 ((LLVM_MAJOR_VERSION > (major)) || \
70 ((LLVM_MAJOR_VERSION == (major)) && (LLVM_MINOR_VERSION >= (minor))))
72 // extern "C" void LLVMInitializeARMTargetInfo();
73 // extern "C" void LLVMInitializeARMTarget ();
74 // extern "C" void LLVMInitializeARMTargetMC ();
78 #ifndef MONO_CROSS_COMPILE
80 class MonoJITMemoryManager : public JITMemoryManager
86 /* Callbacks installed by mono */
87 AllocCodeMemoryCb *alloc_cb;
90 MonoJITMemoryManager ();
91 ~MonoJITMemoryManager ();
93 void setMemoryWritable (void);
95 void setMemoryExecutable (void);
99 unsigned char *getGOTBase() const {
100 return mm->getGOTBase ();
103 void setPoisonMemory(bool) {
106 unsigned char *startFunctionBody(const Function *F,
107 uintptr_t &ActualSize);
109 unsigned char *allocateStub(const GlobalValue* F, unsigned StubSize,
112 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
113 unsigned char *FunctionEnd);
115 unsigned char *allocateSpace(intptr_t Size, unsigned Alignment);
117 uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment);
119 void deallocateMemForFunction(const Function *F);
121 unsigned char*startExceptionTable(const Function* F,
122 uintptr_t &ActualSize);
124 void endExceptionTable(const Function *F, unsigned char *TableStart,
125 unsigned char *TableEnd,
126 unsigned char* FrameRegister);
128 virtual void deallocateFunctionBody(void*) {
131 virtual void deallocateExceptionTable(void*) {
134 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID,
135 StringRef SectionName) {
141 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID,
142 StringRef SectionName, bool IsReadOnly) {
148 virtual bool applyPermissions(std::string*) {
154 virtual bool finalizeMemory(std::string *ErrMsg = 0) {
160 virtual void* getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure) {
164 err = dlsym_cb (Name.c_str (), &res);
166 outs () << "Unable to resolve: " << Name << ": " << err << "\n";
174 MonoJITMemoryManager::MonoJITMemoryManager ()
176 mm = JITMemoryManager::CreateDefaultMemManager ();
179 MonoJITMemoryManager::~MonoJITMemoryManager ()
185 MonoJITMemoryManager::setMemoryWritable (void)
190 MonoJITMemoryManager::setMemoryExecutable (void)
195 MonoJITMemoryManager::AllocateGOT()
201 MonoJITMemoryManager::startFunctionBody(const Function *F,
202 uintptr_t &ActualSize)
204 // FIXME: This leaks memory
207 return alloc_cb (wrap (F), ActualSize);
211 MonoJITMemoryManager::allocateStub(const GlobalValue* F, unsigned StubSize,
214 return alloc_cb (wrap (F), StubSize);
218 MonoJITMemoryManager::endFunctionBody(const Function *F, unsigned char *FunctionStart,
219 unsigned char *FunctionEnd)
224 MonoJITMemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
226 return new unsigned char [Size];
230 MonoJITMemoryManager::allocateGlobal(uintptr_t Size, unsigned Alignment)
232 return new unsigned char [Size];
236 MonoJITMemoryManager::deallocateMemForFunction(const Function *F)
241 MonoJITMemoryManager::startExceptionTable(const Function* F,
242 uintptr_t &ActualSize)
244 return startFunctionBody(F, ActualSize);
248 MonoJITMemoryManager::endExceptionTable(const Function *F, unsigned char *TableStart,
249 unsigned char *TableEnd,
250 unsigned char* FrameRegister)
256 class MonoJITMemoryManager {
259 #endif /* !MONO_CROSS_COMPILE */
261 class MonoJITEventListener : public JITEventListener {
264 FunctionEmittedCb *emitted_cb;
266 MonoJITEventListener (FunctionEmittedCb *cb) {
270 virtual void NotifyFunctionEmitted(const Function &F,
271 void *Code, size_t Size,
272 const EmittedFunctionDetails &Details) {
274 * X86TargetMachine::setCodeModelForJIT() sets the code model to Large on amd64,
275 * which means the JIT will generate calls of the form
278 * Our trampoline code can't patch this. Passing CodeModel::Small to createJIT
279 * doesn't seem to work, we need Default. A discussion is here:
280 * http://lists.cs.uiuc.edu/pipermail/llvmdev/2009-December/027999.html
281 * There seems to no way to get the TargeMachine used by an EE either, so we
282 * install a profiler hook and reset the code model here.
283 * This should be inside an ifdef, but we can't include our config.h either,
284 * since its definitions conflict with LLVM's config.h.
285 * The LLVM mono branch contains a workaround.
287 emitted_cb (wrap (&F), Code, (char*)Code + Size);
294 MonoJITMemoryManager *mm;
295 MonoJITEventListener *listener;
296 FunctionPassManager *fpm;
300 mono_llvm_optimize_method (MonoEERef eeref, LLVMValueRef method)
302 MonoEE *mono_ee = (MonoEE*)eeref;
305 * The verifier does some checks on the whole module, leading to quadratic behavior.
307 //verifyFunction (*(unwrap<Function> (method)));
308 mono_ee->fpm->run (*unwrap<Function> (method));
312 mono_llvm_dump_value (LLVMValueRef value)
314 /* Same as LLVMDumpValue (), but print to stdout */
316 outs () << (*unwrap<Value> (value));
319 /* Missing overload for building an alloca with an alignment */
321 mono_llvm_build_alloca (LLVMBuilderRef builder, LLVMTypeRef Ty,
322 LLVMValueRef ArraySize,
323 int alignment, const char *Name)
325 return wrap (unwrap (builder)->Insert (new AllocaInst (unwrap (Ty), unwrap (ArraySize), alignment), Name));
329 mono_llvm_build_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
330 const char *Name, gboolean is_volatile)
332 return wrap(unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name));
336 mono_llvm_build_aligned_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
337 const char *Name, gboolean is_volatile, int alignment)
341 ins = unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name);
342 ins->setAlignment (alignment);
348 mono_llvm_build_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
349 gboolean is_volatile)
351 return wrap(unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile));
355 mono_llvm_build_aligned_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
356 gboolean is_volatile, int alignment)
360 ins = unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile);
361 ins->setAlignment (alignment);
367 mono_llvm_build_cmpxchg (LLVMBuilderRef builder, LLVMValueRef ptr, LLVMValueRef cmp, LLVMValueRef val)
369 AtomicCmpXchgInst *ins;
371 #if LLVM_API_VERSION >= 1
372 ins = unwrap(builder)->CreateAtomicCmpXchg (unwrap(ptr), unwrap (cmp), unwrap (val), SequentiallyConsistent, SequentiallyConsistent);
374 ins = unwrap(builder)->CreateAtomicCmpXchg (unwrap(ptr), unwrap (cmp), unwrap (val), SequentiallyConsistent);
380 mono_llvm_build_atomic_rmw (LLVMBuilderRef builder, AtomicRMWOp op, LLVMValueRef ptr, LLVMValueRef val)
382 AtomicRMWInst::BinOp aop = AtomicRMWInst::Xchg;
386 case LLVM_ATOMICRMW_OP_XCHG:
387 aop = AtomicRMWInst::Xchg;
389 case LLVM_ATOMICRMW_OP_ADD:
390 aop = AtomicRMWInst::Add;
393 g_assert_not_reached ();
397 ins = unwrap (builder)->CreateAtomicRMW (aop, unwrap (ptr), unwrap (val), AcquireRelease);
402 mono_llvm_build_fence (LLVMBuilderRef builder)
406 ins = unwrap (builder)->CreateFence (AcquireRelease);
411 mono_llvm_replace_uses_of (LLVMValueRef var, LLVMValueRef v)
413 Value *V = ConstantExpr::getTruncOrBitCast (unwrap<Constant> (v), unwrap (var)->getType ());
414 unwrap (var)->replaceAllUsesWith (V);
417 static cl::list<const PassInfo*, bool, PassNameParser>
418 PassList(cl::desc("Optimizations available:"));
421 force_pass_linking (void)
423 // Make sure the rest is linked in, but never executed
424 if (g_getenv ("FOO") != (char*)-1)
427 // This is a subset of the passes in LinkAllPasses.h
428 // The utility passes and the interprocedural passes are commented out
430 (void) llvm::createAAEvalPass();
431 (void) llvm::createAggressiveDCEPass();
432 (void) llvm::createAliasAnalysisCounterPass();
433 (void) llvm::createAliasDebugger();
435 (void) llvm::createArgumentPromotionPass();
436 (void) llvm::createStructRetPromotionPass();
438 (void) llvm::createBasicAliasAnalysisPass();
439 (void) llvm::createLibCallAliasAnalysisPass(0);
440 (void) llvm::createScalarEvolutionAliasAnalysisPass();
441 //(void) llvm::createBlockPlacementPass();
442 (void) llvm::createBreakCriticalEdgesPass();
443 (void) llvm::createCFGSimplificationPass();
445 (void) llvm::createConstantMergePass();
446 (void) llvm::createConstantPropagationPass();
449 (void) llvm::createDeadArgEliminationPass();
451 (void) llvm::createDeadCodeEliminationPass();
452 (void) llvm::createDeadInstEliminationPass();
453 (void) llvm::createDeadStoreEliminationPass();
455 (void) llvm::createDeadTypeEliminationPass();
456 (void) llvm::createDomOnlyPrinterPass();
457 (void) llvm::createDomPrinterPass();
458 (void) llvm::createDomOnlyViewerPass();
459 (void) llvm::createDomViewerPass();
460 (void) llvm::createEdgeProfilerPass();
461 (void) llvm::createOptimalEdgeProfilerPass();
462 (void) llvm::createFunctionInliningPass();
463 (void) llvm::createAlwaysInlinerPass();
464 (void) llvm::createGlobalDCEPass();
465 (void) llvm::createGlobalOptimizerPass();
466 (void) llvm::createGlobalsModRefPass();
467 (void) llvm::createIPConstantPropagationPass();
468 (void) llvm::createIPSCCPPass();
470 (void) llvm::createIndVarSimplifyPass();
471 (void) llvm::createInstructionCombiningPass();
473 (void) llvm::createInternalizePass(false);
475 (void) llvm::createLCSSAPass();
476 (void) llvm::createLICMPass();
477 (void) llvm::createLazyValueInfoPass();
478 //(void) llvm::createLoopDependenceAnalysisPass();
480 (void) llvm::createLoopExtractorPass();
482 (void) llvm::createLoopSimplifyPass();
483 (void) llvm::createLoopStrengthReducePass();
484 (void) llvm::createLoopUnrollPass();
485 (void) llvm::createLoopUnswitchPass();
486 (void) llvm::createLoopRotatePass();
487 (void) llvm::createLowerInvokePass();
489 (void) llvm::createLowerSetJmpPass();
491 (void) llvm::createLowerSwitchPass();
492 (void) llvm::createNoAAPass();
494 (void) llvm::createNoProfileInfoPass();
495 (void) llvm::createProfileEstimatorPass();
496 (void) llvm::createProfileVerifierPass();
497 (void) llvm::createProfileLoaderPass();
499 (void) llvm::createPromoteMemoryToRegisterPass();
500 (void) llvm::createDemoteRegisterToMemoryPass();
502 (void) llvm::createPruneEHPass();
503 (void) llvm::createPostDomOnlyPrinterPass();
504 (void) llvm::createPostDomPrinterPass();
505 (void) llvm::createPostDomOnlyViewerPass();
506 (void) llvm::createPostDomViewerPass();
508 (void) llvm::createReassociatePass();
509 (void) llvm::createSCCPPass();
510 (void) llvm::createScalarReplAggregatesPass();
511 //(void) llvm::createSimplifyLibCallsPass();
513 (void) llvm::createSingleLoopExtractorPass();
514 (void) llvm::createStripSymbolsPass();
515 (void) llvm::createStripNonDebugSymbolsPass();
516 (void) llvm::createStripDeadDebugInfoPass();
517 (void) llvm::createStripDeadPrototypesPass();
518 (void) llvm::createTailCallEliminationPass();
519 (void) llvm::createTailDuplicationPass();
520 (void) llvm::createJumpThreadingPass();
523 (void) llvm::createUnifyFunctionExitNodesPass();
525 (void) llvm::createInstCountPass();
526 (void) llvm::createCodeGenPreparePass();
527 (void) llvm::createGVNPass();
528 (void) llvm::createMemCpyOptPass();
529 (void) llvm::createLoopDeletionPass();
531 (void) llvm::createPostDomTree();
532 (void) llvm::createPostDomFrontier();
533 (void) llvm::createInstructionNamerPass();
534 (void) llvm::createPartialSpecializationPass();
535 (void) llvm::createFunctionAttrsPass();
536 (void) llvm::createMergeFunctionsPass();
537 (void) llvm::createPrintModulePass(0);
538 (void) llvm::createPrintFunctionPass("", 0);
539 (void) llvm::createDbgInfoPrinterPass();
540 (void) llvm::createModuleDebugInfoPrinterPass();
541 (void) llvm::createPartialInliningPass();
542 (void) llvm::createGEPSplitterPass();
543 (void) llvm::createLintPass();
545 (void) llvm::createSinkingPass();
548 #ifndef MONO_CROSS_COMPILE
550 static gboolean inited;
558 force_pass_linking ();
561 LLVMInitializeARMTarget ();
562 LLVMInitializeARMTargetInfo ();
563 LLVMInitializeARMTargetMC ();
565 LLVMInitializeX86Target ();
566 LLVMInitializeX86TargetInfo ();
567 LLVMInitializeX86TargetMC ();
570 PassRegistry &Registry = *PassRegistry::getPassRegistry();
571 initializeCore(Registry);
572 initializeScalarOpts(Registry);
573 initializeAnalysis(Registry);
574 initializeIPA(Registry);
575 initializeTransformUtils(Registry);
576 initializeInstCombine(Registry);
577 initializeTarget(Registry);
579 llvm::cl::ParseEnvironmentOptions("mono", "MONO_LLVM", "");
585 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb, DlSymCb *dlsym_cb, LLVMExecutionEngineRef *ee)
592 mono_ee = new MonoEE ();
594 MonoJITMemoryManager *mono_mm = new MonoJITMemoryManager ();
595 mono_mm->alloc_cb = alloc_cb;
596 mono_mm->dlsym_cb = dlsym_cb;
597 mono_ee->mm = mono_mm;
600 * The Default code model doesn't seem to work on amd64,
601 * test_0_fields_with_big_offsets (among others) crashes, because LLVM tries to call
602 * memset using a normal pcrel code which is in 32bit memory, while memset isn't.
606 opts.JITExceptionHandling = 1;
608 EngineBuilder b (unwrap (MP));
610 ExecutionEngine *EE = b.setJITMemoryManager (mono_mm).setTargetOptions (opts).setCodeModel (CodeModel::Large).setAllocateGVsWithCode (true).create ();
612 ExecutionEngine *EE = b.setJITMemoryManager (mono_mm).setTargetOptions (opts).setAllocateGVsWithCode (true).create ();
617 EE->InstallExceptionTableRegister (exception_cb);
618 MonoJITEventListener *listener = new MonoJITEventListener (emitted_cb);
619 EE->RegisterJITEventListener (listener);
620 mono_ee->listener = listener;
622 FunctionPassManager *fpm = new FunctionPassManager (unwrap (MP));
625 #if LLVM_API_VERSION >= 1
626 fpm->add(new DataLayoutPass(*EE->getDataLayout()));
628 fpm->add(new DataLayout(*EE->getDataLayout()));
631 if (PassList.size() > 0) {
632 /* Use the passes specified by the env variable */
633 /* Only the passes in force_pass_linking () can be used */
634 for (unsigned i = 0; i < PassList.size(); ++i) {
635 const PassInfo *PassInf = PassList[i];
638 if (PassInf->getNormalCtor())
639 P = PassInf->getNormalCtor()();
643 /* Use the same passes used by 'opt' by default, without the ipo passes */
644 const char *opts = "-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -gvn -simplifycfg";
648 args = g_strsplit (opts, " ", 1000);
649 for (i = 0; args [i]; i++)
651 llvm::cl::ParseCommandLineOptions (i, args, "");
654 for (unsigned i = 0; i < PassList.size(); ++i) {
655 const PassInfo *PassInf = PassList[i];
658 if (PassInf->getNormalCtor())
659 P = PassInf->getNormalCtor()();
660 g_assert (P->getPassKind () == llvm::PT_Function || P->getPassKind () == llvm::PT_Loop);
665 fpm->add(createInstructionCombiningPass());
666 fpm->add(createReassociatePass());
667 fpm->add(createGVNPass());
668 fpm->add(createCFGSimplificationPass());
678 mono_llvm_dispose_ee (MonoEERef *eeref)
680 MonoEE *mono_ee = (MonoEE*)eeref;
684 //delete mono_ee->mm;
685 delete mono_ee->listener;
692 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb, DlSymCb *dlsym_cb, LLVMExecutionEngineRef *ee)
694 g_assert_not_reached ();
699 mono_llvm_dispose_ee (MonoEERef *eeref)
701 g_assert_not_reached ();
706 LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
709 g_assert_not_reached ();
713 LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global)
715 g_assert_not_reached ();
719 #endif /* !MONO_CROSS_COMPILE */