15a440378SAlex Zinenko //===- ExecutionEngine.cpp - MLIR Execution engine and utils --------------===// 25a440378SAlex Zinenko // 35a440378SAlex Zinenko // Copyright 2019 The MLIR Authors. 45a440378SAlex Zinenko // 55a440378SAlex Zinenko // Licensed under the Apache License, Version 2.0 (the "License"); 65a440378SAlex Zinenko // you may not use this file except in compliance with the License. 75a440378SAlex Zinenko // You may obtain a copy of the License at 85a440378SAlex Zinenko // 95a440378SAlex Zinenko // http://www.apache.org/licenses/LICENSE-2.0 105a440378SAlex Zinenko // 115a440378SAlex Zinenko // Unless required by applicable law or agreed to in writing, software 125a440378SAlex Zinenko // distributed under the License is distributed on an "AS IS" BASIS, 135a440378SAlex Zinenko // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 145a440378SAlex Zinenko // See the License for the specific language governing permissions and 155a440378SAlex Zinenko // limitations under the License. 165a440378SAlex Zinenko // ============================================================================= 175a440378SAlex Zinenko // 185a440378SAlex Zinenko // This file implements the execution engine for MLIR modules based on LLVM Orc 195a440378SAlex Zinenko // JIT engine. 205a440378SAlex Zinenko // 215a440378SAlex Zinenko //===----------------------------------------------------------------------===// 225a440378SAlex Zinenko #include "mlir/ExecutionEngine/ExecutionEngine.h" 235a440378SAlex Zinenko #include "mlir/IR/Function.h" 245a440378SAlex Zinenko #include "mlir/IR/Module.h" 25*c6c53449SRiver Riddle #include "mlir/Pass/PassManager.h" 265a440378SAlex Zinenko #include "mlir/Target/LLVMIR.h" 275a440378SAlex Zinenko #include "mlir/Transforms/Passes.h" 285a440378SAlex Zinenko 295a440378SAlex Zinenko #include "llvm/ExecutionEngine/Orc/CompileUtils.h" 305a440378SAlex Zinenko #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" 315a440378SAlex Zinenko #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" 328093f17aSAlex Zinenko #include "llvm/ExecutionEngine/Orc/IRTransformLayer.h" 335a440378SAlex Zinenko #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" 345a440378SAlex Zinenko #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" 355a440378SAlex Zinenko #include "llvm/ExecutionEngine/SectionMemoryManager.h" 365a440378SAlex Zinenko #include "llvm/IR/IRBuilder.h" 375a440378SAlex Zinenko #include "llvm/Support/Error.h" 385a440378SAlex Zinenko #include "llvm/Support/TargetRegistry.h" 395a440378SAlex Zinenko 405a440378SAlex Zinenko using namespace mlir; 415a440378SAlex Zinenko using llvm::Error; 425a440378SAlex Zinenko using llvm::Expected; 435a440378SAlex Zinenko 445a440378SAlex Zinenko namespace { 455a440378SAlex Zinenko // Memory manager for the JIT's objectLayer. Its main goal is to fallback to 465a440378SAlex Zinenko // resolving functions in the current process if they cannot be resolved in the 475a440378SAlex Zinenko // JIT-compiled modules. 485a440378SAlex Zinenko class MemoryManager : public llvm::SectionMemoryManager { 495a440378SAlex Zinenko public: 505a440378SAlex Zinenko MemoryManager(llvm::orc::ExecutionSession &execSession) 515a440378SAlex Zinenko : session(execSession) {} 525a440378SAlex Zinenko 535a440378SAlex Zinenko // Resolve the named symbol. First, try looking it up in the main library of 545a440378SAlex Zinenko // the execution session. If there is no such symbol, try looking it up in 555a440378SAlex Zinenko // the current process (for example, if it is a standard library function). 565a440378SAlex Zinenko // Return `nullptr` if lookup fails. 575a440378SAlex Zinenko llvm::JITSymbol findSymbol(const std::string &name) override { 585a440378SAlex Zinenko auto mainLibSymbol = session.lookup({&session.getMainJITDylib()}, name); 595a440378SAlex Zinenko if (mainLibSymbol) 605a440378SAlex Zinenko return mainLibSymbol.get(); 615a440378SAlex Zinenko auto address = llvm::RTDyldMemoryManager::getSymbolAddressInProcess(name); 625a440378SAlex Zinenko if (!address) { 635a440378SAlex Zinenko llvm::errs() << "Could not look up: " << name << '\n'; 645a440378SAlex Zinenko return nullptr; 655a440378SAlex Zinenko } 665a440378SAlex Zinenko return llvm::JITSymbol(address, llvm::JITSymbolFlags::Exported); 675a440378SAlex Zinenko } 685a440378SAlex Zinenko 695a440378SAlex Zinenko private: 705a440378SAlex Zinenko llvm::orc::ExecutionSession &session; 715a440378SAlex Zinenko }; 725a440378SAlex Zinenko } // end anonymous namespace 735a440378SAlex Zinenko 745a440378SAlex Zinenko namespace mlir { 755a440378SAlex Zinenko namespace impl { 765a440378SAlex Zinenko // Simple layered Orc JIT compilation engine. 775a440378SAlex Zinenko class OrcJIT { 785a440378SAlex Zinenko public: 798093f17aSAlex Zinenko using IRTransformer = std::function<Error(llvm::Module *)>; 808093f17aSAlex Zinenko 815a440378SAlex Zinenko // Construct a JIT engine for the target host defined by `machineBuilder`, 825a440378SAlex Zinenko // using the data layout provided as `dataLayout`. 835a440378SAlex Zinenko // Setup the object layer to use our custom memory manager in order to resolve 845a440378SAlex Zinenko // calls to library functions present in the process. 855a440378SAlex Zinenko OrcJIT(llvm::orc::JITTargetMachineBuilder machineBuilder, 868093f17aSAlex Zinenko llvm::DataLayout layout, IRTransformer transform) 878093f17aSAlex Zinenko : irTransformer(transform), 888093f17aSAlex Zinenko objectLayer( 895a440378SAlex Zinenko session, 905a440378SAlex Zinenko [this]() { return llvm::make_unique<MemoryManager>(session); }), 915a440378SAlex Zinenko compileLayer( 925a440378SAlex Zinenko session, objectLayer, 935a440378SAlex Zinenko llvm::orc::ConcurrentIRCompiler(std::move(machineBuilder))), 948093f17aSAlex Zinenko transformLayer(session, compileLayer, makeIRTransformFunction()), 955a440378SAlex Zinenko dataLayout(layout), mangler(session, this->dataLayout), 965a440378SAlex Zinenko threadSafeCtx(llvm::make_unique<llvm::LLVMContext>()) { 975a440378SAlex Zinenko session.getMainJITDylib().setGenerator( 985a440378SAlex Zinenko cantFail(llvm::orc::DynamicLibrarySearchGenerator::GetForCurrentProcess( 995a440378SAlex Zinenko layout))); 1005a440378SAlex Zinenko } 1015a440378SAlex Zinenko 1025a440378SAlex Zinenko // Create a JIT engine for the current host. 1038093f17aSAlex Zinenko static Expected<std::unique_ptr<OrcJIT>> 104f5b99275SAlex Zinenko createDefault(IRTransformer transformer) { 1055a440378SAlex Zinenko auto machineBuilder = llvm::orc::JITTargetMachineBuilder::detectHost(); 1065a440378SAlex Zinenko if (!machineBuilder) 1075a440378SAlex Zinenko return machineBuilder.takeError(); 1085a440378SAlex Zinenko 1095a440378SAlex Zinenko auto dataLayout = machineBuilder->getDefaultDataLayoutForTarget(); 1105a440378SAlex Zinenko if (!dataLayout) 1115a440378SAlex Zinenko return dataLayout.takeError(); 1125a440378SAlex Zinenko 1135a440378SAlex Zinenko return llvm::make_unique<OrcJIT>(std::move(*machineBuilder), 1148093f17aSAlex Zinenko std::move(*dataLayout), transformer); 1155a440378SAlex Zinenko } 1165a440378SAlex Zinenko 1175a440378SAlex Zinenko // Add an LLVM module to the main library managed by the JIT engine. 1185a440378SAlex Zinenko Error addModule(std::unique_ptr<llvm::Module> M) { 119f5b99275SAlex Zinenko return transformLayer.add( 1205a440378SAlex Zinenko session.getMainJITDylib(), 1215a440378SAlex Zinenko llvm::orc::ThreadSafeModule(std::move(M), threadSafeCtx)); 1225a440378SAlex Zinenko } 1235a440378SAlex Zinenko 1245a440378SAlex Zinenko // Lookup a symbol in the main library managed by the JIT engine. 1255a440378SAlex Zinenko Expected<llvm::JITEvaluatedSymbol> lookup(StringRef Name) { 1265a440378SAlex Zinenko return session.lookup({&session.getMainJITDylib()}, mangler(Name.str())); 1275a440378SAlex Zinenko } 1285a440378SAlex Zinenko 1295a440378SAlex Zinenko private: 1308093f17aSAlex Zinenko // Wrap the `irTransformer` into a function that can be called by the 1318093f17aSAlex Zinenko // IRTranformLayer. If `irTransformer` is not set up, return the module as is 1328093f17aSAlex Zinenko // without errors. 1338093f17aSAlex Zinenko llvm::orc::IRTransformLayer::TransformFunction makeIRTransformFunction() { 1348093f17aSAlex Zinenko return [this](llvm::orc::ThreadSafeModule module, 1358093f17aSAlex Zinenko const llvm::orc::MaterializationResponsibility &resp) 1368093f17aSAlex Zinenko -> Expected<llvm::orc::ThreadSafeModule> { 1378093f17aSAlex Zinenko (void)resp; 1388093f17aSAlex Zinenko if (!irTransformer) 1398093f17aSAlex Zinenko return module; 1408093f17aSAlex Zinenko if (Error err = irTransformer(module.getModule())) 1418093f17aSAlex Zinenko return std::move(err); 1428093f17aSAlex Zinenko return module; 1438093f17aSAlex Zinenko }; 1448093f17aSAlex Zinenko } 1458093f17aSAlex Zinenko 1468093f17aSAlex Zinenko IRTransformer irTransformer; 1475a440378SAlex Zinenko llvm::orc::ExecutionSession session; 1485a440378SAlex Zinenko llvm::orc::RTDyldObjectLinkingLayer objectLayer; 1495a440378SAlex Zinenko llvm::orc::IRCompileLayer compileLayer; 1508093f17aSAlex Zinenko llvm::orc::IRTransformLayer transformLayer; 1515a440378SAlex Zinenko llvm::DataLayout dataLayout; 1525a440378SAlex Zinenko llvm::orc::MangleAndInterner mangler; 1535a440378SAlex Zinenko llvm::orc::ThreadSafeContext threadSafeCtx; 1545a440378SAlex Zinenko }; 1555a440378SAlex Zinenko } // end namespace impl 1565a440378SAlex Zinenko } // namespace mlir 1575a440378SAlex Zinenko 1585a440378SAlex Zinenko // Wrap a string into an llvm::StringError. 1595a440378SAlex Zinenko static inline Error make_string_error(const llvm::Twine &message) { 1605a440378SAlex Zinenko return llvm::make_error<llvm::StringError>(message.str(), 1615a440378SAlex Zinenko llvm::inconvertibleErrorCode()); 1625a440378SAlex Zinenko } 1635a440378SAlex Zinenko 1645a440378SAlex Zinenko // Given a list of PassInfo coming from a higher level, creates the passes to 1655a440378SAlex Zinenko // run as an owning vector and appends the extra required passes to lower to 1665a440378SAlex Zinenko // LLVMIR. Currently, these extra passes are: 1675a440378SAlex Zinenko // - constant folding 1685a440378SAlex Zinenko // - CSE 1695a440378SAlex Zinenko // - canonicalization 1705a440378SAlex Zinenko // - affine lowering 171*c6c53449SRiver Riddle static void 172*c6c53449SRiver Riddle getDefaultPasses(PassManager &manager, 173*c6c53449SRiver Riddle const std::vector<const mlir::PassInfo *> &mlirPassInfoList) { 1745a440378SAlex Zinenko // Run each of the passes that were selected. 1755a440378SAlex Zinenko for (const auto *passInfo : mlirPassInfoList) { 176*c6c53449SRiver Riddle manager.addPass(passInfo->createPass()); 1775a440378SAlex Zinenko } 1785a440378SAlex Zinenko 179*c6c53449SRiver Riddle // Append the extra passes for lowering to MLIR. 180*c6c53449SRiver Riddle manager.addPass(mlir::createConstantFoldPass()); 181*c6c53449SRiver Riddle manager.addPass(mlir::createCSEPass()); 182*c6c53449SRiver Riddle manager.addPass(mlir::createCanonicalizerPass()); 183*c6c53449SRiver Riddle manager.addPass(mlir::createLowerAffinePass()); 184*c6c53449SRiver Riddle manager.addPass(mlir::createConvertToLLVMIRPass()); 1855a440378SAlex Zinenko } 1865a440378SAlex Zinenko 1875a440378SAlex Zinenko // Setup LLVM target triple from the current machine. 1885a440378SAlex Zinenko static bool setupTargetTriple(llvm::Module *llvmModule) { 1895a440378SAlex Zinenko // Setup the machine properties from the current architecture. 1905a440378SAlex Zinenko auto targetTriple = llvm::sys::getDefaultTargetTriple(); 1915a440378SAlex Zinenko std::string errorMessage; 1925a440378SAlex Zinenko auto target = llvm::TargetRegistry::lookupTarget(targetTriple, errorMessage); 1935a440378SAlex Zinenko if (!target) { 1945a440378SAlex Zinenko llvm::errs() << "NO target: " << errorMessage << "\n"; 1955a440378SAlex Zinenko return true; 1965a440378SAlex Zinenko } 1975a440378SAlex Zinenko auto machine = 1985a440378SAlex Zinenko target->createTargetMachine(targetTriple, "generic", "", {}, {}); 1995a440378SAlex Zinenko llvmModule->setDataLayout(machine->createDataLayout()); 2005a440378SAlex Zinenko llvmModule->setTargetTriple(targetTriple); 2015a440378SAlex Zinenko return false; 2025a440378SAlex Zinenko } 2035a440378SAlex Zinenko 2045a440378SAlex Zinenko static std::string makePackedFunctionName(StringRef name) { 2055a440378SAlex Zinenko return "_mlir_" + name.str(); 2065a440378SAlex Zinenko } 2075a440378SAlex Zinenko 2085a440378SAlex Zinenko // For each function in the LLVM module, define an interface function that wraps 2095a440378SAlex Zinenko // all the arguments of the original function and all its results into an i8** 2105a440378SAlex Zinenko // pointer to provide a unified invocation interface. 2115a440378SAlex Zinenko void packFunctionArguments(llvm::Module *module) { 2125a440378SAlex Zinenko auto &ctx = module->getContext(); 2135a440378SAlex Zinenko llvm::IRBuilder<> builder(ctx); 2145a440378SAlex Zinenko llvm::DenseSet<llvm::Function *> interfaceFunctions; 2155a440378SAlex Zinenko for (auto &func : module->getFunctionList()) { 2165a440378SAlex Zinenko if (func.isDeclaration()) { 2175a440378SAlex Zinenko continue; 2185a440378SAlex Zinenko } 2195a440378SAlex Zinenko if (interfaceFunctions.count(&func)) { 2205a440378SAlex Zinenko continue; 2215a440378SAlex Zinenko } 2225a440378SAlex Zinenko 2235a440378SAlex Zinenko // Given a function `foo(<...>)`, define the interface function 2245a440378SAlex Zinenko // `mlir_foo(i8**)`. 2255a440378SAlex Zinenko auto newType = llvm::FunctionType::get( 2265a440378SAlex Zinenko builder.getVoidTy(), builder.getInt8PtrTy()->getPointerTo(), 2275a440378SAlex Zinenko /*isVarArg=*/false); 2285a440378SAlex Zinenko auto newName = makePackedFunctionName(func.getName()); 229c46b0feaSRiver Riddle auto funcCst = module->getOrInsertFunction(newName, newType); 230c46b0feaSRiver Riddle llvm::Function *interfaceFunc = 231c46b0feaSRiver Riddle llvm::cast<llvm::Function>(funcCst.getCallee()); 2325a440378SAlex Zinenko interfaceFunctions.insert(interfaceFunc); 2335a440378SAlex Zinenko 2345a440378SAlex Zinenko // Extract the arguments from the type-erased argument list and cast them to 2355a440378SAlex Zinenko // the proper types. 2365a440378SAlex Zinenko auto bb = llvm::BasicBlock::Create(ctx); 2375a440378SAlex Zinenko bb->insertInto(interfaceFunc); 2385a440378SAlex Zinenko builder.SetInsertPoint(bb); 2395a440378SAlex Zinenko llvm::Value *argList = interfaceFunc->arg_begin(); 2405a440378SAlex Zinenko llvm::SmallVector<llvm::Value *, 8> args; 2415a440378SAlex Zinenko args.reserve(llvm::size(func.args())); 2425a440378SAlex Zinenko for (auto &indexedArg : llvm::enumerate(func.args())) { 2435a440378SAlex Zinenko llvm::Value *argIndex = llvm::Constant::getIntegerValue( 2445a440378SAlex Zinenko builder.getInt64Ty(), llvm::APInt(64, indexedArg.index())); 2455a440378SAlex Zinenko llvm::Value *argPtrPtr = builder.CreateGEP(argList, argIndex); 2465a440378SAlex Zinenko llvm::Value *argPtr = builder.CreateLoad(argPtrPtr); 2475a440378SAlex Zinenko argPtr = builder.CreateBitCast( 2485a440378SAlex Zinenko argPtr, indexedArg.value().getType()->getPointerTo()); 2495a440378SAlex Zinenko llvm::Value *arg = builder.CreateLoad(argPtr); 2505a440378SAlex Zinenko args.push_back(arg); 2515a440378SAlex Zinenko } 2525a440378SAlex Zinenko 2535a440378SAlex Zinenko // Call the implementation function with the extracted arguments. 2545a440378SAlex Zinenko llvm::Value *result = builder.CreateCall(&func, args); 2555a440378SAlex Zinenko 2565a440378SAlex Zinenko // Assuming the result is one value, potentially of type `void`. 2575a440378SAlex Zinenko if (!result->getType()->isVoidTy()) { 2585a440378SAlex Zinenko llvm::Value *retIndex = llvm::Constant::getIntegerValue( 2595a440378SAlex Zinenko builder.getInt64Ty(), llvm::APInt(64, llvm::size(func.args()))); 2605a440378SAlex Zinenko llvm::Value *retPtrPtr = builder.CreateGEP(argList, retIndex); 2615a440378SAlex Zinenko llvm::Value *retPtr = builder.CreateLoad(retPtrPtr); 2625a440378SAlex Zinenko retPtr = builder.CreateBitCast(retPtr, result->getType()->getPointerTo()); 2635a440378SAlex Zinenko builder.CreateStore(result, retPtr); 2645a440378SAlex Zinenko } 2655a440378SAlex Zinenko 2665a440378SAlex Zinenko // The interface function returns void. 2675a440378SAlex Zinenko builder.CreateRetVoid(); 2685a440378SAlex Zinenko } 2695a440378SAlex Zinenko } 2705a440378SAlex Zinenko 271d9ce382fSMehdi Amini // Out of line for PIMPL unique_ptr. 272d9ce382fSMehdi Amini ExecutionEngine::~ExecutionEngine() = default; 2735a440378SAlex Zinenko 27450700b81SAlex Zinenko std::unique_ptr<llvm::Module> translateModuleToLLVMIR(const Module &m); 27550700b81SAlex Zinenko 2768093f17aSAlex Zinenko Expected<std::unique_ptr<ExecutionEngine>> ExecutionEngine::create( 2778093f17aSAlex Zinenko Module *m, std::function<llvm::Error(llvm::Module *)> transformer) { 2785a440378SAlex Zinenko auto engine = llvm::make_unique<ExecutionEngine>(); 2798093f17aSAlex Zinenko auto expectedJIT = impl::OrcJIT::createDefault(transformer); 2805a440378SAlex Zinenko if (!expectedJIT) 2815a440378SAlex Zinenko return expectedJIT.takeError(); 2825a440378SAlex Zinenko 283*c6c53449SRiver Riddle // Construct and run the default MLIR pipeline. 284*c6c53449SRiver Riddle PassManager manager; 285*c6c53449SRiver Riddle getDefaultPasses(manager, {}); 286*c6c53449SRiver Riddle if (manager.run(m)) 2875a440378SAlex Zinenko return make_string_error("passes failed"); 2885a440378SAlex Zinenko 28950700b81SAlex Zinenko auto llvmModule = translateModuleToLLVMIR(*m); 2905a440378SAlex Zinenko if (!llvmModule) 2915a440378SAlex Zinenko return make_string_error("could not convert to LLVM IR"); 2925a440378SAlex Zinenko // FIXME: the triple should be passed to the translation or dialect conversion 2935a440378SAlex Zinenko // instead of this. Currently, the LLVM module created above has no triple 2945a440378SAlex Zinenko // associated with it. 2955a440378SAlex Zinenko setupTargetTriple(llvmModule.get()); 2965a440378SAlex Zinenko packFunctionArguments(llvmModule.get()); 2975a440378SAlex Zinenko 298cacf0589SNicolas Vasilache if (auto err = (*expectedJIT)->addModule(std::move(llvmModule))) 2995a440378SAlex Zinenko return std::move(err); 300cacf0589SNicolas Vasilache engine->jit = std::move(*expectedJIT); 3015a440378SAlex Zinenko 3025a440378SAlex Zinenko return engine; 3035a440378SAlex Zinenko } 3045a440378SAlex Zinenko 3055a440378SAlex Zinenko Expected<void (*)(void **)> ExecutionEngine::lookup(StringRef name) const { 3065a440378SAlex Zinenko auto expectedSymbol = jit->lookup(makePackedFunctionName(name)); 3075a440378SAlex Zinenko if (!expectedSymbol) 3085a440378SAlex Zinenko return expectedSymbol.takeError(); 3095a440378SAlex Zinenko auto rawFPtr = expectedSymbol->getAddress(); 3105a440378SAlex Zinenko auto fptr = reinterpret_cast<void (*)(void **)>(rawFPtr); 3115a440378SAlex Zinenko if (!fptr) 3125a440378SAlex Zinenko return make_string_error("looked up function is null"); 3135a440378SAlex Zinenko return fptr; 3145a440378SAlex Zinenko } 315629f5b7fSNicolas Vasilache 316629f5b7fSNicolas Vasilache llvm::Error ExecutionEngine::invoke(StringRef name, 317629f5b7fSNicolas Vasilache MutableArrayRef<void *> args) { 318629f5b7fSNicolas Vasilache auto expectedFPtr = lookup(name); 319629f5b7fSNicolas Vasilache if (!expectedFPtr) 320629f5b7fSNicolas Vasilache return expectedFPtr.takeError(); 321629f5b7fSNicolas Vasilache auto fptr = *expectedFPtr; 322629f5b7fSNicolas Vasilache 323629f5b7fSNicolas Vasilache (*fptr)(args.data()); 324629f5b7fSNicolas Vasilache 325629f5b7fSNicolas Vasilache return llvm::Error::success(); 326629f5b7fSNicolas Vasilache } 327