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
27 #include <llvm/Support/raw_ostream.h>
28 #include <llvm/Support/Host.h>
29 #include <llvm/PassManager.h>
30 #include <llvm/ExecutionEngine/ExecutionEngine.h>
31 #include <llvm/ExecutionEngine/JITMemoryManager.h>
32 #include <llvm/ExecutionEngine/JITEventListener.h>
33 #include <llvm/Target/TargetOptions.h>
34 #include <llvm/Target/TargetRegisterInfo.h>
35 #include <llvm/IR/Verifier.h>
36 #include <llvm/Analysis/Passes.h>
37 #include <llvm/Transforms/Scalar.h>
38 #include <llvm/Support/CommandLine.h>
39 #include "llvm/IR/LegacyPassNameParser.h"
40 #include "llvm/Support/PrettyStackTrace.h"
41 #include <llvm/CodeGen/Passes.h>
42 #include <llvm/CodeGen/MachineFunctionPass.h>
43 #include <llvm/CodeGen/MachineFunction.h>
44 #include <llvm/CodeGen/MachineFrameInfo.h>
45 #include <llvm/IR/Function.h>
46 #include <llvm/IR/IRBuilder.h>
47 #include <llvm/IR/Module.h>
48 //#include <llvm/LinkAllPasses.h>
50 #include "llvm-c/Core.h"
51 #include "llvm-c/ExecutionEngine.h"
53 #include "mini-llvm-cpp.h"
55 // extern "C" void LLVMInitializeARMTargetInfo();
56 // extern "C" void LLVMInitializeARMTarget ();
57 // extern "C" void LLVMInitializeARMTargetMC ();
61 #ifndef MONO_CROSS_COMPILE
63 class MonoJITMemoryManager : public JITMemoryManager
69 /* Callbacks installed by mono */
70 AllocCodeMemoryCb *alloc_cb;
72 ExceptionTableCb *exception_cb;
74 MonoJITMemoryManager ();
75 ~MonoJITMemoryManager ();
77 void setMemoryWritable (void);
79 void setMemoryExecutable (void);
83 unsigned char *getGOTBase() const {
84 return mm->getGOTBase ();
87 void setPoisonMemory(bool) {
90 unsigned char *startFunctionBody(const Function *F,
91 uintptr_t &ActualSize);
93 unsigned char *allocateStub(const GlobalValue* F, unsigned StubSize,
96 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
97 unsigned char *FunctionEnd);
99 unsigned char *allocateSpace(intptr_t Size, unsigned Alignment);
101 uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment);
103 void deallocateMemForFunction(const Function *F);
105 unsigned char*startExceptionTable(const Function* F,
106 uintptr_t &ActualSize);
108 void endExceptionTable(const Function *F, unsigned char *TableStart,
109 unsigned char *TableEnd,
110 unsigned char* FrameRegister);
112 virtual void deallocateFunctionBody(void*) {
115 virtual void deallocateExceptionTable(void*) {
118 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID,
119 StringRef SectionName) {
125 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID,
126 StringRef SectionName, bool IsReadOnly) {
132 virtual bool applyPermissions(std::string*) {
138 virtual bool finalizeMemory(std::string *ErrMsg = 0) {
144 virtual void* getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure) {
148 err = dlsym_cb (Name.c_str (), &res);
150 outs () << "Unable to resolve: " << Name << ": " << err << "\n";
158 MonoJITMemoryManager::MonoJITMemoryManager ()
160 mm = JITMemoryManager::CreateDefaultMemManager ();
163 MonoJITMemoryManager::~MonoJITMemoryManager ()
169 MonoJITMemoryManager::setMemoryWritable (void)
174 MonoJITMemoryManager::setMemoryExecutable (void)
179 MonoJITMemoryManager::AllocateGOT()
185 MonoJITMemoryManager::startFunctionBody(const Function *F,
186 uintptr_t &ActualSize)
188 // FIXME: This leaks memory
191 return alloc_cb (wrap (F), ActualSize);
195 MonoJITMemoryManager::allocateStub(const GlobalValue* F, unsigned StubSize,
198 return alloc_cb (wrap (F), StubSize);
202 MonoJITMemoryManager::endFunctionBody(const Function *F, unsigned char *FunctionStart,
203 unsigned char *FunctionEnd)
208 MonoJITMemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
210 return new unsigned char [Size];
214 MonoJITMemoryManager::allocateGlobal(uintptr_t Size, unsigned Alignment)
216 return new unsigned char [Size];
220 MonoJITMemoryManager::deallocateMemForFunction(const Function *F)
225 MonoJITMemoryManager::startExceptionTable(const Function* F,
226 uintptr_t &ActualSize)
228 return startFunctionBody(F, ActualSize);
232 MonoJITMemoryManager::endExceptionTable(const Function *F, unsigned char *TableStart,
233 unsigned char *TableEnd,
234 unsigned char* FrameRegister)
236 exception_cb (FrameRegister);
241 class MonoJITMemoryManager {
244 #endif /* !MONO_CROSS_COMPILE */
246 class MonoJITEventListener : public JITEventListener {
249 FunctionEmittedCb *emitted_cb;
251 MonoJITEventListener (FunctionEmittedCb *cb) {
255 virtual void NotifyFunctionEmitted(const Function &F,
256 void *Code, size_t Size,
257 const EmittedFunctionDetails &Details) {
258 emitted_cb (wrap (&F), Code, (char*)Code + Size);
265 MonoJITMemoryManager *mm;
266 MonoJITEventListener *listener;
267 FunctionPassManager *fpm;
271 mono_llvm_optimize_method (MonoEERef eeref, LLVMValueRef method)
273 MonoEE *mono_ee = (MonoEE*)eeref;
276 * The verifier does some checks on the whole module, leading to quadratic behavior.
278 //verifyFunction (*(unwrap<Function> (method)));
279 mono_ee->fpm->run (*unwrap<Function> (method));
283 mono_llvm_dump_value (LLVMValueRef value)
285 /* Same as LLVMDumpValue (), but print to stdout */
287 outs () << (*unwrap<Value> (value));
290 /* Missing overload for building an alloca with an alignment */
292 mono_llvm_build_alloca (LLVMBuilderRef builder, LLVMTypeRef Ty,
293 LLVMValueRef ArraySize,
294 int alignment, const char *Name)
296 return wrap (unwrap (builder)->Insert (new AllocaInst (unwrap (Ty), unwrap (ArraySize), alignment), Name));
300 mono_llvm_build_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
301 const char *Name, gboolean is_volatile, BarrierKind barrier)
303 LoadInst *ins = unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name);
306 case LLVM_BARRIER_NONE:
308 case LLVM_BARRIER_ACQ:
309 ins->setOrdering(Acquire);
311 case LLVM_BARRIER_SEQ:
312 ins->setOrdering(SequentiallyConsistent);
315 g_assert_not_reached ();
323 mono_llvm_build_aligned_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
324 const char *Name, gboolean is_volatile, int alignment)
328 ins = unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name);
329 ins->setAlignment (alignment);
335 mono_llvm_build_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
336 gboolean is_volatile, BarrierKind barrier)
338 StoreInst *ins = unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile);
341 case LLVM_BARRIER_NONE:
343 case LLVM_BARRIER_REL:
344 ins->setOrdering(Release);
346 case LLVM_BARRIER_SEQ:
347 ins->setOrdering(SequentiallyConsistent);
350 g_assert_not_reached ();
358 mono_llvm_build_aligned_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
359 gboolean is_volatile, int alignment)
363 ins = unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile);
364 ins->setAlignment (alignment);
370 mono_llvm_build_cmpxchg (LLVMBuilderRef builder, LLVMValueRef ptr, LLVMValueRef cmp, LLVMValueRef val)
372 AtomicCmpXchgInst *ins;
374 ins = unwrap(builder)->CreateAtomicCmpXchg (unwrap(ptr), unwrap (cmp), unwrap (val), SequentiallyConsistent, SequentiallyConsistent);
379 mono_llvm_build_atomic_rmw (LLVMBuilderRef builder, AtomicRMWOp op, LLVMValueRef ptr, LLVMValueRef val)
381 AtomicRMWInst::BinOp aop = AtomicRMWInst::Xchg;
385 case LLVM_ATOMICRMW_OP_XCHG:
386 aop = AtomicRMWInst::Xchg;
388 case LLVM_ATOMICRMW_OP_ADD:
389 aop = AtomicRMWInst::Add;
392 g_assert_not_reached ();
396 ins = unwrap (builder)->CreateAtomicRMW (aop, unwrap (ptr), unwrap (val), SequentiallyConsistent);
401 mono_llvm_build_fence (LLVMBuilderRef builder, BarrierKind kind)
404 AtomicOrdering ordering;
406 g_assert (kind != LLVM_BARRIER_NONE);
409 case LLVM_BARRIER_ACQ:
412 case LLVM_BARRIER_REL:
415 case LLVM_BARRIER_SEQ:
416 ordering = SequentiallyConsistent;
419 g_assert_not_reached ();
423 ins = unwrap (builder)->CreateFence (ordering);
428 mono_llvm_set_must_tail (LLVMValueRef call_ins)
430 CallInst *ins = (CallInst*)unwrap (call_ins);
432 ins->setTailCallKind (CallInst::TailCallKind::TCK_MustTail);
436 mono_llvm_replace_uses_of (LLVMValueRef var, LLVMValueRef v)
438 Value *V = ConstantExpr::getTruncOrBitCast (unwrap<Constant> (v), unwrap (var)->getType ());
439 unwrap (var)->replaceAllUsesWith (V);
443 mono_llvm_create_constant_data_array (const uint8_t *data, int len)
445 return wrap(ConstantDataArray::get (*unwrap(LLVMGetGlobalContext ()), makeArrayRef(data, len)));
448 static cl::list<const PassInfo*, bool, PassNameParser>
449 PassList(cl::desc("Optimizations available:"));
452 force_pass_linking (void)
454 // Make sure the rest is linked in, but never executed
455 if (g_getenv ("FOO") != (char*)-1)
458 // This is a subset of the passes in LinkAllPasses.h
459 // The utility passes and the interprocedural passes are commented out
461 (void) llvm::createAAEvalPass();
462 (void) llvm::createAggressiveDCEPass();
463 (void) llvm::createAliasAnalysisCounterPass();
464 (void) llvm::createAliasDebugger();
466 (void) llvm::createArgumentPromotionPass();
467 (void) llvm::createStructRetPromotionPass();
469 (void) llvm::createBasicAliasAnalysisPass();
470 (void) llvm::createLibCallAliasAnalysisPass(0);
471 (void) llvm::createScalarEvolutionAliasAnalysisPass();
472 //(void) llvm::createBlockPlacementPass();
473 (void) llvm::createBreakCriticalEdgesPass();
474 (void) llvm::createCFGSimplificationPass();
476 (void) llvm::createConstantMergePass();
477 (void) llvm::createConstantPropagationPass();
480 (void) llvm::createDeadArgEliminationPass();
482 (void) llvm::createDeadCodeEliminationPass();
483 (void) llvm::createDeadInstEliminationPass();
484 (void) llvm::createDeadStoreEliminationPass();
486 (void) llvm::createDeadTypeEliminationPass();
487 (void) llvm::createDomOnlyPrinterPass();
488 (void) llvm::createDomPrinterPass();
489 (void) llvm::createDomOnlyViewerPass();
490 (void) llvm::createDomViewerPass();
491 (void) llvm::createEdgeProfilerPass();
492 (void) llvm::createOptimalEdgeProfilerPass();
493 (void) llvm::createFunctionInliningPass();
494 (void) llvm::createAlwaysInlinerPass();
495 (void) llvm::createGlobalDCEPass();
496 (void) llvm::createGlobalOptimizerPass();
497 (void) llvm::createGlobalsModRefPass();
498 (void) llvm::createIPConstantPropagationPass();
499 (void) llvm::createIPSCCPPass();
501 (void) llvm::createIndVarSimplifyPass();
502 (void) llvm::createInstructionCombiningPass();
504 (void) llvm::createInternalizePass(false);
506 (void) llvm::createLCSSAPass();
507 (void) llvm::createLICMPass();
508 (void) llvm::createLazyValueInfoPass();
509 //(void) llvm::createLoopDependenceAnalysisPass();
511 (void) llvm::createLoopExtractorPass();
513 (void) llvm::createLoopSimplifyPass();
514 (void) llvm::createLoopStrengthReducePass();
515 (void) llvm::createLoopUnrollPass();
516 (void) llvm::createLoopUnswitchPass();
517 (void) llvm::createLoopRotatePass();
518 (void) llvm::createLowerInvokePass();
520 (void) llvm::createLowerSetJmpPass();
522 (void) llvm::createLowerSwitchPass();
523 (void) llvm::createNoAAPass();
525 (void) llvm::createNoProfileInfoPass();
526 (void) llvm::createProfileEstimatorPass();
527 (void) llvm::createProfileVerifierPass();
528 (void) llvm::createProfileLoaderPass();
530 (void) llvm::createPromoteMemoryToRegisterPass();
531 (void) llvm::createDemoteRegisterToMemoryPass();
533 (void) llvm::createPruneEHPass();
534 (void) llvm::createPostDomOnlyPrinterPass();
535 (void) llvm::createPostDomPrinterPass();
536 (void) llvm::createPostDomOnlyViewerPass();
537 (void) llvm::createPostDomViewerPass();
539 (void) llvm::createReassociatePass();
540 (void) llvm::createSCCPPass();
541 (void) llvm::createScalarReplAggregatesPass();
542 //(void) llvm::createSimplifyLibCallsPass();
544 (void) llvm::createSingleLoopExtractorPass();
545 (void) llvm::createStripSymbolsPass();
546 (void) llvm::createStripNonDebugSymbolsPass();
547 (void) llvm::createStripDeadDebugInfoPass();
548 (void) llvm::createStripDeadPrototypesPass();
549 (void) llvm::createTailCallEliminationPass();
550 (void) llvm::createTailDuplicationPass();
551 (void) llvm::createJumpThreadingPass();
554 (void) llvm::createUnifyFunctionExitNodesPass();
556 (void) llvm::createInstCountPass();
557 (void) llvm::createCodeGenPreparePass();
558 (void) llvm::createGVNPass();
559 (void) llvm::createMemCpyOptPass();
560 (void) llvm::createLoopDeletionPass();
562 (void) llvm::createPostDomTree();
563 (void) llvm::createPostDomFrontier();
564 (void) llvm::createInstructionNamerPass();
565 (void) llvm::createPartialSpecializationPass();
566 (void) llvm::createFunctionAttrsPass();
567 (void) llvm::createMergeFunctionsPass();
568 (void) llvm::createPrintModulePass(0);
569 (void) llvm::createPrintFunctionPass("", 0);
570 (void) llvm::createDbgInfoPrinterPass();
571 (void) llvm::createModuleDebugInfoPrinterPass();
572 (void) llvm::createPartialInliningPass();
573 (void) llvm::createGEPSplitterPass();
574 (void) llvm::createLintPass();
576 (void) llvm::createSinkingPass();
579 #ifndef MONO_CROSS_COMPILE
581 static gboolean inited;
589 force_pass_linking ();
592 LLVMInitializeARMTarget ();
593 LLVMInitializeARMTargetInfo ();
594 LLVMInitializeARMTargetMC ();
596 LLVMInitializeX86Target ();
597 LLVMInitializeX86TargetInfo ();
598 LLVMInitializeX86TargetMC ();
601 PassRegistry &Registry = *PassRegistry::getPassRegistry();
602 initializeCore(Registry);
603 initializeScalarOpts(Registry);
604 initializeAnalysis(Registry);
605 initializeIPA(Registry);
606 initializeTransformUtils(Registry);
607 initializeInstCombine(Registry);
608 initializeTarget(Registry);
610 llvm::cl::ParseEnvironmentOptions("mono", "MONO_LLVM", "");
616 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb, DlSymCb *dlsym_cb, LLVMExecutionEngineRef *ee)
623 mono_ee = new MonoEE ();
625 MonoJITMemoryManager *mono_mm = new MonoJITMemoryManager ();
626 mono_mm->alloc_cb = alloc_cb;
627 mono_mm->dlsym_cb = dlsym_cb;
628 mono_mm->exception_cb = exception_cb;
629 mono_ee->mm = mono_mm;
632 * The Default code model doesn't seem to work on amd64,
633 * test_0_fields_with_big_offsets (among others) crashes, because LLVM tries to call
634 * memset using a normal pcrel code which is in 32bit memory, while memset isn't.
638 opts.JITExceptionHandling = 1;
640 StringRef cpu_name = sys::getHostCPUName ();
642 // EngineBuilder no longer has a copy assignment operator (?)
643 std::unique_ptr<Module> Owner(unwrap(MP));
644 EngineBuilder b (std::move(Owner));
646 ExecutionEngine *EE = b.setJITMemoryManager (mono_mm).setTargetOptions (opts).setAllocateGVsWithCode (true).setMCPU (cpu_name).setCodeModel (CodeModel::Large).create ();
648 ExecutionEngine *EE = b.setJITMemoryManager (mono_mm).setTargetOptions (opts).setAllocateGVsWithCode (true).setMCPU (cpu_name).create ();
654 MonoJITEventListener *listener = new MonoJITEventListener (emitted_cb);
655 EE->RegisterJITEventListener (listener);
656 mono_ee->listener = listener;
658 FunctionPassManager *fpm = new FunctionPassManager (unwrap (MP));
661 fpm->add(new DataLayoutPass(*EE->getDataLayout()));
663 if (PassList.size() > 0) {
664 /* Use the passes specified by the env variable */
665 /* Only the passes in force_pass_linking () can be used */
666 for (unsigned i = 0; i < PassList.size(); ++i) {
667 const PassInfo *PassInf = PassList[i];
670 if (PassInf->getNormalCtor())
671 P = PassInf->getNormalCtor()();
675 /* Use the same passes used by 'opt' by default, without the ipo passes */
676 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";
680 args = g_strsplit (opts, " ", 1000);
681 for (i = 0; args [i]; i++)
683 llvm::cl::ParseCommandLineOptions (i, args, "");
686 for (unsigned i = 0; i < PassList.size(); ++i) {
687 const PassInfo *PassInf = PassList[i];
690 if (PassInf->getNormalCtor())
691 P = PassInf->getNormalCtor()();
692 g_assert (P->getPassKind () == llvm::PT_Function || P->getPassKind () == llvm::PT_Loop);
697 fpm->add(createInstructionCombiningPass());
698 fpm->add(createReassociatePass());
699 fpm->add(createGVNPass());
700 fpm->add(createCFGSimplificationPass());
710 mono_llvm_dispose_ee (MonoEERef *eeref)
712 MonoEE *mono_ee = (MonoEE*)eeref;
716 //delete mono_ee->mm;
717 delete mono_ee->listener;
724 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb, DlSymCb *dlsym_cb, LLVMExecutionEngineRef *ee)
726 g_assert_not_reached ();
731 mono_llvm_dispose_ee (MonoEERef *eeref)
733 g_assert_not_reached ();
738 LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
741 g_assert_not_reached ();
745 LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global)
747 g_assert_not_reached ();
751 #endif /* !MONO_CROSS_COMPILE */