21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/SmallVector.h"
28 using namespace py::literals;
33 using llvm::StringRef;
41 R
"(Parses the assembly form of a type.
43 Returns a Type object or raises an MLIRError if the type cannot be parsed.
45 See also: https://mlir.llvm.org/docs/LangRef/#type-system
49 R
"(Gets a Location representing a caller and callsite)";
52 R
"(Gets a Location representing a file, line and column)";
55 R
"(Gets a Location representing a fused location with optional metadata)";
58 R
"(Gets a Location representing a named location with optional child location)";
61 R
"(Parses a module's assembly format from a string.
63 Returns a new MlirModule or raises an MLIRError if the parsing fails.
65 See also: https://mlir.llvm.org/docs/LangRef/
69 R
"(Creates a new operation.
72 name: Operation name (e.g. "dialect.operation").
73 results: Sequence of Type representing op result types.
74 attributes: Dict of str:Attribute.
75 successors: List of Block for the operation's successors.
76 regions: Number of regions to create.
77 location: A Location object (defaults to resolve from context manager).
78 ip: An InsertionPoint (defaults to resolve from context manager or set to
79 False to disable insertion, even with an insertion point set in the
81 infer_type: Whether to infer result types.
83 A new "detached" Operation object. Detached operations can be added
84 to blocks, which causes them to become "attached."
88 R
"(Prints the assembly form of the operation to a file like object.
91 file: The file like object to write to. Defaults to sys.stdout.
92 binary: Whether to write bytes (True) or str (False). Defaults to False.
93 large_elements_limit: Whether to elide elements attributes above this
94 number of elements. Defaults to None (no limit).
95 enable_debug_info: Whether to print debug/location information. Defaults
97 pretty_debug_info: Whether to format debug information for easier reading
98 by a human (warning: the result is unparseable).
99 print_generic_op_form: Whether to print the generic assembly forms of all
100 ops. Defaults to False.
101 use_local_Scope: Whether to print in a way that is more optimized for
102 multi-threaded access but may not be consistent with how the overall
104 assume_verified: By default, if not printing generic form, the verifier
105 will be run and if it fails, generic form will be printed with a comment
106 about failed verification. While a reasonable default for interactive use,
107 for systematic use, it is often better for the caller to verify explicitly
108 and report failures in a more robust fashion. Set this to True if doing this
109 in order to avoid running a redundant verification. If the IR is actually
110 invalid, behavior is undefined.
114 R
"(Prints the assembly form of the operation to a file like object.
117 file: The file like object to write to. Defaults to sys.stdout.
118 binary: Whether to write bytes (True) or str (False). Defaults to False.
119 state: AsmState capturing the operation numbering and flags.
123 R
"(Gets the assembly form of the operation with all options available.
126 binary: Whether to return a bytes (True) or str (False) object. Defaults to
128 ... others ...: See the print() method for common keyword arguments for
129 configuring the printout.
131 Either a bytes or str object, depending on the setting of the 'binary'
136 R
"(Write the bytecode form of the operation to a file like object.
139 file: The file like object to write to.
140 desired_version: The version of bytecode to emit.
142 The bytecode writer status.
146 R
"(Gets the assembly form of the operation with default options.
148 If more advanced control over the assembly formatting or I/O options is needed,
149 use the dedicated print or get_asm method, which supports keyword arguments to
154 R
"(Dumps a debug representation of the object to stderr.)";
157 R
"(Appends a new block, with argument types as positional args.
164 R
"(Returns the string form of the value.
166 If the value is a block argument, this is the assembly form of its type and the
167 position in the argument list. If the value is an operation result, this is
168 equivalent to printing the operation that produced it.
172 R
"(Returns the string form of value as an operand (i.e., the ValueID).
176 R
"(Replace all uses of value with the new value, updating anything in
177 the IR that uses 'self' to use the other value instead.
185 template <
class Func,
typename... Args>
187 py::object cf = py::cpp_function(f, args...);
188 return py::reinterpret_borrow<py::object>((PyClassMethod_New(cf.ptr())));
193 py::object dialectDescriptor) {
194 auto dialectClass =
PyGlobals::get().lookupDialectClass(dialectNamespace);
197 return py::cast(
PyDialect(std::move(dialectDescriptor)));
201 return (*dialectClass)(std::move(dialectDescriptor));
211 const std::optional<py::sequence> &pyArgLocs) {
213 argTypes.reserve(pyArgTypes.size());
214 for (
const auto &pyType : pyArgTypes)
215 argTypes.push_back(pyType.cast<
PyType &>());
219 argLocs.reserve(pyArgLocs->size());
220 for (
const auto &pyLoc : *pyArgLocs)
221 argLocs.push_back(pyLoc.cast<
PyLocation &>());
222 }
else if (!argTypes.empty()) {
223 argLocs.assign(argTypes.size(), DefaultingPyLocation::resolve());
226 if (argTypes.size() != argLocs.size())
227 throw py::value_error((
"Expected " + Twine(argTypes.size()) +
228 " locations, got: " + Twine(argLocs.size()))
230 return mlirBlockCreate(argTypes.size(), argTypes.data(), argLocs.data());
239 static void bind(py::module &m) {
241 py::class_<PyGlobalDebugFlag>(m,
"_GlobalDebug", py::module_local())
249 return PyGlobals::get().lookupAttributeBuilder(attributeKind).has_value();
252 auto builder =
PyGlobals::get().lookupAttributeBuilder(attributeKind);
254 throw py::key_error(attributeKind);
258 py::function func,
bool replace) {
259 PyGlobals::get().registerAttributeBuilder(attributeKind, std::move(func),
263 static void bind(py::module &m) {
264 py::class_<PyAttrBuilderMap>(m,
"AttrBuilder", py::module_local())
268 "attribute_kind"_a,
"attr_builder"_a,
"replace"_a =
false,
269 "Register an attribute builder for building MLIR "
270 "attributes from python values.");
278 py::object PyBlock::getCapsule() {
288 class PyRegionIterator {
291 : operation(std::move(operation)) {}
293 PyRegionIterator &dunderIter() {
return *
this; }
298 throw py::stop_iteration();
304 static void bind(py::module &m) {
305 py::class_<PyRegionIterator>(m,
"RegionIterator", py::module_local())
306 .def(
"__iter__", &PyRegionIterator::dunderIter)
307 .def(
"__next__", &PyRegionIterator::dunderNext);
319 PyRegionList(
PyOperationRef operation) : operation(std::move(operation)) {}
321 PyRegionIterator dunderIter() {
323 return PyRegionIterator(operation);
326 intptr_t dunderLen() {
327 operation->checkValid();
331 PyRegion dunderGetItem(intptr_t index) {
333 if (index < 0 || index >= dunderLen()) {
334 throw py::index_error(
"attempt to access out of bounds region");
340 static void bind(py::module &m) {
341 py::class_<PyRegionList>(m,
"RegionSequence", py::module_local())
342 .def(
"__len__", &PyRegionList::dunderLen)
343 .def(
"__iter__", &PyRegionList::dunderIter)
344 .def(
"__getitem__", &PyRegionList::dunderGetItem);
351 class PyBlockIterator {
354 : operation(std::move(operation)), next(next) {}
356 PyBlockIterator &dunderIter() {
return *
this; }
361 throw py::stop_iteration();
364 PyBlock returnBlock(operation, next);
369 static void bind(py::module &m) {
370 py::class_<PyBlockIterator>(m,
"BlockIterator", py::module_local())
371 .def(
"__iter__", &PyBlockIterator::dunderIter)
372 .def(
"__next__", &PyBlockIterator::dunderNext);
386 : operation(std::move(operation)), region(region) {}
388 PyBlockIterator dunderIter() {
393 intptr_t dunderLen() {
394 operation->checkValid();
404 PyBlock dunderGetItem(intptr_t index) {
407 throw py::index_error(
"attempt to access out of bounds block");
412 return PyBlock(operation, block);
417 throw py::index_error(
"attempt to access out of bounds block");
420 PyBlock appendBlock(
const py::args &pyArgTypes,
421 const std::optional<py::sequence> &pyArgLocs) {
423 MlirBlock block =
createBlock(pyArgTypes, pyArgLocs);
425 return PyBlock(operation, block);
428 static void bind(py::module &m) {
429 py::class_<PyBlockList>(m,
"BlockList", py::module_local())
430 .def(
"__getitem__", &PyBlockList::dunderGetItem)
431 .def(
"__iter__", &PyBlockList::dunderIter)
432 .def(
"__len__", &PyBlockList::dunderLen)
434 py::arg(
"arg_locs") = std::nullopt);
442 class PyOperationIterator {
444 PyOperationIterator(
PyOperationRef parentOperation, MlirOperation next)
445 : parentOperation(std::move(parentOperation)), next(next) {}
447 PyOperationIterator &dunderIter() {
return *
this; }
449 py::object dunderNext() {
452 throw py::stop_iteration();
456 PyOperation::forOperation(parentOperation->getContext(), next);
461 static void bind(py::module &m) {
462 py::class_<PyOperationIterator>(m,
"OperationIterator", py::module_local())
463 .def(
"__iter__", &PyOperationIterator::dunderIter)
464 .def(
"__next__", &PyOperationIterator::dunderNext);
476 class PyOperationList {
479 : parentOperation(std::move(parentOperation)), block(block) {}
481 PyOperationIterator dunderIter() {
483 return PyOperationIterator(parentOperation,
487 intptr_t dunderLen() {
488 parentOperation->checkValid();
498 py::object dunderGetItem(intptr_t index) {
499 parentOperation->checkValid();
501 throw py::index_error(
"attempt to access out of bounds operation");
506 return PyOperation::forOperation(parentOperation->getContext(), childOp)
512 throw py::index_error(
"attempt to access out of bounds operation");
515 static void bind(py::module &m) {
516 py::class_<PyOperationList>(m,
"OperationList", py::module_local())
517 .def(
"__getitem__", &PyOperationList::dunderGetItem)
518 .def(
"__iter__", &PyOperationList::dunderIter)
519 .def(
"__len__", &PyOperationList::dunderLen);
529 PyOpOperand(MlirOpOperand opOperand) : opOperand(opOperand) {}
531 py::object getOwner() {
535 return PyOperation::forOperation(context, owner)->createOpView();
540 static void bind(py::module &m) {
541 py::class_<PyOpOperand>(m,
"OpOperand", py::module_local())
542 .def_property_readonly(
"owner", &PyOpOperand::getOwner)
543 .def_property_readonly(
"operand_number",
544 &PyOpOperand::getOperandNumber);
548 MlirOpOperand opOperand;
551 class PyOpOperandIterator {
553 PyOpOperandIterator(MlirOpOperand opOperand) : opOperand(opOperand) {}
555 PyOpOperandIterator &dunderIter() {
return *
this; }
557 PyOpOperand dunderNext() {
559 throw py::stop_iteration();
561 PyOpOperand returnOpOperand(opOperand);
563 return returnOpOperand;
566 static void bind(py::module &m) {
567 py::class_<PyOpOperandIterator>(m,
"OpOperandIterator", py::module_local())
568 .def(
"__iter__", &PyOpOperandIterator::dunderIter)
569 .def(
"__next__", &PyOpOperandIterator::dunderNext);
573 MlirOpOperand opOperand;
582 PyMlirContext::PyMlirContext(MlirContext context) : context(context) {
583 py::gil_scoped_acquire acquire;
584 auto &liveContexts = getLiveContexts();
585 liveContexts[context.ptr] =
this;
592 py::gil_scoped_acquire acquire;
593 getLiveContexts().erase(context.ptr);
604 throw py::error_already_set();
614 py::gil_scoped_acquire acquire;
615 auto &liveContexts = getLiveContexts();
616 auto it = liveContexts.find(context.ptr);
617 if (it == liveContexts.end()) {
620 py::object pyRef = py::cast(unownedContextWrapper);
621 assert(pyRef &&
"cast to py::object failed");
622 liveContexts[context.ptr] = unownedContextWrapper;
626 py::object pyRef = py::cast(it->second);
631 static LiveContextMap liveContexts;
640 std::vector<PyOperation *> liveObjects;
641 for (
auto &entry : liveOperations)
642 liveObjects.push_back(entry.second.second);
647 for (
auto &op : liveOperations)
648 op.second.second->setInvalid();
649 size_t numInvalidated = liveOperations.size();
650 liveOperations.clear();
651 return numInvalidated;
655 auto it = liveOperations.find(op.ptr);
656 if (it != liveOperations.end()) {
657 it->second.second->setInvalid();
658 liveOperations.erase(it);
667 callBackData data{op.getOperation(),
false};
672 callBackData *data =
static_cast<callBackData *
>(userData);
673 if (LLVM_LIKELY(data->rootSeen))
674 data->rootOp.getOperation().getContext()->clearOperation(op);
676 data->rootSeen =
true;
694 const pybind11::object &excVal,
695 const pybind11::object &excTb) {
704 py::object pyHandlerObject =
705 py::cast(pyHandler, py::return_value_policy::take_ownership);
706 pyHandlerObject.inc_ref();
710 auto handlerCallback =
713 py::object pyDiagnosticObject =
714 py::cast(pyDiagnostic, py::return_value_policy::take_ownership);
721 py::gil_scoped_acquire gil;
723 result = py::cast<bool>(pyHandler->callback(pyDiagnostic));
724 }
catch (std::exception &e) {
725 fprintf(stderr,
"MLIR Python Diagnostic handler raised exception: %s\n",
727 pyHandler->hadError =
true;
734 auto deleteCallback = +[](
void *userData) {
736 assert(pyHandler->registeredID &&
"handler is not registered");
737 pyHandler->registeredID.reset();
740 py::object pyHandlerObject =
741 py::cast(pyHandler, py::return_value_policy::reference);
742 pyHandlerObject.dec_ref();
746 get(), handlerCallback,
static_cast<void *
>(pyHandler), deleteCallback);
747 return pyHandlerObject;
754 if (self->ctx->emitErrorDiagnostics)
767 throw std::runtime_error(
768 "An MLIR function requires a Context but none was provided in the call "
769 "or from the surrounding environment. Either pass to the function with "
770 "a 'context=' argument or establish a default using 'with Context():'");
780 static thread_local std::vector<PyThreadContextEntry> stack;
785 auto &stack = getStack();
788 return &stack.back();
791 void PyThreadContextEntry::push(FrameKind frameKind, py::object context,
792 py::object insertionPoint,
793 py::object location) {
794 auto &stack = getStack();
795 stack.emplace_back(frameKind, std::move(context), std::move(insertionPoint),
796 std::move(location));
800 if (stack.size() > 1) {
801 auto &prev = *(stack.rbegin() + 1);
802 auto ¤t = stack.back();
803 if (current.context.is(prev.context)) {
805 if (!current.insertionPoint)
806 current.insertionPoint = prev.insertionPoint;
807 if (!current.location)
808 current.location = prev.location;
816 return py::cast<PyMlirContext *>(context);
822 return py::cast<PyInsertionPoint *>(insertionPoint);
828 return py::cast<PyLocation *>(location);
832 auto *tos = getTopOfStack();
833 return tos ? tos->getContext() :
nullptr;
837 auto *tos = getTopOfStack();
838 return tos ? tos->getInsertionPoint() :
nullptr;
842 auto *tos = getTopOfStack();
843 return tos ? tos->getLocation() :
nullptr;
847 py::object contextObj = py::cast(context);
848 push(FrameKind::Context, contextObj,
855 auto &stack = getStack();
857 throw std::runtime_error(
"Unbalanced Context enter/exit");
858 auto &tos = stack.back();
859 if (tos.frameKind != FrameKind::Context && tos.getContext() != &context)
860 throw std::runtime_error(
"Unbalanced Context enter/exit");
866 py::object contextObj =
868 py::object insertionPointObj = py::cast(insertionPoint);
869 push(FrameKind::InsertionPoint,
873 return insertionPointObj;
877 auto &stack = getStack();
879 throw std::runtime_error(
"Unbalanced InsertionPoint enter/exit");
880 auto &tos = stack.back();
881 if (tos.frameKind != FrameKind::InsertionPoint &&
882 tos.getInsertionPoint() != &insertionPoint)
883 throw std::runtime_error(
"Unbalanced InsertionPoint enter/exit");
889 py::object locationObj = py::cast(location);
890 push(FrameKind::Location, contextObj,
897 auto &stack = getStack();
899 throw std::runtime_error(
"Unbalanced Location enter/exit");
900 auto &tos = stack.back();
901 if (tos.frameKind != FrameKind::Location && tos.getLocation() != &location)
902 throw std::runtime_error(
"Unbalanced Location enter/exit");
912 if (materializedNotes) {
913 for (
auto ¬eObject : *materializedNotes) {
914 PyDiagnostic *note = py::cast<PyDiagnostic *>(noteObject);
922 : context(context), callback(std::move(callback)) {}
931 assert(!registeredID &&
"should have unregistered");
937 void PyDiagnostic::checkValid() {
939 throw std::invalid_argument(
940 "Diagnostic is invalid (used outside of callback)");
958 py::object fileObject = py::module::import(
"io").attr(
"StringIO")();
961 return fileObject.attr(
"getvalue")();
966 if (materializedNotes)
967 return *materializedNotes;
969 materializedNotes = py::tuple(numNotes);
970 for (intptr_t i = 0; i < numNotes; ++i) {
974 return *materializedNotes;
978 std::vector<DiagnosticInfo> notes;
991 {key.data(), key.size()});
993 std::string msg = (Twine(
"Dialect '") + key +
"' not found").str();
995 throw py::attribute_error(msg);
996 throw py::index_error(msg);
1002 return py::reinterpret_steal<py::object>(
1007 MlirDialectRegistry rawRegistry =
1010 throw py::error_already_set();
1025 throw py::error_already_set();
1035 const pybind11::object &excVal,
1036 const pybind11::object &excTb) {
1043 throw std::runtime_error(
1044 "An MLIR function requires a Location but none was provided in the "
1045 "call or from the surrounding environment. Either pass to the function "
1046 "with a 'loc=' argument or establish a default using 'with loc:'");
1059 py::gil_scoped_acquire acquire;
1060 auto &liveModules =
getContext()->liveModules;
1061 assert(liveModules.count(module.ptr) == 1 &&
1062 "destroying module not in live map");
1063 liveModules.erase(module.ptr);
1071 py::gil_scoped_acquire acquire;
1072 auto &liveModules = contextRef->liveModules;
1073 auto it = liveModules.find(module.ptr);
1074 if (it == liveModules.end()) {
1081 py::cast(unownedModule, py::return_value_policy::take_ownership);
1082 unownedModule->handle = pyRef;
1083 liveModules[module.ptr] =
1084 std::make_pair(unownedModule->handle, unownedModule);
1085 return PyModuleRef(unownedModule, std::move(pyRef));
1088 PyModule *existing = it->second.second;
1089 py::object pyRef = py::reinterpret_borrow<py::object>(it->second.first);
1096 throw py::error_already_set();
1108 PyOperation::PyOperation(
PyMlirContextRef contextRef, MlirOperation operation)
1115 auto &liveOperations =
getContext()->liveOperations;
1116 assert(liveOperations.count(operation.ptr) == 1 &&
1117 "destroying operation not in live map");
1118 liveOperations.erase(operation.ptr);
1125 MlirOperation operation,
1126 py::object parentKeepAlive) {
1127 auto &liveOperations = contextRef->liveOperations;
1130 new PyOperation(std::move(contextRef), operation);
1135 py::cast(unownedOperation, py::return_value_policy::take_ownership);
1136 unownedOperation->handle = pyRef;
1137 if (parentKeepAlive) {
1138 unownedOperation->parentKeepAlive = std::move(parentKeepAlive);
1140 liveOperations[operation.ptr] = std::make_pair(pyRef, unownedOperation);
1145 MlirOperation operation,
1146 py::object parentKeepAlive) {
1147 auto &liveOperations = contextRef->liveOperations;
1148 auto it = liveOperations.find(operation.ptr);
1149 if (it == liveOperations.end()) {
1151 return createInstance(std::move(contextRef), operation,
1152 std::move(parentKeepAlive));
1156 py::object pyRef = py::reinterpret_borrow<py::object>(it->second.first);
1161 MlirOperation operation,
1162 py::object parentKeepAlive) {
1163 auto &liveOperations = contextRef->liveOperations;
1164 assert(liveOperations.count(operation.ptr) == 0 &&
1165 "cannot create detached operation that already exists");
1166 (void)liveOperations;
1168 PyOperationRef created = createInstance(std::move(contextRef), operation,
1169 std::move(parentKeepAlive));
1170 created->attached =
false;
1175 const std::string &sourceStr,
1176 const std::string &sourceName) {
1182 throw MLIRError(
"Unable to parse operation assembly", errors.
take());
1188 throw std::runtime_error(
"the operation has been invalidated");
1193 bool enableDebugInfo,
bool prettyDebugInfo,
1194 bool printGenericOpForm,
bool useLocalScope,
1195 bool assumeVerified, py::object fileObject,
1199 if (fileObject.is_none())
1200 fileObject = py::module::import(
"sys").attr(
"stdout");
1203 if (largeElementsLimit)
1205 if (enableDebugInfo)
1208 if (printGenericOpForm)
1225 if (fileObject.is_none())
1226 fileObject = py::module::import(
"sys").attr(
"stdout");
1233 std::optional<int64_t> bytecodeVersion) {
1238 if (!bytecodeVersion.has_value())
1248 throw py::value_error((Twine(
"Unable to honor desired bytecode version ") +
1249 Twine(*bytecodeVersion))
1261 std::string exceptionWhat;
1262 py::object exceptionType;
1264 UserData userData{callback,
false, {}, {}};
1267 UserData *calleeUserData =
static_cast<UserData *
>(userData);
1269 return (calleeUserData->callback)(op);
1270 }
catch (py::error_already_set &e) {
1271 calleeUserData->gotException =
true;
1272 calleeUserData->exceptionWhat = e.what();
1273 calleeUserData->exceptionType = e.type();
1278 if (userData.gotException) {
1279 std::string message(
"Exception raised in callback: ");
1280 message.append(userData.exceptionWhat);
1281 throw std::runtime_error(message);
1286 std::optional<int64_t> largeElementsLimit,
1287 bool enableDebugInfo,
bool prettyDebugInfo,
1288 bool printGenericOpForm,
bool useLocalScope,
1289 bool assumeVerified) {
1290 py::object fileObject;
1292 fileObject = py::module::import(
"io").attr(
"BytesIO")();
1294 fileObject = py::module::import(
"io").attr(
"StringIO")();
1296 print(largeElementsLimit,
1305 return fileObject.attr(
"getvalue")();
1314 operation.parentKeepAlive = otherOp.parentKeepAlive;
1323 operation.parentKeepAlive = otherOp.parentKeepAlive;
1337 throw py::value_error(
"Detached operations have no parent");
1348 assert(!
mlirBlockIsNull(block) &&
"Attached operation has null parent");
1349 assert(parentOperation &&
"Operation has no parent");
1350 return PyBlock{std::move(*parentOperation), block};
1361 throw py::error_already_set();
1368 const py::object &maybeIp) {
1370 if (!maybeIp.is(py::cast(
false))) {
1372 if (maybeIp.is_none()) {
1375 ip = py::cast<PyInsertionPoint *>(maybeIp);
1383 std::optional<std::vector<PyType *>> results,
1384 std::optional<std::vector<PyValue *>> operands,
1385 std::optional<py::dict> attributes,
1386 std::optional<std::vector<PyBlock *>> successors,
1388 const py::object &maybeIp,
bool inferType) {
1396 throw py::value_error(
"number of regions must be >= 0");
1400 mlirOperands.reserve(operands->size());
1401 for (
PyValue *operand : *operands) {
1403 throw py::value_error(
"operand value cannot be None");
1404 mlirOperands.push_back(operand->get());
1410 mlirResults.reserve(results->size());
1411 for (
PyType *result : *results) {
1414 throw py::value_error(
"result type cannot be None");
1415 mlirResults.push_back(*result);
1420 mlirAttributes.reserve(attributes->size());
1421 for (
auto &it : *attributes) {
1424 key = it.first.cast<std::string>();
1425 }
catch (py::cast_error &err) {
1426 std::string msg =
"Invalid attribute key (not a string) when "
1427 "attempting to create the operation \"" +
1428 name +
"\" (" + err.what() +
")";
1429 throw py::cast_error(msg);
1432 auto &attribute = it.second.cast<
PyAttribute &>();
1434 mlirAttributes.emplace_back(std::move(key), attribute);
1435 }
catch (py::reference_cast_error &) {
1438 "Found an invalid (`None`?) attribute value for the key \"" + key +
1439 "\" when attempting to create the operation \"" + name +
"\"";
1440 throw py::cast_error(msg);
1441 }
catch (py::cast_error &err) {
1442 std::string msg =
"Invalid attribute value for the key \"" + key +
1443 "\" when attempting to create the operation \"" +
1444 name +
"\" (" + err.what() +
")";
1445 throw py::cast_error(msg);
1451 mlirSuccessors.reserve(successors->size());
1452 for (
auto *successor : *successors) {
1455 throw py::value_error(
"successor block cannot be None");
1456 mlirSuccessors.push_back(successor->get());
1464 if (!mlirOperands.empty())
1466 mlirOperands.data());
1467 state.enableResultTypeInference = inferType;
1468 if (!mlirResults.empty())
1470 mlirResults.data());
1471 if (!mlirAttributes.empty()) {
1476 mlirNamedAttributes.reserve(mlirAttributes.size());
1477 for (
auto &it : mlirAttributes)
1483 mlirNamedAttributes.data());
1485 if (!mlirSuccessors.empty())
1487 mlirSuccessors.data());
1490 mlirRegions.resize(regions);
1491 for (
int i = 0; i < regions; ++i)
1494 mlirRegions.data());
1500 throw py::value_error(
"Operation creation failed");
1533 auto &liveOperations =
getContext()->liveOperations;
1534 if (liveOperations.count(operation.ptr))
1535 liveOperations.erase(operation.ptr);
1545 const py::object &resultSegmentSpecObj,
1546 std::vector<int32_t> &resultSegmentLengths,
1547 std::vector<PyType *> &resultTypes) {
1548 resultTypes.reserve(resultTypeList.size());
1549 if (resultSegmentSpecObj.is_none()) {
1553 resultTypes.push_back(py::cast<PyType *>(it.value()));
1554 if (!resultTypes.back())
1555 throw py::cast_error();
1556 }
catch (py::cast_error &err) {
1557 throw py::value_error((llvm::Twine(
"Result ") +
1558 llvm::Twine(it.index()) +
" of operation \"" +
1559 name +
"\" must be a Type (" + err.what() +
")")
1565 auto resultSegmentSpec = py::cast<std::vector<int>>(resultSegmentSpecObj);
1566 if (resultSegmentSpec.size() != resultTypeList.size()) {
1567 throw py::value_error((llvm::Twine(
"Operation \"") + name +
1569 llvm::Twine(resultSegmentSpec.size()) +
1570 " result segments but was provided " +
1571 llvm::Twine(resultTypeList.size()))
1574 resultSegmentLengths.reserve(resultTypeList.size());
1575 for (
const auto &it :
1577 int segmentSpec = std::get<1>(it.value());
1578 if (segmentSpec == 1 || segmentSpec == 0) {
1581 auto *resultType = py::cast<PyType *>(std::get<0>(it.value()));
1583 resultTypes.push_back(resultType);
1584 resultSegmentLengths.push_back(1);
1585 }
else if (segmentSpec == 0) {
1587 resultSegmentLengths.push_back(0);
1589 throw py::cast_error(
"was None and result is not optional");
1591 }
catch (py::cast_error &err) {
1592 throw py::value_error((llvm::Twine(
"Result ") +
1593 llvm::Twine(it.index()) +
" of operation \"" +
1594 name +
"\" must be a Type (" + err.what() +
1598 }
else if (segmentSpec == -1) {
1601 if (std::get<0>(it.value()).is_none()) {
1603 resultSegmentLengths.push_back(0);
1606 auto segment = py::cast<py::sequence>(std::get<0>(it.value()));
1607 for (py::object segmentItem : segment) {
1608 resultTypes.push_back(py::cast<PyType *>(segmentItem));
1609 if (!resultTypes.back()) {
1610 throw py::cast_error(
"contained a None item");
1613 resultSegmentLengths.push_back(segment.size());
1615 }
catch (std::exception &err) {
1619 throw py::value_error((llvm::Twine(
"Result ") +
1620 llvm::Twine(it.index()) +
" of operation \"" +
1621 name +
"\" must be a Sequence of Types (" +
1626 throw py::value_error(
"Unexpected segment spec");
1633 const py::object &cls, std::optional<py::list> resultTypeList,
1634 py::list operandList, std::optional<py::dict> attributes,
1635 std::optional<std::vector<PyBlock *>> successors,
1637 const py::object &maybeIp) {
1640 std::string name = py::cast<std::string>(cls.attr(
"OPERATION_NAME"));
1646 py::object operandSegmentSpecObj = cls.attr(
"_ODS_OPERAND_SEGMENTS");
1647 py::object resultSegmentSpecObj = cls.attr(
"_ODS_RESULT_SEGMENTS");
1649 std::vector<int32_t> operandSegmentLengths;
1650 std::vector<int32_t> resultSegmentLengths;
1653 auto opRegionSpec = py::cast<std::tuple<int, bool>>(cls.attr(
"_ODS_REGIONS"));
1654 int opMinRegionCount = std::get<0>(opRegionSpec);
1655 bool opHasNoVariadicRegions = std::get<1>(opRegionSpec);
1657 regions = opMinRegionCount;
1659 if (*regions < opMinRegionCount) {
1660 throw py::value_error(
1661 (llvm::Twine(
"Operation \"") + name +
"\" requires a minimum of " +
1662 llvm::Twine(opMinRegionCount) +
1663 " regions but was built with regions=" + llvm::Twine(*regions))
1666 if (opHasNoVariadicRegions && *regions > opMinRegionCount) {
1667 throw py::value_error(
1668 (llvm::Twine(
"Operation \"") + name +
"\" requires a maximum of " +
1669 llvm::Twine(opMinRegionCount) +
1670 " regions but was built with regions=" + llvm::Twine(*regions))
1675 std::vector<PyType *> resultTypes;
1676 if (resultTypeList.has_value()) {
1678 resultSegmentLengths, resultTypes);
1682 std::vector<PyValue *> operands;
1683 operands.reserve(operands.size());
1684 if (operandSegmentSpecObj.is_none()) {
1688 operands.push_back(py::cast<PyValue *>(it.value()));
1689 if (!operands.back())
1690 throw py::cast_error();
1691 }
catch (py::cast_error &err) {
1692 throw py::value_error((llvm::Twine(
"Operand ") +
1693 llvm::Twine(it.index()) +
" of operation \"" +
1694 name +
"\" must be a Value (" + err.what() +
")")
1700 auto operandSegmentSpec = py::cast<std::vector<int>>(operandSegmentSpecObj);
1701 if (operandSegmentSpec.size() != operandList.size()) {
1702 throw py::value_error((llvm::Twine(
"Operation \"") + name +
1704 llvm::Twine(operandSegmentSpec.size()) +
1705 "operand segments but was provided " +
1706 llvm::Twine(operandList.size()))
1709 operandSegmentLengths.reserve(operandList.size());
1710 for (
const auto &it :
1712 int segmentSpec = std::get<1>(it.value());
1713 if (segmentSpec == 1 || segmentSpec == 0) {
1716 auto *operandValue = py::cast<PyValue *>(std::get<0>(it.value()));
1718 operands.push_back(operandValue);
1719 operandSegmentLengths.push_back(1);
1720 }
else if (segmentSpec == 0) {
1722 operandSegmentLengths.push_back(0);
1724 throw py::cast_error(
"was None and operand is not optional");
1726 }
catch (py::cast_error &err) {
1727 throw py::value_error((llvm::Twine(
"Operand ") +
1728 llvm::Twine(it.index()) +
" of operation \"" +
1729 name +
"\" must be a Value (" + err.what() +
1733 }
else if (segmentSpec == -1) {
1736 if (std::get<0>(it.value()).is_none()) {
1738 operandSegmentLengths.push_back(0);
1741 auto segment = py::cast<py::sequence>(std::get<0>(it.value()));
1742 for (py::object segmentItem : segment) {
1743 operands.push_back(py::cast<PyValue *>(segmentItem));
1744 if (!operands.back()) {
1745 throw py::cast_error(
"contained a None item");
1748 operandSegmentLengths.push_back(segment.size());
1750 }
catch (std::exception &err) {
1754 throw py::value_error((llvm::Twine(
"Operand ") +
1755 llvm::Twine(it.index()) +
" of operation \"" +
1756 name +
"\" must be a Sequence of Values (" +
1761 throw py::value_error(
"Unexpected segment spec");
1767 if (!operandSegmentLengths.empty() || !resultSegmentLengths.empty()) {
1770 attributes = py::dict(*attributes);
1772 attributes = py::dict();
1774 if (attributes->contains(
"resultSegmentSizes") ||
1775 attributes->contains(
"operandSegmentSizes")) {
1776 throw py::value_error(
"Manually setting a 'resultSegmentSizes' or "
1777 "'operandSegmentSizes' attribute is unsupported. "
1778 "Use Operation.create for such low-level access.");
1782 if (!resultSegmentLengths.empty()) {
1783 MlirAttribute segmentLengthAttr =
1785 resultSegmentLengths.data());
1786 (*attributes)[
"resultSegmentSizes"] =
1791 if (!operandSegmentLengths.empty()) {
1792 MlirAttribute segmentLengthAttr =
1794 operandSegmentLengths.data());
1795 (*attributes)[
"operandSegmentSizes"] =
1802 std::move(resultTypes),
1803 std::move(operands),
1804 std::move(attributes),
1805 std::move(successors),
1806 *regions, location, maybeIp,
1815 py::handle opViewType = py::detail::get_type_handle(
typeid(
PyOpView),
true);
1816 py::object instance = cls.attr(
"__new__")(cls);
1817 opViewType.attr(
"__init__")(instance, operation);
1825 operationObject(operation.getRef().getObject()) {}
1834 : refOperation(beforeOperationBase.getOperation().getRef()),
1835 block((*refOperation)->getBlock()) {}
1840 throw py::value_error(
1841 "Attempt to insert operation that is already attached");
1842 block.getParentOperation()->checkValid();
1843 MlirOperation beforeOp = {
nullptr};
1846 (*refOperation)->checkValid();
1847 beforeOp = (*refOperation)->get();
1853 throw py::index_error(
"Cannot insert operation at the end of a block "
1854 "that already has a terminator. Did you mean to "
1855 "use 'InsertionPoint.at_block_terminator(block)' "
1856 "versus 'InsertionPoint(block)'?");
1879 throw py::value_error(
"Block has no terminator");
1890 const pybind11::object &excVal,
1891 const pybind11::object &excTb) {
1910 throw py::error_already_set();
1920 : ownedName(new std::string(std::move(ownedName))) {
1942 throw py::error_already_set();
1958 throw py::error_already_set();
1977 "mlirTypeID was expected to be non-null.");
1978 std::optional<pybind11::function> valueCaster =
1982 py::object thisObj = py::cast(
this, py::return_value_policy::move);
1985 return valueCaster.value()(thisObj);
1991 throw py::error_already_set();
1992 MlirOperation owner;
1998 throw py::error_already_set();
2002 return PyValue(ownerRef, value);
2010 : operation(operation.getOperation().getRef()) {
2013 throw py::cast_error(
"Operation is not a Symbol Table.");
2018 operation->checkValid();
2022 throw py::key_error(
"Symbol '" + name +
"' not in the symbol table.");
2025 operation.getObject())
2030 operation->checkValid();
2041 erase(py::cast<PyOperationBase &>(operation));
2045 operation->checkValid();
2050 throw py::value_error(
"Expected operation to have a symbol name.");
2059 MlirAttribute existingNameAttr =
2062 throw py::value_error(
"Expected operation to have a symbol name.");
2063 return existingNameAttr;
2067 const std::string &name) {
2072 MlirAttribute existingNameAttr =
2075 throw py::value_error(
"Expected operation to have a symbol name.");
2076 MlirAttribute newNameAttr =
2085 MlirAttribute existingVisAttr =
2088 throw py::value_error(
"Expected operation to have a symbol visibility.");
2089 return existingVisAttr;
2093 const std::string &visibility) {
2094 if (visibility !=
"public" && visibility !=
"private" &&
2095 visibility !=
"nested")
2096 throw py::value_error(
2097 "Expected visibility to be 'public', 'private' or 'nested'");
2101 MlirAttribute existingVisAttr =
2104 throw py::value_error(
"Expected operation to have a symbol visibility.");
2111 const std::string &newSymbol,
2119 throw py::value_error(
"Symbol rename failed");
2123 bool allSymUsesVisible,
2124 py::object callback) {
2129 py::object callback;
2131 std::string exceptionWhat;
2132 py::object exceptionType;
2135 fromOperation.
getContext(), std::move(callback),
false, {}, {}};
2137 fromOperation.
get(), allSymUsesVisible,
2138 [](MlirOperation foundOp,
bool isVisible,
void *calleeUserDataVoid) {
2139 UserData *calleeUserData = static_cast<UserData *>(calleeUserDataVoid);
2141 PyOperation::forOperation(calleeUserData->context, foundOp);
2142 if (calleeUserData->gotException)
2145 calleeUserData->callback(pyFoundOp.getObject(), isVisible);
2146 } catch (py::error_already_set &e) {
2147 calleeUserData->gotException =
true;
2148 calleeUserData->exceptionWhat = e.what();
2149 calleeUserData->exceptionType = e.type();
2152 static_cast<void *
>(&userData));
2153 if (userData.gotException) {
2154 std::string message(
"Exception raised in callback: ");
2155 message.append(userData.exceptionWhat);
2156 throw std::runtime_error(message);
2164 template <
typename DerivedTy>
2165 class PyConcreteValue :
public PyValue {
2171 using ClassTy = py::class_<DerivedTy, PyValue>;
2172 using IsAFunctionTy = bool (*)(MlirValue);
2174 PyConcreteValue() =
default;
2176 :
PyValue(operationRef, value) {}
2177 PyConcreteValue(
PyValue &orig)
2178 : PyConcreteValue(orig.getParentOperation(), castFrom(orig)) {}
2182 static MlirValue castFrom(
PyValue &orig) {
2183 if (!DerivedTy::isaFunction(orig.
get())) {
2184 auto origRepr = py::repr(py::cast(orig)).cast<std::string>();
2185 throw py::value_error((Twine(
"Cannot cast value to ") +
2186 DerivedTy::pyClassName +
" (from " + origRepr +
2194 static void bind(py::module &m) {
2195 auto cls = ClassTy(m, DerivedTy::pyClassName, py::module_local());
2196 cls.def(py::init<PyValue &>(), py::keep_alive<0, 1>(), py::arg(
"value"));
2199 [](
PyValue &otherValue) ->
bool {
2200 return DerivedTy::isaFunction(otherValue);
2202 py::arg(
"other_value"));
2204 [](
DerivedTy &
self) {
return self.maybeDownCast(); });
2205 DerivedTy::bindDerived(cls);
2209 static void bindDerived(ClassTy &m) {}
2213 class PyBlockArgument :
public PyConcreteValue<PyBlockArgument> {
2216 static constexpr
const char *pyClassName =
"BlockArgument";
2217 using PyConcreteValue::PyConcreteValue;
2219 static void bindDerived(ClassTy &c) {
2220 c.def_property_readonly(
"owner", [](PyBlockArgument &
self) {
2221 return PyBlock(
self.getParentOperation(),
2224 c.def_property_readonly(
"arg_number", [](PyBlockArgument &
self) {
2229 [](PyBlockArgument &
self,
PyType type) {
2237 class PyOpResult :
public PyConcreteValue<PyOpResult> {
2240 static constexpr
const char *pyClassName =
"OpResult";
2241 using PyConcreteValue::PyConcreteValue;
2243 static void bindDerived(ClassTy &c) {
2244 c.def_property_readonly(
"owner", [](PyOpResult &
self) {
2248 "expected the owner of the value in Python to match that in the IR");
2249 return self.getParentOperation().getObject();
2251 c.def_property_readonly(
"result_number", [](PyOpResult &
self) {
2258 template <
typename Container>
2259 static std::vector<MlirType> getValueTypes(Container &container,
2261 std::vector<MlirType> result;
2262 result.reserve(container.size());
2263 for (
int i = 0, e = container.size(); i < e; ++i) {
2273 class PyBlockArgumentList
2274 :
public Sliceable<PyBlockArgumentList, PyBlockArgument> {
2276 static constexpr
const char *pyClassName =
"BlockArgumentList";
2280 intptr_t startIndex = 0, intptr_t length = -1,
2285 operation(std::move(operation)), block(block) {}
2287 static void bindDerived(ClassTy &c) {
2288 c.def_property_readonly(
"types", [](PyBlockArgumentList &
self) {
2289 return getValueTypes(
self,
self.operation->getContext());
2295 friend class Sliceable<PyBlockArgumentList, PyBlockArgument>;
2298 intptr_t getRawNumElements() {
2299 operation->checkValid();
2304 PyBlockArgument getRawElement(intptr_t pos) {
2306 return PyBlockArgument(operation, argument);
2310 PyBlockArgumentList slice(intptr_t startIndex, intptr_t length,
2312 return PyBlockArgumentList(operation, block, startIndex, length, step);
2323 class PyOpOperandList :
public Sliceable<PyOpOperandList, PyValue> {
2325 static constexpr
const char *pyClassName =
"OpOperandList";
2328 PyOpOperandList(
PyOperationRef operation, intptr_t startIndex = 0,
2329 intptr_t length = -1, intptr_t step = 1)
2334 operation(operation) {}
2336 void dunderSetItem(intptr_t index,
PyValue value) {
2337 index = wrapIndex(index);
2341 static void bindDerived(ClassTy &c) {
2342 c.def(
"__setitem__", &PyOpOperandList::dunderSetItem);
2349 intptr_t getRawNumElements() {
2354 PyValue getRawElement(intptr_t pos) {
2356 MlirOperation owner;
2362 assert(
false &&
"Value must be an block arg or op result.");
2364 PyOperation::forOperation(operation->getContext(), owner);
2365 return PyValue(pyOwner, operand);
2368 PyOpOperandList slice(intptr_t startIndex, intptr_t length, intptr_t step) {
2369 return PyOpOperandList(operation, startIndex, length, step);
2379 class PyOpResultList :
public Sliceable<PyOpResultList, PyOpResult> {
2381 static constexpr
const char *pyClassName =
"OpResultList";
2384 PyOpResultList(
PyOperationRef operation, intptr_t startIndex = 0,
2385 intptr_t length = -1, intptr_t step = 1)
2390 operation(std::move(operation)) {}
2392 static void bindDerived(ClassTy &c) {
2393 c.def_property_readonly(
"types", [](PyOpResultList &
self) {
2394 return getValueTypes(
self,
self.operation->getContext());
2396 c.def_property_readonly(
"owner", [](PyOpResultList &
self) {
2397 return self.operation->createOpView();
2403 friend class Sliceable<PyOpResultList, PyOpResult>;
2405 intptr_t getRawNumElements() {
2406 operation->checkValid();
2410 PyOpResult getRawElement(intptr_t index) {
2412 return PyOpResult(value);
2415 PyOpResultList slice(intptr_t startIndex, intptr_t length, intptr_t step) {
2416 return PyOpResultList(operation, startIndex, length, step);
2426 class PyOpSuccessors :
public Sliceable<PyOpSuccessors, PyBlock> {
2428 static constexpr
const char *pyClassName =
"OpSuccessors";
2430 PyOpSuccessors(
PyOperationRef operation, intptr_t startIndex = 0,
2431 intptr_t length = -1, intptr_t step = 1)
2436 operation(operation) {}
2438 void dunderSetItem(intptr_t index,
PyBlock block) {
2439 index = wrapIndex(index);
2443 static void bindDerived(ClassTy &c) {
2444 c.def(
"__setitem__", &PyOpSuccessors::dunderSetItem);
2451 intptr_t getRawNumElements() {
2456 PyBlock getRawElement(intptr_t pos) {
2458 return PyBlock(operation, block);
2461 PyOpSuccessors slice(intptr_t startIndex, intptr_t length, intptr_t step) {
2462 return PyOpSuccessors(operation, startIndex, length, step);
2470 class PyOpAttributeMap {
2473 : operation(std::move(operation)) {}
2475 MlirAttribute dunderGetItemNamed(
const std::string &name) {
2479 throw py::key_error(
"attempt to access a non-existent attribute");
2485 if (index < 0 || index >= dunderLen()) {
2486 throw py::index_error(
"attempt to access out of bounds attribute");
2496 void dunderSetItem(
const std::string &name,
const PyAttribute &attr) {
2501 void dunderDelItem(
const std::string &name) {
2505 throw py::key_error(
"attempt to delete a non-existent attribute");
2508 intptr_t dunderLen() {
2512 bool dunderContains(
const std::string &name) {
2517 static void bind(py::module &m) {
2518 py::class_<PyOpAttributeMap>(m,
"OpAttributeMap", py::module_local())
2519 .def(
"__contains__", &PyOpAttributeMap::dunderContains)
2520 .def(
"__len__", &PyOpAttributeMap::dunderLen)
2521 .def(
"__getitem__", &PyOpAttributeMap::dunderGetItemNamed)
2522 .def(
"__getitem__", &PyOpAttributeMap::dunderGetItemIndexed)
2523 .def(
"__setitem__", &PyOpAttributeMap::dunderSetItem)
2524 .def(
"__delitem__", &PyOpAttributeMap::dunderDelItem);
2541 py::enum_<MlirDiagnosticSeverity>(m,
"DiagnosticSeverity", py::module_local())
2547 py::enum_<MlirWalkOrder>(m,
"WalkOrder", py::module_local())
2551 py::enum_<MlirWalkResult>(m,
"WalkResult", py::module_local())
2559 py::class_<PyDiagnostic>(m,
"Diagnostic", py::module_local())
2560 .def_property_readonly(
"severity", &PyDiagnostic::getSeverity)
2561 .def_property_readonly(
"location", &PyDiagnostic::getLocation)
2562 .def_property_readonly(
"message", &PyDiagnostic::getMessage)
2563 .def_property_readonly(
"notes", &PyDiagnostic::getNotes)
2565 if (!
self.isValid())
2566 return "<Invalid Diagnostic>";
2567 return self.getMessage();
2570 py::class_<PyDiagnostic::DiagnosticInfo>(m,
"DiagnosticInfo",
2573 .def_readonly(
"severity", &PyDiagnostic::DiagnosticInfo::severity)
2574 .def_readonly(
"location", &PyDiagnostic::DiagnosticInfo::location)
2575 .def_readonly(
"message", &PyDiagnostic::DiagnosticInfo::message)
2576 .def_readonly(
"notes", &PyDiagnostic::DiagnosticInfo::notes)
2580 py::class_<PyDiagnosticHandler>(m,
"DiagnosticHandler", py::module_local())
2581 .def(
"detach", &PyDiagnosticHandler::detach)
2582 .def_property_readonly(
"attached", &PyDiagnosticHandler::isAttached)
2583 .def_property_readonly(
"had_error", &PyDiagnosticHandler::getHadError)
2584 .def(
"__enter__", &PyDiagnosticHandler::contextEnter)
2585 .def(
"__exit__", &PyDiagnosticHandler::contextExit);
2593 py::class_<PyMlirContext>(m,
"_BaseContext", py::module_local())
2594 .def(py::init<>(&PyMlirContext::createNewContextForInit))
2595 .def_static(
"_get_live_count", &PyMlirContext::getLiveCount)
2596 .def(
"_get_context_again",
2601 .def(
"_get_live_operation_count", &PyMlirContext::getLiveOperationCount)
2602 .def(
"_get_live_operation_objects",
2603 &PyMlirContext::getLiveOperationObjects)
2604 .def(
"_clear_live_operations", &PyMlirContext::clearLiveOperations)
2605 .def(
"_clear_live_operations_inside",
2606 py::overload_cast<MlirOperation>(
2607 &PyMlirContext::clearOperationsInside))
2608 .def(
"_get_live_module_count", &PyMlirContext::getLiveModuleCount)
2610 &PyMlirContext::getCapsule)
2612 .def(
"__enter__", &PyMlirContext::contextEnter)
2613 .def(
"__exit__", &PyMlirContext::contextExit)
2614 .def_property_readonly_static(
2619 return py::none().cast<py::object>();
2620 return py::cast(context);
2622 "Gets the Context bound to the current thread or raises ValueError")
2623 .def_property_readonly(
2626 "Gets a container for accessing dialects by name")
2627 .def_property_readonly(
2629 "Alias for 'dialect'")
2631 "get_dialect_descriptor",
2634 self.
get(), {name.data(), name.size()});
2636 throw py::value_error(
2637 (Twine(
"Dialect '") + name +
"' not found").str());
2641 py::arg(
"dialect_name"),
2642 "Gets or loads a dialect by name, returning its descriptor object")
2644 "allow_unregistered_dialects",
2651 .def(
"attach_diagnostic_handler", &PyMlirContext::attachDiagnosticHandler,
2652 py::arg(
"callback"),
2653 "Attaches a diagnostic handler that will receive callbacks")
2655 "enable_multithreading",
2661 "is_registered_operation",
2666 py::arg(
"operation_name"))
2668 "append_dialect_registry",
2672 py::arg(
"registry"))
2673 .def_property(
"emit_error_diagnostics",
nullptr,
2674 &PyMlirContext::setEmitErrorDiagnostics,
2675 "Emit error diagnostics to diagnostic handlers. By default "
2676 "error diagnostics are captured and reported through "
2677 "MLIRError exceptions.")
2678 .def(
"load_all_available_dialects", [](
PyMlirContext &
self) {
2685 py::class_<PyDialectDescriptor>(m,
"DialectDescriptor", py::module_local())
2686 .def_property_readonly(
"namespace",
2694 std::string repr(
"<DialectDescriptor ");
2703 py::class_<PyDialects>(m,
"Dialects", py::module_local())
2706 MlirDialect dialect =
2707 self.getDialectForKey(keyName,
false);
2708 py::object descriptor =
2712 .def(
"__getattr__", [=](
PyDialects &
self, std::string attrName) {
2713 MlirDialect dialect =
2714 self.getDialectForKey(attrName,
true);
2715 py::object descriptor =
2723 py::class_<PyDialect>(m,
"Dialect", py::module_local())
2724 .def(py::init<py::object>(), py::arg(
"descriptor"))
2725 .def_property_readonly(
2726 "descriptor", [](
PyDialect &
self) {
return self.getDescriptor(); })
2727 .def(
"__repr__", [](py::object
self) {
2728 auto clazz =
self.attr(
"__class__");
2729 return py::str(
"<Dialect ") +
2730 self.attr(
"descriptor").attr(
"namespace") + py::str(
" (class ") +
2731 clazz.attr(
"__module__") + py::str(
".") +
2732 clazz.attr(
"__name__") + py::str(
")>");
2738 py::class_<PyDialectRegistry>(m,
"DialectRegistry", py::module_local())
2740 &PyDialectRegistry::getCapsule)
2747 py::class_<PyLocation>(m,
"Location", py::module_local())
2750 .def(
"__enter__", &PyLocation::contextEnter)
2751 .def(
"__exit__", &PyLocation::contextExit)
2756 .def(
"__eq__", [](
PyLocation &
self, py::object other) {
return false; })
2757 .def_property_readonly_static(
2760 auto *loc = PyThreadContextEntry::getDefaultLocation();
2762 throw py::value_error(
"No current Location");
2765 "Gets the Location bound to the current thread or raises ValueError")
2772 py::arg(
"context") = py::none(),
2773 "Gets a Location representing an unknown location")
2776 [](
PyLocation callee,
const std::vector<PyLocation> &frames,
2779 throw py::value_error(
"No caller frames provided");
2780 MlirLocation caller = frames.back().get();
2787 py::arg(
"callee"), py::arg(
"frames"), py::arg(
"context") = py::none(),
2791 [](std::string filename,
int line,
int col,
2798 py::arg(
"filename"), py::arg(
"line"), py::arg(
"col"),
2802 [](
const std::vector<PyLocation> &pyLocations,
2803 std::optional<PyAttribute> metadata,
2806 locations.reserve(pyLocations.size());
2807 for (
auto &pyLocation : pyLocations)
2808 locations.push_back(pyLocation.get());
2810 context->
get(), locations.size(), locations.data(),
2811 metadata ? metadata->get() : MlirAttribute{0});
2812 return PyLocation(context->getRef(), location);
2814 py::arg(
"locations"), py::arg(
"metadata") = py::none(),
2818 [](std::string name, std::optional<PyLocation> childLoc,
2824 childLoc ? childLoc->get()
2827 py::arg(
"name"), py::arg(
"childLoc") = py::none(),
2835 py::arg(
"attribute"), py::arg(
"context") = py::none(),
2836 "Gets a Location from a LocationAttr")
2837 .def_property_readonly(
2839 [](
PyLocation &
self) {
return self.getContext().getObject(); },
2840 "Context that owns the Location")
2841 .def_property_readonly(
2844 "Get the underlying LocationAttr")
2850 py::arg(
"message"),
"Emits an error at this location")
2855 return printAccum.
join();
2861 py::class_<PyModule>(m,
"Module", py::module_local())
2871 throw MLIRError(
"Unable to parse module assembly", errors.take());
2872 return PyModule::forModule(module).releaseObject();
2874 py::arg(
"asm"), py::arg(
"context") = py::none(),
2880 return PyModule::forModule(module).releaseObject();
2882 py::arg(
"loc") = py::none(),
"Creates an empty module")
2883 .def_property_readonly(
2885 [](
PyModule &
self) {
return self.getContext().getObject(); },
2886 "Context that created the Module")
2887 .def_property_readonly(
2890 return PyOperation::forOperation(
self.
getContext(),
2892 self.getRef().releaseObject())
2895 "Accesses the module as an operation")
2896 .def_property_readonly(
2901 self.getRef().releaseObject());
2905 "Return the block for this module")
2914 [](py::object
self) {
2916 return self.attr(
"operation").attr(
"__str__")();
2923 py::class_<PyOperationBase>(m,
"_OperationBase", py::module_local())
2926 return self.getOperation().getCapsule();
2938 .def_property_readonly(
"attributes",
2940 return PyOpAttributeMap(
2941 self.getOperation().getRef());
2943 .def_property_readonly(
2950 "Context that owns the Operation")
2951 .def_property_readonly(
"name",
2955 MlirOperation operation =
2956 concreteOperation.
get();
2961 .def_property_readonly(
"operands",
2963 return PyOpOperandList(
2964 self.getOperation().getRef());
2966 .def_property_readonly(
"regions",
2968 return PyRegionList(
2969 self.getOperation().getRef());
2971 .def_property_readonly(
2974 return PyOpResultList(
self.getOperation().getRef());
2976 "Returns the list of Operation results.")
2977 .def_property_readonly(
2980 auto &operation =
self.getOperation();
2982 if (numResults != 1) {
2984 throw py::value_error(
2985 (Twine(
"Cannot call .result on operation ") +
2986 StringRef(name.
data, name.
length) +
" which has " +
2988 " results (it is only valid for operations with a "
2992 return PyOpResult(operation.getRef(),
2996 "Shortcut to get an op result if it has only one (throws an error "
2998 .def_property_readonly(
3005 "Returns the source location the operation was defined or derived "
3007 .def_property_readonly(
"parent",
3010 self.getOperation().getParentOperation();
3012 return parent->getObject();
3018 return self.getAsm(
false,
3026 "Returns the assembly form of the operation.")
3028 py::overload_cast<PyAsmState &, pybind11::object, bool>(
3030 py::arg(
"state"), py::arg(
"file") = py::none(),
3033 py::overload_cast<std::optional<int64_t>,
bool,
bool,
bool,
bool,
3036 py::arg(
"large_elements_limit") = py::none(),
3037 py::arg(
"enable_debug_info") =
false,
3038 py::arg(
"pretty_debug_info") =
false,
3039 py::arg(
"print_generic_op_form") =
false,
3040 py::arg(
"use_local_scope") =
false,
3041 py::arg(
"assume_verified") =
false, py::arg(
"file") = py::none(),
3043 .def(
"write_bytecode", &PyOperationBase::writeBytecode, py::arg(
"file"),
3044 py::arg(
"desired_version") = py::none(),
3046 .def(
"get_asm", &PyOperationBase::getAsm,
3048 py::arg(
"binary") =
false,
3049 py::arg(
"large_elements_limit") = py::none(),
3050 py::arg(
"enable_debug_info") =
false,
3051 py::arg(
"pretty_debug_info") =
false,
3052 py::arg(
"print_generic_op_form") =
false,
3053 py::arg(
"use_local_scope") =
false,
3056 "Verify the operation. Raises MLIRError if verification fails, and "
3057 "returns true otherwise.")
3058 .def(
"move_after", &PyOperationBase::moveAfter, py::arg(
"other"),
3059 "Puts self immediately after the other operation in its parent "
3061 .def(
"move_before", &PyOperationBase::moveBefore, py::arg(
"other"),
3062 "Puts self immediately before the other operation in its parent "
3067 return self.getOperation().clone(ip);
3069 py::arg(
"ip") = py::none())
3071 "detach_from_parent",
3076 throw py::value_error(
"Detached operation has no parent.");
3081 "Detaches the operation from its parent block.")
3082 .def(
"erase", [](
PyOperationBase &
self) {
self.getOperation().erase(); })
3086 py::class_<PyOperation, PyOperationBase>(m,
"Operation", py::module_local())
3087 .def_static(
"create", &PyOperation::create, py::arg(
"name"),
3088 py::arg(
"results") = py::none(),
3089 py::arg(
"operands") = py::none(),
3090 py::arg(
"attributes") = py::none(),
3091 py::arg(
"successors") = py::none(), py::arg(
"regions") = 0,
3092 py::arg(
"loc") = py::none(), py::arg(
"ip") = py::none(),
3096 [](
const std::string &sourceStr,
const std::string &sourceName,
3101 py::arg(
"source"), py::kw_only(), py::arg(
"source_name") =
"",
3102 py::arg(
"context") = py::none(),
3103 "Parses an operation. Supports both text assembly format and binary "
3106 &PyOperation::getCapsule)
3108 .def_property_readonly(
"operation", [](py::object
self) {
return self; })
3109 .def_property_readonly(
"opview", &PyOperation::createOpView)
3110 .def_property_readonly(
3113 return PyOpSuccessors(
self.getOperation().getRef());
3115 "Returns the list of Operation successors.");
3118 py::class_<PyOpView, PyOperationBase>(m,
"OpView", py::module_local())
3119 .def(py::init<py::object>(), py::arg(
"operation"))
3120 .def_property_readonly(
"operation", &PyOpView::getOperationObject)
3121 .def_property_readonly(
"opview", [](py::object
self) {
return self; })
3124 [](
PyOpView &
self) {
return py::str(
self.getOperationObject()); })
3125 .def_property_readonly(
3128 return PyOpSuccessors(
self.getOperation().getRef());
3130 "Returns the list of Operation successors.");
3131 opViewClass.attr(
"_ODS_REGIONS") = py::make_tuple(0,
true);
3132 opViewClass.attr(
"_ODS_OPERAND_SEGMENTS") = py::none();
3133 opViewClass.attr(
"_ODS_RESULT_SEGMENTS") = py::none();
3135 &PyOpView::buildGeneric, py::arg(
"cls"), py::arg(
"results") = py::none(),
3136 py::arg(
"operands") = py::none(), py::arg(
"attributes") = py::none(),
3137 py::arg(
"successors") = py::none(), py::arg(
"regions") = py::none(),
3138 py::arg(
"loc") = py::none(), py::arg(
"ip") = py::none(),
3139 "Builds a specific, generated OpView based on class level attributes.");
3141 [](
const py::object &cls,
const std::string &sourceStr,
3151 std::string clsOpName =
3152 py::cast<std::string>(cls.attr(
"OPERATION_NAME"));
3155 std::string_view parsedOpName(identifier.
data, identifier.
length);
3156 if (clsOpName != parsedOpName)
3157 throw MLIRError(Twine(
"Expected a '") + clsOpName +
"' op, got: '" +
3158 parsedOpName +
"'");
3159 return PyOpView::constructDerived(cls, *parsed.
get());
3161 py::arg(
"cls"), py::arg(
"source"), py::kw_only(),
3162 py::arg(
"source_name") =
"", py::arg(
"context") = py::none(),
3163 "Parses a specific, generated OpView based on class level attributes");
3168 py::class_<PyRegion>(m,
"Region", py::module_local())
3169 .def_property_readonly(
3172 return PyBlockList(
self.getParentOperation(),
self.
get());
3174 "Returns a forward-optimized sequence of blocks.")
3175 .def_property_readonly(
3178 return self.getParentOperation()->createOpView();
3180 "Returns the operation owning this region.")
3186 return PyBlockIterator(
self.getParentOperation(), firstBlock);
3188 "Iterates over blocks in the region.")
3191 return self.get().ptr == other.
get().ptr;
3193 .def(
"__eq__", [](
PyRegion &
self, py::object &other) {
return false; });
3198 py::class_<PyBlock>(m,
"Block", py::module_local())
3200 .def_property_readonly(
3203 return self.getParentOperation()->createOpView();
3205 "Returns the owning operation of this block.")
3206 .def_property_readonly(
3210 return PyRegion(
self.getParentOperation(), region);
3212 "Returns the owning region of this block.")
3213 .def_property_readonly(
3216 return PyBlockArgumentList(
self.getParentOperation(),
self.
get());
3218 "Returns a list of block arguments.")
3219 .def_property_readonly(
3222 return PyOperationList(
self.getParentOperation(),
self.
get());
3224 "Returns a forward-optimized sequence of operations.")
3227 [](
PyRegion &parent,
const py::list &pyArgTypes,
3228 const std::optional<py::sequence> &pyArgLocs) {
3230 MlirBlock block =
createBlock(pyArgTypes, pyArgLocs);
3234 py::arg(
"parent"), py::arg(
"arg_types") = py::list(),
3235 py::arg(
"arg_locs") = std::nullopt,
3236 "Creates and returns a new Block at the beginning of the given "
3237 "region (with given argument types and locations).")
3241 MlirBlock b =
self.get();
3246 "Append this block to a region, transferring ownership if necessary")
3249 [](
PyBlock &
self,
const py::args &pyArgTypes,
3250 const std::optional<py::sequence> &pyArgLocs) {
3252 MlirBlock block =
createBlock(pyArgTypes, pyArgLocs);
3255 return PyBlock(
self.getParentOperation(), block);
3257 py::arg(
"arg_locs") = std::nullopt,
3258 "Creates and returns a new Block before this block "
3259 "(with given argument types and locations).")
3262 [](
PyBlock &
self,
const py::args &pyArgTypes,
3263 const std::optional<py::sequence> &pyArgLocs) {
3265 MlirBlock block =
createBlock(pyArgTypes, pyArgLocs);
3268 return PyBlock(
self.getParentOperation(), block);
3270 py::arg(
"arg_locs") = std::nullopt,
3271 "Creates and returns a new Block after this block "
3272 "(with given argument types and locations).")
3277 MlirOperation firstOperation =
3279 return PyOperationIterator(
self.getParentOperation(),
3282 "Iterates over operations in the block.")
3285 return self.get().ptr == other.
get().ptr;
3287 .def(
"__eq__", [](
PyBlock &
self, py::object &other) {
return false; })
3299 return printAccum.
join();
3301 "Returns the assembly form of the block.")
3311 self.getParentOperation().getObject());
3313 py::arg(
"operation"),
3314 "Appends an operation to this block. If the operation is currently "
3315 "in another block, it will be moved.");
3321 py::class_<PyInsertionPoint>(m,
"InsertionPoint", py::module_local())
3322 .def(py::init<PyBlock &>(), py::arg(
"block"),
3323 "Inserts after the last operation but still inside the block.")
3324 .def(
"__enter__", &PyInsertionPoint::contextEnter)
3325 .def(
"__exit__", &PyInsertionPoint::contextExit)
3326 .def_property_readonly_static(
3329 auto *ip = PyThreadContextEntry::getDefaultInsertionPoint();
3331 throw py::value_error(
"No current InsertionPoint");
3334 "Gets the InsertionPoint bound to the current thread or raises "
3335 "ValueError if none has been set")
3336 .def(py::init<PyOperationBase &>(), py::arg(
"beforeOperation"),
3337 "Inserts before a referenced operation.")
3338 .def_static(
"at_block_begin", &PyInsertionPoint::atBlockBegin,
3339 py::arg(
"block"),
"Inserts at the beginning of the block.")
3340 .def_static(
"at_block_terminator", &PyInsertionPoint::atBlockTerminator,
3341 py::arg(
"block"),
"Inserts before the block terminator.")
3342 .def(
"insert", &PyInsertionPoint::insert, py::arg(
"operation"),
3343 "Inserts an operation.")
3344 .def_property_readonly(
3346 "Returns the block that this InsertionPoint points to.")
3347 .def_property_readonly(
3350 auto refOperation =
self.getRefOperation();
3352 return refOperation->getObject();
3355 "The reference operation before which new operations are "
3356 "inserted, or None if the insertion point is at the end of "
3362 py::class_<PyAttribute>(m,
"Attribute", py::module_local())
3365 .def(py::init<PyAttribute &>(), py::arg(
"cast_from_type"),
3366 "Casts the passed attribute to the generic Attribute")
3368 &PyAttribute::getCapsule)
3377 throw MLIRError(
"Unable to parse attribute", errors.take());
3380 py::arg(
"asm"), py::arg(
"context") = py::none(),
3381 "Parses an attribute from an assembly form. Raises an MLIRError on "
3383 .def_property_readonly(
3385 [](
PyAttribute &
self) {
return self.getContext().getObject(); },
3386 "Context that owns the Attribute")
3387 .def_property_readonly(
3394 py::keep_alive<0, 1>(),
"Binds a name to the attribute")
3397 .def(
"__eq__", [](
PyAttribute &
self, py::object &other) {
return false; })
3411 return printAccum.
join();
3413 "Returns the assembly form of the Attribute.")
3422 printAccum.
parts.append(
"Attribute(");
3425 printAccum.
parts.append(
")");
3426 return printAccum.
join();
3428 .def_property_readonly(
3433 "mlirTypeID was expected to be non-null.");
3439 "mlirTypeID was expected to be non-null.");
3440 std::optional<pybind11::function> typeCaster =
3444 return py::cast(
self);
3445 return typeCaster.value()(
self);
3451 py::class_<PyNamedAttribute>(m,
"NamedAttribute", py::module_local())
3455 printAccum.
parts.append(
"NamedAttribute(");
3456 printAccum.
parts.append(
3459 printAccum.
parts.append(
"=");
3463 printAccum.
parts.append(
")");
3464 return printAccum.
join();
3466 .def_property_readonly(
3472 "The name of the NamedAttribute binding")
3473 .def_property_readonly(
3476 py::keep_alive<0, 1>(),
3477 "The underlying generic attribute of the NamedAttribute binding");
3482 py::class_<PyType>(m,
"Type", py::module_local())
3485 .def(py::init<PyType &>(), py::arg(
"cast_from_type"),
3486 "Casts the passed type to the generic Type")
3496 throw MLIRError(
"Unable to parse type", errors.take());
3499 py::arg(
"asm"), py::arg(
"context") = py::none(),
3501 .def_property_readonly(
3502 "context", [](
PyType &
self) {
return self.getContext().getObject(); },
3503 "Context that owns the Type")
3504 .def(
"__eq__", [](
PyType &
self,
PyType &other) {
return self == other; })
3505 .def(
"__eq__", [](
PyType &
self, py::object &other) {
return false; })
3518 return printAccum.
join();
3520 "Returns the assembly form of the type.")
3528 printAccum.
parts.append(
"Type(");
3531 printAccum.
parts.append(
")");
3532 return printAccum.
join();
3538 "mlirTypeID was expected to be non-null.");
3539 std::optional<pybind11::function> typeCaster =
3543 return py::cast(
self);
3544 return typeCaster.value()(
self);
3546 .def_property_readonly(
"typeid", [](
PyType &
self) -> MlirTypeID {
3551 pybind11::repr(pybind11::cast(
self)).cast<std::string>();
3552 throw py::value_error(
3553 (origRepr + llvm::Twine(
" has no typeid.")).str());
3559 py::class_<PyTypeID>(m,
"TypeID", py::module_local())
3568 [](
PyTypeID &
self,
const py::object &other) {
return false; })
3572 .def(
"__hash__", [](
PyTypeID &
self) {
3579 py::class_<PyValue>(m,
"Value", py::module_local())
3580 .def(py::init<PyValue &>(), py::keep_alive<0, 1>(), py::arg(
"value"))
3583 .def_property_readonly(
3586 "Context in which the value lives.")
3590 .def_property_readonly(
3592 [](
PyValue &
self) -> py::object {
3593 MlirValue v =
self.get();
3598 "expected the owner of the value in Python to match that in "
3600 return self.getParentOperation().getObject();
3605 return py::cast(
PyBlock(
self.getParentOperation(), block));
3608 assert(
false &&
"Value must be a block argument or an op result");
3611 .def_property_readonly(
"uses",
3613 return PyOpOperandIterator(
3618 return self.get().ptr == other.
get().ptr;
3620 .def(
"__eq__", [](
PyValue &
self, py::object other) {
return false; })
3629 printAccum.
parts.append(
"Value(");
3632 printAccum.
parts.append(
")");
3633 return printAccum.
join();
3638 [](
PyValue &
self,
bool useLocalScope) {
3643 MlirAsmState valueState =
3650 return printAccum.
join();
3652 py::arg(
"use_local_scope") =
false)
3655 [](
PyValue &
self, std::reference_wrapper<PyAsmState> state) {
3657 MlirAsmState valueState = state.get().get();
3661 return printAccum.
join();
3664 .def_property_readonly(
3673 "replace_all_uses_with",
3679 [](
PyValue &
self) {
return self.maybeDownCast(); });
3680 PyBlockArgument::bind(m);
3681 PyOpResult::bind(m);
3682 PyOpOperand::bind(m);
3684 py::class_<PyAsmState>(m,
"AsmState", py::module_local())
3685 .def(py::init<PyValue &, bool>(), py::arg(
"value"),
3686 py::arg(
"use_local_scope") =
false)
3687 .def(py::init<PyOperationBase &, bool>(), py::arg(
"op"),
3688 py::arg(
"use_local_scope") =
false);
3693 py::class_<PySymbolTable>(m,
"SymbolTable", py::module_local())
3694 .def(py::init<PyOperationBase &>())
3695 .def(
"__getitem__", &PySymbolTable::dunderGetItem)
3696 .def(
"insert", &PySymbolTable::insert, py::arg(
"operation"))
3697 .def(
"erase", &PySymbolTable::erase, py::arg(
"operation"))
3698 .def(
"__delitem__", &PySymbolTable::dunderDel)
3699 .def(
"__contains__",
3705 .def_static(
"set_symbol_name", &PySymbolTable::setSymbolName,
3706 py::arg(
"symbol"), py::arg(
"name"))
3707 .def_static(
"get_symbol_name", &PySymbolTable::getSymbolName,
3709 .def_static(
"get_visibility", &PySymbolTable::getVisibility,
3711 .def_static(
"set_visibility", &PySymbolTable::setVisibility,
3712 py::arg(
"symbol"), py::arg(
"visibility"))
3713 .def_static(
"replace_all_symbol_uses",
3714 &PySymbolTable::replaceAllSymbolUses, py::arg(
"old_symbol"),
3715 py::arg(
"new_symbol"), py::arg(
"from_op"))
3716 .def_static(
"walk_symbol_tables", &PySymbolTable::walkSymbolTables,
3717 py::arg(
"from_op"), py::arg(
"all_sym_uses_visible"),
3718 py::arg(
"callback"));
3721 PyBlockArgumentList::bind(m);
3722 PyBlockIterator::bind(m);
3723 PyBlockList::bind(m);
3724 PyOperationIterator::bind(m);
3725 PyOperationList::bind(m);
3726 PyOpAttributeMap::bind(m);
3727 PyOpOperandIterator::bind(m);
3728 PyOpOperandList::bind(m);
3729 PyOpResultList::bind(m);
3730 PyOpSuccessors::bind(m);
3731 PyRegionIterator::bind(m);
3732 PyRegionList::bind(m);
3740 py::register_local_exception_translator([](std::exception_ptr p) {
3745 std::rethrow_exception(p);
3749 PyErr_SetObject(PyExc_Exception, obj.ptr());
MLIR_CAPI_EXPORTED bool mlirIsGlobalDebugEnabled()
Retuns true if the global debugging flag is set, false otherwise.
MLIR_CAPI_EXPORTED void mlirEnableGlobalDebug(bool enable)
Sets the global debugging flag.
static const char kOperationPrintStateDocstring[]
static const char kValueReplaceAllUsesWithDocstring[]
static py::object createCustomDialectWrapper(const std::string &dialectNamespace, py::object dialectDescriptor)
static const char kContextGetNameLocationDocString[]
static const char kGetNameAsOperand[]
static MlirStringRef toMlirStringRef(const std::string &s)
static const char kModuleParseDocstring[]
static const char kOperationStrDunderDocstring[]
static const char kOperationPrintDocstring[]
static const char kContextGetFileLocationDocstring[]
static const char kDumpDocstring[]
static const char kAppendBlockDocstring[]
static const char kContextGetFusedLocationDocstring[]
static void maybeInsertOperation(PyOperationRef &op, const py::object &maybeIp)
static MlirBlock createBlock(const py::sequence &pyArgTypes, const std::optional< py::sequence > &pyArgLocs)
Create a block, using the current location context if no locations are specified.
static const char kOperationPrintBytecodeDocstring[]
static const char kOperationGetAsmDocstring[]
static void populateResultTypes(StringRef name, py::list resultTypeList, const py::object &resultSegmentSpecObj, std::vector< int32_t > &resultSegmentLengths, std::vector< PyType * > &resultTypes)
static const char kOperationCreateDocstring[]
static const char kContextParseTypeDocstring[]
static const char kContextGetCallSiteLocationDocstring[]
static const char kValueDunderStrDocstring[]
py::object classmethod(Func f, Args... args)
Helper for creating an @classmethod.
static MLIRContext * getContext(OpFoldResult val)
static PyObject * mlirPythonModuleToCapsule(MlirModule module)
Creates a capsule object encapsulating the raw C-API MlirModule.
#define MLIR_PYTHON_MAYBE_DOWNCAST_ATTR
Attribute on MLIR Python objects that expose a function for downcasting the corresponding Python obje...
static PyObject * mlirPythonTypeIDToCapsule(MlirTypeID typeID)
Creates a capsule object encapsulating the raw C-API MlirTypeID.
static MlirOperation mlirPythonCapsuleToOperation(PyObject *capsule)
Extracts an MlirOperations from a capsule as produced from mlirPythonOperationToCapsule.
#define MLIR_PYTHON_CAPI_PTR_ATTR
Attribute on MLIR Python objects that expose their C-API pointer.
static MlirAttribute mlirPythonCapsuleToAttribute(PyObject *capsule)
Extracts an MlirAttribute from a capsule as produced from mlirPythonAttributeToCapsule.
static PyObject * mlirPythonAttributeToCapsule(MlirAttribute attribute)
Creates a capsule object encapsulating the raw C-API MlirAttribute.
static PyObject * mlirPythonLocationToCapsule(MlirLocation loc)
Creates a capsule object encapsulating the raw C-API MlirLocation.
#define MLIR_PYTHON_CAPI_FACTORY_ATTR
Attribute on MLIR Python objects that exposes a factory function for constructing the corresponding P...
static MlirModule mlirPythonCapsuleToModule(PyObject *capsule)
Extracts an MlirModule from a capsule as produced from mlirPythonModuleToCapsule.
static MlirContext mlirPythonCapsuleToContext(PyObject *capsule)
Extracts a MlirContext from a capsule as produced from mlirPythonContextToCapsule.
static MlirTypeID mlirPythonCapsuleToTypeID(PyObject *capsule)
Extracts an MlirTypeID from a capsule as produced from mlirPythonTypeIDToCapsule.
static PyObject * mlirPythonDialectRegistryToCapsule(MlirDialectRegistry registry)
Creates a capsule object encapsulating the raw C-API MlirDialectRegistry.
static PyObject * mlirPythonTypeToCapsule(MlirType type)
Creates a capsule object encapsulating the raw C-API MlirType.
static MlirDialectRegistry mlirPythonCapsuleToDialectRegistry(PyObject *capsule)
Extracts an MlirDialectRegistry from a capsule as produced from mlirPythonDialectRegistryToCapsule.
#define MAKE_MLIR_PYTHON_QUALNAME(local)
static MlirType mlirPythonCapsuleToType(PyObject *capsule)
Extracts an MlirType from a capsule as produced from mlirPythonTypeToCapsule.
static MlirValue mlirPythonCapsuleToValue(PyObject *capsule)
Extracts an MlirValue from a capsule as produced from mlirPythonValueToCapsule.
static PyObject * mlirPythonBlockToCapsule(MlirBlock block)
Creates a capsule object encapsulating the raw C-API MlirBlock.
static PyObject * mlirPythonOperationToCapsule(MlirOperation operation)
Creates a capsule object encapsulating the raw C-API MlirOperation.
static MlirLocation mlirPythonCapsuleToLocation(PyObject *capsule)
Extracts an MlirLocation from a capsule as produced from mlirPythonLocationToCapsule.
static PyObject * mlirPythonValueToCapsule(MlirValue value)
Creates a capsule object encapsulating the raw C-API MlirValue.
static PyObject * mlirPythonContextToCapsule(MlirContext context)
Creates a capsule object encapsulating the raw C-API MlirContext.
static LogicalResult nextIndex(ArrayRef< int64_t > shape, MutableArrayRef< int64_t > index)
Walks over the indices of the elements of a tensor of a given shape by updating index in place to the...
static std::string diag(const llvm::Value &value)
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
static sycl::context getDefaultContext()
MLIRContext * getContext()
Return the context this operation is associated with.
Accumulates int a python file-like object, either writing text (default) or binary.
MlirStringCallback getCallback()
A CRTP base class for pseudo-containers willing to support Python-type slicing access on top of index...
Base class for all objects that directly or indirectly depend on an MlirContext.
PyMlirContextRef & getContext()
Accesses the context reference.
Used in function arguments when None should resolve to the current context manager set instance.
static PyLocation & resolve()
Used in function arguments when None should resolve to the current context manager set instance.
static PyMlirContext & resolve()
ReferrentTy * get() const
Wrapper around an MlirAsmState.
Wrapper around the generic MlirAttribute.
PyAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
static PyAttribute createFromCapsule(pybind11::object capsule)
Creates a PyAttribute from the MlirAttribute wrapped by a capsule.
pybind11::object getCapsule()
Gets a capsule wrapping the void* within the MlirAttribute.
bool operator==(const PyAttribute &other) const
Wrapper around an MlirBlock.
PyOperationRef & getParentOperation()
Represents a diagnostic handler attached to the context.
void detach()
Detaches the handler. Does nothing if not attached.
PyDiagnosticHandler(MlirContext context, pybind11::object callback)
Python class mirroring the C MlirDiagnostic struct.
pybind11::str getMessage()
PyDiagnostic(MlirDiagnostic diagnostic)
MlirDiagnosticSeverity getSeverity()
pybind11::tuple getNotes()
Wrapper around an MlirDialect.
Wrapper around an MlirDialectRegistry.
static PyDialectRegistry createFromCapsule(pybind11::object capsule)
pybind11::object getCapsule()
User-level dialect object.
User-level object for accessing dialects with dotted syntax such as: ctx.dialect.std.
MlirDialect getDialectForKey(const std::string &key, bool attrError)
static PyGlobals & get()
Most code should get the globals via this static accessor.
std::optional< pybind11::object > lookupOperationClass(llvm::StringRef operationName)
Looks up a registered operation class (deriving from OpView) by operation name.
std::optional< pybind11::function > lookupValueCaster(MlirTypeID mlirTypeID, MlirDialect dialect)
Returns the custom value caster for MlirTypeID mlirTypeID.
An insertion point maintains a pointer to a Block and a reference operation.
static PyInsertionPoint atBlockTerminator(PyBlock &block)
Shortcut to create an insertion point before the block terminator.
PyInsertionPoint(PyBlock &block)
Creates an insertion point positioned after the last operation in the block, but still inside the blo...
static PyInsertionPoint atBlockBegin(PyBlock &block)
Shortcut to create an insertion point at the beginning of the block.
void insert(PyOperationBase &operationBase)
Inserts an operation.
void contextExit(const pybind11::object &excType, const pybind11::object &excVal, const pybind11::object &excTb)
pybind11::object contextEnter()
Enter and exit the context manager.
Wrapper around an MlirLocation.
PyLocation(PyMlirContextRef contextRef, MlirLocation loc)
pybind11::object getCapsule()
Gets a capsule wrapping the void* within the MlirLocation.
static PyLocation createFromCapsule(pybind11::object capsule)
Creates a PyLocation from the MlirLocation wrapped by a capsule.
void contextExit(const pybind11::object &excType, const pybind11::object &excVal, const pybind11::object &excTb)
pybind11::object contextEnter()
Enter and exit the context manager.
pybind11::object attachDiagnosticHandler(pybind11::object callback)
Attaches a Python callback as a diagnostic handler, returning a registration object (internally a PyD...
MlirContext get()
Accesses the underlying MlirContext.
PyMlirContextRef getRef()
Gets a strong reference to this context, which will ensure it is kept alive for the life of the refer...
static pybind11::object createFromCapsule(pybind11::object capsule)
Creates a PyMlirContext from the MlirContext wrapped by a capsule.
void clearOperationsInside(PyOperationBase &op)
Clears all operations nested inside the given op using clearOperation(MlirOperation).
static size_t getLiveCount()
Gets the count of live context objects. Used for testing.
static PyMlirContext * createNewContextForInit()
For the case of a python init (py::init) method, pybind11 is quite strict about needing to return a p...
size_t getLiveModuleCount()
Gets the count of live modules associated with this context.
pybind11::object contextEnter()
Enter and exit the context manager.
size_t clearLiveOperations()
Clears the live operations map, returning the number of entries which were invalidated.
std::vector< PyOperation * > getLiveOperationObjects()
Get a list of Python objects which are still in the live context map.
void contextExit(const pybind11::object &excType, const pybind11::object &excVal, const pybind11::object &excTb)
void clearOperation(MlirOperation op)
Removes an operation from the live operations map and sets it invalid.
static PyMlirContextRef forContext(MlirContext context)
Returns a context reference for the singleton PyMlirContext wrapper for the given context.
size_t getLiveOperationCount()
Gets the count of live operations associated with this context.
pybind11::object getCapsule()
Gets a capsule wrapping the void* within the MlirContext.
MlirModule get()
Gets the backing MlirModule.
static PyModuleRef forModule(MlirModule module)
Returns a PyModule reference for the given MlirModule.
pybind11::object getCapsule()
Gets a capsule wrapping the void* within the MlirModule.
static pybind11::object createFromCapsule(pybind11::object capsule)
Creates a PyModule from the MlirModule wrapped by a capsule.
PyModule(PyModule &)=delete
Represents a Python MlirNamedAttr, carrying an optional owned name.
PyNamedAttribute(MlirAttribute attr, std::string ownedName)
Constructs a PyNamedAttr that retains an owned name.
MlirNamedAttribute namedAttr
pybind11::object getObject()
pybind11::object releaseObject()
Releases the object held by this instance, returning it.
A PyOpView is equivalent to the C++ "Op" wrappers: these are the basis for providing more instance-sp...
PyOpView(const pybind11::object &operationObject)
static pybind11::object buildGeneric(const pybind11::object &cls, std::optional< pybind11::list > resultTypeList, pybind11::list operandList, std::optional< pybind11::dict > attributes, std::optional< std::vector< PyBlock * >> successors, std::optional< int > regions, DefaultingPyLocation location, const pybind11::object &maybeIp)
static pybind11::object constructDerived(const pybind11::object &cls, const PyOperation &operation)
Construct an instance of a class deriving from OpView, bypassing its __init__ method.
Base class for PyOperation and PyOpView which exposes the primary, user visible methods for manipulat...
void walk(std::function< MlirWalkResult(MlirOperation)> callback, MlirWalkOrder walkOrder)
virtual PyOperation & getOperation()=0
Each must provide access to the raw Operation.
void writeBytecode(const pybind11::object &fileObject, std::optional< int64_t > bytecodeVersion)
pybind11::object getAsm(bool binary, std::optional< int64_t > largeElementsLimit, bool enableDebugInfo, bool prettyDebugInfo, bool printGenericOpForm, bool useLocalScope, bool assumeVerified)
void moveAfter(PyOperationBase &other)
Moves the operation before or after the other operation.
void print(std::optional< int64_t > largeElementsLimit, bool enableDebugInfo, bool prettyDebugInfo, bool printGenericOpForm, bool useLocalScope, bool assumeVerified, py::object fileObject, bool binary)
Implements the bound 'print' method and helps with others.
void moveBefore(PyOperationBase &other)
bool verify()
Verify the operation.
pybind11::object clone(const pybind11::object &ip)
Clones this operation.
void detachFromParent()
Detaches the operation from its parent block and updates its state accordingly.
void erase()
Erases the underlying MlirOperation, removes its pointer from the parent context's live operations ma...
pybind11::object getCapsule()
Gets a capsule wrapping the void* within the MlirOperation.
PyOperation & getOperation() override
Each must provide access to the raw Operation.
MlirOperation get() const
void setAttached(const pybind11::object &parent=pybind11::object())
static pybind11::object create(const std::string &name, std::optional< std::vector< PyType * >> results, std::optional< std::vector< PyValue * >> operands, std::optional< pybind11::dict > attributes, std::optional< std::vector< PyBlock * >> successors, int regions, DefaultingPyLocation location, const pybind11::object &ip, bool inferType)
Creates an operation. See corresponding python docstring.
pybind11::object createOpView()
Creates an OpView suitable for this operation.
static PyOperationRef forOperation(PyMlirContextRef contextRef, MlirOperation operation, pybind11::object parentKeepAlive=pybind11::object())
Returns a PyOperation for the given MlirOperation, optionally associating it with a parentKeepAlive.
std::optional< PyOperationRef > getParentOperation()
Gets the parent operation or raises an exception if the operation has no parent.
PyBlock getBlock()
Gets the owning block or raises an exception if the operation has no owning block.
static PyOperationRef createDetached(PyMlirContextRef contextRef, MlirOperation operation, pybind11::object parentKeepAlive=pybind11::object())
Creates a detached operation.
static PyOperationRef parse(PyMlirContextRef contextRef, const std::string &sourceStr, const std::string &sourceName)
Parses a source string (either text assembly or bytecode), creating a detached operation.
static pybind11::object createFromCapsule(pybind11::object capsule)
Creates a PyOperation from the MlirOperation wrapped by a capsule.
Wrapper around an MlirRegion.
PyOperationRef & getParentOperation()
Bindings for MLIR symbol tables.
void dunderDel(const std::string &name)
Removes the operation with the given name from the symbol table and erases it, throws if there is no ...
static void replaceAllSymbolUses(const std::string &oldSymbol, const std::string &newSymbol, PyOperationBase &from)
Replaces all symbol uses within an operation.
static void setVisibility(PyOperationBase &symbol, const std::string &visibility)
static void setSymbolName(PyOperationBase &symbol, const std::string &name)
MlirAttribute insert(PyOperationBase &symbol)
Inserts the given operation into the symbol table.
void erase(PyOperationBase &symbol)
Removes the given operation from the symbol table and erases it.
PySymbolTable(PyOperationBase &operation)
Constructs a symbol table for the given operation.
static MlirAttribute getSymbolName(PyOperationBase &symbol)
Gets and sets the name of a symbol op.
pybind11::object dunderGetItem(const std::string &name)
Returns the symbol (opview) with the given name, throws if there is no such symbol in the table.
static MlirAttribute getVisibility(PyOperationBase &symbol)
Gets and sets the visibility of a symbol op.
static void walkSymbolTables(PyOperationBase &from, bool allSymUsesVisible, pybind11::object callback)
Walks all symbol tables under and including 'from'.
Tracks an entry in the thread context stack.
static PyThreadContextEntry * getTopOfStack()
Stack management.
static void popLocation(PyLocation &location)
PyLocation * getLocation()
static pybind11::object pushContext(PyMlirContext &context)
static PyLocation * getDefaultLocation()
Gets the top of stack location and returns nullptr if not defined.
static void popInsertionPoint(PyInsertionPoint &insertionPoint)
static void popContext(PyMlirContext &context)
static PyInsertionPoint * getDefaultInsertionPoint()
Gets the top of stack insertion point and return nullptr if not defined.
static pybind11::object pushInsertionPoint(PyInsertionPoint &insertionPoint)
static pybind11::object pushLocation(PyLocation &location)
PyMlirContext * getContext()
static PyMlirContext * getDefaultContext()
Gets the top of stack context and return nullptr if not defined.
static std::vector< PyThreadContextEntry > & getStack()
Gets the thread local stack.
PyInsertionPoint * getInsertionPoint()
A TypeID provides an efficient and unique identifier for a specific C++ type.
bool operator==(const PyTypeID &other) const
static PyTypeID createFromCapsule(pybind11::object capsule)
Creates a PyTypeID from the MlirTypeID wrapped by a capsule.
pybind11::object getCapsule()
Gets a capsule wrapping the void* within the MlirTypeID.
PyTypeID(MlirTypeID typeID)
Wrapper around the generic MlirType.
pybind11::object getCapsule()
Gets a capsule wrapping the void* within the MlirType.
static PyType createFromCapsule(pybind11::object capsule)
Creates a PyType from the MlirType wrapped by a capsule.
PyType(PyMlirContextRef contextRef, MlirType type)
bool operator==(const PyType &other) const
Wrapper around the generic MlirValue.
static PyValue createFromCapsule(pybind11::object capsule)
Creates a PyValue from the MlirValue wrapped by a capsule.
PyValue(PyOperationRef parentOperation, MlirValue value)
pybind11::object getCapsule()
Gets a capsule wrapping the void* within the MlirValue.
pybind11::object maybeDownCast()
MLIR_CAPI_EXPORTED intptr_t mlirDiagnosticGetNumNotes(MlirDiagnostic diagnostic)
Returns the number of notes attached to the diagnostic.
MLIR_CAPI_EXPORTED MlirDiagnosticSeverity mlirDiagnosticGetSeverity(MlirDiagnostic diagnostic)
Returns the severity of the diagnostic.
MLIR_CAPI_EXPORTED void mlirDiagnosticPrint(MlirDiagnostic diagnostic, MlirStringCallback callback, void *userData)
Prints a diagnostic using the provided callback.
MlirDiagnosticSeverity
Severity of a diagnostic.
MLIR_CAPI_EXPORTED MlirDiagnostic mlirDiagnosticGetNote(MlirDiagnostic diagnostic, intptr_t pos)
Returns pos-th note attached to the diagnostic.
MLIR_CAPI_EXPORTED void mlirEmitError(MlirLocation location, const char *message)
Emits an error at the given location through the diagnostics engine.
MLIR_CAPI_EXPORTED MlirDiagnosticHandlerID mlirContextAttachDiagnosticHandler(MlirContext context, MlirDiagnosticHandler handler, void *userData, void(*deleteUserData)(void *))
Attaches the diagnostic handler to the context.
MLIR_CAPI_EXPORTED void mlirContextDetachDiagnosticHandler(MlirContext context, MlirDiagnosticHandlerID id)
Detaches an attached diagnostic handler from the context given its identifier.
uint64_t MlirDiagnosticHandlerID
Opaque identifier of a diagnostic handler, useful to detach a handler.
MLIR_CAPI_EXPORTED MlirLocation mlirDiagnosticGetLocation(MlirDiagnostic diagnostic)
Returns the location at which the diagnostic is reported.
MLIR_CAPI_EXPORTED MlirAttribute mlirDenseI32ArrayGet(MlirContext ctx, intptr_t size, int32_t const *values)
MLIR_CAPI_EXPORTED MlirAttribute mlirStringAttrGet(MlirContext ctx, MlirStringRef str)
Creates a string attribute in the given context containing the given string.
MLIR_CAPI_EXPORTED MlirAttribute mlirLocationGetAttribute(MlirLocation location)
Returns the underlying location attribute of this location.
MLIR_CAPI_EXPORTED intptr_t mlirBlockArgumentGetArgNumber(MlirValue value)
Returns the position of the value in the argument list of its block.
static bool mlirAttributeIsNull(MlirAttribute attr)
Checks whether an attribute is null.
MlirWalkResult(* MlirOperationWalkCallback)(MlirOperation, void *userData)
Operation walker type.
MLIR_CAPI_EXPORTED void mlirOperationWriteBytecode(MlirOperation op, MlirStringCallback callback, void *userData)
Same as mlirOperationPrint but writing the bytecode format.
MLIR_CAPI_EXPORTED MlirIdentifier mlirOperationGetName(MlirOperation op)
Gets the name of the operation as an identifier.
MLIR_CAPI_EXPORTED MlirLocation mlirLocationFileLineColGet(MlirContext context, MlirStringRef filename, unsigned line, unsigned col)
Creates an File/Line/Column location owned by the given context.
MLIR_CAPI_EXPORTED void mlirSymbolTableWalkSymbolTables(MlirOperation from, bool allSymUsesVisible, void(*callback)(MlirOperation, bool, void *userData), void *userData)
Walks all symbol table operations nested within, and including, op.
MLIR_CAPI_EXPORTED MlirStringRef mlirDialectGetNamespace(MlirDialect dialect)
Returns the namespace of the given dialect.
MLIR_CAPI_EXPORTED intptr_t mlirOperationGetNumResults(MlirOperation op)
Returns the number of results of the operation.
MLIR_CAPI_EXPORTED MlirAttribute mlirSymbolTableInsert(MlirSymbolTable symbolTable, MlirOperation operation)
Inserts the given operation into the given symbol table.
MlirWalkOrder
Traversal order for operation walk.
MLIR_CAPI_EXPORTED MlirNamedAttribute mlirOperationGetAttribute(MlirOperation op, intptr_t pos)
Return pos-th attribute of the operation.
MLIR_CAPI_EXPORTED void mlirOperationStateAddOperands(MlirOperationState *state, intptr_t n, MlirValue const *operands)
MLIR_CAPI_EXPORTED void mlirModuleDestroy(MlirModule module)
Takes a module owned by the caller and deletes it.
MLIR_CAPI_EXPORTED MlirNamedAttribute mlirNamedAttributeGet(MlirIdentifier name, MlirAttribute attr)
Associates an attribute with the name. Takes ownership of neither.
MLIR_CAPI_EXPORTED void mlirSymbolTableErase(MlirSymbolTable symbolTable, MlirOperation operation)
Removes the given operation from the symbol table and erases it.
MLIR_CAPI_EXPORTED void mlirOpPrintingFlagsUseLocalScope(MlirOpPrintingFlags flags)
Use local scope when printing the operation.
MLIR_CAPI_EXPORTED bool mlirValueIsABlockArgument(MlirValue value)
Returns 1 if the value is a block argument, 0 otherwise.
MLIR_CAPI_EXPORTED void mlirContextAppendDialectRegistry(MlirContext ctx, MlirDialectRegistry registry)
Append the contents of the given dialect registry to the registry associated with the context.
MLIR_CAPI_EXPORTED MlirStringRef mlirIdentifierStr(MlirIdentifier ident)
Gets the string value of the identifier.
static bool mlirModuleIsNull(MlirModule module)
Checks whether a module is null.
MLIR_CAPI_EXPORTED MlirType mlirTypeParseGet(MlirContext context, MlirStringRef type)
Parses a type. The type is owned by the context.
MLIR_CAPI_EXPORTED MlirOpOperand mlirOpOperandGetNextUse(MlirOpOperand opOperand)
Returns an op operand representing the next use of the value, or a null op operand if there is no nex...
MLIR_CAPI_EXPORTED MlirType mlirAttributeGetType(MlirAttribute attribute)
Gets the type of this attribute.
MLIR_CAPI_EXPORTED void mlirContextSetAllowUnregisteredDialects(MlirContext context, bool allow)
Sets whether unregistered dialects are allowed in this context.
MLIR_CAPI_EXPORTED void mlirRegionInsertOwnedBlockBefore(MlirRegion region, MlirBlock reference, MlirBlock block)
Takes a block owned by the caller and inserts it before the (non-owned) reference block in the given ...
MLIR_CAPI_EXPORTED void mlirValueReplaceAllUsesOfWith(MlirValue of, MlirValue with)
Replace all uses of 'of' value with the 'with' value, updating anything in the IR that uses 'of' to u...
MLIR_CAPI_EXPORTED MlirBlock mlirOperationGetSuccessor(MlirOperation op, intptr_t pos)
Returns pos-th successor of the operation.
MLIR_CAPI_EXPORTED void mlirValuePrintAsOperand(MlirValue value, MlirAsmState state, MlirStringCallback callback, void *userData)
Prints a value as an operand (i.e., the ValueID).
MLIR_CAPI_EXPORTED MlirLocation mlirLocationUnknownGet(MlirContext context)
Creates a location with unknown position owned by the given context.
MLIR_CAPI_EXPORTED void mlirTypePrint(MlirType type, MlirStringCallback callback, void *userData)
Prints a location by sending chunks of the string representation and forwarding userData tocallback`.
MLIR_CAPI_EXPORTED void mlirOperationSetAttributeByName(MlirOperation op, MlirStringRef name, MlirAttribute attr)
Sets an attribute by name, replacing the existing if it exists or adding a new one otherwise.
MLIR_CAPI_EXPORTED MlirOperation mlirOpOperandGetOwner(MlirOpOperand opOperand)
Returns the owner operation of an op operand.
MLIR_CAPI_EXPORTED MlirDialect mlirAttributeGetDialect(MlirAttribute attribute)
Gets the dialect of the attribute.
MLIR_CAPI_EXPORTED void mlirAttributePrint(MlirAttribute attr, MlirStringCallback callback, void *userData)
Prints an attribute by sending chunks of the string representation and forwarding userData tocallback...
MLIR_CAPI_EXPORTED MlirRegion mlirBlockGetParentRegion(MlirBlock block)
Returns the region that contains this block.
MLIR_CAPI_EXPORTED void mlirOperationMoveBefore(MlirOperation op, MlirOperation other)
Moves the given operation immediately before the other operation in its parent block.
static bool mlirValueIsNull(MlirValue value)
Returns whether the value is null.
MLIR_CAPI_EXPORTED void mlirOperationPrintWithState(MlirOperation op, MlirAsmState state, MlirStringCallback callback, void *userData)
Same as mlirOperationPrint but accepts AsmState controlling the printing behavior as well as caching ...
MlirWalkResult
Operation walk result.
@ MlirWalkResultInterrupt
MLIR_CAPI_EXPORTED void mlirRegionInsertOwnedBlock(MlirRegion region, intptr_t pos, MlirBlock block)
Takes a block owned by the caller and inserts it at pos to the given region.
MLIR_CAPI_EXPORTED MlirAttribute mlirOperationGetAttributeByName(MlirOperation op, MlirStringRef name)
Returns an attribute attached to the operation given its name.
static bool mlirTypeIsNull(MlirType type)
Checks whether a type is null.
MLIR_CAPI_EXPORTED bool mlirContextIsRegisteredOperation(MlirContext context, MlirStringRef name)
Returns whether the given fully-qualified operation (i.e.
MLIR_CAPI_EXPORTED intptr_t mlirOperationGetNumSuccessors(MlirOperation op)
Returns the number of successor blocks of the operation.
MLIR_CAPI_EXPORTED MlirOperation mlirOperationClone(MlirOperation op)
Creates a deep copy of an operation.
MLIR_CAPI_EXPORTED intptr_t mlirBlockGetNumArguments(MlirBlock block)
Returns the number of arguments of the block.
MLIR_CAPI_EXPORTED void mlirOpPrintingFlagsPrintGenericOpForm(MlirOpPrintingFlags flags)
Always print operations in the generic form.
MLIR_CAPI_EXPORTED MlirLocation mlirLocationFusedGet(MlirContext ctx, intptr_t nLocations, MlirLocation const *locations, MlirAttribute metadata)
Creates a fused location with an array of locations and metadata.
MLIR_CAPI_EXPORTED void mlirBlockInsertOwnedOperationBefore(MlirBlock block, MlirOperation reference, MlirOperation operation)
Takes an operation owned by the caller and inserts it before the (non-owned) reference operation in t...
MLIR_CAPI_EXPORTED void mlirAsmStateDestroy(MlirAsmState state)
Destroys printing flags created with mlirAsmStateCreate.
static bool mlirContextIsNull(MlirContext context)
Checks whether a context is null.
MLIR_CAPI_EXPORTED MlirDialect mlirContextGetOrLoadDialect(MlirContext context, MlirStringRef name)
Gets the dialect instance owned by the given context using the dialect namespace to identify it,...
MLIR_CAPI_EXPORTED void mlirOpPrintingFlagsElideLargeElementsAttrs(MlirOpPrintingFlags flags, intptr_t largeElementLimit)
Enables the elision of large elements attributes by printing a lexically valid but otherwise meaningl...
MLIR_CAPI_EXPORTED void mlirRegionInsertOwnedBlockAfter(MlirRegion region, MlirBlock reference, MlirBlock block)
Takes a block owned by the caller and inserts it after the (non-owned) reference block in the given r...
MLIR_CAPI_EXPORTED void mlirBlockArgumentSetType(MlirValue value, MlirType type)
Sets the type of the block argument to the given type.
MLIR_CAPI_EXPORTED MlirContext mlirOperationGetContext(MlirOperation op)
Gets the context this operation is associated with.
MLIR_CAPI_EXPORTED MlirBlock mlirBlockCreate(intptr_t nArgs, MlirType const *args, MlirLocation const *locs)
Creates a new empty block with the given argument types and transfers ownership to the caller.
static bool mlirBlockIsNull(MlirBlock block)
Checks whether a block is null.
MLIR_CAPI_EXPORTED void mlirBlockAppendOwnedOperation(MlirBlock block, MlirOperation operation)
Takes an operation owned by the caller and appends it to the block.
MLIR_CAPI_EXPORTED MlirValue mlirBlockGetArgument(MlirBlock block, intptr_t pos)
Returns pos-th argument of the block.
MLIR_CAPI_EXPORTED MlirOperation mlirSymbolTableLookup(MlirSymbolTable symbolTable, MlirStringRef name)
Looks up a symbol with the given name in the given symbol table and returns the operation that corres...
MLIR_CAPI_EXPORTED MlirContext mlirTypeGetContext(MlirType type)
Gets the context that a type was created with.
MLIR_CAPI_EXPORTED void mlirValueDump(MlirValue value)
Prints the value to the standard error stream.
MLIR_CAPI_EXPORTED MlirModule mlirModuleCreateEmpty(MlirLocation location)
Creates a new, empty module and transfers ownership to the caller.
MLIR_CAPI_EXPORTED bool mlirOpOperandIsNull(MlirOpOperand opOperand)
Returns whether the op operand is null.
MLIR_CAPI_EXPORTED MlirSymbolTable mlirSymbolTableCreate(MlirOperation operation)
Creates a symbol table for the given operation.
MLIR_CAPI_EXPORTED bool mlirLocationEqual(MlirLocation l1, MlirLocation l2)
Checks if two locations are equal.
MLIR_CAPI_EXPORTED MlirBlock mlirOperationGetBlock(MlirOperation op)
Gets the block that owns this operation, returning null if the operation is not owned.
static bool mlirLocationIsNull(MlirLocation location)
Checks if the location is null.
MLIR_CAPI_EXPORTED bool mlirOperationEqual(MlirOperation op, MlirOperation other)
Checks whether two operation handles point to the same operation.
MLIR_CAPI_EXPORTED void mlirOperationPrintWithFlags(MlirOperation op, MlirOpPrintingFlags flags, MlirStringCallback callback, void *userData)
Same as mlirOperationPrint but accepts flags controlling the printing behavior.
MLIR_CAPI_EXPORTED MlirOpOperand mlirValueGetFirstUse(MlirValue value)
Returns an op operand representing the first use of the value, or a null op operand if there are no u...
MLIR_CAPI_EXPORTED void mlirLocationPrint(MlirLocation location, MlirStringCallback callback, void *userData)
Prints a location by sending chunks of the string representation and forwarding userData tocallback`.
MLIR_CAPI_EXPORTED bool mlirOperationVerify(MlirOperation op)
Verify the operation and return true if it passes, false if it fails.
MLIR_CAPI_EXPORTED MlirOperation mlirModuleGetOperation(MlirModule module)
Views the module as a generic operation.
MLIR_CAPI_EXPORTED bool mlirTypeEqual(MlirType t1, MlirType t2)
Checks if two types are equal.
MLIR_CAPI_EXPORTED MlirOperationState mlirOperationStateGet(MlirStringRef name, MlirLocation loc)
Constructs an operation state from a name and a location.
MLIR_CAPI_EXPORTED unsigned mlirOpOperandGetOperandNumber(MlirOpOperand opOperand)
Returns the operand number of an op operand.
MLIR_CAPI_EXPORTED MlirOperation mlirBlockGetTerminator(MlirBlock block)
Returns the terminator operation in the block or null if no terminator.
MLIR_CAPI_EXPORTED MlirOperation mlirOperationGetNextInBlock(MlirOperation op)
Returns an operation immediately following the given operation it its enclosing block.
MLIR_CAPI_EXPORTED MlirOperation mlirOperationGetParentOperation(MlirOperation op)
Gets the operation that owns this operation, returning null if the operation is not owned.
MLIR_CAPI_EXPORTED MlirContext mlirModuleGetContext(MlirModule module)
Gets the context that a module was created with.
MLIR_CAPI_EXPORTED MlirLocation mlirLocationFromAttribute(MlirAttribute attribute)
Creates a location from a location attribute.
MLIR_CAPI_EXPORTED void mlirOpPrintingFlagsAssumeVerified(MlirOpPrintingFlags flags)
Do not verify the operation when using custom operation printers.
MLIR_CAPI_EXPORTED MlirTypeID mlirTypeGetTypeID(MlirType type)
Gets the type ID of the type.
MLIR_CAPI_EXPORTED MlirStringRef mlirSymbolTableGetVisibilityAttributeName(void)
Returns the name of the attribute used to store symbol visibility.
static bool mlirDialectIsNull(MlirDialect dialect)
Checks if the dialect is null.
MLIR_CAPI_EXPORTED void mlirBytecodeWriterConfigDestroy(MlirBytecodeWriterConfig config)
Destroys printing flags created with mlirBytecodeWriterConfigCreate.
MLIR_CAPI_EXPORTED MlirValue mlirOperationGetOperand(MlirOperation op, intptr_t pos)
Returns pos-th operand of the operation.
MLIR_CAPI_EXPORTED void mlirOperationStateAddAttributes(MlirOperationState *state, intptr_t n, MlirNamedAttribute const *attributes)
MLIR_CAPI_EXPORTED MlirBlock mlirBlockGetNextInRegion(MlirBlock block)
Returns the block immediately following the given block in its parent region.
MLIR_CAPI_EXPORTED MlirLocation mlirLocationCallSiteGet(MlirLocation callee, MlirLocation caller)
Creates a call site location with a callee and a caller.
MLIR_CAPI_EXPORTED MlirOperation mlirOpResultGetOwner(MlirValue value)
Returns an operation that produced this value as its result.
MLIR_CAPI_EXPORTED bool mlirValueIsAOpResult(MlirValue value)
Returns 1 if the value is an operation result, 0 otherwise.
MLIR_CAPI_EXPORTED intptr_t mlirOperationGetNumOperands(MlirOperation op)
Returns the number of operands of the operation.
static bool mlirDialectRegistryIsNull(MlirDialectRegistry registry)
Checks if the dialect registry is null.
MLIR_CAPI_EXPORTED void mlirOperationWalk(MlirOperation op, MlirOperationWalkCallback callback, void *userData, MlirWalkOrder walkOrder)
Walks operation op in walkOrder and calls callback on that operation.
MLIR_CAPI_EXPORTED MlirContext mlirContextCreateWithThreading(bool threadingEnabled)
Creates an MLIR context with an explicit setting of the multithreading setting and transfers its owne...
MLIR_CAPI_EXPORTED MlirOperation mlirBlockGetParentOperation(MlirBlock)
Returns the closest surrounding operation that contains this block.
MLIR_CAPI_EXPORTED intptr_t mlirOperationGetNumRegions(MlirOperation op)
Returns the number of regions attached to the given operation.
MLIR_CAPI_EXPORTED MlirContext mlirLocationGetContext(MlirLocation location)
Gets the context that a location was created with.
MLIR_CAPI_EXPORTED bool mlirOperationRemoveAttributeByName(MlirOperation op, MlirStringRef name)
Removes an attribute by name.
MLIR_CAPI_EXPORTED void mlirAttributeDump(MlirAttribute attr)
Prints the attribute to the standard error stream.
MLIR_CAPI_EXPORTED MlirLogicalResult mlirSymbolTableReplaceAllSymbolUses(MlirStringRef oldSymbol, MlirStringRef newSymbol, MlirOperation from)
Attempt to replace all uses that are nested within the given operation of the given symbol 'oldSymbol...
MLIR_CAPI_EXPORTED MlirAttribute mlirAttributeParseGet(MlirContext context, MlirStringRef attr)
Parses an attribute. The attribute is owned by the context.
MLIR_CAPI_EXPORTED MlirModule mlirModuleCreateParse(MlirContext context, MlirStringRef module)
Parses a module from the string and transfers ownership to the caller.
MLIR_CAPI_EXPORTED void mlirRegionAppendOwnedBlock(MlirRegion region, MlirBlock block)
Takes a block owned by the caller and appends it to the given region.
MLIR_CAPI_EXPORTED MlirOperation mlirBlockGetFirstOperation(MlirBlock block)
Returns the first operation in the block.
MLIR_CAPI_EXPORTED void mlirTypeDump(MlirType type)
Prints the type to the standard error stream.
MLIR_CAPI_EXPORTED MlirValue mlirOperationGetResult(MlirOperation op, intptr_t pos)
Returns pos-th result of the operation.
MLIR_CAPI_EXPORTED MlirBytecodeWriterConfig mlirBytecodeWriterConfigCreate(void)
Creates new printing flags with defaults, intended for customization.
MLIR_CAPI_EXPORTED MlirContext mlirAttributeGetContext(MlirAttribute attribute)
Gets the context that an attribute was created with.
MLIR_CAPI_EXPORTED MlirBlock mlirBlockArgumentGetOwner(MlirValue value)
Returns the block in which this value is defined as an argument.
static bool mlirRegionIsNull(MlirRegion region)
Checks whether a region is null.
MLIR_CAPI_EXPORTED void mlirOperationDestroy(MlirOperation op)
Takes an operation owned by the caller and destroys it.
MLIR_CAPI_EXPORTED MlirRegion mlirOperationGetRegion(MlirOperation op, intptr_t pos)
Returns pos-th region attached to the operation.
MLIR_CAPI_EXPORTED MlirDialect mlirTypeGetDialect(MlirType type)
Gets the dialect a type belongs to.
MLIR_CAPI_EXPORTED MlirIdentifier mlirIdentifierGet(MlirContext context, MlirStringRef str)
Gets an identifier with the given string value.
MLIR_CAPI_EXPORTED void mlirOperationSetSuccessor(MlirOperation op, intptr_t pos, MlirBlock block)
Set pos-th successor of the operation.
MLIR_CAPI_EXPORTED void mlirContextLoadAllAvailableDialects(MlirContext context)
Eagerly loads all available dialects registered with a context, making them available for use for IR ...
MLIR_CAPI_EXPORTED void mlirOperationStateAddOwnedRegions(MlirOperationState *state, intptr_t n, MlirRegion const *regions)
MLIR_CAPI_EXPORTED void mlirOperationStateAddSuccessors(MlirOperationState *state, intptr_t n, MlirBlock const *successors)
MLIR_CAPI_EXPORTED MlirBlock mlirModuleGetBody(MlirModule module)
Gets the body of the module, i.e. the only block it contains.
MLIR_CAPI_EXPORTED void mlirOpPrintingFlagsDestroy(MlirOpPrintingFlags flags)
Destroys printing flags created with mlirOpPrintingFlagsCreate.
MLIR_CAPI_EXPORTED MlirLocation mlirLocationNameGet(MlirContext context, MlirStringRef name, MlirLocation childLoc)
Creates a name location owned by the given context.
MLIR_CAPI_EXPORTED void mlirContextEnableMultithreading(MlirContext context, bool enable)
Set threading mode (must be set to false to mlir-print-ir-after-all).
MLIR_CAPI_EXPORTED void mlirBlockPrint(MlirBlock block, MlirStringCallback callback, void *userData)
Prints a block by sending chunks of the string representation and forwarding userData tocallback`.
MLIR_CAPI_EXPORTED void mlirBytecodeWriterConfigDesiredEmitVersion(MlirBytecodeWriterConfig flags, int64_t version)
Sets the version to emit in the writer config.
MLIR_CAPI_EXPORTED MlirStringRef mlirSymbolTableGetSymbolAttributeName(void)
Returns the name of the attribute used to store symbol names compatible with symbol tables.
MLIR_CAPI_EXPORTED MlirRegion mlirRegionCreate(void)
Creates a new empty region and transfers ownership to the caller.
MLIR_CAPI_EXPORTED void mlirBlockDetach(MlirBlock block)
Detach a block from the owning region and assume ownership.
MLIR_CAPI_EXPORTED void mlirOperationStateAddResults(MlirOperationState *state, intptr_t n, MlirType const *results)
Adds a list of components to the operation state.
MLIR_CAPI_EXPORTED void mlirOpPrintingFlagsEnableDebugInfo(MlirOpPrintingFlags flags, bool enable, bool prettyForm)
Enable or disable printing of debug information (based on enable).
MLIR_CAPI_EXPORTED MlirLocation mlirOperationGetLocation(MlirOperation op)
Gets the location of the operation.
MLIR_CAPI_EXPORTED MlirTypeID mlirAttributeGetTypeID(MlirAttribute attribute)
Gets the type id of the attribute.
MLIR_CAPI_EXPORTED void mlirOperationSetOperand(MlirOperation op, intptr_t pos, MlirValue newValue)
Sets the pos-th operand of the operation.
MLIR_CAPI_EXPORTED void mlirOperationDump(MlirOperation op)
Prints an operation to stderr.
MLIR_CAPI_EXPORTED intptr_t mlirOpResultGetResultNumber(MlirValue value)
Returns the position of the value in the list of results of the operation that produced it.
MLIR_CAPI_EXPORTED MlirOpPrintingFlags mlirOpPrintingFlagsCreate(void)
Creates new printing flags with defaults, intended for customization.
MLIR_CAPI_EXPORTED MlirAsmState mlirAsmStateCreateForValue(MlirValue value, MlirOpPrintingFlags flags)
Creates new AsmState from value.
MLIR_CAPI_EXPORTED MlirOperation mlirOperationCreate(MlirOperationState *state)
Creates an operation and transfers ownership to the caller.
static bool mlirSymbolTableIsNull(MlirSymbolTable symbolTable)
Returns true if the symbol table is null.
MLIR_CAPI_EXPORTED bool mlirContextGetAllowUnregisteredDialects(MlirContext context)
Returns whether the context allows unregistered dialects.
MLIR_CAPI_EXPORTED void mlirOperationMoveAfter(MlirOperation op, MlirOperation other)
Moves the given operation immediately after the other operation in its parent block.
MLIR_CAPI_EXPORTED intptr_t mlirOperationGetNumAttributes(MlirOperation op)
Returns the number of attributes attached to the operation.
MLIR_CAPI_EXPORTED void mlirValuePrint(MlirValue value, MlirStringCallback callback, void *userData)
Prints a value by sending chunks of the string representation and forwarding userData tocallback`.
MLIR_CAPI_EXPORTED MlirLogicalResult mlirOperationWriteBytecodeWithConfig(MlirOperation op, MlirBytecodeWriterConfig config, MlirStringCallback callback, void *userData)
Same as mlirOperationWriteBytecode but with writer config and returns failure only if desired bytecod...
MLIR_CAPI_EXPORTED void mlirValueSetType(MlirValue value, MlirType type)
Set the type of the value.
MLIR_CAPI_EXPORTED MlirType mlirValueGetType(MlirValue value)
Returns the type of the value.
MLIR_CAPI_EXPORTED void mlirContextDestroy(MlirContext context)
Takes an MLIR context owned by the caller and destroys it.
MLIR_CAPI_EXPORTED MlirOperation mlirOperationCreateParse(MlirContext context, MlirStringRef sourceStr, MlirStringRef sourceName)
Parses an operation, giving ownership to the caller.
MLIR_CAPI_EXPORTED bool mlirAttributeEqual(MlirAttribute a1, MlirAttribute a2)
Checks if two attributes are equal.
static bool mlirOperationIsNull(MlirOperation op)
Checks whether the underlying operation is null.
MLIR_CAPI_EXPORTED MlirBlock mlirRegionGetFirstBlock(MlirRegion region)
Gets the first block in the region.
static MlirStringRef mlirStringRefCreate(const char *str, size_t length)
Constructs a string reference from the pointer and length.
static MlirLogicalResult mlirLogicalResultFailure(void)
Creates a logical result representing a failure.
MLIR_CAPI_EXPORTED size_t mlirTypeIDHashValue(MlirTypeID typeID)
Returns the hash value of the type id.
static MlirLogicalResult mlirLogicalResultSuccess(void)
Creates a logical result representing a success.
static bool mlirLogicalResultIsFailure(MlirLogicalResult res)
Checks if the given logical result represents a failure.
static bool mlirTypeIDIsNull(MlirTypeID typeID)
Checks whether a type id is null.
MLIR_CAPI_EXPORTED bool mlirTypeIDEqual(MlirTypeID typeID1, MlirTypeID typeID2)
Checks if two type ids are equal.
void walk(Operation *op, function_ref< void(Region *)> callback, WalkOrder order)
Walk all of the regions, blocks, or operations nested under (and including) the given operation.
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
llvm::hash_code hash_value(const MPInt &x)
Redeclarations of friend declaration above to make it discoverable by lookups.
PyObjectRef< PyMlirContext > PyMlirContextRef
Wrapper around MlirContext.
PyObjectRef< PyModule > PyModuleRef
void populateIRCore(pybind11::module &m)
PyObjectRef< PyOperation > PyOperationRef
QueryRef parse(llvm::StringRef line, const QuerySession &qs)
Include the generated interface declarations.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
LogicalResult verify(Operation *op, bool verifyRecursively=true)
Perform (potentially expensive) checks of invariants, used to detect compiler bugs,...
An opaque reference to a diagnostic, always owned by the diagnostics engine (context).
A logical result value, essentially a boolean with named states.
An auxiliary class for constructing operations.
A pointer to a sized fragment of a string, not necessarily null-terminated.
const char * data
Pointer to the first symbol.
size_t length
Length of the fragment.
static bool dunderContains(const std::string &attributeKind)
static void dundeSetItemNamed(const std::string &attributeKind, py::function func, bool replace)
static py::function dundeGetItemNamed(const std::string &attributeKind)
static void bind(py::module &m)
Wrapper for the global LLVM debugging flag.
static void bind(py::module &m)
static bool get(const py::object &)
static void set(py::object &o, bool enable)
Accumulates into a python string from a method that accepts an MlirStringCallback.
MlirStringCallback getCallback()
Custom exception that allows access to error diagnostic information.
std::vector< PyDiagnostic::DiagnosticInfo > errorDiagnostics
Materialized diagnostic information.
RAII object that captures any error diagnostics emitted to the provided context.
std::vector< PyDiagnostic::DiagnosticInfo > take()
ErrorCapture(PyMlirContextRef ctx)