1 //===- ExecutionEngine.cpp - MLIR Execution engine and utils --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the execution engine for MLIR modules based on LLVM Orc 10 // JIT engine. 11 // 12 //===----------------------------------------------------------------------===// 13 #include "mlir/ExecutionEngine/ExecutionEngine.h" 14 #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 15 #include "mlir/IR/Function.h" 16 #include "mlir/IR/Module.h" 17 #include "mlir/Support/FileUtilities.h" 18 #include "mlir/Target/LLVMIR.h" 19 20 #include "llvm/ExecutionEngine/JITEventListener.h" 21 #include "llvm/ExecutionEngine/ObjectCache.h" 22 #include "llvm/ExecutionEngine/Orc/CompileUtils.h" 23 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" 24 #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" 25 #include "llvm/ExecutionEngine/Orc/IRTransformLayer.h" 26 #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" 27 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" 28 #include "llvm/ExecutionEngine/SectionMemoryManager.h" 29 #include "llvm/IR/IRBuilder.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/Error.h" 32 #include "llvm/Support/Host.h" 33 #include "llvm/Support/TargetRegistry.h" 34 #include "llvm/Support/ToolOutputFile.h" 35 36 #define DEBUG_TYPE "execution-engine" 37 38 using namespace mlir; 39 using llvm::dbgs; 40 using llvm::Error; 41 using llvm::errs; 42 using llvm::Expected; 43 using llvm::LLVMContext; 44 using llvm::MemoryBuffer; 45 using llvm::MemoryBufferRef; 46 using llvm::Module; 47 using llvm::SectionMemoryManager; 48 using llvm::StringError; 49 using llvm::Triple; 50 using llvm::orc::DynamicLibrarySearchGenerator; 51 using llvm::orc::ExecutionSession; 52 using llvm::orc::IRCompileLayer; 53 using llvm::orc::JITTargetMachineBuilder; 54 using llvm::orc::MangleAndInterner; 55 using llvm::orc::RTDyldObjectLinkingLayer; 56 using llvm::orc::SymbolMap; 57 using llvm::orc::ThreadSafeModule; 58 using llvm::orc::TMOwningSimpleCompiler; 59 60 /// Wrap a string into an llvm::StringError. 61 static Error make_string_error(const Twine &message) { 62 return llvm::make_error<StringError>(message.str(), 63 llvm::inconvertibleErrorCode()); 64 } 65 66 void SimpleObjectCache::notifyObjectCompiled(const Module *M, 67 MemoryBufferRef ObjBuffer) { 68 cachedObjects[M->getModuleIdentifier()] = MemoryBuffer::getMemBufferCopy( 69 ObjBuffer.getBuffer(), ObjBuffer.getBufferIdentifier()); 70 } 71 72 std::unique_ptr<MemoryBuffer> SimpleObjectCache::getObject(const Module *M) { 73 auto I = cachedObjects.find(M->getModuleIdentifier()); 74 if (I == cachedObjects.end()) { 75 LLVM_DEBUG(dbgs() << "No object for " << M->getModuleIdentifier() 76 << " in cache. Compiling.\n"); 77 return nullptr; 78 } 79 LLVM_DEBUG(dbgs() << "Object for " << M->getModuleIdentifier() 80 << " loaded from cache.\n"); 81 return MemoryBuffer::getMemBuffer(I->second->getMemBufferRef()); 82 } 83 84 void SimpleObjectCache::dumpToObjectFile(StringRef outputFilename) { 85 // Set up the output file. 86 std::string errorMessage; 87 auto file = openOutputFile(outputFilename, &errorMessage); 88 if (!file) { 89 llvm::errs() << errorMessage << "\n"; 90 return; 91 } 92 93 // Dump the object generated for a single module to the output file. 94 assert(cachedObjects.size() == 1 && "Expected only one object entry."); 95 auto &cachedObject = cachedObjects.begin()->second; 96 file->os() << cachedObject->getBuffer(); 97 file->keep(); 98 } 99 100 void ExecutionEngine::dumpToObjectFile(StringRef filename) { 101 cache->dumpToObjectFile(filename); 102 } 103 104 void ExecutionEngine::registerSymbols( 105 llvm::function_ref<SymbolMap(MangleAndInterner)> symbolMap) { 106 auto &mainJitDylib = jit->getMainJITDylib(); 107 cantFail(mainJitDylib.define( 108 absoluteSymbols(symbolMap(llvm::orc::MangleAndInterner( 109 mainJitDylib.getExecutionSession(), jit->getDataLayout()))))); 110 } 111 112 // Setup LLVM target triple from the current machine. 113 bool ExecutionEngine::setupTargetTriple(Module *llvmModule) { 114 // Setup the machine properties from the current architecture. 115 auto targetTriple = llvm::sys::getDefaultTargetTriple(); 116 std::string errorMessage; 117 auto target = llvm::TargetRegistry::lookupTarget(targetTriple, errorMessage); 118 if (!target) { 119 errs() << "NO target: " << errorMessage << "\n"; 120 return true; 121 } 122 std::unique_ptr<llvm::TargetMachine> machine( 123 target->createTargetMachine(targetTriple, "generic", "", {}, {})); 124 llvmModule->setDataLayout(machine->createDataLayout()); 125 llvmModule->setTargetTriple(targetTriple); 126 return false; 127 } 128 129 static std::string makePackedFunctionName(StringRef name) { 130 return "_mlir_" + name.str(); 131 } 132 133 // For each function in the LLVM module, define an interface function that wraps 134 // all the arguments of the original function and all its results into an i8** 135 // pointer to provide a unified invocation interface. 136 static void packFunctionArguments(Module *module) { 137 auto &ctx = module->getContext(); 138 llvm::IRBuilder<> builder(ctx); 139 DenseSet<llvm::Function *> interfaceFunctions; 140 for (auto &func : module->getFunctionList()) { 141 if (func.isDeclaration()) { 142 continue; 143 } 144 if (interfaceFunctions.count(&func)) { 145 continue; 146 } 147 148 // Given a function `foo(<...>)`, define the interface function 149 // `mlir_foo(i8**)`. 150 auto newType = llvm::FunctionType::get( 151 builder.getVoidTy(), builder.getInt8PtrTy()->getPointerTo(), 152 /*isVarArg=*/false); 153 auto newName = makePackedFunctionName(func.getName()); 154 auto funcCst = module->getOrInsertFunction(newName, newType); 155 llvm::Function *interfaceFunc = cast<llvm::Function>(funcCst.getCallee()); 156 interfaceFunctions.insert(interfaceFunc); 157 158 // Extract the arguments from the type-erased argument list and cast them to 159 // the proper types. 160 auto bb = llvm::BasicBlock::Create(ctx); 161 bb->insertInto(interfaceFunc); 162 builder.SetInsertPoint(bb); 163 llvm::Value *argList = interfaceFunc->arg_begin(); 164 SmallVector<llvm::Value *, 8> args; 165 args.reserve(llvm::size(func.args())); 166 for (auto &indexedArg : llvm::enumerate(func.args())) { 167 llvm::Value *argIndex = llvm::Constant::getIntegerValue( 168 builder.getInt64Ty(), APInt(64, indexedArg.index())); 169 llvm::Value *argPtrPtr = builder.CreateGEP(argList, argIndex); 170 llvm::Value *argPtr = builder.CreateLoad(argPtrPtr); 171 argPtr = builder.CreateBitCast( 172 argPtr, indexedArg.value().getType()->getPointerTo()); 173 llvm::Value *arg = builder.CreateLoad(argPtr); 174 args.push_back(arg); 175 } 176 177 // Call the implementation function with the extracted arguments. 178 llvm::Value *result = builder.CreateCall(&func, args); 179 180 // Assuming the result is one value, potentially of type `void`. 181 if (!result->getType()->isVoidTy()) { 182 llvm::Value *retIndex = llvm::Constant::getIntegerValue( 183 builder.getInt64Ty(), APInt(64, llvm::size(func.args()))); 184 llvm::Value *retPtrPtr = builder.CreateGEP(argList, retIndex); 185 llvm::Value *retPtr = builder.CreateLoad(retPtrPtr); 186 retPtr = builder.CreateBitCast(retPtr, result->getType()->getPointerTo()); 187 builder.CreateStore(result, retPtr); 188 } 189 190 // The interface function returns void. 191 builder.CreateRetVoid(); 192 } 193 } 194 195 ExecutionEngine::ExecutionEngine(bool enableObjectCache, 196 bool enableGDBNotificationListener, 197 bool enablePerfNotificationListener) 198 : cache(enableObjectCache ? new SimpleObjectCache() : nullptr), 199 gdbListener(enableGDBNotificationListener 200 ? llvm::JITEventListener::createGDBRegistrationListener() 201 : nullptr), 202 perfListener(enablePerfNotificationListener 203 ? llvm::JITEventListener::createPerfJITEventListener() 204 : nullptr) {} 205 206 Expected<std::unique_ptr<ExecutionEngine>> ExecutionEngine::create( 207 ModuleOp m, llvm::function_ref<Error(llvm::Module *)> transformer, 208 Optional<llvm::CodeGenOpt::Level> jitCodeGenOptLevel, 209 ArrayRef<StringRef> sharedLibPaths, bool enableObjectCache, 210 bool enableGDBNotificationListener, bool enablePerfNotificationListener) { 211 auto engine = std::make_unique<ExecutionEngine>( 212 enableObjectCache, enableGDBNotificationListener, 213 enablePerfNotificationListener); 214 215 std::unique_ptr<llvm::LLVMContext> ctx(new llvm::LLVMContext); 216 auto llvmModule = translateModuleToLLVMIR(m); 217 if (!llvmModule) 218 return make_string_error("could not convert to LLVM IR"); 219 // FIXME: the triple should be passed to the translation or dialect conversion 220 // instead of this. Currently, the LLVM module created above has no triple 221 // associated with it. 222 setupTargetTriple(llvmModule.get()); 223 packFunctionArguments(llvmModule.get()); 224 225 // Clone module in a new LLVMContext since translateModuleToLLVMIR buries 226 // ownership too deeply. 227 // TODO(zinenko): Reevaluate model of ownership of LLVMContext in LLVMDialect. 228 std::unique_ptr<Module> deserModule = 229 LLVM::cloneModuleIntoNewContext(ctx.get(), llvmModule.get()); 230 auto dataLayout = deserModule->getDataLayout(); 231 232 // Callback to create the object layer with symbol resolution to current 233 // process and dynamically linked libraries. 234 auto objectLinkingLayerCreator = [&](ExecutionSession &session, 235 const Triple &TT) { 236 auto objectLayer = std::make_unique<RTDyldObjectLinkingLayer>( 237 session, []() { return std::make_unique<SectionMemoryManager>(); }); 238 239 // Register JIT event listeners if they are enabled. 240 if (engine->gdbListener) 241 objectLayer->registerJITEventListener(*engine->gdbListener); 242 if (engine->perfListener) 243 objectLayer->registerJITEventListener(*engine->perfListener); 244 245 // Resolve symbols from shared libraries. 246 for (auto libPath : sharedLibPaths) { 247 auto mb = llvm::MemoryBuffer::getFile(libPath); 248 if (!mb) { 249 errs() << "Fail to create MemoryBuffer for: " << libPath << "\n"; 250 continue; 251 } 252 auto &JD = session.createBareJITDylib(std::string(libPath)); 253 auto loaded = DynamicLibrarySearchGenerator::Load( 254 libPath.data(), dataLayout.getGlobalPrefix()); 255 if (!loaded) { 256 errs() << "Could not load " << libPath << ":\n " << loaded.takeError() 257 << "\n"; 258 continue; 259 } 260 JD.addGenerator(std::move(*loaded)); 261 cantFail(objectLayer->add(JD, std::move(mb.get()))); 262 } 263 264 return objectLayer; 265 }; 266 267 // Callback to inspect the cache and recompile on demand. This follows Lang's 268 // LLJITWithObjectCache example. 269 auto compileFunctionCreator = [&](JITTargetMachineBuilder JTMB) 270 -> Expected<std::unique_ptr<IRCompileLayer::IRCompiler>> { 271 if (jitCodeGenOptLevel) 272 JTMB.setCodeGenOptLevel(jitCodeGenOptLevel.getValue()); 273 auto TM = JTMB.createTargetMachine(); 274 if (!TM) 275 return TM.takeError(); 276 return std::make_unique<TMOwningSimpleCompiler>(std::move(*TM), 277 engine->cache.get()); 278 }; 279 280 // Create the LLJIT by calling the LLJITBuilder with 2 callbacks. 281 auto jit = 282 cantFail(llvm::orc::LLJITBuilder() 283 .setCompileFunctionCreator(compileFunctionCreator) 284 .setObjectLinkingLayerCreator(objectLinkingLayerCreator) 285 .create()); 286 287 // Add a ThreadSafemodule to the engine and return. 288 ThreadSafeModule tsm(std::move(deserModule), std::move(ctx)); 289 if (transformer) 290 cantFail(tsm.withModuleDo( 291 [&](llvm::Module &module) { return transformer(&module); })); 292 cantFail(jit->addIRModule(std::move(tsm))); 293 engine->jit = std::move(jit); 294 295 // Resolve symbols that are statically linked in the current process. 296 llvm::orc::JITDylib &mainJD = engine->jit->getMainJITDylib(); 297 mainJD.addGenerator( 298 cantFail(DynamicLibrarySearchGenerator::GetForCurrentProcess( 299 dataLayout.getGlobalPrefix()))); 300 301 return std::move(engine); 302 } 303 304 Expected<void (*)(void **)> ExecutionEngine::lookup(StringRef name) const { 305 auto expectedSymbol = jit->lookup(makePackedFunctionName(name)); 306 307 // JIT lookup may return an Error referring to strings stored internally by 308 // the JIT. If the Error outlives the ExecutionEngine, it would want have a 309 // dangling reference, which is currently caught by an assertion inside JIT 310 // thanks to hand-rolled reference counting. Rewrap the error message into a 311 // string before returning. Alternatively, ORC JIT should consider copying 312 // the string into the error message. 313 if (!expectedSymbol) { 314 std::string errorMessage; 315 llvm::raw_string_ostream os(errorMessage); 316 llvm::handleAllErrors(expectedSymbol.takeError(), 317 [&os](llvm::ErrorInfoBase &ei) { ei.log(os); }); 318 return make_string_error(os.str()); 319 } 320 321 auto rawFPtr = expectedSymbol->getAddress(); 322 auto fptr = reinterpret_cast<void (*)(void **)>(rawFPtr); 323 if (!fptr) 324 return make_string_error("looked up function is null"); 325 return fptr; 326 } 327 328 Error ExecutionEngine::invoke(StringRef name, MutableArrayRef<void *> args) { 329 auto expectedFPtr = lookup(name); 330 if (!expectedFPtr) 331 return expectedFPtr.takeError(); 332 auto fptr = *expectedFPtr; 333 334 (*fptr)(args.data()); 335 336 return Error::success(); 337 } 338