void init() { InitializeNativeTarget(); master.version = 0.9; master.Program = new Module("Hylas Lisp",Context); master.Engine = ExecutionEngine::createJIT(master.Program); master.Loader = new Linker("Hylas Lisp",master.Program); master.Loader->addSystemPaths(); master.allow_RedefineMacros = true; master.allow_RedefineWordMacros = true; master.allow_RedefinePrePostfixes = true; master.allow_RedefineFunctions = false; master.Colorscheme = defaultColorscheme(); master.CSS = defaultCSS(); master.errormode = NormalError; init_stdlib(); init_types(); init_optimizer(); master.Engine = EngineBuilder(master.Program).create(); try { ifstream base("src/base.hylas"); if(!base.good()) nerror("Could not find base.hylas. You will not have print functions for the basic types."); stringstream file; file << base.rdbuf(); JIT(Compile(readString(file.str()))); Run(); } catch(exception except) { cerr << getError() << endl; exit(-1); } }
/* Executes the AST by running the main function */ GenericValue CodeGenContext::runCode() { std::cout << "Running begining...\n"; std::cout << "========================================" << std::endl; ExecutionEngine *ee = EngineBuilder(module).create(); std::vector<GenericValue> noargs; GenericValue v = ee->runFunction(mainFunction, noargs); std::cout << "========================================" << std::endl; std::cout << "Running end.\n"; return v; }
LLVMFormula::LLVMFormula () { // We need to initialize the native target info, once. static bool initializeNative = false; if (!initializeNative) { InitializeNativeTarget (); initializeNative = true; } // Build a module and a JIT engine module = new Module ("AFormula JIT", getGlobalContext ()); // The Engine is going to take control of this module, // don't delete them later. std::string errorString; engine = EngineBuilder (module).setErrorStr (&errorString).create (); if (!engine) { // We won't let you call buildFunction if you catch this error errorMessage.reset (new std::string ("LLVM Error: " + errorString)); return; } // Create an IRBuilder builder = new IRBuilder<> (getGlobalContext ()); // Get a data layout for this module const std::string &moduleDataLayout = module->getDataLayout (); if (!moduleDataLayout.empty ()) TD = new DataLayout (moduleDataLayout); else TD = NULL; // Build an optimizer. We're going to get default optimization settings // in the same way that LLVM does. FPM = new FunctionPassManager (module); if (TD) FPM->add (TD); FPM->add (createVerifierPass()); PassManagerBuilder builder; builder.OptLevel = 3; builder.populateFunctionPassManager (*FPM); FPM->doInitialization (); }
ExternalDispatcherImpl::ExternalDispatcherImpl(LLVMContext &ctx) : ctx(ctx), lastErrno(0) { std::string error; singleDispatchModule = new Module(getFreshModuleID(), ctx); #if LLVM_VERSION_CODE < LLVM_VERSION(3, 6) // Use old JIT executionEngine = ExecutionEngine::createJIT(singleDispatchModule, &error); #else // Use MCJIT. // The MCJIT JITs whole modules at a time rather than individual functions // so we will let it manage the modules. // Note that we don't do anything with `singleDispatchModule`. This is just // so we can use the EngineBuilder API. auto dispatchModuleUniq = std::unique_ptr<Module>(singleDispatchModule); executionEngine = EngineBuilder(std::move(dispatchModuleUniq)) .setErrorStr(&error) .setEngineKind(EngineKind::JIT) .create(); #endif if (!executionEngine) { llvm::errs() << "unable to make jit: " << error << "\n"; abort(); } // If we have a native target, initialize it to ensure it is linked in and // usable by the JIT. llvm::InitializeNativeTarget(); #if LLVM_VERSION_CODE >= LLVM_VERSION(3, 6) llvm::InitializeNativeTargetAsmParser(); llvm::InitializeNativeTargetAsmPrinter(); #endif // from ExecutionEngine::create if (executionEngine) { // Make sure we can resolve symbols in the program as well. The zero arg // to the function tells DynamicLibrary to load the program, not a library. sys::DynamicLibrary::LoadLibraryPermanently(0); } #ifdef WINDOWS preboundFunctions["getpid"] = (void *)(long)getpid; preboundFunctions["putchar"] = (void *)(long)putchar; preboundFunctions["printf"] = (void *)(long)printf; preboundFunctions["fprintf"] = (void *)(long)fprintf; preboundFunctions["sprintf"] = (void *)(long)sprintf; #endif }
main_func_type jit_engine::compile(const ast::Program &prog) { llvm::LLVMContext &c=llvm::getGlobalContext(); llvm::Module *m=new llvm::Module("brainfuck", c); brainfuck::codegen(*m, prog); //m->dump(); std::string ErrStr; ExecutionEngine *TheExecutionEngine = EngineBuilder(m).setErrorStr(&ErrStr).create(); if (!TheExecutionEngine) { fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str()); exit(1); } Function *f_main=m->getFunction("main"); // Optimize, target dependant if(optimization_level_>0) { FunctionPassManager OurFPM(m); // Set up the optimizer pipeline. Start with registering info about how the // target lays out data structures. OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData())); // Provide basic AliasAnalysis support for GVN. OurFPM.add(createBasicAliasAnalysisPass()); // Do simple "peephole" optimizations and bit-twiddling optzns. OurFPM.add(createInstructionCombiningPass()); // Reassociate expressions. OurFPM.add(createReassociatePass()); // Eliminate Common SubExpressions. OurFPM.add(createGVNPass()); // Simplify the control flow graph (deleting unreachable blocks, etc). OurFPM.add(createCFGSimplificationPass()); //OurFPM.add(createLoopSimplifyPass()); //OurFPM.add(createBlockPlacementPass()); //OurFPM.add(createConstantPropagationPass()); OurFPM.doInitialization(); OurFPM.run(*f_main); } //m->dump(); void *rp=TheExecutionEngine->getPointerToFunction(f_main); main_func_type fp=reinterpret_cast<main_func_type>(rp); return fp; }
ExecutionEngine* createExecutionEngine(Module* mod) { if (globalExecEngine == 0) { //we first have to initialize the native target for code generation const bool initFailed = InitializeNativeTarget(); if (initFailed) { errs() << "ERROR: could not initialize native target (required for " << "LLVM execution engine)\n"; return NULL; } std::string errorMessage = ""; EngineBuilder eb = EngineBuilder(mod); eb.setEngineKind(EngineKind::JIT); eb.setErrorStr(&errorMessage); eb.setJITMemoryManager(JITMemoryManager::CreateDefaultMemManager()); eb.setOptLevel(CodeGenOpt::Aggressive); eb.setAllocateGVsWithCode(false); eb.setCodeModel(CodeModel::Default); //eb.setMArch("x86-64"); //eb.setMCPU("corei7"); //std::vector<std::string> attrs; //attrs.push_back("+sse41"); //eb.setMAttrs(attrs); globalExecEngine = eb.create(); if (errorMessage != "") { errs() << "ERROR: could not create execution engine for module " << mod->getModuleIdentifier() << ": " << errorMessage << "\n"; return NULL; } if (!globalExecEngine) { errs() << "ERROR: could not create execution engine for module " << mod->getModuleIdentifier() << "!\n"; return NULL; } } return globalExecEngine; }
NNModule_(NNModule* o) : o_(o), context_(getGlobalContext()), module_("NNModule", context_), builder_(context_){ _mutex.lock(); if(!_initialized){ InitializeNativeTarget(); _initialized = true; } _mutex.unlock(); engine_ = EngineBuilder(&module_).setUseMCJIT(true).create(); TypeVec args; args.push_back(doubleType()); createExtern("llvm.exp.f64", doubleType(), args); }
llvm::Module * CreateModule() { static bool init = false; if (!init) { init = true; llvm_start_multithreaded(); } llvm::InitializeNativeTarget(); //llvm::LLVMContext &Context = *(new LLVMContext); llvm::LLVMContext &Context = llvm::getGlobalContext(); char name[128]; sprintf(name, "QDT JIT %d", rand()); llvm::Module * mod = new llvm::Module(name, Context); std::string ErrStr; llvm::UnsafeFPMath = true; llvm::NoInfsFPMath = true; llvm::NoNaNsFPMath = true; llvm::HonorSignDependentRoundingFPMathOption = false; TheModule= mod; TheExecutionEngine = EngineBuilder(TheModule). setErrorStr(&ErrStr). //setOptLevel(CodeGenOpt::Aggressive). setOptLevel(CodeGenOpt::None). setEngineKind(EngineKind::JIT). create(); if (!TheExecutionEngine) { fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str()); exit(1); } TheExecutionEngine->DisableLazyCompilation(true); return mod; }
int main(int argc, char** argv){ // verif M unit #ifdef CORE_DBG verif_m_unit(); #endif if(argc < 2) { return 0; } Core *pCore = Core::start(); pCore->init(); COFF_parser parser(argv[1]); pCore->set_mode(BK_AT_MAIN); if(argc >= 3) { core_mode_t mode = (core_mode_t)strtoul(argv[2],NULL,10); pCore->set_mode(mode); } if(argc >= 4) { word_t thres = strtoul(argv[3],NULL,10); Profiler::set_jit_threshold_times(thres); } if(argc >= 5) { word_t thres = strtoul(argv[4],NULL,10); Profiler::set_jit_threshold_len(thres); } parser.connect(pCore); parser.set_reverse(false); parser.parse(); pCore->init(); #if 0 pCore->reg_write(0,0,2); // A0 = 2 pCore->reg_write(1,0,3); // B0 = 3 llvm::Function *func = llvm::cast<llvm::Function>(Core::get_llvm_module().getOrInsertFunction("func", Type::getInt32Ty(getGlobalContext()),(Type*)0)); llvm::BasicBlock* bb = llvm::BasicBlock::Create(getGlobalContext(),"entry",func); Core::get_llvm_builder().SetInsertPoint(bb); llvm::Constant* a_side_addr = llvm::ConstantInt::get(llvm::Type::getInt32Ty(getGlobalContext()) ,(uint64_t)pCore->get_reg_a()); llvm::Constant* b_side_addr = llvm::ConstantInt::get(llvm::Type::getInt32Ty(getGlobalContext()) ,(uint64_t)pCore->get_reg_b()); llvm::Constant* dst_addr = llvm::ConstantInt::get(llvm::Type::getInt32Ty(getGlobalContext()) ,(uint64_t)(pCore->get_reg_b()+1)); // B1 llvm::Value* a_side = llvm::ConstantExpr::getIntToPtr(a_side_addr, llvm::PointerType::getUnqual(llvm::Type::getInt32Ty(getGlobalContext()))); llvm::Value* b_side = llvm::ConstantExpr::getIntToPtr(b_side_addr, llvm::PointerType::getUnqual(llvm::Type::getInt32Ty(getGlobalContext()))); llvm::Value* b1 = llvm::ConstantExpr::getIntToPtr(dst_addr, llvm::PointerType::getUnqual(llvm::Type::getInt32Ty(getGlobalContext()))); llvm::Value* left = Core::get_llvm_builder().CreateLoad(a_side); llvm::Value* right = Core::get_llvm_builder().CreateLoad(b_side); llvm::Value* re = Core::get_llvm_builder().CreateAdd(left,right); Core::get_llvm_builder().CreateStore(re,b1,true); Core::get_llvm_builder().CreateRet(re); ExecutionEngine* EE = EngineBuilder(&Core::get_llvm_module()).create(); // Call the `foo' function with no arguments: //std::vector<GenericValue> noargs; //GenericValue gv = EE->runFunction(func, noargs); void* FPtr = EE->getPointerToFunction(func); int (*FP)() = (int (*)())(intptr_t)FPtr; FP(); // Import result of execution: std::cout << "Result: " << pCore->reg_read(B_SIDE,1) << "\n"; //outs() << "re: " << gv.IntVal << "\n"; #endif #if 0 pCore->reg_write(A_SIDE,3,0xFF); de_func_t de_func = JIT::gen_su_de_32bit_1or2_src_shl_f2_nc(pCore,0x018d0ca0); c6x::Instruction inst; pCore->reg_ch_num = 1; de_func(pCore,&inst); pCore->step(); std::cout << to_hex_str(pCore->reg_read(A_SIDE,3)) << "\n"; system("pause"); #endif pCore->run(); return 0; }
bool CompiledCondition::compile(){ InitializeNativeTarget(); // Assume we're on main thread... LLVMContext &context = getGlobalContext(); // Initialize module Module* module = new Module("Compiled function", context); // Create exection engine ExecutionEngine* engine = EngineBuilder(module).create(); /********** Generate code **********/ //Get a type for representing an integer pointer //Maybe this should be unsigned integer pointer type... PointerType* integerPointerType = PointerType::get(IntegerType::get(module->getContext(), 32), 0); //Create function type, for our function, int*, int* -> bool vector<const Type*> paramType; paramType.push_back(integerPointerType); paramType.push_back(integerPointerType); FunctionType* functionType = FunctionType::get(IntegerType::get(module->getContext(), 8), paramType, false); //Declare new function Function* function = Function::Create(functionType, GlobalValue::ExternalLinkage, "evaluate", module); //Use C calling convention function->setCallingConv(CallingConv::C); //TODO: Read documentation and reconsider this //Get arguments from function Function::arg_iterator args = function->arg_begin(); Value* marking = args++; Value* valuation = args++; marking->setName("marking"); valuation->setName("valuation"); //Create function block BasicBlock* functionBlock = BasicBlock::Create(module->getContext(), "functionBlock", function, 0); //Generate code CodeGenerationContext codeGenContext(marking, valuation, functionBlock, context); Value* result = _cond->codegen(codeGenContext); //Zero extend the result, e.g. make it a 8 bit bool CastInst* retval = new ZExtInst(result, IntegerType::get(module->getContext(), 8), "retval", functionBlock); //Create a return instruction ReturnInst::Create(module->getContext(), retval, functionBlock); /********** Optimize and Compile **********/ // Create function pass manager, to optimize query FunctionPassManager optimizer(module); optimizer.add(new TargetData(*engine->getTargetData())); optimizer.add(createBasicAliasAnalysisPass()); optimizer.add(createInstructionCombiningPass()); optimizer.add(createReassociatePass()); optimizer.add(createGVNPass()); optimizer.add(createCFGSimplificationPass()); optimizer.doInitialization(); // Verify function, errors written to stderr if(verifyFunction(*function)) return false; // Optimize function optimizer.run(*function); // Compile the function _nativeFunction = (bool(*)(const MarkVal*, const VarVal*))engine->getPointerToFunction(function); return _nativeFunction != NULL; }