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.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.
make_string_error(const Twine & message)61 static Error make_string_error(const Twine &message) {
62 return llvm::make_error<StringError>(message.str(),
63 llvm::inconvertibleErrorCode());
64 }
65
notifyObjectCompiled(const Module * M,MemoryBufferRef ObjBuffer)66 void SimpleObjectCache::notifyObjectCompiled(const Module *M,
67 MemoryBufferRef ObjBuffer) {
68 cachedObjects[M->getModuleIdentifier()] = MemoryBuffer::getMemBufferCopy(
69 ObjBuffer.getBuffer(), ObjBuffer.getBufferIdentifier());
70 }
71
getObject(const Module * M)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
dumpToObjectFile(StringRef outputFilename)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
dumpToObjectFile(StringRef filename)100 void ExecutionEngine::dumpToObjectFile(StringRef filename) {
101 cache->dumpToObjectFile(filename);
102 }
103
registerSymbols(llvm::function_ref<SymbolMap (MangleAndInterner)> symbolMap)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.
setupTargetTriple(Module * llvmModule)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
makePackedFunctionName(StringRef name)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.
packFunctionArguments(Module * module)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
ExecutionEngine(bool enableObjectCache,bool enableGDBNotificationListener,bool enablePerfNotificationListener)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
create(ModuleOp m,llvm::function_ref<std::unique_ptr<llvm::Module> (ModuleOp,llvm::LLVMContext &)> llvmModuleBuilder,llvm::function_ref<Error (llvm::Module *)> transformer,Optional<llvm::CodeGenOpt::Level> jitCodeGenOptLevel,ArrayRef<StringRef> sharedLibPaths,bool enableObjectCache,bool enableGDBNotificationListener,bool enablePerfNotificationListener)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 // Resolve symbols from shared libraries.
259 for (auto libPath : sharedLibPaths) {
260 auto mb = llvm::MemoryBuffer::getFile(libPath);
261 if (!mb) {
262 errs() << "Failed to create MemoryBuffer for: " << libPath
263 << "\nError: " << mb.getError().message() << "\n";
264 continue;
265 }
266 auto &JD = session.createBareJITDylib(std::string(libPath));
267 auto loaded = DynamicLibrarySearchGenerator::Load(
268 libPath.data(), dataLayout.getGlobalPrefix());
269 if (!loaded) {
270 errs() << "Could not load " << libPath << ":\n " << loaded.takeError()
271 << "\n";
272 continue;
273 }
274 JD.addGenerator(std::move(*loaded));
275 cantFail(objectLayer->add(JD, std::move(mb.get())));
276 }
277
278 return objectLayer;
279 };
280
281 // Callback to inspect the cache and recompile on demand. This follows Lang's
282 // LLJITWithObjectCache example.
283 auto compileFunctionCreator = [&](JITTargetMachineBuilder JTMB)
284 -> Expected<std::unique_ptr<IRCompileLayer::IRCompiler>> {
285 if (jitCodeGenOptLevel)
286 JTMB.setCodeGenOptLevel(jitCodeGenOptLevel.getValue());
287 auto TM = JTMB.createTargetMachine();
288 if (!TM)
289 return TM.takeError();
290 return std::make_unique<TMOwningSimpleCompiler>(std::move(*TM),
291 engine->cache.get());
292 };
293
294 // Create the LLJIT by calling the LLJITBuilder with 2 callbacks.
295 auto jit =
296 cantFail(llvm::orc::LLJITBuilder()
297 .setCompileFunctionCreator(compileFunctionCreator)
298 .setObjectLinkingLayerCreator(objectLinkingLayerCreator)
299 .create());
300
301 // Add a ThreadSafemodule to the engine and return.
302 ThreadSafeModule tsm(std::move(llvmModule), std::move(ctx));
303 if (transformer)
304 cantFail(tsm.withModuleDo(
305 [&](llvm::Module &module) { return transformer(&module); }));
306 cantFail(jit->addIRModule(std::move(tsm)));
307 engine->jit = std::move(jit);
308
309 // Resolve symbols that are statically linked in the current process.
310 llvm::orc::JITDylib &mainJD = engine->jit->getMainJITDylib();
311 mainJD.addGenerator(
312 cantFail(DynamicLibrarySearchGenerator::GetForCurrentProcess(
313 dataLayout.getGlobalPrefix())));
314
315 return std::move(engine);
316 }
317
lookup(StringRef name) const318 Expected<void (*)(void **)> ExecutionEngine::lookup(StringRef name) const {
319 auto expectedSymbol = jit->lookup(makePackedFunctionName(name));
320
321 // JIT lookup may return an Error referring to strings stored internally by
322 // the JIT. If the Error outlives the ExecutionEngine, it would want have a
323 // dangling reference, which is currently caught by an assertion inside JIT
324 // thanks to hand-rolled reference counting. Rewrap the error message into a
325 // string before returning. Alternatively, ORC JIT should consider copying
326 // the string into the error message.
327 if (!expectedSymbol) {
328 std::string errorMessage;
329 llvm::raw_string_ostream os(errorMessage);
330 llvm::handleAllErrors(expectedSymbol.takeError(),
331 [&os](llvm::ErrorInfoBase &ei) { ei.log(os); });
332 return make_string_error(os.str());
333 }
334
335 auto rawFPtr = expectedSymbol->getAddress();
336 auto fptr = reinterpret_cast<void (*)(void **)>(rawFPtr);
337 if (!fptr)
338 return make_string_error("looked up function is null");
339 return fptr;
340 }
341
invoke(StringRef name,MutableArrayRef<void * > args)342 Error ExecutionEngine::invoke(StringRef name, MutableArrayRef<void *> args) {
343 auto expectedFPtr = lookup(name);
344 if (!expectedFPtr)
345 return expectedFPtr.takeError();
346 auto fptr = *expectedFPtr;
347
348 (*fptr)(args.data());
349
350 return Error::success();
351 }
352