MLIR 23.0.0git
ExecutionEngineModule.cpp
Go to the documentation of this file.
1//===- ExecutionEngineModule.cpp - Python module for execution engine -----===//
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
13
14namespace nb = nanobind;
15
16namespace mlir {
17namespace python {
20
21/// Owning Wrapper around an ExecutionEngine.
23public:
24 PyExecutionEngine(MlirExecutionEngine executionEngine)
25 : executionEngine(executionEngine) {}
27 : executionEngine(other.executionEngine) {
28 other.executionEngine.ptr = nullptr;
29 }
31 if (!mlirExecutionEngineIsNull(executionEngine))
32 mlirExecutionEngineDestroy(executionEngine);
33 }
34 MlirExecutionEngine get() { return executionEngine; }
35
36 void release() {
37 executionEngine.ptr = nullptr;
38 referencedObjects.clear();
39 }
40 nb::object getCapsule() {
41 return nb::steal<nb::object>(mlirPythonExecutionEngineToCapsule(get()));
42 }
43
44 // Add an object to the list of referenced objects whose lifetime must exceed
45 // those of the ExecutionEngine.
46 void addReferencedObject(const nb::object &obj) {
47 referencedObjects.push_back(obj);
48 }
49
50 static nb::object createFromCapsule(const nb::object &capsule) {
51 MlirExecutionEngine rawPm =
54 throw nb::python_error();
55 return nb::cast(PyExecutionEngine(rawPm), nb::rv_policy::move);
56 }
57
58private:
59 MlirExecutionEngine executionEngine;
60 // We support Python ctypes closures as callbacks. Keep a list of the objects
61 // so that they don't get garbage collected. (The ExecutionEngine itself
62 // just holds raw pointers with no lifetime semantics).
63 std::vector<nb::object> referencedObjects;
64};
65
66} // namespace execution_engine
67} // namespace MLIR_BINDINGS_PYTHON_DOMAIN
68} // namespace python
69} // namespace mlir
70
71/// Create the `mlir.execution_engine` module here.
72NB_MODULE(_mlirExecutionEngine, m) {
73 m.doc() = "MLIR Execution Engine";
74
76 using namespace execution_engine;
77 //----------------------------------------------------------------------------
78 // Mapping of the top-level PassManager
79 //----------------------------------------------------------------------------
80 nb::class_<PyExecutionEngine>(m, "ExecutionEngine")
81 .def(
82 "__init__",
83 [](PyExecutionEngine &self, PyModule &module, int optLevel,
84 const std::vector<std::string> &sharedLibPaths,
85 bool enableObjectDump, bool enablePIC) {
87 for (const std::string &path : sharedLibPaths)
88 libPaths.push_back({path.c_str(), path.length()});
89 MlirExecutionEngine executionEngine = mlirExecutionEngineCreate(
90 module.get(), optLevel, libPaths.size(), libPaths.data(),
91 enableObjectDump, enablePIC);
92 if (mlirExecutionEngineIsNull(executionEngine))
93 throw std::runtime_error(
94 "Failure while creating the ExecutionEngine.");
95 new (&self) PyExecutionEngine(executionEngine);
96 },
97 nb::arg("module"), nb::arg("opt_level") = 2,
98 nb::arg("shared_libs") = nb::list(),
99 nb::arg("enable_object_dump") = true, nb::arg("enable_pic") = false,
100 "Create a new ExecutionEngine instance for the given Module. The "
101 "module must contain only dialects that can be translated to LLVM. "
102 "Perform transformations and code generation at the optimization "
103 "level `opt_level` if specified, or otherwise at the default "
104 "level of two (-O2). Load a list of libraries specified in "
105 "`shared_libs`.")
106 .def_prop_ro(MLIR_PYTHON_CAPI_PTR_ATTR, &PyExecutionEngine::getCapsule)
107 .def("_testing_release", &PyExecutionEngine::release,
108 "Releases (leaks) the backing ExecutionEngine (for testing purpose)")
109 .def(MLIR_PYTHON_CAPI_FACTORY_ATTR, &PyExecutionEngine::createFromCapsule)
110 .def(
111 "raw_lookup",
112 [](PyExecutionEngine &executionEngine, const std::string &func) {
114 executionEngine.get(),
115 mlirStringRefCreate(func.c_str(), func.size()));
116 return reinterpret_cast<uintptr_t>(res);
117 },
118 nb::arg("func_name"),
119 "Lookup function `func` in the ExecutionEngine.")
120 .def(
121 "raw_register_runtime",
122 [](PyExecutionEngine &executionEngine, const std::string &name,
123 const nb::object &callbackObj) {
124 executionEngine.addReferencedObject(callbackObj);
125 uintptr_t rawSym =
126 nb::cast<uintptr_t>(nb::getattr(callbackObj, "value"));
128 executionEngine.get(),
129 mlirStringRefCreate(name.c_str(), name.size()),
130 reinterpret_cast<void *>(rawSym));
131 },
132 nb::arg("name"), nb::arg("callback"),
133 "Register `callback` as the runtime symbol `name`.")
134 .def(
135 "initialize",
136 [](PyExecutionEngine &executionEngine) {
137 mlirExecutionEngineInitialize(executionEngine.get());
138 },
139 "Initialize the ExecutionEngine. Global constructors specified by "
140 "`llvm.mlir.global_ctors` will be run. One common scenario is that "
141 "kernel binary compiled from `gpu.module` gets loaded during "
142 "initialization. Make sure all symbols are resolvable before "
143 "initialization by calling `register_runtime` or including "
144 "shared libraries.")
145 .def(
146 "dump_to_object_file",
147 [](PyExecutionEngine &executionEngine, const std::string &fileName) {
149 executionEngine.get(),
150 mlirStringRefCreate(fileName.c_str(), fileName.size()));
151 },
152 nb::arg("file_name"), "Dump ExecutionEngine to an object file.");
153}
NB_MODULE(_mlirExecutionEngine, m)
Create the mlir.execution_engine module here.
static MlirExecutionEngine mlirPythonCapsuleToExecutionEngine(PyObject *capsule)
Extracts an MlirExecutionEngine from a capsule as produced from mlirPythonIntegerSetToCapsule.
Definition Interop.h:434
#define MLIR_PYTHON_CAPI_PTR_ATTR
Attribute on MLIR Python objects that expose their C-API pointer.
Definition Interop.h:97
static PyObject * mlirPythonExecutionEngineToCapsule(MlirExecutionEngine jit)
Creates a capsule object encapsulating the raw C-API MlirExecutionEngine.
Definition Interop.h:424
#define MLIR_PYTHON_CAPI_FACTORY_ATTR
Attribute on MLIR Python objects that exposes a factory function for constructing the corresponding P...
Definition Interop.h:110
MlirModule get()
Gets the backing MlirModule.
Definition IRCore.h:549
MLIR_CAPI_EXPORTED void * mlirExecutionEngineLookupPacked(MlirExecutionEngine jit, MlirStringRef name)
Lookup the wrapper of the native function in the execution engine with the given name,...
MLIR_CAPI_EXPORTED void mlirExecutionEngineDumpToObjectFile(MlirExecutionEngine jit, MlirStringRef fileName)
Dump as an object in fileName.
MLIR_CAPI_EXPORTED MlirExecutionEngine mlirExecutionEngineCreate(MlirModule op, int optLevel, int numPaths, const MlirStringRef *sharedLibPaths, bool enableObjectDump, bool enablePIC)
Creates an ExecutionEngine for the provided ModuleOp.
MLIR_CAPI_EXPORTED void mlirExecutionEngineDestroy(MlirExecutionEngine jit)
Destroy an ExecutionEngine instance.
MLIR_CAPI_EXPORTED void mlirExecutionEngineInitialize(MlirExecutionEngine jit)
Initialize the ExecutionEngine.
MLIR_CAPI_EXPORTED void mlirExecutionEngineRegisterSymbol(MlirExecutionEngine jit, MlirStringRef name, void *sym)
Register a symbol with the jit: this symbol will be accessible to the jitted code.
static bool mlirExecutionEngineIsNull(MlirExecutionEngine jit)
Checks whether an execution engine is null.
static MlirStringRef mlirStringRefCreate(const char *str, size_t length)
Constructs a string reference from the pointer and length.
Definition Support.h:84
Include the generated interface declarations.