MLIR 24.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
9#include <vector>
10
15
16namespace nb = nanobind;
17
18namespace mlir {
19namespace python {
22
23/// Owning Wrapper around an ExecutionEngine.
25public:
26 PyExecutionEngine(MlirExecutionEngine executionEngine)
27 : executionEngine(executionEngine) {}
29 : executionEngine(other.executionEngine) {
30 other.executionEngine.ptr = nullptr;
31 }
33 if (!mlirExecutionEngineIsNull(executionEngine))
34 mlirExecutionEngineDestroy(executionEngine);
35 }
36 MlirExecutionEngine get() { return executionEngine; }
37
38 void release() {
39 executionEngine.ptr = nullptr;
40 referencedObjects.clear();
41 }
42 nb::object getCapsule() {
43 return nb::steal<nb::object>(mlirPythonExecutionEngineToCapsule(get()));
44 }
45
46 // Add an object to the list of referenced objects whose lifetime must exceed
47 // those of the ExecutionEngine.
48 void addReferencedObject(const nb::object &obj) {
49 referencedObjects.push_back(obj);
50 }
51
52 static nb::object createFromCapsule(const nb::object &capsule) {
53 MlirExecutionEngine rawPm =
56 throw nb::python_error();
57 return nb::cast(PyExecutionEngine(rawPm), nb::rv_policy::move);
58 }
59
60private:
61 MlirExecutionEngine executionEngine;
62 // We support Python ctypes closures as callbacks. Keep a list of the objects
63 // so that they don't get garbage collected. (The ExecutionEngine itself
64 // just holds raw pointers with no lifetime semantics).
65 std::vector<nb::object> referencedObjects;
66};
67
68} // namespace execution_engine
69} // namespace MLIR_BINDINGS_PYTHON_DOMAIN
70} // namespace python
71} // namespace mlir
72
73/// Create the `mlir.execution_engine` module here.
74NB_MODULE(_mlirExecutionEngine, m) {
75 m.doc() = "MLIR Execution Engine";
76
78 using namespace execution_engine;
79 //----------------------------------------------------------------------------
80 // Mapping of the top-level PassManager
81 //----------------------------------------------------------------------------
82 nb::class_<PyExecutionEngine>(m, "ExecutionEngine")
83 .def(
84 "__init__",
85 [](PyExecutionEngine &self, PyModule &module, int optLevel,
86 const std::vector<std::string> &sharedLibPaths,
87 bool enableObjectDump, bool enablePIC) {
88 std::vector<MlirStringRef> libPaths;
89 libPaths.reserve(sharedLibPaths.size());
90 for (const std::string &path : sharedLibPaths)
91 libPaths.push_back({path.c_str(), path.length()});
92
93 // Access any Python objects before releasing the GIL.
94 MlirModule mlirModule = module.get();
95
96 MlirExecutionEngine executionEngine;
97 {
98 nb::gil_scoped_release release;
99 executionEngine = mlirExecutionEngineCreate(
100 mlirModule, optLevel, libPaths.size(), libPaths.data(),
101 enableObjectDump, enablePIC);
102 }
103 if (mlirExecutionEngineIsNull(executionEngine))
104 throw std::runtime_error(
105 "Failure while creating the ExecutionEngine.");
106 new (&self) PyExecutionEngine(executionEngine);
107 },
108 nb::arg("module"), nb::arg("opt_level") = 2,
109 nb::arg("shared_libs") = nb::list(),
110 nb::arg("enable_object_dump") = true, nb::arg("enable_pic") = false,
111 "Create a new ExecutionEngine instance for the given Module. The "
112 "module must contain only dialects that can be translated to LLVM. "
113 "Perform transformations and code generation at the optimization "
114 "level `opt_level` if specified, or otherwise at the default "
115 "level of two (-O2). Load a list of libraries specified in "
116 "`shared_libs`.")
117 .def_prop_ro(MLIR_PYTHON_CAPI_PTR_ATTR, &PyExecutionEngine::getCapsule)
118 .def("_testing_release", &PyExecutionEngine::release,
119 "Releases (leaks) the backing ExecutionEngine (for testing purpose)")
120 .def(MLIR_PYTHON_CAPI_FACTORY_ATTR, &PyExecutionEngine::createFromCapsule)
121 .def(
122 "raw_lookup",
123 [](PyExecutionEngine &executionEngine, const std::string &func) {
125 executionEngine.get(),
126 mlirStringRefCreate(func.c_str(), func.size()));
127 return reinterpret_cast<uintptr_t>(res);
128 },
129 nb::arg("func_name"),
130 "Lookup function `func` in the ExecutionEngine.")
131 .def(
132 "raw_register_runtime",
133 [](PyExecutionEngine &executionEngine, const std::string &name,
134 const nb::object &callbackObj) {
135 executionEngine.addReferencedObject(callbackObj);
136 uintptr_t rawSym =
137 nb::cast<uintptr_t>(nb::getattr(callbackObj, "value"));
139 executionEngine.get(),
140 mlirStringRefCreate(name.c_str(), name.size()),
141 reinterpret_cast<void *>(rawSym));
142 },
143 nb::arg("name"), nb::arg("callback"),
144 "Register `callback` as the runtime symbol `name`.")
145 .def(
146 "initialize",
147 [](PyExecutionEngine &executionEngine) {
148 mlirExecutionEngineInitialize(executionEngine.get());
149 },
150 "Initialize the ExecutionEngine. Global constructors specified by "
151 "`llvm.mlir.global_ctors` will be run. One common scenario is that "
152 "kernel binary compiled from `gpu.module` gets loaded during "
153 "initialization. Make sure all symbols are resolvable before "
154 "initialization by calling `register_runtime` or including "
155 "shared libraries.")
156 .def(
157 "dump_to_object_file",
158 [](PyExecutionEngine &executionEngine, const std::string &fileName) {
160 executionEngine.get(),
161 mlirStringRefCreate(fileName.c_str(), fileName.size()));
162 },
163 nb::arg("file_name"), "Dump ExecutionEngine to an object file.");
164}
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
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:87
Include the generated interface declarations.