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/BuiltinOps.h" 16 #include "mlir/Support/FileUtilities.h" 17 #include "mlir/Target/LLVMIR/Export.h" 18 19 #include "llvm/ExecutionEngine/JITEventListener.h" 20 #include "llvm/ExecutionEngine/ObjectCache.h" 21 #include "llvm/ExecutionEngine/Orc/CompileUtils.h" 22 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" 23 #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" 24 #include "llvm/ExecutionEngine/Orc/IRTransformLayer.h" 25 #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" 26 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" 27 #include "llvm/ExecutionEngine/SectionMemoryManager.h" 28 #include "llvm/IR/IRBuilder.h" 29 #include "llvm/MC/SubtargetFeature.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 123 std::string cpu(llvm::sys::getHostCPUName()); 124 llvm::SubtargetFeatures features; 125 llvm::StringMap<bool> hostFeatures; 126 127 if (llvm::sys::getHostCPUFeatures(hostFeatures)) 128 for (auto &f : hostFeatures) 129 features.AddFeature(f.first(), f.second); 130 131 std::unique_ptr<llvm::TargetMachine> machine(target->createTargetMachine( 132 targetTriple, cpu, features.getString(), {}, {})); 133 if (!machine) { 134 errs() << "Unable to create target machine\n"; 135 return true; 136 } 137 llvmModule->setDataLayout(machine->createDataLayout()); 138 llvmModule->setTargetTriple(targetTriple); 139 return false; 140 } 141 142 static std::string makePackedFunctionName(StringRef name) { 143 return "_mlir_" + name.str(); 144 } 145 146 // For each function in the LLVM module, define an interface function that wraps 147 // all the arguments of the original function and all its results into an i8** 148 // pointer to provide a unified invocation interface. 149 static void packFunctionArguments(Module *module) { 150 auto &ctx = module->getContext(); 151 llvm::IRBuilder<> builder(ctx); 152 DenseSet<llvm::Function *> interfaceFunctions; 153 for (auto &func : module->getFunctionList()) { 154 if (func.isDeclaration()) { 155 continue; 156 } 157 if (interfaceFunctions.count(&func)) { 158 continue; 159 } 160 161 // Given a function `foo(<...>)`, define the interface function 162 // `mlir_foo(i8**)`. 163 auto newType = llvm::FunctionType::get( 164 builder.getVoidTy(), builder.getInt8PtrTy()->getPointerTo(), 165 /*isVarArg=*/false); 166 auto newName = makePackedFunctionName(func.getName()); 167 auto funcCst = module->getOrInsertFunction(newName, newType); 168 llvm::Function *interfaceFunc = cast<llvm::Function>(funcCst.getCallee()); 169 interfaceFunctions.insert(interfaceFunc); 170 171 // Extract the arguments from the type-erased argument list and cast them to 172 // the proper types. 173 auto bb = llvm::BasicBlock::Create(ctx); 174 bb->insertInto(interfaceFunc); 175 builder.SetInsertPoint(bb); 176 llvm::Value *argList = interfaceFunc->arg_begin(); 177 SmallVector<llvm::Value *, 8> args; 178 args.reserve(llvm::size(func.args())); 179 for (auto &indexedArg : llvm::enumerate(func.args())) { 180 llvm::Value *argIndex = llvm::Constant::getIntegerValue( 181 builder.getInt64Ty(), APInt(64, indexedArg.index())); 182 llvm::Value *argPtrPtr = builder.CreateGEP(argList, argIndex); 183 llvm::Value *argPtr = builder.CreateLoad(argPtrPtr); 184 argPtr = builder.CreateBitCast( 185 argPtr, indexedArg.value().getType()->getPointerTo()); 186 llvm::Value *arg = builder.CreateLoad(argPtr); 187 args.push_back(arg); 188 } 189 190 // Call the implementation function with the extracted arguments. 191 llvm::Value *result = builder.CreateCall(&func, args); 192 193 // Assuming the result is one value, potentially of type `void`. 194 if (!result->getType()->isVoidTy()) { 195 llvm::Value *retIndex = llvm::Constant::getIntegerValue( 196 builder.getInt64Ty(), APInt(64, llvm::size(func.args()))); 197 llvm::Value *retPtrPtr = builder.CreateGEP(argList, retIndex); 198 llvm::Value *retPtr = builder.CreateLoad(retPtrPtr); 199 retPtr = builder.CreateBitCast(retPtr, result->getType()->getPointerTo()); 200 builder.CreateStore(result, retPtr); 201 } 202 203 // The interface function returns void. 204 builder.CreateRetVoid(); 205 } 206 } 207 208 ExecutionEngine::ExecutionEngine(bool enableObjectCache, 209 bool enableGDBNotificationListener, 210 bool enablePerfNotificationListener) 211 : cache(enableObjectCache ? new SimpleObjectCache() : nullptr), 212 gdbListener(enableGDBNotificationListener 213 ? llvm::JITEventListener::createGDBRegistrationListener() 214 : nullptr), 215 perfListener(enablePerfNotificationListener 216 ? llvm::JITEventListener::createPerfJITEventListener() 217 : nullptr) {} 218 219 Expected<std::unique_ptr<ExecutionEngine>> ExecutionEngine::create( 220 ModuleOp m, 221 llvm::function_ref<std::unique_ptr<llvm::Module>(ModuleOp, 222 llvm::LLVMContext &)> 223 llvmModuleBuilder, 224 llvm::function_ref<Error(llvm::Module *)> transformer, 225 Optional<llvm::CodeGenOpt::Level> jitCodeGenOptLevel, 226 ArrayRef<StringRef> sharedLibPaths, bool enableObjectCache, 227 bool enableGDBNotificationListener, bool enablePerfNotificationListener) { 228 auto engine = std::make_unique<ExecutionEngine>( 229 enableObjectCache, enableGDBNotificationListener, 230 enablePerfNotificationListener); 231 232 std::unique_ptr<llvm::LLVMContext> ctx(new llvm::LLVMContext); 233 auto llvmModule = llvmModuleBuilder ? llvmModuleBuilder(m, *ctx) 234 : translateModuleToLLVMIR(m, *ctx); 235 if (!llvmModule) 236 return make_string_error("could not convert to LLVM IR"); 237 // FIXME: the triple should be passed to the translation or dialect conversion 238 // instead of this. Currently, the LLVM module created above has no triple 239 // associated with it. 240 setupTargetTriple(llvmModule.get()); 241 packFunctionArguments(llvmModule.get()); 242 243 auto dataLayout = llvmModule->getDataLayout(); 244 245 // Callback to create the object layer with symbol resolution to current 246 // process and dynamically linked libraries. 247 auto objectLinkingLayerCreator = [&](ExecutionSession &session, 248 const Triple &TT) { 249 auto objectLayer = std::make_unique<RTDyldObjectLinkingLayer>( 250 session, []() { return std::make_unique<SectionMemoryManager>(); }); 251 252 // Register JIT event listeners if they are enabled. 253 if (engine->gdbListener) 254 objectLayer->registerJITEventListener(*engine->gdbListener); 255 if (engine->perfListener) 256 objectLayer->registerJITEventListener(*engine->perfListener); 257 258 // COFF format binaries (Windows) need special handling to deal with 259 // exported symbol visibility. 260 // cf llvm/lib/ExecutionEngine/Orc/LLJIT.cpp LLJIT::createObjectLinkingLayer 261 llvm::Triple targetTriple(llvm::Twine(llvmModule->getTargetTriple())); 262 if (targetTriple.isOSBinFormatCOFF()) { 263 objectLayer->setOverrideObjectFlagsWithResponsibilityFlags(true); 264 objectLayer->setAutoClaimResponsibilityForObjectSymbols(true); 265 } 266 267 // Resolve symbols from shared libraries. 268 for (auto libPath : sharedLibPaths) { 269 auto mb = llvm::MemoryBuffer::getFile(libPath); 270 if (!mb) { 271 errs() << "Failed to create MemoryBuffer for: " << libPath 272 << "\nError: " << mb.getError().message() << "\n"; 273 continue; 274 } 275 auto &JD = session.createBareJITDylib(std::string(libPath)); 276 auto loaded = DynamicLibrarySearchGenerator::Load( 277 libPath.data(), dataLayout.getGlobalPrefix()); 278 if (!loaded) { 279 errs() << "Could not load " << libPath << ":\n " << loaded.takeError() 280 << "\n"; 281 continue; 282 } 283 JD.addGenerator(std::move(*loaded)); 284 cantFail(objectLayer->add(JD, std::move(mb.get()))); 285 } 286 287 return objectLayer; 288 }; 289 290 // Callback to inspect the cache and recompile on demand. This follows Lang's 291 // LLJITWithObjectCache example. 292 auto compileFunctionCreator = [&](JITTargetMachineBuilder JTMB) 293 -> Expected<std::unique_ptr<IRCompileLayer::IRCompiler>> { 294 if (jitCodeGenOptLevel) 295 JTMB.setCodeGenOptLevel(jitCodeGenOptLevel.getValue()); 296 auto TM = JTMB.createTargetMachine(); 297 if (!TM) 298 return TM.takeError(); 299 return std::make_unique<TMOwningSimpleCompiler>(std::move(*TM), 300 engine->cache.get()); 301 }; 302 303 // Create the LLJIT by calling the LLJITBuilder with 2 callbacks. 304 auto jit = 305 cantFail(llvm::orc::LLJITBuilder() 306 .setCompileFunctionCreator(compileFunctionCreator) 307 .setObjectLinkingLayerCreator(objectLinkingLayerCreator) 308 .create()); 309 310 // Add a ThreadSafemodule to the engine and return. 311 ThreadSafeModule tsm(std::move(llvmModule), std::move(ctx)); 312 if (transformer) 313 cantFail(tsm.withModuleDo( 314 [&](llvm::Module &module) { return transformer(&module); })); 315 cantFail(jit->addIRModule(std::move(tsm))); 316 engine->jit = std::move(jit); 317 318 // Resolve symbols that are statically linked in the current process. 319 llvm::orc::JITDylib &mainJD = engine->jit->getMainJITDylib(); 320 mainJD.addGenerator( 321 cantFail(DynamicLibrarySearchGenerator::GetForCurrentProcess( 322 dataLayout.getGlobalPrefix()))); 323 324 return std::move(engine); 325 } 326 327 Expected<void (*)(void **)> ExecutionEngine::lookup(StringRef name) const { 328 auto expectedSymbol = jit->lookup(makePackedFunctionName(name)); 329 330 // JIT lookup may return an Error referring to strings stored internally by 331 // the JIT. If the Error outlives the ExecutionEngine, it would want have a 332 // dangling reference, which is currently caught by an assertion inside JIT 333 // thanks to hand-rolled reference counting. Rewrap the error message into a 334 // string before returning. Alternatively, ORC JIT should consider copying 335 // the string into the error message. 336 if (!expectedSymbol) { 337 std::string errorMessage; 338 llvm::raw_string_ostream os(errorMessage); 339 llvm::handleAllErrors(expectedSymbol.takeError(), 340 [&os](llvm::ErrorInfoBase &ei) { ei.log(os); }); 341 return make_string_error(os.str()); 342 } 343 344 auto rawFPtr = expectedSymbol->getAddress(); 345 auto fptr = reinterpret_cast<void (*)(void **)>(rawFPtr); 346 if (!fptr) 347 return make_string_error("looked up function is null"); 348 return fptr; 349 } 350 351 Error ExecutionEngine::invokePacked(StringRef name, 352 MutableArrayRef<void *> args) { 353 auto expectedFPtr = lookup(name); 354 if (!expectedFPtr) 355 return expectedFPtr.takeError(); 356 auto fptr = *expectedFPtr; 357 358 (*fptr)(args.data()); 359 360 return Error::success(); 361 } 362