1 //===- ExecutionEngine.cpp - MLIR Execution engine and utils --------------===// 2 // 3 // Copyright 2019 The MLIR Authors. 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 // ============================================================================= 17 // 18 // This file implements the execution engine for MLIR modules based on LLVM Orc 19 // JIT engine. 20 // 21 //===----------------------------------------------------------------------===// 22 #include "mlir/ExecutionEngine/ExecutionEngine.h" 23 #include "mlir/IR/Function.h" 24 #include "mlir/IR/Module.h" 25 #include "mlir/Support/FileUtilities.h" 26 #include "mlir/Target/LLVMIR.h" 27 28 #include "llvm/Bitcode/BitcodeReader.h" 29 #include "llvm/Bitcode/BitcodeWriter.h" 30 #include "llvm/ExecutionEngine/ObjectCache.h" 31 #include "llvm/ExecutionEngine/Orc/CompileUtils.h" 32 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" 33 #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" 34 #include "llvm/ExecutionEngine/Orc/IRTransformLayer.h" 35 #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" 36 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" 37 #include "llvm/ExecutionEngine/SectionMemoryManager.h" 38 #include "llvm/IR/IRBuilder.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/Error.h" 41 #include "llvm/Support/TargetRegistry.h" 42 #include "llvm/Support/ToolOutputFile.h" 43 44 #define DEBUG_TYPE "execution-engine" 45 46 using namespace mlir; 47 using llvm::dbgs; 48 using llvm::Error; 49 using llvm::errs; 50 using llvm::Expected; 51 using llvm::LLVMContext; 52 using llvm::MemoryBuffer; 53 using llvm::MemoryBufferRef; 54 using llvm::Module; 55 using llvm::SectionMemoryManager; 56 using llvm::StringError; 57 using llvm::Triple; 58 using llvm::orc::DynamicLibrarySearchGenerator; 59 using llvm::orc::ExecutionSession; 60 using llvm::orc::IRCompileLayer; 61 using llvm::orc::JITTargetMachineBuilder; 62 using llvm::orc::RTDyldObjectLinkingLayer; 63 using llvm::orc::ThreadSafeModule; 64 using llvm::orc::TMOwningSimpleCompiler; 65 66 // Wrap a string into an llvm::StringError. 67 static inline Error make_string_error(const Twine &message) { 68 return llvm::make_error<StringError>(message.str(), 69 llvm::inconvertibleErrorCode()); 70 } 71 72 namespace mlir { 73 74 void SimpleObjectCache::notifyObjectCompiled(const Module *M, 75 MemoryBufferRef ObjBuffer) { 76 cachedObjects[M->getModuleIdentifier()] = MemoryBuffer::getMemBufferCopy( 77 ObjBuffer.getBuffer(), ObjBuffer.getBufferIdentifier()); 78 } 79 80 std::unique_ptr<MemoryBuffer> SimpleObjectCache::getObject(const Module *M) { 81 auto I = cachedObjects.find(M->getModuleIdentifier()); 82 if (I == cachedObjects.end()) { 83 LLVM_DEBUG(dbgs() << "No object for " << M->getModuleIdentifier() 84 << " in cache. Compiling.\n"); 85 return nullptr; 86 } 87 LLVM_DEBUG(dbgs() << "Object for " << M->getModuleIdentifier() 88 << " loaded from cache.\n"); 89 return MemoryBuffer::getMemBuffer(I->second->getMemBufferRef()); 90 } 91 92 void SimpleObjectCache::dumpToObjectFile(StringRef outputFilename) { 93 // Set up the output file. 94 std::string errorMessage; 95 auto file = openOutputFile(outputFilename, &errorMessage); 96 if (!file) { 97 llvm::errs() << errorMessage << "\n"; 98 return; 99 } 100 101 // Dump the object generated for a single module to the output file. 102 assert(cachedObjects.size() == 1 && "Expected only one object entry."); 103 auto &cachedObject = cachedObjects.begin()->second; 104 file->os() << cachedObject->getBuffer(); 105 file->keep(); 106 } 107 108 void ExecutionEngine::dumpToObjectFile(StringRef filename) { 109 cache->dumpToObjectFile(filename); 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 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 : cache(enableObjectCache ? nullptr : new SimpleObjectCache()) {} 197 198 Expected<std::unique_ptr<ExecutionEngine>> ExecutionEngine::create( 199 ModuleOp m, std::function<Error(llvm::Module *)> transformer, 200 Optional<llvm::CodeGenOpt::Level> jitCodeGenOptLevel, 201 ArrayRef<StringRef> sharedLibPaths, bool enableObjectCache) { 202 auto engine = std::make_unique<ExecutionEngine>(enableObjectCache); 203 204 std::unique_ptr<llvm::LLVMContext> ctx(new llvm::LLVMContext); 205 auto llvmModule = translateModuleToLLVMIR(m); 206 if (!llvmModule) 207 return make_string_error("could not convert to LLVM IR"); 208 // FIXME: the triple should be passed to the translation or dialect conversion 209 // instead of this. Currently, the LLVM module created above has no triple 210 // associated with it. 211 setupTargetTriple(llvmModule.get()); 212 packFunctionArguments(llvmModule.get()); 213 214 // Clone module in a new LLVMContext since translateModuleToLLVMIR buries 215 // ownership too deeply. 216 // TODO(zinenko): Reevaluate model of ownership of LLVMContext in LLVMDialect. 217 SmallVector<char, 1> buffer; 218 { 219 llvm::raw_svector_ostream os(buffer); 220 WriteBitcodeToFile(*llvmModule, os); 221 } 222 llvm::MemoryBufferRef bufferRef(StringRef(buffer.data(), buffer.size()), 223 "cloned module buffer"); 224 auto expectedModule = parseBitcodeFile(bufferRef, *ctx); 225 if (!expectedModule) 226 return expectedModule.takeError(); 227 std::unique_ptr<Module> deserModule = std::move(*expectedModule); 228 229 // Callback to create the object layer with symbol resolution to current 230 // process and dynamically linked libraries. 231 auto objectLinkingLayerCreator = [&](ExecutionSession &session, 232 const Triple &TT) { 233 auto objectLayer = std::make_unique<RTDyldObjectLinkingLayer>( 234 session, []() { return std::make_unique<SectionMemoryManager>(); }); 235 auto dataLayout = deserModule->getDataLayout(); 236 llvm::orc::JITDylib *mainJD = session.getJITDylibByName("<main>"); 237 if (!mainJD) 238 mainJD = &session.createJITDylib("<main>"); 239 240 // Resolve symbols that are statically linked in the current process. 241 mainJD->addGenerator( 242 cantFail(DynamicLibrarySearchGenerator::GetForCurrentProcess( 243 dataLayout.getGlobalPrefix()))); 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.createJITDylib(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<IRCompileLayer::CompileFunction> { 271 if (jitCodeGenOptLevel) 272 JTMB.setCodeGenOptLevel(jitCodeGenOptLevel.getValue()); 273 auto TM = JTMB.createTargetMachine(); 274 if (!TM) 275 return TM.takeError(); 276 return IRCompileLayer::CompileFunction( 277 TMOwningSimpleCompiler(std::move(*TM), 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 return std::move(engine); 296 } 297 298 Expected<void (*)(void **)> ExecutionEngine::lookup(StringRef name) const { 299 auto expectedSymbol = jit->lookup(makePackedFunctionName(name)); 300 if (!expectedSymbol) 301 return expectedSymbol.takeError(); 302 auto rawFPtr = expectedSymbol->getAddress(); 303 auto fptr = reinterpret_cast<void (*)(void **)>(rawFPtr); 304 if (!fptr) 305 return make_string_error("looked up function is null"); 306 return fptr; 307 } 308 309 Error ExecutionEngine::invoke(StringRef name, MutableArrayRef<void *> args) { 310 auto expectedFPtr = lookup(name); 311 if (!expectedFPtr) 312 return expectedFPtr.takeError(); 313 auto fptr = *expectedFPtr; 314 315 (*fptr)(args.data()); 316 317 return Error::success(); 318 } 319 } // end namespace mlir 320