1 //===- jit-runner.cpp - MLIR CPU Execution Driver Library -----------------===//
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 is a library that provides a shared implementation for command line
10 // utilities that execute an MLIR file on the CPU by translating MLIR to LLVM
11 // IR before JIT-compiling and executing the latter.
12 //
13 // The translation can be customized by providing an MLIR to MLIR
14 // transformation.
15 //===----------------------------------------------------------------------===//
16 
17 #include "mlir/ExecutionEngine/JitRunner.h"
18 
19 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
20 #include "mlir/ExecutionEngine/ExecutionEngine.h"
21 #include "mlir/ExecutionEngine/OptUtils.h"
22 #include "mlir/IR/BuiltinTypes.h"
23 #include "mlir/IR/MLIRContext.h"
24 #include "mlir/Parser.h"
25 #include "mlir/Support/FileUtilities.h"
26 
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/LegacyPassNameParser.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/StringSaver.h"
36 #include "llvm/Support/ToolOutputFile.h"
37 #include <cstdint>
38 #include <numeric>
39 
40 using namespace mlir;
41 using llvm::Error;
42 
43 namespace {
44 /// This options struct prevents the need for global static initializers, and
45 /// is only initialized if the JITRunner is invoked.
46 struct Options {
47   llvm::cl::opt<std::string> inputFilename{llvm::cl::Positional,
48                                            llvm::cl::desc("<input file>"),
49                                            llvm::cl::init("-")};
50   llvm::cl::opt<std::string> mainFuncName{
51       "e", llvm::cl::desc("The function to be called"),
52       llvm::cl::value_desc("<function name>"), llvm::cl::init("main")};
53   llvm::cl::opt<std::string> mainFuncType{
54       "entry-point-result",
55       llvm::cl::desc("Textual description of the function type to be called"),
56       llvm::cl::value_desc("f32 | i32 | i64 | void"), llvm::cl::init("f32")};
57 
58   llvm::cl::OptionCategory optFlags{"opt-like flags"};
59 
60   // CLI list of pass information
61   llvm::cl::list<const llvm::PassInfo *, bool, llvm::PassNameParser> llvmPasses{
62       llvm::cl::desc("LLVM optimizing passes to run"), llvm::cl::cat(optFlags)};
63 
64   // CLI variables for -On options.
65   llvm::cl::opt<bool> optO0{"O0",
66                             llvm::cl::desc("Run opt passes and codegen at O0"),
67                             llvm::cl::cat(optFlags)};
68   llvm::cl::opt<bool> optO1{"O1",
69                             llvm::cl::desc("Run opt passes and codegen at O1"),
70                             llvm::cl::cat(optFlags)};
71   llvm::cl::opt<bool> optO2{"O2",
72                             llvm::cl::desc("Run opt passes and codegen at O2"),
73                             llvm::cl::cat(optFlags)};
74   llvm::cl::opt<bool> optO3{"O3",
75                             llvm::cl::desc("Run opt passes and codegen at O3"),
76                             llvm::cl::cat(optFlags)};
77 
78   llvm::cl::OptionCategory clOptionsCategory{"linking options"};
79   llvm::cl::list<std::string> clSharedLibs{
80       "shared-libs", llvm::cl::desc("Libraries to link dynamically"),
81       llvm::cl::ZeroOrMore, llvm::cl::MiscFlags::CommaSeparated,
82       llvm::cl::cat(clOptionsCategory)};
83 
84   /// CLI variables for debugging.
85   llvm::cl::opt<bool> dumpObjectFile{
86       "dump-object-file",
87       llvm::cl::desc("Dump JITted-compiled object to file specified with "
88                      "-object-filename (<input file>.o by default).")};
89 
90   llvm::cl::opt<std::string> objectFilename{
91       "object-filename",
92       llvm::cl::desc("Dump JITted-compiled object to file <input file>.o")};
93 };
94 
95 struct CompileAndExecuteConfig {
96   /// LLVM module transformer that is passed to ExecutionEngine.
97   llvm::function_ref<llvm::Error(llvm::Module *)> transformer;
98 
99   /// A custom function that is passed to ExecutionEngine. It processes MLIR
100   /// module and creates LLVM IR module.
101   llvm::function_ref<std::unique_ptr<llvm::Module>(ModuleOp,
102                                                    llvm::LLVMContext &)>
103       llvmModuleBuilder;
104 
105   /// A custom function that is passed to ExecutinEngine to register symbols at
106   /// runtime.
107   llvm::function_ref<llvm::orc::SymbolMap(llvm::orc::MangleAndInterner)>
108       runtimeSymbolMap;
109 };
110 
111 } // namespace
112 
113 static OwningOpRef<ModuleOp> parseMLIRInput(StringRef inputFilename,
114                                             MLIRContext *context) {
115   // Set up the input file.
116   std::string errorMessage;
117   auto file = openInputFile(inputFilename, &errorMessage);
118   if (!file) {
119     llvm::errs() << errorMessage << "\n";
120     return nullptr;
121   }
122 
123   llvm::SourceMgr sourceMgr;
124   sourceMgr.AddNewSourceBuffer(std::move(file), SMLoc());
125   return OwningOpRef<ModuleOp>(parseSourceFile(sourceMgr, context));
126 }
127 
128 static inline Error makeStringError(const Twine &message) {
129   return llvm::make_error<llvm::StringError>(message.str(),
130                                              llvm::inconvertibleErrorCode());
131 }
132 
133 static Optional<unsigned> getCommandLineOptLevel(Options &options) {
134   Optional<unsigned> optLevel;
135   SmallVector<std::reference_wrapper<llvm::cl::opt<bool>>, 4> optFlags{
136       options.optO0, options.optO1, options.optO2, options.optO3};
137 
138   // Determine if there is an optimization flag present.
139   for (unsigned j = 0; j < 4; ++j) {
140     auto &flag = optFlags[j].get();
141     if (flag) {
142       optLevel = j;
143       break;
144     }
145   }
146   return optLevel;
147 }
148 
149 // JIT-compile the given module and run "entryPoint" with "args" as arguments.
150 static Error compileAndExecute(Options &options, ModuleOp module,
151                                StringRef entryPoint,
152                                CompileAndExecuteConfig config, void **args) {
153   Optional<llvm::CodeGenOpt::Level> jitCodeGenOptLevel;
154   if (auto clOptLevel = getCommandLineOptLevel(options))
155     jitCodeGenOptLevel =
156         static_cast<llvm::CodeGenOpt::Level>(clOptLevel.getValue());
157 
158   // If shared library implements custom mlir-runner library init and destroy
159   // functions, we'll use them to register the library with the execution
160   // engine. Otherwise we'll pass library directly to the execution engine.
161   SmallVector<SmallString<256>, 4> libPaths;
162 
163   // Use absolute library path so that gdb can find the symbol table.
164   transform(
165       options.clSharedLibs, std::back_inserter(libPaths),
166       [](std::string libPath) {
167         SmallString<256> absPath(libPath.begin(), libPath.end());
168         cantFail(llvm::errorCodeToError(llvm::sys::fs::make_absolute(absPath)));
169         return absPath;
170       });
171 
172   // Libraries that we'll pass to the ExecutionEngine for loading.
173   SmallVector<StringRef, 4> executionEngineLibs;
174 
175   using MlirRunnerInitFn = void (*)(llvm::StringMap<void *> &);
176   using MlirRunnerDestroyFn = void (*)();
177 
178   llvm::StringMap<void *> exportSymbols;
179   SmallVector<MlirRunnerDestroyFn> destroyFns;
180 
181   // Handle libraries that do support mlir-runner init/destroy callbacks.
182   for (auto &libPath : libPaths) {
183     auto lib = llvm::sys::DynamicLibrary::getPermanentLibrary(libPath.c_str());
184     void *initSym = lib.getAddressOfSymbol("__mlir_runner_init");
185     void *destroySim = lib.getAddressOfSymbol("__mlir_runner_destroy");
186 
187     // Library does not support mlir runner, load it with ExecutionEngine.
188     if (!initSym || !destroySim) {
189       executionEngineLibs.push_back(libPath);
190       continue;
191     }
192 
193     auto initFn = reinterpret_cast<MlirRunnerInitFn>(initSym);
194     initFn(exportSymbols);
195 
196     auto destroyFn = reinterpret_cast<MlirRunnerDestroyFn>(destroySim);
197     destroyFns.push_back(destroyFn);
198   }
199 
200   // Build a runtime symbol map from the config and exported symbols.
201   auto runtimeSymbolMap = [&](llvm::orc::MangleAndInterner interner) {
202     auto symbolMap = config.runtimeSymbolMap ? config.runtimeSymbolMap(interner)
203                                              : llvm::orc::SymbolMap();
204     for (auto &exportSymbol : exportSymbols)
205       symbolMap[interner(exportSymbol.getKey())] =
206           llvm::JITEvaluatedSymbol::fromPointer(exportSymbol.getValue());
207     return symbolMap;
208   };
209 
210   mlir::ExecutionEngineOptions engineOptions;
211   engineOptions.llvmModuleBuilder = config.llvmModuleBuilder;
212   engineOptions.transformer = config.transformer;
213   engineOptions.jitCodeGenOptLevel = jitCodeGenOptLevel;
214   engineOptions.sharedLibPaths = executionEngineLibs;
215   auto expectedEngine = mlir::ExecutionEngine::create(module, engineOptions);
216   if (!expectedEngine)
217     return expectedEngine.takeError();
218 
219   auto engine = std::move(*expectedEngine);
220   engine->registerSymbols(runtimeSymbolMap);
221 
222   auto expectedFPtr = engine->lookupPacked(entryPoint);
223   if (!expectedFPtr)
224     return expectedFPtr.takeError();
225 
226   if (options.dumpObjectFile)
227     engine->dumpToObjectFile(options.objectFilename.empty()
228                                  ? options.inputFilename + ".o"
229                                  : options.objectFilename);
230 
231   void (*fptr)(void **) = *expectedFPtr;
232   (*fptr)(args);
233 
234   // Run all dynamic library destroy callbacks to prepare for the shutdown.
235   llvm::for_each(destroyFns, [](MlirRunnerDestroyFn destroy) { destroy(); });
236 
237   return Error::success();
238 }
239 
240 static Error compileAndExecuteVoidFunction(Options &options, ModuleOp module,
241                                            StringRef entryPoint,
242                                            CompileAndExecuteConfig config) {
243   auto mainFunction = module.lookupSymbol<LLVM::LLVMFuncOp>(entryPoint);
244   if (!mainFunction || mainFunction.empty())
245     return makeStringError("entry point not found");
246   void *empty = nullptr;
247   return compileAndExecute(options, module, entryPoint, config, &empty);
248 }
249 
250 template <typename Type>
251 Error checkCompatibleReturnType(LLVM::LLVMFuncOp mainFunction);
252 template <>
253 Error checkCompatibleReturnType<int32_t>(LLVM::LLVMFuncOp mainFunction) {
254   auto resultType = mainFunction.getType()
255                         .cast<LLVM::LLVMFunctionType>()
256                         .getReturnType()
257                         .dyn_cast<IntegerType>();
258   if (!resultType || resultType.getWidth() != 32)
259     return makeStringError("only single i32 function result supported");
260   return Error::success();
261 }
262 template <>
263 Error checkCompatibleReturnType<int64_t>(LLVM::LLVMFuncOp mainFunction) {
264   auto resultType = mainFunction.getType()
265                         .cast<LLVM::LLVMFunctionType>()
266                         .getReturnType()
267                         .dyn_cast<IntegerType>();
268   if (!resultType || resultType.getWidth() != 64)
269     return makeStringError("only single i64 function result supported");
270   return Error::success();
271 }
272 template <>
273 Error checkCompatibleReturnType<float>(LLVM::LLVMFuncOp mainFunction) {
274   if (!mainFunction.getType()
275            .cast<LLVM::LLVMFunctionType>()
276            .getReturnType()
277            .isa<Float32Type>())
278     return makeStringError("only single f32 function result supported");
279   return Error::success();
280 }
281 template <typename Type>
282 Error compileAndExecuteSingleReturnFunction(Options &options, ModuleOp module,
283                                             StringRef entryPoint,
284                                             CompileAndExecuteConfig config) {
285   auto mainFunction = module.lookupSymbol<LLVM::LLVMFuncOp>(entryPoint);
286   if (!mainFunction || mainFunction.isExternal())
287     return makeStringError("entry point not found");
288 
289   if (mainFunction.getType().cast<LLVM::LLVMFunctionType>().getNumParams() != 0)
290     return makeStringError("function inputs not supported");
291 
292   if (Error error = checkCompatibleReturnType<Type>(mainFunction))
293     return error;
294 
295   Type res;
296   struct {
297     void *data;
298   } data;
299   data.data = &res;
300   if (auto error = compileAndExecute(options, module, entryPoint, config,
301                                      (void **)&data))
302     return error;
303 
304   // Intentional printing of the output so we can test.
305   llvm::outs() << res << '\n';
306 
307   return Error::success();
308 }
309 
310 /// Entry point for all CPU runners. Expects the common argc/argv arguments for
311 /// standard C++ main functions.
312 int mlir::JitRunnerMain(int argc, char **argv, const DialectRegistry &registry,
313                         JitRunnerConfig config) {
314   // Create the options struct containing the command line options for the
315   // runner. This must come before the command line options are parsed.
316   Options options;
317   llvm::cl::ParseCommandLineOptions(argc, argv, "MLIR CPU execution driver\n");
318 
319   Optional<unsigned> optLevel = getCommandLineOptLevel(options);
320   SmallVector<std::reference_wrapper<llvm::cl::opt<bool>>, 4> optFlags{
321       options.optO0, options.optO1, options.optO2, options.optO3};
322   unsigned optCLIPosition = 0;
323   // Determine if there is an optimization flag present, and its CLI position
324   // (optCLIPosition).
325   for (unsigned j = 0; j < 4; ++j) {
326     auto &flag = optFlags[j].get();
327     if (flag) {
328       optCLIPosition = flag.getPosition();
329       break;
330     }
331   }
332   // Generate vector of pass information, plus the index at which we should
333   // insert any optimization passes in that vector (optPosition).
334   SmallVector<const llvm::PassInfo *, 4> passes;
335   unsigned optPosition = 0;
336   for (unsigned i = 0, e = options.llvmPasses.size(); i < e; ++i) {
337     passes.push_back(options.llvmPasses[i]);
338     if (optCLIPosition < options.llvmPasses.getPosition(i)) {
339       optPosition = i;
340       optCLIPosition = UINT_MAX; // To ensure we never insert again
341     }
342   }
343 
344   MLIRContext context(registry);
345 
346   auto m = parseMLIRInput(options.inputFilename, &context);
347   if (!m) {
348     llvm::errs() << "could not parse the input IR\n";
349     return 1;
350   }
351 
352   if (config.mlirTransformer)
353     if (failed(config.mlirTransformer(m.get())))
354       return EXIT_FAILURE;
355 
356   auto tmBuilderOrError = llvm::orc::JITTargetMachineBuilder::detectHost();
357   if (!tmBuilderOrError) {
358     llvm::errs() << "Failed to create a JITTargetMachineBuilder for the host\n";
359     return EXIT_FAILURE;
360   }
361   auto tmOrError = tmBuilderOrError->createTargetMachine();
362   if (!tmOrError) {
363     llvm::errs() << "Failed to create a TargetMachine for the host\n";
364     return EXIT_FAILURE;
365   }
366 
367   auto transformer = mlir::makeLLVMPassesTransformer(
368       passes, optLevel, /*targetMachine=*/tmOrError->get(), optPosition);
369 
370   CompileAndExecuteConfig compileAndExecuteConfig;
371   compileAndExecuteConfig.transformer = transformer;
372   compileAndExecuteConfig.llvmModuleBuilder = config.llvmModuleBuilder;
373   compileAndExecuteConfig.runtimeSymbolMap = config.runtimesymbolMap;
374 
375   // Get the function used to compile and execute the module.
376   using CompileAndExecuteFnT =
377       Error (*)(Options &, ModuleOp, StringRef, CompileAndExecuteConfig);
378   auto compileAndExecuteFn =
379       StringSwitch<CompileAndExecuteFnT>(options.mainFuncType.getValue())
380           .Case("i32", compileAndExecuteSingleReturnFunction<int32_t>)
381           .Case("i64", compileAndExecuteSingleReturnFunction<int64_t>)
382           .Case("f32", compileAndExecuteSingleReturnFunction<float>)
383           .Case("void", compileAndExecuteVoidFunction)
384           .Default(nullptr);
385 
386   Error error = compileAndExecuteFn
387                     ? compileAndExecuteFn(options, m.get(),
388                                           options.mainFuncName.getValue(),
389                                           compileAndExecuteConfig)
390                     : makeStringError("unsupported function type");
391 
392   int exitCode = EXIT_SUCCESS;
393   llvm::handleAllErrors(std::move(error),
394                         [&exitCode](const llvm::ErrorInfoBase &info) {
395                           llvm::errs() << "Error: ";
396                           info.log(llvm::errs());
397                           llvm::errs() << '\n';
398                           exitCode = EXIT_FAILURE;
399                         });
400 
401   return exitCode;
402 }
403