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;
73 MonoJITMemoryManager ();
74 ~MonoJITMemoryManager ();
76 void setMemoryWritable (void);
78 void setMemoryExecutable (void);
82 unsigned char *getGOTBase() const {
83 return mm->getGOTBase ();
86 void setPoisonMemory(bool) {
89 unsigned char *startFunctionBody(const Function *F,
90 uintptr_t &ActualSize);
92 unsigned char *allocateStub(const GlobalValue* F, unsigned StubSize,
95 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
96 unsigned char *FunctionEnd);
98 unsigned char *allocateSpace(intptr_t Size, unsigned Alignment);
100 uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment);
102 void deallocateMemForFunction(const Function *F);
104 unsigned char*startExceptionTable(const Function* F,
105 uintptr_t &ActualSize);
107 void endExceptionTable(const Function *F, unsigned char *TableStart,
108 unsigned char *TableEnd,
109 unsigned char* FrameRegister);
111 virtual void deallocateFunctionBody(void*) {
114 virtual void deallocateExceptionTable(void*) {
117 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID,
118 StringRef SectionName) {
124 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID,
125 StringRef SectionName, bool IsReadOnly) {
131 virtual bool applyPermissions(std::string*) {
137 virtual bool finalizeMemory(std::string *ErrMsg = 0) {
143 virtual void* getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure) {
147 err = dlsym_cb (Name.c_str (), &res);
149 outs () << "Unable to resolve: " << Name << ": " << err << "\n";
157 MonoJITMemoryManager::MonoJITMemoryManager ()
159 mm = JITMemoryManager::CreateDefaultMemManager ();
162 MonoJITMemoryManager::~MonoJITMemoryManager ()
168 MonoJITMemoryManager::setMemoryWritable (void)
173 MonoJITMemoryManager::setMemoryExecutable (void)
178 MonoJITMemoryManager::AllocateGOT()
184 MonoJITMemoryManager::startFunctionBody(const Function *F,
185 uintptr_t &ActualSize)
187 // FIXME: This leaks memory
190 return alloc_cb (wrap (F), ActualSize);
194 MonoJITMemoryManager::allocateStub(const GlobalValue* F, unsigned StubSize,
197 return alloc_cb (wrap (F), StubSize);
201 MonoJITMemoryManager::endFunctionBody(const Function *F, unsigned char *FunctionStart,
202 unsigned char *FunctionEnd)
207 MonoJITMemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
209 return new unsigned char [Size];
213 MonoJITMemoryManager::allocateGlobal(uintptr_t Size, unsigned Alignment)
215 return new unsigned char [Size];
219 MonoJITMemoryManager::deallocateMemForFunction(const Function *F)
224 MonoJITMemoryManager::startExceptionTable(const Function* F,
225 uintptr_t &ActualSize)
227 return startFunctionBody(F, ActualSize);
231 MonoJITMemoryManager::endExceptionTable(const Function *F, unsigned char *TableStart,
232 unsigned char *TableEnd,
233 unsigned char* FrameRegister)
239 class MonoJITMemoryManager {
242 #endif /* !MONO_CROSS_COMPILE */
244 class MonoJITEventListener : public JITEventListener {
247 FunctionEmittedCb *emitted_cb;
249 MonoJITEventListener (FunctionEmittedCb *cb) {
253 virtual void NotifyFunctionEmitted(const Function &F,
254 void *Code, size_t Size,
255 const EmittedFunctionDetails &Details) {
257 * X86TargetMachine::setCodeModelForJIT() sets the code model to Large on amd64,
258 * which means the JIT will generate calls of the form
261 * Our trampoline code can't patch this. Passing CodeModel::Small to createJIT
262 * doesn't seem to work, we need Default. A discussion is here:
263 * http://lists.cs.uiuc.edu/pipermail/llvmdev/2009-December/027999.html
264 * There seems to no way to get the TargeMachine used by an EE either, so we
265 * install a profiler hook and reset the code model here.
266 * This should be inside an ifdef, but we can't include our config.h either,
267 * since its definitions conflict with LLVM's config.h.
268 * The LLVM mono branch contains a workaround.
270 emitted_cb (wrap (&F), Code, (char*)Code + Size);
277 MonoJITMemoryManager *mm;
278 MonoJITEventListener *listener;
279 FunctionPassManager *fpm;
283 mono_llvm_optimize_method (MonoEERef eeref, LLVMValueRef method)
285 MonoEE *mono_ee = (MonoEE*)eeref;
288 * The verifier does some checks on the whole module, leading to quadratic behavior.
290 //verifyFunction (*(unwrap<Function> (method)));
291 mono_ee->fpm->run (*unwrap<Function> (method));
295 mono_llvm_dump_value (LLVMValueRef value)
297 /* Same as LLVMDumpValue (), but print to stdout */
299 outs () << (*unwrap<Value> (value));
302 /* Missing overload for building an alloca with an alignment */
304 mono_llvm_build_alloca (LLVMBuilderRef builder, LLVMTypeRef Ty,
305 LLVMValueRef ArraySize,
306 int alignment, const char *Name)
308 return wrap (unwrap (builder)->Insert (new AllocaInst (unwrap (Ty), unwrap (ArraySize), alignment), Name));
312 mono_llvm_build_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
313 const char *Name, gboolean is_volatile, BarrierKind barrier)
315 LoadInst *ins = unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name);
318 case LLVM_BARRIER_NONE:
320 case LLVM_BARRIER_ACQ:
321 ins->setOrdering(Acquire);
323 case LLVM_BARRIER_SEQ:
324 ins->setOrdering(SequentiallyConsistent);
327 g_assert_not_reached ();
335 mono_llvm_build_aligned_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
336 const char *Name, gboolean is_volatile, int alignment)
340 ins = unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name);
341 ins->setAlignment (alignment);
347 mono_llvm_build_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
348 gboolean is_volatile, BarrierKind barrier)
350 StoreInst *ins = unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile);
353 case LLVM_BARRIER_NONE:
355 case LLVM_BARRIER_REL:
356 ins->setOrdering(Release);
358 case LLVM_BARRIER_SEQ:
359 ins->setOrdering(SequentiallyConsistent);
362 g_assert_not_reached ();
370 mono_llvm_build_aligned_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
371 gboolean is_volatile, int alignment)
375 ins = unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile);
376 ins->setAlignment (alignment);
382 mono_llvm_build_cmpxchg (LLVMBuilderRef builder, LLVMValueRef ptr, LLVMValueRef cmp, LLVMValueRef val)
384 AtomicCmpXchgInst *ins;
386 ins = unwrap(builder)->CreateAtomicCmpXchg (unwrap(ptr), unwrap (cmp), unwrap (val), SequentiallyConsistent, SequentiallyConsistent);
391 mono_llvm_build_atomic_rmw (LLVMBuilderRef builder, AtomicRMWOp op, LLVMValueRef ptr, LLVMValueRef val)
393 AtomicRMWInst::BinOp aop = AtomicRMWInst::Xchg;
397 case LLVM_ATOMICRMW_OP_XCHG:
398 aop = AtomicRMWInst::Xchg;
400 case LLVM_ATOMICRMW_OP_ADD:
401 aop = AtomicRMWInst::Add;
404 g_assert_not_reached ();
408 ins = unwrap (builder)->CreateAtomicRMW (aop, unwrap (ptr), unwrap (val), SequentiallyConsistent);
413 mono_llvm_build_fence (LLVMBuilderRef builder, BarrierKind kind)
416 AtomicOrdering ordering;
418 g_assert (kind != LLVM_BARRIER_NONE);
421 case LLVM_BARRIER_ACQ:
424 case LLVM_BARRIER_REL:
427 case LLVM_BARRIER_SEQ:
428 ordering = SequentiallyConsistent;
431 g_assert_not_reached ();
435 ins = unwrap (builder)->CreateFence (ordering);
440 mono_llvm_replace_uses_of (LLVMValueRef var, LLVMValueRef v)
442 Value *V = ConstantExpr::getTruncOrBitCast (unwrap<Constant> (v), unwrap (var)->getType ());
443 unwrap (var)->replaceAllUsesWith (V);
446 static cl::list<const PassInfo*, bool, PassNameParser>
447 PassList(cl::desc("Optimizations available:"));
450 force_pass_linking (void)
452 // Make sure the rest is linked in, but never executed
453 if (g_getenv ("FOO") != (char*)-1)
456 // This is a subset of the passes in LinkAllPasses.h
457 // The utility passes and the interprocedural passes are commented out
459 (void) llvm::createAAEvalPass();
460 (void) llvm::createAggressiveDCEPass();
461 (void) llvm::createAliasAnalysisCounterPass();
462 (void) llvm::createAliasDebugger();
464 (void) llvm::createArgumentPromotionPass();
465 (void) llvm::createStructRetPromotionPass();
467 (void) llvm::createBasicAliasAnalysisPass();
468 (void) llvm::createLibCallAliasAnalysisPass(0);
469 (void) llvm::createScalarEvolutionAliasAnalysisPass();
470 //(void) llvm::createBlockPlacementPass();
471 (void) llvm::createBreakCriticalEdgesPass();
472 (void) llvm::createCFGSimplificationPass();
474 (void) llvm::createConstantMergePass();
475 (void) llvm::createConstantPropagationPass();
478 (void) llvm::createDeadArgEliminationPass();
480 (void) llvm::createDeadCodeEliminationPass();
481 (void) llvm::createDeadInstEliminationPass();
482 (void) llvm::createDeadStoreEliminationPass();
484 (void) llvm::createDeadTypeEliminationPass();
485 (void) llvm::createDomOnlyPrinterPass();
486 (void) llvm::createDomPrinterPass();
487 (void) llvm::createDomOnlyViewerPass();
488 (void) llvm::createDomViewerPass();
489 (void) llvm::createEdgeProfilerPass();
490 (void) llvm::createOptimalEdgeProfilerPass();
491 (void) llvm::createFunctionInliningPass();
492 (void) llvm::createAlwaysInlinerPass();
493 (void) llvm::createGlobalDCEPass();
494 (void) llvm::createGlobalOptimizerPass();
495 (void) llvm::createGlobalsModRefPass();
496 (void) llvm::createIPConstantPropagationPass();
497 (void) llvm::createIPSCCPPass();
499 (void) llvm::createIndVarSimplifyPass();
500 (void) llvm::createInstructionCombiningPass();
502 (void) llvm::createInternalizePass(false);
504 (void) llvm::createLCSSAPass();
505 (void) llvm::createLICMPass();
506 (void) llvm::createLazyValueInfoPass();
507 //(void) llvm::createLoopDependenceAnalysisPass();
509 (void) llvm::createLoopExtractorPass();
511 (void) llvm::createLoopSimplifyPass();
512 (void) llvm::createLoopStrengthReducePass();
513 (void) llvm::createLoopUnrollPass();
514 (void) llvm::createLoopUnswitchPass();
515 (void) llvm::createLoopRotatePass();
516 (void) llvm::createLowerInvokePass();
518 (void) llvm::createLowerSetJmpPass();
520 (void) llvm::createLowerSwitchPass();
521 (void) llvm::createNoAAPass();
523 (void) llvm::createNoProfileInfoPass();
524 (void) llvm::createProfileEstimatorPass();
525 (void) llvm::createProfileVerifierPass();
526 (void) llvm::createProfileLoaderPass();
528 (void) llvm::createPromoteMemoryToRegisterPass();
529 (void) llvm::createDemoteRegisterToMemoryPass();
531 (void) llvm::createPruneEHPass();
532 (void) llvm::createPostDomOnlyPrinterPass();
533 (void) llvm::createPostDomPrinterPass();
534 (void) llvm::createPostDomOnlyViewerPass();
535 (void) llvm::createPostDomViewerPass();
537 (void) llvm::createReassociatePass();
538 (void) llvm::createSCCPPass();
539 (void) llvm::createScalarReplAggregatesPass();
540 //(void) llvm::createSimplifyLibCallsPass();
542 (void) llvm::createSingleLoopExtractorPass();
543 (void) llvm::createStripSymbolsPass();
544 (void) llvm::createStripNonDebugSymbolsPass();
545 (void) llvm::createStripDeadDebugInfoPass();
546 (void) llvm::createStripDeadPrototypesPass();
547 (void) llvm::createTailCallEliminationPass();
548 (void) llvm::createTailDuplicationPass();
549 (void) llvm::createJumpThreadingPass();
552 (void) llvm::createUnifyFunctionExitNodesPass();
554 (void) llvm::createInstCountPass();
555 (void) llvm::createCodeGenPreparePass();
556 (void) llvm::createGVNPass();
557 (void) llvm::createMemCpyOptPass();
558 (void) llvm::createLoopDeletionPass();
560 (void) llvm::createPostDomTree();
561 (void) llvm::createPostDomFrontier();
562 (void) llvm::createInstructionNamerPass();
563 (void) llvm::createPartialSpecializationPass();
564 (void) llvm::createFunctionAttrsPass();
565 (void) llvm::createMergeFunctionsPass();
566 (void) llvm::createPrintModulePass(0);
567 (void) llvm::createPrintFunctionPass("", 0);
568 (void) llvm::createDbgInfoPrinterPass();
569 (void) llvm::createModuleDebugInfoPrinterPass();
570 (void) llvm::createPartialInliningPass();
571 (void) llvm::createGEPSplitterPass();
572 (void) llvm::createLintPass();
574 (void) llvm::createSinkingPass();
577 #ifndef MONO_CROSS_COMPILE
579 static gboolean inited;
587 force_pass_linking ();
590 LLVMInitializeARMTarget ();
591 LLVMInitializeARMTargetInfo ();
592 LLVMInitializeARMTargetMC ();
594 LLVMInitializeX86Target ();
595 LLVMInitializeX86TargetInfo ();
596 LLVMInitializeX86TargetMC ();
599 PassRegistry &Registry = *PassRegistry::getPassRegistry();
600 initializeCore(Registry);
601 initializeScalarOpts(Registry);
602 initializeAnalysis(Registry);
603 initializeIPA(Registry);
604 initializeTransformUtils(Registry);
605 initializeInstCombine(Registry);
606 initializeTarget(Registry);
608 llvm::cl::ParseEnvironmentOptions("mono", "MONO_LLVM", "");
614 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb, DlSymCb *dlsym_cb, LLVMExecutionEngineRef *ee)
621 mono_ee = new MonoEE ();
623 MonoJITMemoryManager *mono_mm = new MonoJITMemoryManager ();
624 mono_mm->alloc_cb = alloc_cb;
625 mono_mm->dlsym_cb = dlsym_cb;
626 mono_ee->mm = mono_mm;
629 * The Default code model doesn't seem to work on amd64,
630 * test_0_fields_with_big_offsets (among others) crashes, because LLVM tries to call
631 * memset using a normal pcrel code which is in 32bit memory, while memset isn't.
635 opts.JITExceptionHandling = 1;
637 StringRef cpu_name = sys::getHostCPUName ();
639 // EngineBuilder no longer has a copy assignment operator (?)
640 std::unique_ptr<Module> Owner(unwrap(MP));
641 EngineBuilder b (std::move(Owner));
643 ExecutionEngine *EE = b.setJITMemoryManager (mono_mm).setTargetOptions (opts).setAllocateGVsWithCode (true).setMCPU (cpu_name).setCodeModel (CodeModel::Large).create ();
645 ExecutionEngine *EE = b.setJITMemoryManager (mono_mm).setTargetOptions (opts).setAllocateGVsWithCode (true).setMCPU (cpu_name).create ();
651 EE->InstallExceptionTableRegister (exception_cb);
652 MonoJITEventListener *listener = new MonoJITEventListener (emitted_cb);
653 EE->RegisterJITEventListener (listener);
654 mono_ee->listener = listener;
656 FunctionPassManager *fpm = new FunctionPassManager (unwrap (MP));
659 fpm->add(new DataLayoutPass(*EE->getDataLayout()));
661 if (PassList.size() > 0) {
662 /* Use the passes specified by the env variable */
663 /* Only the passes in force_pass_linking () can be used */
664 for (unsigned i = 0; i < PassList.size(); ++i) {
665 const PassInfo *PassInf = PassList[i];
668 if (PassInf->getNormalCtor())
669 P = PassInf->getNormalCtor()();
673 /* Use the same passes used by 'opt' by default, without the ipo passes */
674 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";
678 args = g_strsplit (opts, " ", 1000);
679 for (i = 0; args [i]; i++)
681 llvm::cl::ParseCommandLineOptions (i, args, "");
684 for (unsigned i = 0; i < PassList.size(); ++i) {
685 const PassInfo *PassInf = PassList[i];
688 if (PassInf->getNormalCtor())
689 P = PassInf->getNormalCtor()();
690 g_assert (P->getPassKind () == llvm::PT_Function || P->getPassKind () == llvm::PT_Loop);
695 fpm->add(createInstructionCombiningPass());
696 fpm->add(createReassociatePass());
697 fpm->add(createGVNPass());
698 fpm->add(createCFGSimplificationPass());
708 mono_llvm_dispose_ee (MonoEERef *eeref)
710 MonoEE *mono_ee = (MonoEE*)eeref;
714 //delete mono_ee->mm;
715 delete mono_ee->listener;
722 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb, DlSymCb *dlsym_cb, LLVMExecutionEngineRef *ee)
724 g_assert_not_reached ();
729 mono_llvm_dispose_ee (MonoEERef *eeref)
731 g_assert_not_reached ();
736 LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
739 g_assert_not_reached ();
743 LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global)
745 g_assert_not_reached ();
749 #endif /* !MONO_CROSS_COMPILE */