MLIR 24.0.0git
IRCore.h
Go to the documentation of this file.
1//===- IRCore.h - IR helpers of python bindings ---------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef MLIR_BINDINGS_PYTHON_IRCORE_H
10#define MLIR_BINDINGS_PYTHON_IRCORE_H
11
12#include <cstddef>
13#include <exception>
14#include <optional>
15#include <sstream>
16#include <utility>
17#include <vector>
18
19#include "Globals.h"
20#include "NanobindUtils.h"
21#include "mlir-c/AffineExpr.h"
22#include "mlir-c/AffineMap.h"
24#include "mlir-c/Debug.h"
25#include "mlir-c/Diagnostics.h"
27#include "mlir-c/IR.h"
28#include "mlir-c/IntegerSet.h"
29#include "mlir-c/Remarks.h"
30#include "mlir-c/Support.h"
31#include "mlir-c/Transforms.h"
34
35namespace mlir {
36namespace python {
38
39class PyBlock;
40class PyDiagnostic;
43class PyLocation;
45class PyMlirContext;
47class PyModule;
48class PyOperation;
49class PyOperationBase;
50class PyType;
51class PySymbolTable;
52class PyValue;
53
54/// Wrapper for the global LLVM debugging flag.
56 static void set(nanobind::object &o, bool enable);
57 static bool get(const nanobind::object &);
58 static void bind(nanobind::module_ &m);
59
60private:
61 static nanobind::ft_mutex mutex;
62};
63
64/// Template for a reference to a concrete type which captures a python
65/// reference to its underlying python object.
66template <typename T>
68public:
69 PyObjectRef(T *referrent, nanobind::object object)
70 : referrent(referrent), object(std::move(object)) {
71 assert(this->referrent &&
72 "cannot construct PyObjectRef with null referrent");
73 assert(this->object && "cannot construct PyObjectRef with null object");
74 }
75 PyObjectRef(PyObjectRef &&other) noexcept
76 : referrent(other.referrent), object(std::move(other.object)) {
77 other.referrent = nullptr;
78 assert(!other.object);
79 }
81 : referrent(other.referrent), object(other.object /* copies */) {}
83 referrent = other.referrent;
84 object = other.object;
85 return *this;
86 }
87 PyObjectRef &operator=(PyObjectRef &&other) noexcept {
88 referrent = other.referrent;
89 object = std::move(other.object);
90 other.referrent = nullptr;
91 assert(!other.object);
92 return *this;
93 }
94 ~PyObjectRef() = default;
95
97 if (!object)
98 return 0;
99 return Py_REFCNT(object.ptr());
100 }
101
102 /// Releases the object held by this instance, returning it.
103 /// This is the proper thing to return from a function that wants to return
104 /// the reference. Note that this does not work from initializers.
105 nanobind::object releaseObject() {
106 assert(referrent && object);
107 referrent = nullptr;
108 auto stolen = std::move(object);
109 return stolen;
110 }
111
112 T *get() { return referrent; }
114 assert(referrent && object);
115 return referrent;
116 }
117 nanobind::object getObject() {
118 assert(referrent && object);
119 return object;
120 }
121 operator bool() const { return referrent && object; }
122
123 using NBTypedT = nanobind::typed<nanobind::object, T>;
124
125private:
126 T *referrent;
127 nanobind::object object;
128};
129
130/// Tracks an entry in the thread context stack. New entries are pushed onto
131/// here for each with block that activates a new InsertionPoint, Context or
132/// Location.
133///
134/// Pushing either a Location or InsertionPoint also pushes its associated
135/// Context. Pushing a Context will not modify the Location or InsertionPoint
136/// unless if they are from a different context, in which case, they are
137/// cleared.
139public:
145
146 PyThreadContextEntry(FrameKind frameKind, nanobind::object context,
147 nanobind::object insertionPoint,
148 nanobind::object location)
149 : context(std::move(context)), insertionPoint(std::move(insertionPoint)),
150 location(std::move(location)), frameKind(frameKind) {}
151
152 /// Gets the top of stack context and return nullptr if not defined.
154
155 /// Gets the top of stack insertion point and return nullptr if not defined.
156 static PyInsertionPoint *getDefaultInsertionPoint();
157
158 /// Gets the top of stack location and returns nullptr if not defined.
159 static PyLocation *getDefaultLocation();
160
162 PyInsertionPoint *getInsertionPoint();
163 PyLocation *getLocation();
164 FrameKind getFrameKind() { return frameKind; }
165
166 /// Stack management.
167 static PyThreadContextEntry *getTopOfStack();
168 static nanobind::object pushContext(nanobind::object context);
169 static void popContext(PyMlirContext &context);
170 static nanobind::object pushInsertionPoint(nanobind::object insertionPoint);
171 static void popInsertionPoint(PyInsertionPoint &insertionPoint);
172 static nanobind::object pushLocation(nanobind::object location);
173 static void popLocation(PyLocation &location);
174
175 /// Gets the thread local stack.
176 static std::vector<PyThreadContextEntry> &getStack();
177
178private:
179 static void push(FrameKind frameKind, nanobind::object context,
180 nanobind::object insertionPoint, nanobind::object location);
181
182 /// An object reference to the PyContext.
183 nanobind::object context;
184 /// An object reference to the current insertion point.
185 nanobind::object insertionPoint;
186 /// An object reference to the current location.
187 nanobind::object location;
188 // The kind of push that was performed.
189 FrameKind frameKind;
190};
191
192/// Wrapper around MlirLlvmThreadPool
193/// Python object owns the C++ thread pool
195public:
196 PyThreadPool();
198 PyThreadPool(const PyThreadPool &) = delete;
200
201 int getMaxConcurrency() const;
202 MlirLlvmThreadPool get() { return threadPool; }
203
204 std::string _mlir_thread_pool_ptr() const;
205
206private:
207 MlirLlvmThreadPool threadPool;
208};
209
210/// The kinds, emitting policies and file formats of the remark engine
211/// (mlir-c/Remarks.h).
219
220enum class PyRemarkPolicy : std::underlying_type_t<MlirRemarkPolicy> {
223};
224
225enum class PyRemarkFormat : std::underlying_type_t<MlirRemarkFileFormat> {
228};
229
230/// Wrapper around MlirContext.
233public:
234 PyMlirContext() = delete;
235 PyMlirContext(MlirContext context);
236 PyMlirContext(const PyMlirContext &) = delete;
238
239 /// Returns a context reference for the singleton PyMlirContext wrapper for
240 /// the given context.
241 static PyMlirContextRef forContext(MlirContext context);
243
244 /// Accesses the underlying MlirContext.
245 MlirContext get() { return context; }
246
247 /// Gets a strong reference to this context, which will ensure it is kept
248 /// alive for the life of the reference.
249 PyMlirContextRef getRef();
250
251 /// Gets a capsule wrapping the void* within the MlirContext.
252 nanobind::object getCapsule();
253
254 /// Creates a PyMlirContext from the MlirContext wrapped by a capsule.
255 /// Note that PyMlirContext instances are uniqued, so the returned object
256 /// may be a pre-existing object. Ownership of the underlying MlirContext
257 /// is taken by calling this function.
258 static nanobind::object createFromCapsule(nanobind::object capsule);
259
260 /// Gets the count of live context objects. Used for testing.
261 static size_t getLiveCount();
262
263 /// Gets the count of live modules associated with this context.
264 /// Used for testing.
265 size_t getLiveModuleCount();
266
267 /// Enter and exit the context manager.
268 static nanobind::object contextEnter(nanobind::object context);
269 void contextExit(const nanobind::object &excType,
270 const nanobind::object &excVal,
271 const nanobind::object &excTb);
272
273 /// Attaches a Python callback as a diagnostic handler, returning a
274 /// registration object (internally a PyDiagnosticHandler).
275 nanobind::object attachDiagnosticHandler(nanobind::object callback);
276
277 /// Enables the optimization remark engine of the context, streaming to
278 /// `outputFile`, to `callback`, or (without either) to MLIR remark
279 /// diagnostics. Raises ValueError on an invalid combination, when an engine
280 /// is already enabled or when the file cannot be written.
281 void enableRemarks(PyRemarkPolicy policy,
282 const std::optional<std::string> &outputFile,
283 PyRemarkFormat format, const std::string &allFilter,
284 const std::string &passedFilter,
285 const std::string &missedFilter,
286 const std::string &analysisFilter,
287 const std::string &failedFilter, nanobind::object callback,
288 std::optional<bool> printAsEmitRemarks);
289 /// Finalizes and removes the remark engine; no-op when none is enabled.
290 void finalizeRemarks();
291 /// Whether a remark engine is enabled on the context.
292 bool getRemarksEnabled();
293 /// Whether `context` still has a live Python wrapper (false while it is
294 /// being destroyed).
295 static bool isLiveContext(MlirContext context);
296
297 /// Controls whether error diagnostics should be propagated to diagnostic
298 /// handlers, instead of being captured by `ErrorCapture`.
299 void setEmitErrorDiagnostics(bool value) { emitErrorDiagnostics = value; }
300 bool getEmitErrorDiagnostics() { return emitErrorDiagnostics; }
301 struct ErrorCapture;
302
303private:
304 // Interns the mapping of live MlirContext::ptr to PyMlirContext instances,
305 // preserving the relationship that an MlirContext maps to a single
306 // PyMlirContext wrapper. This could be replaced in the future with an
307 // extension mechanism on the MlirContext for stashing user pointers.
308 // Note that this holds a handle, which does not imply ownership.
309 // Mappings will be removed when the context is destructed.
310 using LiveContextMap = std::unordered_map<void *, PyMlirContext *>;
311 static nanobind::ft_mutex live_contexts_mutex;
312 static LiveContextMap &getLiveContexts();
313
314 // Interns all live modules associated with this context. Modules tracked
315 // in this map are valid. When a module is invalidated, it is removed
316 // from this map, and while it still exists as an instance, any
317 // attempt to access it will raise an error.
318 using LiveModuleMap =
319 std::unordered_map<const void *, std::pair<nanobind::handle, PyModule *>>;
320 LiveModuleMap liveModules;
321
322 bool emitErrorDiagnostics = false;
323
324 MlirContext context;
325 friend class PyModule;
326 friend class PyOperation;
327};
328
329/// Used in function arguments when None should resolve to the current context
330/// manager set instance.
332 : public Defaulting<DefaultingPyMlirContext, PyMlirContext> {
333public:
335 static constexpr const char kTypeDescription[] = "_mlir.ir.Context";
336 static PyMlirContext &resolve();
337};
338
339/// Base class for all objects that directly or indirectly depend on an
340/// MlirContext. The lifetime of the context will extend at least to the
341/// lifetime of these instances.
342/// Immutable objects that depend on a context extend this directly.
344public:
345 BaseContextObject(PyMlirContextRef ref) : contextRef(std::move(ref)) {
346 assert(this->contextRef &&
347 "context object constructed with null context ref");
348 }
349
350 /// Accesses the context reference.
351 PyMlirContextRef &getContext() { return contextRef; }
352
353private:
354 PyMlirContextRef contextRef;
355};
356
357/// Wrapper around an MlirLocation.
359public:
360 PyLocation(PyMlirContextRef contextRef, MlirLocation loc)
361 : BaseContextObject(std::move(contextRef)), loc(loc) {}
362
363 operator MlirLocation() const { return loc; }
364 MlirLocation get() const { return loc; }
365
366 /// Enter and exit the context manager.
367 static nanobind::object contextEnter(nanobind::object location);
368 void contextExit(const nanobind::object &excType,
369 const nanobind::object &excVal,
370 const nanobind::object &excTb);
371
372 /// Gets a capsule wrapping the void* within the MlirLocation.
373 nanobind::object getCapsule();
374
375 /// Creates a PyLocation from the MlirLocation wrapped by a capsule.
376 /// Note that PyLocation instances are uniqued, so the returned object
377 /// may be a pre-existing object. Ownership of the underlying MlirLocation
378 /// is taken by calling this function.
379 static PyLocation createFromCapsule(nanobind::object capsule);
380
381 /// Returns the most-derived Location subclass registered for this TypeID,
382 /// or self.
383 nanobind::typed<nanobind::object, PyLocation> maybeDownCast();
384
385private:
386 MlirLocation loc;
387};
388
396
397enum class PyWalkResult : std::underlying_type_t<MlirWalkResult> {
401};
402
403/// Traversal order for operation walk.
404enum class PyWalkOrder : std::underlying_type_t<MlirWalkOrder> {
407};
408
409/// Flags controlling structural operation equivalence and hashing.
410enum class PyOperationEquivalenceFlags : std::underlying_type_t<
411 MlirOperationEquivalenceFlags> {
412 None = MLIR_OPERATION_EQUIVALENCE_NONE,
413 IgnoreLocations = MLIR_OPERATION_EQUIVALENCE_IGNORE_LOCATIONS,
414 IgnoreDiscardableAttrs = MLIR_OPERATION_EQUIVALENCE_IGNORE_DISCARDABLE_ATTRS,
415 IgnoreProperties = MLIR_OPERATION_EQUIVALENCE_IGNORE_PROPERTIES,
416 IgnoreCommutativity = MLIR_OPERATION_EQUIVALENCE_IGNORE_COMMUTATIVITY
417};
418
419/// Python class mirroring the C MlirDiagnostic struct. Note that these structs
420/// are only valid for the duration of a diagnostic callback and attempting
421/// to access them outside of that will raise an exception. This applies to
422/// nested diagnostics (in the notes) as well.
424public:
425 PyDiagnostic(MlirDiagnostic diagnostic) : diagnostic(diagnostic) {}
426 void invalidate();
427 bool isValid() { return valid; }
428 PyDiagnosticSeverity getSeverity();
429 nanobind::typed<nanobind::object, PyLocation> getLocation();
430 nanobind::str getMessage();
431 nanobind::typed<nanobind::tuple, PyDiagnostic> getNotes();
432
433 /// Materialized diagnostic information. This is safe to access outside the
434 /// diagnostic callback.
438 std::string message;
439 std::vector<DiagnosticInfo> notes;
440 };
442
443private:
444 MlirDiagnostic diagnostic;
445
446 void checkValid();
447 /// If notes have been materialized from the diagnostic, then this will
448 /// be populated with the corresponding objects (all castable to
449 /// PyDiagnostic).
450 std::optional<nanobind::tuple> materializedNotes;
451 bool valid = true;
452};
453
454/// Wrapper around an MlirRemark as delivered to a remark callback. Like a
455/// PyDiagnostic it is only valid for the duration of the callback; accessing
456/// an invalidated remark raises ValueError.
458public:
459 explicit PyRemark(MlirRemark remark) : remark(remark) {}
460 void invalidate() { valid = false; }
461 bool isValid() const { return valid; }
462 PyRemarkKind getKind() const;
463 nanobind::str getRemarkName() const;
464 nanobind::str getCategoryName() const;
465 nanobind::str getFullCategoryName() const;
466 nanobind::str getFunctionName() const;
467 nanobind::typed<nanobind::object, PyLocation> getLocation() const;
468 uint64_t getId() const;
469 nanobind::list getRelatedIds() const;
470 /// The key/value arguments as a list of `(key, value)` tuples.
471 nanobind::list getArgs() const;
472 /// The textual form of the remark, without its location.
473 nanobind::str getMessage() const;
474
475private:
476 void checkValid() const;
478 bool valid = true;
479};
480
481/// Represents a diagnostic handler attached to the context. The handler's
482/// callback will be invoked with PyDiagnostic instances until the detach()
483/// method is called or the context is destroyed. A diagnostic handler can be
484/// the subject of a `with` block, which will detach it when the block exits.
485///
486/// Since diagnostic handlers can call back into Python code which can do
487/// unsafe things (i.e. recursively emitting diagnostics, raising exceptions,
488/// etc), this is generally not deemed to be a great user-level API. Users
489/// should generally use some form of DiagnosticCollector. If the handler raises
490/// any exceptions, they will just be emitted to stderr and dropped.
491///
492/// The unique usage of this class means that its lifetime management is
493/// different from most other parts of the API. Instances are always created
494/// in an attached state and can transition to a detached state by either:
495/// a) The context being destroyed and unregistering all handlers.
496/// b) An explicit call to detach().
497/// The object may remain live from a Python perspective for an arbitrary time
498/// after detachment, but there is nothing the user can do with it (since there
499/// is no way to attach an existing handler object).
501public:
502 PyDiagnosticHandler(MlirContext context, nanobind::object callback);
504
505 bool isAttached() { return registeredID.has_value(); }
506 bool getHadError() { return hadError; }
507
508 /// Detaches the handler. Does nothing if not attached.
509 void detach();
510
511 nanobind::object contextEnter() { return nanobind::cast(this); }
512 void contextExit(const nanobind::object &excType,
513 const nanobind::object &excVal,
514 const nanobind::object &excTb) {
515 detach();
516 }
517
518private:
519 MlirContext context;
520 nanobind::object callback;
521 std::optional<MlirDiagnosticHandlerID> registeredID;
522 bool hadError = false;
523 friend class PyMlirContext;
524};
525
526/// RAII object that captures any error diagnostics emitted to the provided
527/// context.
530 : ctx(ctx), handlerID(mlirContextAttachDiagnosticHandler(
531 ctx->get(), handler, /*userData=*/this,
532 /*deleteUserData=*/nullptr)) {}
534 mlirContextDetachDiagnosticHandler(ctx->get(), handlerID);
535 assert(errors.empty() && "unhandled captured errors");
536 }
537
538 std::vector<PyDiagnostic::DiagnosticInfo> take() {
539 return std::move(errors);
540 };
541
542private:
544 MlirDiagnosticHandlerID handlerID;
545 std::vector<PyDiagnostic::DiagnosticInfo> errors;
546
547 static MlirLogicalResult handler(MlirDiagnostic diag, void *userData);
548};
549
550/// Wrapper around an MlirDialect. This is exported as `DialectDescriptor` in
551/// order to differentiate it from the `Dialect` base class which is extended by
552/// plugins which extend dialect functionality through extension python code.
553/// This should be seen as the "low-level" object and `Dialect` as the
554/// high-level, user facing object.
556public:
557 PyDialectDescriptor(PyMlirContextRef contextRef, MlirDialect dialect)
558 : BaseContextObject(std::move(contextRef)), dialect(dialect) {}
559
560 MlirDialect get() { return dialect; }
561
562private:
563 MlirDialect dialect;
564};
565
566/// User-level object for accessing dialects with dotted syntax such as:
567/// ctx.dialect.std
569public:
571 : BaseContextObject(std::move(contextRef)) {}
572
573 MlirDialect getDialectForKey(const std::string &key, bool attrError);
574};
575
576/// User-level dialect object. For dialects that have a registered extension,
577/// this will be the base class of the extension dialect type. For un-extended,
578/// objects of this type will be returned directly.
580public:
581 PyDialect(nanobind::object descriptor) : descriptor(std::move(descriptor)) {}
582
583 nanobind::object getDescriptor() { return descriptor; }
584
585private:
586 nanobind::object descriptor;
587};
588
589/// Wrapper around an MlirDialectRegistry.
590/// Upon construction, the Python wrapper takes ownership of the
591/// underlying MlirDialectRegistry.
593public:
595 PyDialectRegistry(MlirDialectRegistry registry) : registry(registry) {}
597 if (!mlirDialectRegistryIsNull(registry))
599 }
602 : registry(other.registry) {
603 other.registry = {nullptr};
604 }
605
606 operator MlirDialectRegistry() const { return registry; }
607 MlirDialectRegistry get() const { return registry; }
608
609 nanobind::object getCapsule();
610 static PyDialectRegistry createFromCapsule(nanobind::object capsule);
611
612private:
613 MlirDialectRegistry registry;
614};
615
616/// Used in function arguments when None should resolve to the current context
617/// manager set instance.
619 : public Defaulting<DefaultingPyLocation, PyLocation> {
620public:
622 static constexpr const char kTypeDescription[] = "_mlir.ir.Location";
623 static PyLocation &resolve();
624
625 operator MlirLocation() const { return *get(); }
626};
627
628/// Wrapper around MlirModule.
629/// This is the top-level, user-owned object that contains regions/ops/blocks.
630class PyModule;
633public:
634 /// Returns a PyModule reference for the given MlirModule. This always returns
635 /// a new object.
636 static PyModuleRef forModule(MlirModule module);
637 PyModule(PyModule &) = delete;
639 ~PyModule();
640
641 /// Gets the backing MlirModule.
642 MlirModule get() { return module; }
643
644 /// Gets a strong reference to this module.
646 return PyModuleRef(this, nanobind::borrow<nanobind::object>(handle));
647 }
648
649 /// Gets a capsule wrapping the void* within the MlirModule.
650 /// Note that the module does not (yet) provide a corresponding factory for
651 /// constructing from a capsule as that would require uniquing PyModule
652 /// instances, which is not currently done.
653 nanobind::object getCapsule();
654
655 /// Creates a PyModule from the MlirModule wrapped by a capsule.
656 /// Note this returns a new object BUT clearMlirModule() must be called to
657 /// prevent double-frees (of the underlying mlir::Module).
658 static nanobind::object createFromCapsule(nanobind::object capsule);
659
660 void clearMlirModule() { module = {nullptr}; }
661
662private:
663 PyModule(PyMlirContextRef contextRef, MlirModule module);
664 MlirModule module;
665 nanobind::handle handle;
666};
667
668class PyAsmState;
669
670/// Base class for PyOperation and PyOpView which exposes the primary, user
671/// visible methods for manipulating it.
673public:
674 virtual ~PyOperationBase() = default;
675 /// Implements the bound 'print' method and helps with others.
676 void print(std::optional<int64_t> largeElementsLimit,
677 std::optional<int64_t> largeResourceLimit, bool enableDebugInfo,
678 bool prettyDebugInfo, bool printGenericOpForm, bool useLocalScope,
679 bool useNameLocAsPrefix, bool assumeVerified,
680 nanobind::object fileObject, bool binary, bool skipRegions);
681 void print(PyAsmState &state, nanobind::object fileObject, bool binary);
682
683 nanobind::object
684 getAsm(bool binary, std::optional<int64_t> largeElementsLimit,
685 std::optional<int64_t> largeResourceLimit, bool enableDebugInfo,
686 bool prettyDebugInfo, bool printGenericOpForm, bool useLocalScope,
687 bool useNameLocAsPrefix, bool assumeVerified, bool skipRegions);
688
689 // Implement the bound 'writeBytecode' method.
690 void writeBytecode(const nanobind::object &fileObject,
691 std::optional<int64_t> bytecodeVersion);
692
693 // Implement the walk method.
694 void walk(std::function<PyWalkResult(MlirOperation)> callback,
695 PyWalkOrder walkOrder);
696
697 /// Moves the operation before or after the other operation.
698 void moveAfter(PyOperationBase &other);
699 void moveBefore(PyOperationBase &other);
700
701 /// Given an operation 'other' that is within the same parent block, return
702 /// whether the current operation is before 'other' in the operation list
703 /// of the parent block.
704 /// Note: This function has an average complexity of O(1), but worst case may
705 /// take O(N) where N is the number of operations within the parent block.
706 bool isBeforeInBlock(PyOperationBase &other);
707
708 /// Return whether the current operation is an ancestor of 'other', i.e.,
709 /// whether it contains 'other' or is the same operation.
710 bool isAncestor(PyOperationBase &other);
711
712 /// Return whether the current operation is a proper ancestor of 'other',
713 /// i.e., whether it contains 'other' and is not the same operation.
715
716 /// Verify the operation. Throws `MLIRError` if verification fails, and
717 /// returns `true` otherwise.
718 bool verify();
719
720 /// Each must provide access to the raw Operation.
721 virtual PyOperation &getOperation() = 0;
722};
723
724/// Wrapper around PyOperation.
725/// Operations exist in either an attached (dependent) or detached (top-level)
726/// state. In the detached state (as on creation), an operation is owned by
727/// the creator and its lifetime extends either until its reference count
728/// drops to zero or it is attached to a parent, at which point its lifetime
729/// is bounded by its top-level parent reference.
730class PyOperation;
731class PyOpView;
734 public BaseContextObject {
735public:
736 ~PyOperation() override;
737 PyOperation &getOperation() override { return *this; }
738
739 /// Returns a PyOperation for the given MlirOperation, optionally associating
740 /// it with a parentKeepAlive.
741 static PyOperationRef
742 forOperation(PyMlirContextRef contextRef, MlirOperation operation,
743 nanobind::object parentKeepAlive = nanobind::object());
744
745 /// Creates a detached operation. The operation must not be associated with
746 /// any existing live operation.
747 static PyOperationRef
748 createDetached(PyMlirContextRef contextRef, MlirOperation operation,
749 nanobind::object parentKeepAlive = nanobind::object());
750
751 /// Parses a source string (either text assembly or bytecode), creating a
752 /// detached operation.
753 static PyOperationRef parse(PyMlirContextRef contextRef,
754 const std::string &sourceStr,
755 const std::string &sourceName);
756
757 /// Detaches the operation from its parent block and updates its state
758 /// accordingly.
759 void detachFromParent();
760
761 /// Gets the backing operation.
762 operator MlirOperation() const { return get(); }
763 MlirOperation get() const;
764
765 PyOperationRef getRef();
766
767 bool isAttached() { return attached; }
768 void setAttached(const nanobind::object &parent = nanobind::object());
769 void setDetached();
770 void checkValid() const;
771
772 /// Gets the owning block or raises an exception if the operation has no
773 /// owning block.
774 PyBlock getBlock();
775
776 /// Gets the parent operation or raises an exception if the operation has
777 /// no parent.
778 std::optional<PyOperationRef> getParentOperation();
779
780 /// Gets a capsule wrapping the void* within the MlirOperation.
781 nanobind::object getCapsule();
782
783 /// Creates a PyOperation from the MlirOperation wrapped by a capsule.
784 /// Ownership of the underlying MlirOperation is taken by calling this
785 /// function.
786 static nanobind::object createFromCapsule(const nanobind::object &capsule);
787
788 /// Creates an operation. See corresponding python docstring.
789 static nanobind::object
790 create(std::string_view name, std::optional<std::vector<PyType *>> results,
791 const MlirValue *operands, size_t numOperands,
792 std::optional<nanobind::dict> attributes,
793 std::optional<std::vector<PyBlock *>> successors, int regions,
794 PyLocation &location, const nanobind::object &ip, bool inferType);
795
796 /// Creates an OpView suitable for this operation.
797 nanobind::object createOpView();
798
799 /// Erases the underlying MlirOperation, removes its pointer from the
800 /// parent context's live operations map, and sets the valid bit false.
801 void erase();
802
803 /// Invalidate the operation.
804 void setInvalid() { valid = false; }
805
806 /// Clones this operation.
807 nanobind::object clone(const nanobind::object &ip);
808
809 PyOperation(PyMlirContextRef contextRef, MlirOperation operation);
810
811private:
812 static PyOperationRef createInstance(PyMlirContextRef contextRef,
813 MlirOperation operation,
814 nanobind::object parentKeepAlive);
815
816 MlirOperation operation;
817 nanobind::handle handle;
818 // Keeps the parent alive, regardless of whether it is an Operation or
819 // Module.
820 // TODO: As implemented, this facility is only sufficient for modeling the
821 // trivial module parent back-reference. Generalize this to also account for
822 // transitions from detached to attached and address TODOs in the
823 // ir_operation.py regarding testing corresponding lifetime guarantees.
824 nanobind::object parentKeepAlive;
825 bool attached = true;
826 bool valid = true;
827
828 friend class PyOperationBase;
829 friend class PySymbolTable;
830};
831
832/// A PyOpView is equivalent to the C++ "Op" wrappers: these are the basis for
833/// providing more instance-specific accessors and serve as the base class for
834/// custom ODS-style operation classes. Since this class is subclass on the
835/// python side, it must present an __init__ method that operates in pure
836/// python types.
838public:
839 PyOpView(const nanobind::object &operationObject);
840 PyOperation &getOperation() override { return operation; }
841
842 nanobind::object getOperationObject() { return operationObject; }
843
844 static nanobind::typed<nanobind::object, PyOperation>
845 buildGeneric(std::string_view name, std::tuple<int, bool> opRegionSpec,
846 nanobind::object operandSegmentSpecObj,
847 nanobind::object resultSegmentSpecObj,
848 std::optional<nanobind::sequence> resultTypeList,
849 nanobind::sequence operandList,
850 std::optional<nanobind::dict> attributes,
851 std::optional<std::vector<PyBlock *>> successors,
852 std::optional<int> regions, PyLocation &location,
853 const nanobind::object &maybeIp);
854
855 /// Construct an instance of a class deriving from OpView, bypassing its
856 /// `__init__` method. The derived class will typically define a constructor
857 /// that provides a convenient builder, but we need to side-step this when
858 /// constructing an `OpView` for an already-built operation.
859 ///
860 /// The caller is responsible for verifying that `operation` is a valid
861 /// operation to construct `cls` with.
862 static nanobind::object constructDerived(const nanobind::object &cls,
863 const nanobind::object &operation);
864
865private:
866 PyOperation &operation; // For efficient, cast-free access from C++
867 nanobind::object operationObject; // Holds the reference.
868};
869
870/// Wrapper around an MlirRegion.
871/// Regions are managed completely by their containing operation. Unlike the
872/// C++ API, the python API does not support detached regions.
874public:
875 PyRegion(PyOperationRef parentOperation, MlirRegion region)
876 : parentOperation(std::move(parentOperation)), region(region) {
877 assert(!mlirRegionIsNull(region) && "python region cannot be null");
878 }
879 operator MlirRegion() const { return region; }
880
881 MlirRegion get() { return region; }
882 PyOperationRef &getParentOperation() { return parentOperation; }
883
884 void checkValid() { return parentOperation->checkValid(); }
885
886private:
887 PyOperationRef parentOperation;
888 MlirRegion region;
889};
890
891/// Wrapper around an MlirAsmState.
893public:
894 PyAsmState(MlirValue value, bool useLocalScope);
895 PyAsmState(PyOperationBase &operation, bool useLocalScope);
897 // Delete copy constructors.
898 PyAsmState(PyAsmState &other) = delete;
899 PyAsmState(const PyAsmState &other) = delete;
900
901 MlirAsmState get() { return state; }
902
903private:
904 MlirAsmState state;
905 MlirOpPrintingFlags flags;
906};
907
908/// Wrapper around an MlirBlock.
909/// Blocks are managed completely by their containing operation. Unlike the
910/// C++ API, the python API does not support detached blocks.
912public:
913 PyBlock(PyOperationRef parentOperation, MlirBlock block)
914 : parentOperation(std::move(parentOperation)), block(block) {
915 assert(!mlirBlockIsNull(block) && "python block cannot be null");
916 }
917
918 MlirBlock get() { return block; }
919 PyOperationRef &getParentOperation() { return parentOperation; }
920
921 void checkValid() { return parentOperation->checkValid(); }
922
923 /// Gets a capsule wrapping the void* within the MlirBlock.
924 nanobind::object getCapsule();
925
926private:
927 PyOperationRef parentOperation;
928 MlirBlock block;
929};
930
931/// An insertion point maintains a pointer to a Block and a reference operation.
932/// Calls to insert() will insert a new operation before the
933/// reference operation. If the reference operation is null, then appends to
934/// the end of the block.
936public:
937 /// Creates an insertion point positioned after the last operation in the
938 /// block, but still inside the block.
939 PyInsertionPoint(const PyBlock &block);
940 /// Creates an insertion point positioned before a reference operation.
941 PyInsertionPoint(PyOperationBase &beforeOperationBase);
942 /// Creates an insertion point positioned before a reference operation.
943 PyInsertionPoint(PyOperationRef beforeOperationRef);
944
945 /// Shortcut to create an insertion point at the beginning of the block.
947 /// Shortcut to create an insertion point before the block terminator.
949 /// Shortcut to create an insertion point to the node after the specified
950 /// operation.
952
953 /// Inserts an operation.
954 void insert(PyOperationBase &operationBase);
955
956 /// Enter and exit the context manager.
957 static nanobind::object contextEnter(nanobind::object insertionPoint);
958 void contextExit(const nanobind::object &excType,
959 const nanobind::object &excVal,
960 const nanobind::object &excTb);
961
962 PyBlock &getBlock() { return block; }
963 std::optional<PyOperationRef> &getRefOperation() { return refOperation; }
964
965private:
966 // Trampoline constructor that avoids null initializing members while
967 // looking up parents.
968 PyInsertionPoint(PyBlock block, std::optional<PyOperationRef> refOperation)
969 : refOperation(std::move(refOperation)), block(std::move(block)) {}
970
971 std::optional<PyOperationRef> refOperation;
972 PyBlock block;
973};
974
975/// Wrapper around the generic MlirType.
976/// The lifetime of a type is bound by the PyContext that created it.
978public:
979 PyType(PyMlirContextRef contextRef, MlirType type)
980 : BaseContextObject(std::move(contextRef)), type(type) {}
981 bool operator==(const PyType &other) const;
982 operator MlirType() const { return type; }
983 MlirType get() const { return type; }
984
985 /// Gets a capsule wrapping the void* within the MlirType.
986 nanobind::object getCapsule();
987
988 /// Creates a PyType from the MlirType wrapped by a capsule.
989 /// Note that PyType instances are uniqued, so the returned object
990 /// may be a pre-existing object. Ownership of the underlying MlirType
991 /// is taken by calling this function.
992 static PyType createFromCapsule(nanobind::object capsule);
993
994 nanobind::typed<nanobind::object, PyType> maybeDownCast();
995
996private:
997 MlirType type;
998};
999
1000/// A TypeID provides an efficient and unique identifier for a specific C++
1001/// type. This allows for a C++ type to be compared, hashed, and stored in an
1002/// opaque context. This class wraps around the generic MlirTypeID.
1004public:
1005 PyTypeID(MlirTypeID typeID) : typeID(typeID) {}
1006 // Note, this tests whether the underlying TypeIDs are the same,
1007 // not whether the wrapper MlirTypeIDs are the same, nor whether
1008 // the PyTypeID objects are the same (i.e., PyTypeID is a value type).
1009 bool operator==(const PyTypeID &other) const;
1010 operator MlirTypeID() const { return typeID; }
1011 MlirTypeID get() { return typeID; }
1012
1013 /// Gets a capsule wrapping the void* within the MlirTypeID.
1014 nanobind::object getCapsule();
1015
1016 /// Creates a PyTypeID from the MlirTypeID wrapped by a capsule.
1017 static PyTypeID createFromCapsule(nanobind::object capsule);
1018
1019private:
1020 MlirTypeID typeID;
1021};
1022
1023/// CRTP base classes for Python types that subclass Type and should be
1024/// castable from it (i.e. via something like IntegerType(t)).
1025/// By default, type class hierarchies are one level deep (i.e. a
1026/// concrete type class extends PyType); however, intermediate python-visible
1027/// base classes can be modeled by specifying a BaseTy.
1028template <typename DerivedTy, typename BaseTy = PyType>
1030public:
1031 // Derived classes must define statics for:
1032 // IsAFunctionTy isaFunction
1033 // const char *pyClassName
1034 using ClassTy = nanobind::class_<DerivedTy, BaseTy>;
1035 using IsAFunctionTy = bool (*)(MlirType);
1036 using GetTypeIDFunctionTy = MlirTypeID (*)();
1038 static constexpr GetTypeIDFunctionTy getTypeIdFunction = nullptr;
1039 static inline const MlirStringRef name{};
1040
1041 PyConcreteType() = default;
1042 PyConcreteType(PyMlirContextRef contextRef, MlirType t)
1043 : BaseTy(std::move(contextRef), t) {}
1045 : PyConcreteType(orig.getContext(), castFrom(orig)) {}
1046
1047 static MlirType castFrom(PyType &orig) {
1048 if (!DerivedTy::isaFunction(orig)) {
1049 auto origRepr =
1050 nanobind::cast<std::string>(nanobind::repr(nanobind::cast(orig)));
1051 throw nanobind::value_error((std::string("Cannot cast type to ") +
1052 DerivedTy::pyClassName + " (from " +
1053 origRepr + ")")
1054 .c_str());
1055 }
1056 return orig;
1057 }
1058
1059 static void bind(nanobind::module_ &m) {
1060 auto cls = ClassTy(m, DerivedTy::pyClassName, nanobind::is_generic());
1061 cls.def(nanobind::init<PyType &>(), nanobind::keep_alive<0, 1>(),
1062 nanobind::arg("cast_from_type"));
1063 cls.def_prop_ro_static("static_typeid", [](nanobind::object & /*class*/) {
1064 if (DerivedTy::getTypeIdFunction)
1065 return PyTypeID(DerivedTy::getTypeIdFunction());
1066 throw nanobind::attribute_error(
1067 (DerivedTy::pyClassName + std::string(" has no typeid.")).c_str());
1068 });
1069 cls.def_prop_ro("typeid", [](PyType &self) {
1070 return nanobind::cast<PyTypeID>(nanobind::cast(self).attr("typeid"));
1071 });
1072 cls.def("__repr__", [](DerivedTy &self) {
1073 PyPrintAccumulator printAccum;
1074 printAccum.parts.append(DerivedTy::pyClassName);
1075 printAccum.parts.append("(");
1076 mlirTypePrint(self, printAccum.getCallback(), printAccum.getUserData());
1077 printAccum.parts.append(")");
1078 return printAccum.join();
1079 });
1080
1081 if (DerivedTy::getTypeIdFunction) {
1082 PyGlobals::get().registerTypeCaster(
1083 DerivedTy::getTypeIdFunction(),
1084 nanobind::cast<nanobind::callable>(nanobind::cpp_function(
1085 [](PyType pyType) -> DerivedTy { return DerivedTy(pyType); })),
1086 /*replace*/ true);
1087 }
1088
1089 if (DerivedTy::name.length != 0) {
1090 cls.def_prop_ro_static("type_name", [](nanobind::object & /*self*/) {
1091 return nanobind::str(DerivedTy::name.data, DerivedTy::name.length);
1092 });
1093 }
1094
1095 DerivedTy::bindDerived(cls);
1096 }
1097
1098 /// Implemented by derived classes to add methods to the Python subclass.
1099 static void bindDerived(ClassTy &m) {}
1100};
1101
1102/// Wrapper around the generic MlirAttribute.
1103/// The lifetime of a type is bound by the PyContext that created it.
1105public:
1106 PyAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
1107 : BaseContextObject(std::move(contextRef)), attr(attr) {}
1108 bool operator==(const PyAttribute &other) const;
1109 operator MlirAttribute() const { return attr; }
1110 MlirAttribute get() const { return attr; }
1111
1112 /// Gets a capsule wrapping the void* within the MlirAttribute.
1113 nanobind::object getCapsule();
1114
1115 /// Creates a PyAttribute from the MlirAttribute wrapped by a capsule.
1116 /// Note that PyAttribute instances are uniqued, so the returned object
1117 /// may be a pre-existing object. Ownership of the underlying MlirAttribute
1118 /// is taken by calling this function.
1119 static PyAttribute createFromCapsule(const nanobind::object &capsule);
1120
1121 nanobind::typed<nanobind::object, PyAttribute> maybeDownCast();
1122
1123private:
1124 MlirAttribute attr;
1125};
1126
1127/// Represents a Python MlirNamedAttr, carrying an optional owned name.
1128/// TODO: Refactor this and the C-API to be based on an Identifier owned
1129/// by the context so as to avoid ownership issues here.
1131public:
1132 /// Constructs a PyNamedAttr that retains an owned name. This should be
1133 /// used in any code that originates an MlirNamedAttribute from a python
1134 /// string.
1135 /// The lifetime of the PyNamedAttr must extend to the lifetime of the
1136 /// passed attribute.
1137 PyNamedAttribute(MlirAttribute attr, std::string ownedName);
1138
1140
1141private:
1142 // Since the MlirNamedAttr contains an internal pointer to the actual
1143 // memory of the owned string, it must be heap allocated to remain valid.
1144 // Otherwise, strings that fit within the small object optimization threshold
1145 // will have their memory address change as the containing object is moved,
1146 // resulting in an invalid aliased pointer.
1147 std::unique_ptr<std::string> ownedName;
1148};
1149
1150/// CRTP base classes for Python attributes that subclass Attribute and should
1151/// be castable from it (i.e. via something like StringAttr(attr)).
1152/// By default, attribute class hierarchies are one level deep (i.e. a
1153/// concrete attribute class extends PyAttribute); however, intermediate
1154/// python-visible base classes can be modeled by specifying a BaseTy.
1155template <typename DerivedTy, typename BaseTy = PyAttribute>
1157public:
1158 // Derived classes must define statics for:
1159 // IsAFunctionTy isaFunction
1160 // const char *pyClassName
1161 using ClassTy = nanobind::class_<DerivedTy, BaseTy>;
1162 using IsAFunctionTy = bool (*)(MlirAttribute);
1163 using GetTypeIDFunctionTy = MlirTypeID (*)();
1164 static constexpr GetTypeIDFunctionTy getTypeIdFunction = nullptr;
1165 static inline const MlirStringRef name{};
1167
1169 PyConcreteAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
1170 : BaseTy(std::move(contextRef), attr) {}
1173
1174 static MlirAttribute castFrom(PyAttribute &orig) {
1175 if (!DerivedTy::isaFunction(orig)) {
1176 auto origRepr =
1177 nanobind::cast<std::string>(nanobind::repr(nanobind::cast(orig)));
1178 throw nanobind::value_error((std::string("Cannot cast attribute to ") +
1179 DerivedTy::pyClassName + " (from " +
1180 origRepr + ")")
1181 .c_str());
1182 }
1183 return orig;
1184 }
1185
1186 static void bind(nanobind::module_ &m, PyType_Slot *slots = nullptr) {
1187 ClassTy cls;
1188 if (slots) {
1189 cls = ClassTy(m, DerivedTy::pyClassName, nanobind::type_slots(slots),
1190 nanobind::is_generic());
1191 } else {
1192 cls = ClassTy(m, DerivedTy::pyClassName, nanobind::is_generic());
1193 }
1194 cls.def(nanobind::init<PyAttribute &>(), nanobind::keep_alive<0, 1>(),
1195 nanobind::arg("cast_from_attr"));
1196 cls.def_prop_ro(
1197 "type",
1198 [](PyAttribute &attr) -> nanobind::typed<nanobind::object, PyType> {
1199 return PyType(attr.getContext(), mlirAttributeGetType(attr))
1200 .maybeDownCast();
1201 });
1202 cls.def_prop_ro_static("static_typeid", [](nanobind::object & /*class*/) {
1203 if (DerivedTy::getTypeIdFunction)
1204 return PyTypeID(DerivedTy::getTypeIdFunction());
1205 throw nanobind::attribute_error(
1206 (DerivedTy::pyClassName + std::string(" has no typeid.")).c_str());
1207 });
1208 cls.def_prop_ro("typeid", [](PyAttribute &self) {
1209 return nanobind::cast<PyTypeID>(nanobind::cast(self).attr("typeid"));
1210 });
1211 cls.def("__repr__", [](DerivedTy &self) {
1212 PyPrintAccumulator printAccum;
1213 printAccum.parts.append(DerivedTy::pyClassName);
1214 printAccum.parts.append("(");
1215 mlirAttributePrint(self, printAccum.getCallback(),
1216 printAccum.getUserData());
1217 printAccum.parts.append(")");
1218 return printAccum.join();
1219 });
1220
1221 if (DerivedTy::getTypeIdFunction) {
1222 PyGlobals::get().registerTypeCaster(
1223 DerivedTy::getTypeIdFunction(),
1224 nanobind::cast<nanobind::callable>(
1225 nanobind::cpp_function([](PyAttribute pyAttribute) -> DerivedTy {
1226 return DerivedTy(pyAttribute);
1227 })),
1228 /*replace*/ true);
1229 }
1230
1231 if (DerivedTy::name.length != 0) {
1232 cls.def_prop_ro_static("attr_name", [](nanobind::object & /*self*/) {
1233 return nanobind::str(DerivedTy::name.data, DerivedTy::name.length);
1234 });
1235 }
1236
1237 DerivedTy::bindDerived(cls);
1238 }
1239
1240 /// Implemented by derived classes to add methods to the Python subclass.
1241 static void bindDerived(ClassTy &m) {}
1242};
1243
1245 : public PyConcreteAttribute<PyStringAttribute> {
1246public:
1248 static constexpr const char *pyClassName = "StringAttr";
1253
1254 static void bindDerived(ClassTy &c);
1255};
1256
1257/// CRTP base class for Python classes that subclass Location and should be
1258/// castable from it (i.e. via something like FileLineColLoc(loc)).
1259template <typename DerivedTy, typename BaseTy = PyLocation>
1261public:
1262 // Derived classes must define statics for:
1263 // IsAFunctionTy isaFunction
1264 // const char *pyClassName
1265 using ClassTy = nanobind::class_<DerivedTy, BaseTy>;
1266 using IsAFunctionTy = bool (*)(MlirLocation);
1267 using GetTypeIDFunctionTy = MlirTypeID (*)();
1268 static constexpr GetTypeIDFunctionTy getTypeIdFunction = nullptr;
1270
1272 PyConcreteLocation(PyMlirContextRef contextRef, MlirLocation loc)
1273 : BaseTy(std::move(contextRef), loc) {}
1276
1277 static MlirLocation castFrom(PyLocation &orig) {
1278 if (!DerivedTy::isaFunction(orig.get())) {
1279 auto origRepr =
1280 nanobind::cast<std::string>(nanobind::repr(nanobind::cast(orig)));
1281 throw nanobind::value_error((std::string("Cannot cast location to ") +
1282 DerivedTy::pyClassName + " (from " +
1283 origRepr + ")")
1284 .c_str());
1285 }
1286 return orig.get();
1287 }
1288
1289 static void bind(nanobind::module_ &m) {
1290 ClassTy cls(m, DerivedTy::pyClassName, nanobind::is_generic());
1291 cls.def(nanobind::init<PyLocation &>(), nanobind::keep_alive<0, 1>(),
1292 nanobind::arg("cast_from_loc"));
1293 cls.def_prop_ro_static("static_typeid", [](nanobind::object & /*class*/) {
1294 if (DerivedTy::getTypeIdFunction)
1295 return PyTypeID(DerivedTy::getTypeIdFunction());
1296 throw nanobind::attribute_error(
1297 (DerivedTy::pyClassName + std::string(" has no typeid.")).c_str());
1298 });
1299 cls.def("__repr__", [](DerivedTy &self) {
1300 PyPrintAccumulator printAccum;
1301 printAccum.parts.append(DerivedTy::pyClassName);
1302 printAccum.parts.append("(");
1303 mlirLocationPrint(self, printAccum.getCallback(),
1304 printAccum.getUserData());
1305 printAccum.parts.append(")");
1306 return printAccum.join();
1307 });
1308 if (DerivedTy::getTypeIdFunction) {
1309 PyGlobals::get().registerTypeCaster(
1310 DerivedTy::getTypeIdFunction(),
1311 nanobind::cast<nanobind::callable>(nanobind::cpp_function(
1312 [](PyLocation pyLoc) -> DerivedTy { return DerivedTy(pyLoc); })),
1313 /*replace*/ true);
1314 }
1315 DerivedTy::bindDerived(cls);
1316 }
1317
1318 /// Implemented by derived classes to add methods to the Python subclass.
1319 static void bindDerived(ClassTy &m) {}
1320};
1321
1323 : public PyConcreteLocation<PyUnknownLocation> {
1324public:
1326 static constexpr const char *pyClassName = "UnknownLoc";
1330
1331 static void bindDerived(ClassTy &c);
1332};
1333
1335 : public PyConcreteLocation<PyFileLineColLocation> {
1336public:
1338 static constexpr const char *pyClassName = "FileLineColLoc";
1342
1343 static void bindDerived(ClassTy &c);
1344};
1345
1347 : public PyConcreteLocation<PyNameLocation> {
1348public:
1350 static constexpr const char *pyClassName = "NameLoc";
1354
1355 static void bindDerived(ClassTy &c);
1356};
1357
1359 : public PyConcreteLocation<PyCallSiteLocation> {
1360public:
1362 static constexpr const char *pyClassName = "CallSiteLoc";
1366
1367 static void bindDerived(ClassTy &c);
1368};
1369
1371 : public PyConcreteLocation<PyFusedLocation> {
1372public:
1374 static constexpr const char *pyClassName = "FusedLoc";
1378
1379 static void bindDerived(ClassTy &c);
1380};
1381
1382/// Wrapper around the generic MlirValue.
1383/// Values are managed completely by the operation that resulted in their
1384/// definition. For op result value, this is the operation that defines the
1385/// value. For block argument values, this is the operation that contains the
1386/// block to which the value is an argument (blocks cannot be detached in Python
1387/// bindings so such operation always exists).
1388class PyBlockArgument;
1389class PyOpResult;
1391public:
1392 // The virtual here is "load bearing" in that it enables RTTI
1393 // for PyConcreteValue CRTP classes that support maybeDownCast.
1394 // See PyValue::maybeDownCast.
1395 virtual ~PyValue() = default;
1396 PyValue(PyOperationRef parentOperation, MlirValue value)
1397 : parentOperation(std::move(parentOperation)), value(value) {}
1398 operator MlirValue() const { return value; }
1399
1400 MlirValue get() { return value; }
1401 PyOperationRef &getParentOperation() { return parentOperation; }
1402
1403 void checkValid() { return parentOperation->checkValid(); }
1404
1405 /// Gets a capsule wrapping the void* within the MlirValue.
1406 nanobind::object getCapsule();
1407
1408 nanobind::typed<nanobind::object,
1409 std::variant<PyBlockArgument, PyOpResult, PyValue>>
1410 maybeDownCast();
1411
1412 /// Creates a PyValue from the MlirValue wrapped by a capsule. Ownership of
1413 /// the underlying MlirValue is still tied to the owning operation.
1414 static PyValue createFromCapsule(nanobind::object capsule);
1415
1416private:
1417 PyOperationRef parentOperation;
1418 MlirValue value;
1419};
1420
1421/// Wrapper around MlirAffineExpr. Affine expressions are owned by the context.
1423public:
1424 PyAffineExpr(PyMlirContextRef contextRef, MlirAffineExpr affineExpr)
1425 : BaseContextObject(std::move(contextRef)), affineExpr(affineExpr) {}
1426 bool operator==(const PyAffineExpr &other) const;
1427 operator MlirAffineExpr() const { return affineExpr; }
1428 MlirAffineExpr get() const { return affineExpr; }
1429
1430 /// Gets a capsule wrapping the void* within the MlirAffineExpr.
1431 nanobind::object getCapsule();
1432
1433 /// Creates a PyAffineExpr from the MlirAffineExpr wrapped by a capsule.
1434 /// Note that PyAffineExpr instances are uniqued, so the returned object
1435 /// may be a pre-existing object. Ownership of the underlying MlirAffineExpr
1436 /// is taken by calling this function.
1437 static PyAffineExpr createFromCapsule(const nanobind::object &capsule);
1438
1439 PyAffineExpr add(const PyAffineExpr &other) const;
1440 PyAffineExpr mul(const PyAffineExpr &other) const;
1442 PyAffineExpr ceilDiv(const PyAffineExpr &other) const;
1443 PyAffineExpr mod(const PyAffineExpr &other) const;
1444
1445 nanobind::typed<nanobind::object, PyAffineExpr> maybeDownCast();
1446
1447private:
1448 MlirAffineExpr affineExpr;
1449};
1450
1452public:
1453 PyAffineMap(PyMlirContextRef contextRef, MlirAffineMap affineMap)
1454 : BaseContextObject(std::move(contextRef)), affineMap(affineMap) {}
1455 bool operator==(const PyAffineMap &other) const;
1456 operator MlirAffineMap() const { return affineMap; }
1457 MlirAffineMap get() const { return affineMap; }
1458
1459 /// Gets a capsule wrapping the void* within the MlirAffineMap.
1460 nanobind::object getCapsule();
1461
1462 /// Creates a PyAffineMap from the MlirAffineMap wrapped by a capsule.
1463 /// Note that PyAffineMap instances are uniqued, so the returned object
1464 /// may be a pre-existing object. Ownership of the underlying MlirAffineMap
1465 /// is taken by calling this function.
1466 static PyAffineMap createFromCapsule(const nanobind::object &capsule);
1467
1468private:
1469 MlirAffineMap affineMap;
1470};
1471
1473public:
1474 PyIntegerSet(PyMlirContextRef contextRef, MlirIntegerSet integerSet)
1475 : BaseContextObject(std::move(contextRef)), integerSet(integerSet) {}
1476 bool operator==(const PyIntegerSet &other) const;
1477 operator MlirIntegerSet() const { return integerSet; }
1478 MlirIntegerSet get() const { return integerSet; }
1479
1480 /// Gets a capsule wrapping the void* within the MlirIntegerSet.
1481 nanobind::object getCapsule();
1482
1483 /// Creates a PyIntegerSet from the MlirAffineMap wrapped by a capsule.
1484 /// Note that PyIntegerSet instances may be uniqued, so the returned object
1485 /// may be a pre-existing object. Integer sets are owned by the context.
1486 static PyIntegerSet createFromCapsule(const nanobind::object &capsule);
1487
1488private:
1489 MlirIntegerSet integerSet;
1490};
1491
1492/// Bindings for MLIR symbol tables.
1494public:
1495 /// Constructs a symbol table for the given operation.
1496 explicit PySymbolTable(PyOperationBase &operation);
1497
1498 /// Destroys the symbol table.
1500
1501 /// Returns the symbol (opview) with the given name, throws if there is no
1502 /// such symbol in the table.
1503 nanobind::object dunderGetItem(const std::string &name);
1504
1505 /// Removes the given operation from the symbol table and erases it.
1506 void erase(PyOperationBase &symbol);
1507
1508 /// Removes the operation with the given name from the symbol table and erases
1509 /// it, throws if there is no such symbol in the table.
1510 void dunderDel(const std::string &name);
1511
1512 /// Inserts the given operation into the symbol table. The operation must have
1513 /// the symbol trait.
1514 PyStringAttribute insert(PyOperationBase &symbol);
1515
1516 /// Gets and sets the name of a symbol op.
1517 static PyStringAttribute getSymbolName(PyOperationBase &symbol);
1518 static void setSymbolName(PyOperationBase &symbol, const std::string &name);
1519
1520 /// Gets and sets the visibility of a symbol op.
1521 static PyStringAttribute getVisibility(PyOperationBase &symbol);
1522 static void setVisibility(PyOperationBase &symbol,
1523 const std::string &visibility);
1524
1525 /// Replaces all symbol uses within an operation. See the API
1526 /// mlirSymbolTableReplaceAllSymbolUses for all caveats.
1527 static void replaceAllSymbolUses(const std::string &oldSymbol,
1528 const std::string &newSymbol,
1529 PyOperationBase &from);
1530
1531 /// Walks all symbol tables under and including 'from'.
1532 static void walkSymbolTables(PyOperationBase &from, bool allSymUsesVisible,
1533 nanobind::object callback);
1534
1535 /// Casts the bindings class into the C API structure.
1536 operator MlirSymbolTable() { return symbolTable; }
1537
1538private:
1539 PyOperationRef operation;
1540 MlirSymbolTable symbolTable;
1541};
1542
1543/// Custom exception that allows access to error diagnostic information. This is
1544/// translated to the `ir.MLIRError` python exception when thrown.
1545struct MLIR_PYTHON_API_EXPORTED MLIRError : std::exception {
1546 MLIRError(std::string message,
1547 std::vector<PyDiagnostic::DiagnosticInfo> &&errorDiagnostics = {})
1548 : message(std::move(message)),
1549 errorDiagnostics(std::move(errorDiagnostics)) {}
1550 const char *what() const noexcept override { return message.c_str(); }
1551
1552 /// Bind the MLIRError exception class to the given module.
1553 static void bind(nanobind::module_ &m);
1554
1555 std::string message;
1556 std::vector<PyDiagnostic::DiagnosticInfo> errorDiagnostics;
1557};
1558
1559//------------------------------------------------------------------------------
1560// Utilities.
1561//------------------------------------------------------------------------------
1562
1563inline MlirStringRef toMlirStringRef(const std::string &s) {
1564 return mlirStringRefCreate(s.data(), s.size());
1565}
1566
1567inline MlirStringRef toMlirStringRef(std::string_view s) {
1568 return mlirStringRefCreate(s.data(), s.size());
1569}
1570
1571inline MlirStringRef toMlirStringRef(const nanobind::bytes &s) {
1572 return mlirStringRefCreate(static_cast<const char *>(s.data()), s.size());
1573}
1574
1575/// Create a block, using the current location context if no locations are
1576/// specified.
1578createBlock(const nanobind::typed<nanobind::sequence, PyType> &pyArgTypes,
1579 const std::optional<nanobind::typed<nanobind::sequence, PyLocation>>
1580 &pyArgLocs);
1581
1583 static bool dunderContains(const std::string &attributeKind);
1584 static nanobind::callable
1585 dunderGetItemNamed(const std::string &attributeKind);
1586 static void dunderSetItemNamed(const std::string &attributeKind,
1587 nanobind::callable func, bool replace,
1588 bool allow_existing);
1589
1590 static void bind(nanobind::module_ &m);
1591};
1592
1593//------------------------------------------------------------------------------
1594// Collections.
1595//------------------------------------------------------------------------------
1596
1597/// Regions of an op are fixed length and indexed numerically so are represented
1598/// with a sequence-like container.
1600 : public Sliceable<PyRegionList, PyRegion> {
1601public:
1602 static constexpr const char *pyClassName = "RegionSequence";
1603
1605 intptr_t length = -1, intptr_t step = 1);
1606
1607private:
1608 /// Give the parent CRTP class access to hook implementations below.
1609 friend class Sliceable<PyRegionList, PyRegion>;
1610
1611 intptr_t getRawNumElements();
1612
1613 PyRegion getRawElement(intptr_t pos);
1614
1616
1617 PyOperationRef operation;
1618};
1619
1621public:
1622 PyBlockIterator(PyOperationRef operation, MlirBlock next)
1623 : operation(std::move(operation)), next(next) {}
1624
1625 PyBlockIterator &dunderIter() { return *this; }
1626
1627 nanobind::typed<nanobind::object, PyBlock> dunderNext();
1628
1629 static void bind(nanobind::module_ &m);
1630
1631private:
1632 PyOperationRef operation;
1633 MlirBlock next;
1634};
1635
1636/// Blocks are exposed by the C-API as a forward-only linked list. In Python,
1637/// we present them as a more full-featured list-like container but optimize
1638/// it for forward iteration. Blocks are always owned by a region.
1640public:
1641 PyBlockList(PyOperationRef operation, MlirRegion region)
1642 : operation(std::move(operation)), region(region) {}
1643
1644 PyBlockIterator dunderIter();
1645
1646 intptr_t dunderLen();
1647
1648 PyBlock dunderGetItem(intptr_t index);
1649
1650 PyBlock appendBlock(const nanobind::args &pyArgTypes,
1651 const std::optional<nanobind::sequence> &pyArgLocs);
1652
1653 static void bind(nanobind::module_ &m);
1654
1655private:
1656 PyOperationRef operation;
1657 MlirRegion region;
1658};
1659
1661public:
1662 PyOperationIterator(PyOperationRef parentOperation, MlirOperation next)
1663 : parentOperation(std::move(parentOperation)), next(next) {}
1664
1665 PyOperationIterator &dunderIter() { return *this; }
1666
1667 nanobind::typed<nanobind::object, PyOpView> dunderNext();
1668
1669 static void bind(nanobind::module_ &m);
1670
1671private:
1672 PyOperationRef parentOperation;
1673 MlirOperation next;
1674};
1675
1676/// Operations are exposed by the C-API as a forward-only linked list. In
1677/// Python, we present them as a more full-featured list-like container but
1678/// optimize it for forward iteration. Iterable operations are always owned
1679/// by a block.
1681public:
1682 PyOperationList(PyOperationRef parentOperation, MlirBlock block)
1683 : parentOperation(std::move(parentOperation)), block(block) {}
1684
1685 PyOperationIterator dunderIter();
1686
1687 intptr_t dunderLen();
1688
1689 nanobind::typed<nanobind::object, PyOpView> dunderGetItem(intptr_t index);
1690
1691 static void bind(nanobind::module_ &m);
1692
1693private:
1694 PyOperationRef parentOperation;
1695 MlirBlock block;
1696};
1697
1699public:
1700 PyOpOperand(MlirOpOperand opOperand) : opOperand(opOperand) {}
1701 operator MlirOpOperand() const { return opOperand; }
1702
1703 nanobind::typed<nanobind::object, PyOpView> getOwner() const;
1704
1705 size_t getOperandNumber() const;
1706
1707 static void bind(nanobind::module_ &m);
1708
1709private:
1710 MlirOpOperand opOperand;
1711};
1712
1714public:
1715 PyOpOperandIterator(MlirOpOperand opOperand) : opOperand(opOperand) {}
1716
1717 PyOpOperandIterator &dunderIter() { return *this; }
1718
1719 nanobind::typed<nanobind::object, PyOpOperand> dunderNext();
1720
1721 static void bind(nanobind::module_ &m);
1722
1723private:
1724 MlirOpOperand opOperand;
1725};
1726
1727/// CRTP base class for Python MLIR values that subclass Value and should be
1728/// castable from it. The value hierarchy is one level deep and is not supposed
1729/// to accommodate other levels unless core MLIR changes.
1730template <typename DerivedTy>
1732public:
1733 // Derived classes must define statics for:
1734 // IsAFunctionTy isaFunction
1735 // const char *pyClassName
1736 // and redefine bindDerived.
1737 using ClassTy = nanobind::class_<DerivedTy, PyValue>;
1738 using IsAFunctionTy = bool (*)(MlirValue);
1739 using GetTypeIDFunctionTy = MlirTypeID (*)();
1740 static constexpr GetTypeIDFunctionTy getTypeIdFunction = nullptr;
1742
1743 PyConcreteValue() = default;
1744 PyConcreteValue(PyOperationRef operationRef, MlirValue value)
1745 : PyValue(operationRef, value) {}
1748
1749 /// Attempts to cast the original value to the derived type and throws on
1750 /// type mismatches.
1751 static MlirValue castFrom(PyValue &orig) {
1752 if (!DerivedTy::isaFunction(orig.get())) {
1753 auto origRepr =
1754 nanobind::cast<std::string>(nanobind::repr(nanobind::cast(orig)));
1755 throw nanobind::value_error((std::string("Cannot cast value to ") +
1756 DerivedTy::pyClassName + " (from " +
1757 origRepr + ")")
1758 .c_str());
1759 }
1760 return orig.get();
1761 }
1762
1763 /// Binds the Python module objects to functions of this class.
1764 static void bind(nanobind::module_ &m) {
1765 auto cls = ClassTy(m, DerivedTy::pyClassName, nanobind::is_generic(),
1766 nanobind::sig((std::string("class ") +
1767 DerivedTy::pyClassName + "(Value[_T])")
1768 .c_str()));
1769 cls.def(nanobind::init<PyValue &>(), nanobind::keep_alive<0, 1>(),
1770 nanobind::arg("value"));
1771 cls.def(
1773 [](DerivedTy &self) -> nanobind::typed<nanobind::object, DerivedTy> {
1774 return self.maybeDownCast();
1775 });
1776 cls.def("__str__", [](PyValue &self) {
1777 PyPrintAccumulator printAccum;
1778 printAccum.parts.append(std::string(DerivedTy::pyClassName) + "(");
1779 mlirValuePrint(self.get(), printAccum.getCallback(),
1780 printAccum.getUserData());
1781 printAccum.parts.append(")");
1782 return printAccum.join();
1783 });
1784
1785 if (DerivedTy::getTypeIdFunction) {
1786 PyGlobals::get().registerValueCaster(
1787 DerivedTy::getTypeIdFunction(),
1788 nanobind::cast<nanobind::callable>(nanobind::cpp_function(
1789 [](PyValue pyValue) -> DerivedTy { return DerivedTy(pyValue); })),
1790 /*replace*/ true);
1791 }
1792
1793 DerivedTy::bindDerived(cls);
1794 }
1795
1796 /// Implemented by derived classes to add methods to the Python subclass.
1797 static void bindDerived(ClassTy &m) {}
1798};
1799
1800/// Python wrapper for MlirOpResult.
1802public:
1804 static constexpr const char *pyClassName = "OpResult";
1806
1807 static void bindDerived(ClassTy &c);
1808};
1809
1810/// A list of operation results. Internally, these are stored as consecutive
1811/// elements, random access is cheap. The (returned) result list is associated
1812/// with the operation whose results these are, and thus extends the lifetime of
1813/// this operation.
1815 : public Sliceable<PyOpResultList, PyOpResult> {
1816public:
1817 static constexpr const char *pyClassName = "OpResultList";
1818 static constexpr std::array<const char *, 1> typeParams = {"_T"};
1820
1822 intptr_t length = -1, intptr_t step = 1);
1823
1824 static void bindDerived(ClassTy &c);
1825
1826 PyOperationRef &getOperation() { return operation; }
1827
1828private:
1829 /// Give the parent CRTP class access to hook implementations below.
1830 friend class Sliceable<PyOpResultList, PyOpResult>;
1831
1832 intptr_t getRawNumElements();
1833
1834 PyOpResult getRawElement(intptr_t index);
1835
1836 PyOpResultList slice(intptr_t startIndex, intptr_t length,
1837 intptr_t step) const;
1838
1839 PyOperationRef operation;
1840};
1841
1842/// Python wrapper for MlirBlockArgument.
1844 : public PyConcreteValue<PyBlockArgument> {
1845public:
1847 static constexpr const char *pyClassName = "BlockArgument";
1849
1850 static void bindDerived(ClassTy &c);
1851};
1852
1853/// A list of block arguments. Internally, these are stored as consecutive
1854/// elements, random access is cheap. The argument list is associated with the
1855/// operation that contains the block (detached blocks are not allowed in
1856/// Python bindings) and extends its lifetime.
1858 : public Sliceable<PyBlockArgumentList, PyBlockArgument> {
1859public:
1860 static constexpr const char *pyClassName = "BlockArgumentList";
1862
1863 PyBlockArgumentList(PyOperationRef operation, MlirBlock block,
1865 intptr_t step = 1);
1866
1867 static void bindDerived(ClassTy &c);
1868
1869private:
1870 /// Give the parent CRTP class access to hook implementations below.
1872
1873 /// Returns the number of arguments in the list.
1874 intptr_t getRawNumElements();
1875
1876 /// Returns `pos`-the element in the list.
1877 PyBlockArgument getRawElement(intptr_t pos) const;
1878
1879 /// Returns a sublist of this list.
1881 intptr_t step) const;
1882
1883 PyOperationRef operation;
1884 MlirBlock block;
1885};
1886
1887/// A list of operation operands. Internally, these are stored as consecutive
1888/// elements, random access is cheap. The (returned) operand list is associated
1889/// with the operation whose operands these are, and thus extends the lifetime
1890/// of this operation.
1892 : public Sliceable<PyOpOperandList, PyValue> {
1893public:
1894 static constexpr const char *pyClassName = "OpOperandList";
1895 static constexpr std::array<const char *, 1> typeParams = {"_T"};
1897
1899 intptr_t length = -1, intptr_t step = 1);
1900
1901 void dunderSetItem(intptr_t index, PyValue value);
1902
1903 static void bindDerived(ClassTy &c);
1904
1905private:
1906 /// Give the parent CRTP class access to hook implementations below.
1907 friend class Sliceable<PyOpOperandList, PyValue>;
1908
1909 intptr_t getRawNumElements();
1910
1911 PyValue getRawElement(intptr_t pos);
1912
1914 intptr_t step) const;
1915
1916 PyOperationRef operation;
1917};
1918
1919/// A list of operation successors. Internally, these are stored as consecutive
1920/// elements, random access is cheap. The (returned) successor list is
1921/// associated with the operation whose successors these are, and thus extends
1922/// the lifetime of this operation.
1924 : public Sliceable<PyOpSuccessors, PyBlock> {
1925public:
1926 static constexpr const char *pyClassName = "OpSuccessors";
1927
1929 intptr_t length = -1, intptr_t step = 1);
1930
1931 void dunderSetItem(intptr_t index, PyBlock block);
1932
1933 static void bindDerived(ClassTy &c);
1934
1935private:
1936 /// Give the parent CRTP class access to hook implementations below.
1937 friend class Sliceable<PyOpSuccessors, PyBlock>;
1938
1939 intptr_t getRawNumElements();
1940
1941 PyBlock getRawElement(intptr_t pos);
1942
1944 intptr_t step) const;
1945
1946 PyOperationRef operation;
1947};
1948
1949/// A list of block successors. Internally, these are stored as consecutive
1950/// elements, random access is cheap. The (returned) successor list is
1951/// associated with the operation and block whose successors these are, and thus
1952/// extends the lifetime of this operation and block.
1954 : public Sliceable<PyBlockSuccessors, PyBlock> {
1955public:
1956 static constexpr const char *pyClassName = "BlockSuccessors";
1957
1960 intptr_t step = 1);
1961
1962private:
1963 /// Give the parent CRTP class access to hook implementations below.
1964 friend class Sliceable<PyBlockSuccessors, PyBlock>;
1965
1966 intptr_t getRawNumElements();
1967
1968 PyBlock getRawElement(intptr_t pos);
1969
1971 intptr_t step) const;
1972
1973 PyOperationRef operation;
1974 PyBlock block;
1975};
1976
1977/// A list of block predecessors. The (returned) predecessor list is
1978/// associated with the operation and block whose predecessors these are, and
1979/// thus extends the lifetime of this operation and block.
1980///
1981/// WARNING: This Sliceable is more expensive than the others here because
1982/// mlirBlockGetPredecessor actually iterates the use-def chain (of block
1983/// operands) anew for each indexed access.
1985 : public Sliceable<PyBlockPredecessors, PyBlock> {
1986public:
1987 static constexpr const char *pyClassName = "BlockPredecessors";
1988
1991 intptr_t step = 1);
1992
1993private:
1994 /// Give the parent CRTP class access to hook implementations below.
1995 friend class Sliceable<PyBlockPredecessors, PyBlock>;
1996
1997 intptr_t getRawNumElements();
1998
1999 PyBlock getRawElement(intptr_t pos);
2000
2002 intptr_t step) const;
2003
2004 PyOperationRef operation;
2005 PyBlock block;
2006};
2007
2008/// A list of operation attributes. Can be indexed by name, producing
2009/// attributes, or by index, producing named attributes.
2011public:
2013 : operation(std::move(operation)) {}
2014
2015 nanobind::typed<nanobind::object, PyAttribute>
2016 dunderGetItemNamed(const std::string &name);
2017
2018 PyNamedAttribute dunderGetItemIndexed(intptr_t index);
2019
2020 nanobind::typed<nanobind::object, std::optional<PyAttribute>>
2021 get(const std::string &key, nanobind::object defaultValue);
2022
2023 void dunderSetItem(const std::string &name, const PyAttribute &attr);
2024
2025 void dunderDelItem(const std::string &name);
2026
2027 intptr_t dunderLen();
2028
2029 bool dunderContains(const std::string &name);
2030
2031 static void forEachAttr(MlirOperation op,
2032 std::function<void(MlirStringRef, MlirAttribute)> fn);
2033
2034 static void bind(nanobind::module_ &m);
2035
2036private:
2037 PyOperationRef operation;
2038};
2039
2040/// Base class of operation adaptors.
2042public:
2043 PyOpAdaptor(nanobind::list operands, PyOpAttributeMap attributes)
2044 : operands(std::move(operands)), attributes(std::move(attributes)) {}
2045 PyOpAdaptor(nanobind::list operands, PyOpView &opView)
2046 : operands(std::move(operands)),
2047 attributes(opView.getOperation().getRef()) {}
2048
2049 static void bind(nanobind::module_ &m);
2050
2051private:
2052 nanobind::list operands;
2053 PyOpAttributeMap attributes;
2054};
2055
2057public:
2058 static bool attach(const nanobind::object &opName,
2059 const nanobind::object &target, PyMlirContext &context);
2060
2061 static void bind(nanobind::module_ &m);
2062
2063 static inline const char *typeIDAttr = "_trait_typeid";
2064};
2065
2067
2069public:
2070 static bool attach(const nanobind::object &opName, PyMlirContext &context);
2071 static void bind(nanobind::module_ &m);
2072};
2073
2075public:
2076 static bool attach(const nanobind::object &opName, PyMlirContext &context);
2077 static void bind(nanobind::module_ &m);
2078};
2079
2081public:
2082 static bool attach(const nanobind::object &opName, PyMlirContext &context);
2083 static void bind(nanobind::module_ &m);
2084};
2085
2087 : public PyDynamicOpTrait {
2088public:
2089 static bool attach(const nanobind::object &opName, PyMlirContext &context);
2090 static void bind(nanobind::module_ &m);
2091};
2092
2093} // namespace PyDynamicOpTraits
2094
2095MLIR_PYTHON_API_EXPORTED MlirValue getUniqueResult(MlirOperation operation);
2096MLIR_PYTHON_API_EXPORTED void populateIRCore(nanobind::module_ &m);
2098MLIR_PYTHON_API_EXPORTED void populateRoot(nanobind::module_ &m);
2099
2100/// Helper for creating an @classmethod.
2101template <class Func, typename... Args>
2102inline nanobind::object classmethod(Func f, Args... args) {
2103 nanobind::object cf = nanobind::cpp_function(f, args...);
2104 static SafeInit<nanobind::object> classmethodFn([]() {
2105 return std::make_unique<nanobind::object>(
2106 nanobind::module_::import_("builtins").attr("classmethod"));
2107 });
2108 return classmethodFn.get()(cf);
2109}
2110
2111} // namespace MLIR_BINDINGS_PYTHON_DOMAIN
2112} // namespace python
2113} // namespace mlir
2114
2115namespace nanobind {
2116namespace detail {
2117template <>
2118struct type_caster<
2119 mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN::DefaultingPyMlirContext>
2121 mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN::DefaultingPyMlirContext> {
2122};
2123template <>
2124struct type_caster<
2125 mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN::DefaultingPyLocation>
2127 mlir::python::MLIR_BINDINGS_PYTHON_DOMAIN::DefaultingPyLocation> {};
2128
2129} // namespace detail
2130} // namespace nanobind
2131
2132#endif // MLIR_BINDINGS_PYTHON_IRCORE_H
return MutableOperandRange * this
MLIR_FLOAT16_EXPORT bool operator==(const f16 &f1, const f16 &f2)
bool mlirValueIsABlockArgument(MlirValue value)
Definition IR.cpp:1181
void mlirLocationPrint(MlirLocation location, MlirStringCallback callback, void *userData)
Definition IR.cpp:440
MlirType mlirAttributeGetType(MlirAttribute attribute)
Definition IR.cpp:1366
bool mlirValueIsAOpResult(MlirValue value)
Definition IR.cpp:1185
void mlirOpPrintingFlagsDestroy(MlirOpPrintingFlags flags)
Definition IR.cpp:223
void mlirTypePrint(MlirType type, MlirStringCallback callback, void *userData)
Definition IR.cpp:1344
#define MLIR_PYTHON_MAYBE_DOWNCAST_ATTR
Attribute on MLIR Python objects that expose a function for downcasting the corresponding Python obje...
Definition Interop.h:118
b getContext())
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
static sycl::context getDefaultContext()
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
A CRTP base class for pseudo-containers willing to support Python-type slicing access on top of index...
nanobind::class_< PyOpResultList > ClassTy
Sliceable(intptr_t startIndex, intptr_t length, intptr_t step)
Defaulting()=default
Type casters require the type to be default constructible, but using such an instance is illegal.
PyMlirContextRef & getContext()
Accesses the context reference.
Definition IRCore.h:351
Used in function arguments when None should resolve to the current context manager set instance.
Definition IRCore.h:619
Defaulting()=default
Type casters require the type to be default constructible, but using such an instance is illegal.
Used in function arguments when None should resolve to the current context manager set instance.
Definition IRCore.h:332
Defaulting()=default
Type casters require the type to be default constructible, but using such an instance is illegal.
Wrapper around MlirAffineExpr. Affine expressions are owned by the context.
Definition IRCore.h:1422
PyAffineExpr ceilDiv(const PyAffineExpr &other) const
PyAffineExpr floorDiv(const PyAffineExpr &other) const
PyAffineExpr add(const PyAffineExpr &other) const
PyAffineExpr mod(const PyAffineExpr &other) const
PyAffineExpr(PyMlirContextRef contextRef, MlirAffineExpr affineExpr)
Definition IRCore.h:1424
nanobind::typed< nanobind::object, PyAffineExpr > maybeDownCast()
Definition IRAffine.cpp:369
PyAffineExpr mul(const PyAffineExpr &other) const
PyAffineMap(PyMlirContextRef contextRef, MlirAffineMap affineMap)
Definition IRCore.h:1453
PyAsmState(MlirValue value, bool useLocalScope)
Definition IRCore.cpp:1767
Wrapper around the generic MlirAttribute.
Definition IRCore.h:1104
PyAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
Definition IRCore.h:1106
Sliceable< PyBlockArgumentList, PyBlockArgument > SliceableT
Definition IRCore.h:1861
PyBlockArgumentList(PyOperationRef operation, MlirBlock block, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:2223
Python wrapper for MlirBlockArgument.
Definition IRCore.h:1844
PyBlockIterator(PyOperationRef operation, MlirBlock next)
Definition IRCore.h:1622
PyBlockList(PyOperationRef operation, MlirRegion region)
Definition IRCore.h:1641
PyBlockPredecessors(PyBlock block, PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:2383
PyBlockSuccessors(PyBlock block, PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:2360
PyBlock(PyOperationRef parentOperation, MlirBlock block)
Definition IRCore.h:913
static constexpr GetTypeIDFunctionTy getTypeIdFunction
Definition IRCore.h:1364
static constexpr GetTypeIDFunctionTy getTypeIdFunction
Definition IRCore.h:1164
static void bindDerived(ClassTy &m)
Implemented by derived classes to add methods to the Python subclass.
Definition IRCore.h:1241
PyConcreteAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
Definition IRCore.h:1169
static void bind(nanobind::module_ &m, PyType_Slot *slots=nullptr)
Definition IRCore.h:1186
nanobind::class_< DerivedTy, BaseTy > ClassTy
Definition IRCore.h:1161
static MlirAttribute castFrom(PyAttribute &orig)
Definition IRCore.h:1174
static constexpr GetTypeIDFunctionTy getTypeIdFunction
Definition IRCore.h:1268
static void bindDerived(ClassTy &m)
Implemented by derived classes to add methods to the Python subclass.
Definition IRCore.h:1319
static MlirLocation castFrom(PyLocation &orig)
Definition IRCore.h:1277
PyConcreteLocation(PyMlirContextRef contextRef, MlirLocation loc)
Definition IRCore.h:1272
nanobind::class_< DerivedTy, BaseTy > ClassTy
Definition IRCore.h:1265
nanobind::class_< DerivedTy, BaseTy > ClassTy
Definition IRCore.h:1034
static constexpr GetTypeIDFunctionTy getTypeIdFunction
Definition IRCore.h:1038
PyConcreteType(PyMlirContextRef contextRef, MlirType t)
Definition IRCore.h:1042
static void bindDerived(ClassTy &m)
Implemented by derived classes to add methods to the Python subclass.
Definition IRCore.h:1099
PyConcreteValue(PyOperationRef operationRef, MlirValue value)
Definition IRCore.h:1744
static constexpr GetTypeIDFunctionTy getTypeIdFunction
Definition IRCore.h:1740
static void bind(nanobind::module_ &m)
Binds the Python module objects to functions of this class.
Definition IRCore.h:1764
nanobind::class_< DerivedTy, PyValue > ClassTy
Definition IRCore.h:1737
static MlirValue castFrom(PyValue &orig)
Attempts to cast the original value to the derived type and throws on type mismatches.
Definition IRCore.h:1751
static void bindDerived(ClassTy &m)
Implemented by derived classes to add methods to the Python subclass.
Definition IRCore.h:1797
Represents a diagnostic handler attached to the context.
Definition IRCore.h:500
void detach()
Detaches the handler. Does nothing if not attached.
Definition IRCore.cpp:731
PyDiagnosticHandler(MlirContext context, nanobind::object callback)
Definition IRCore.cpp:725
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
Definition IRCore.h:512
Python class mirroring the C MlirDiagnostic struct.
Definition IRCore.h:423
PyDialectDescriptor(PyMlirContextRef contextRef, MlirDialect dialect)
Definition IRCore.h:557
Wrapper around an MlirDialectRegistry.
Definition IRCore.h:592
PyDialectRegistry(PyDialectRegistry &&other) noexcept
Definition IRCore.h:601
static bool attach(const nanobind::object &opName, const nanobind::object &target, PyMlirContext &context)
Definition IRCore.cpp:2588
static bool attach(const nanobind::object &opName, PyMlirContext &context)
Definition IRCore.cpp:2688
static bool attach(const nanobind::object &opName, PyMlirContext &context)
Definition IRCore.cpp:2642
static bool attach(const nanobind::object &opName, PyMlirContext &context)
Definition IRCore.cpp:2665
static bool attach(const nanobind::object &opName, PyMlirContext &context)
Definition IRCore.cpp:2713
static constexpr GetTypeIDFunctionTy getTypeIdFunction
Definition IRCore.h:1340
static constexpr GetTypeIDFunctionTy getTypeIdFunction
Definition IRCore.h:1376
static PyGlobals & get()
Most code should get the globals via this static accessor.
Definition Globals.cpp:59
An insertion point maintains a pointer to a Block and a reference operation.
Definition IRCore.h:935
void insert(PyOperationBase &operationBase)
Inserts an operation.
Definition IRCore.cpp:1798
void contextExit(const nanobind::object &excType, const nanobind::object &excVal, const nanobind::object &excTb)
Definition IRCore.cpp:1863
static PyInsertionPoint atBlockTerminator(PyBlock &block)
Shortcut to create an insertion point before the block terminator.
Definition IRCore.cpp:1837
static PyInsertionPoint after(PyOperationBase &op)
Shortcut to create an insertion point to the node after the specified operation.
Definition IRCore.cpp:1846
std::optional< PyOperationRef > & getRefOperation()
Definition IRCore.h:963
static PyInsertionPoint atBlockBegin(PyBlock &block)
Shortcut to create an insertion point at the beginning of the block.
Definition IRCore.cpp:1824
PyInsertionPoint(const PyBlock &block)
Creates an insertion point positioned after the last operation in the block, but still inside the blo...
Definition IRCore.cpp:1789
static nanobind::object contextEnter(nanobind::object insertionPoint)
Enter and exit the context manager.
Definition IRCore.cpp:1859
PyIntegerSet(PyMlirContextRef contextRef, MlirIntegerSet integerSet)
Definition IRCore.h:1474
PyLocation(PyMlirContextRef contextRef, MlirLocation loc)
Definition IRCore.h:360
static PyMlirContextRef forContext(MlirContext context)
Returns a context reference for the singleton PyMlirContext wrapper for the given context.
Definition IRCore.cpp:461
MlirContext get()
Accesses the underlying MlirContext.
Definition IRCore.h:245
void setEmitErrorDiagnostics(bool value)
Controls whether error diagnostics should be propagated to diagnostic handlers, instead of being capt...
Definition IRCore.h:299
PyModuleRef getRef()
Gets a strong reference to this module.
Definition IRCore.h:645
MlirModule get()
Gets the backing MlirModule.
Definition IRCore.h:642
static PyModuleRef forModule(MlirModule module)
Returns a PyModule reference for the given MlirModule.
Definition IRCore.cpp:876
static constexpr GetTypeIDFunctionTy getTypeIdFunction
Definition IRCore.h:1352
Represents a Python MlirNamedAttr, carrying an optional owned name.
Definition IRCore.h:1130
PyNamedAttribute(MlirAttribute attr, std::string ownedName)
Constructs a PyNamedAttr that retains an owned name.
Definition IRCore.cpp:1924
Template for a reference to a concrete type which captures a python reference to its underlying pytho...
Definition IRCore.h:67
nanobind::typed< nanobind::object, T > NBTypedT
Definition IRCore.h:123
PyObjectRef & operator=(const PyObjectRef &other)
Definition IRCore.h:82
PyObjectRef(PyObjectRef &&other) noexcept
Definition IRCore.h:75
nanobind::object releaseObject()
Releases the object held by this instance, returning it.
Definition IRCore.h:105
PyObjectRef(T *referrent, nanobind::object object)
Definition IRCore.h:69
PyObjectRef & operator=(PyObjectRef &&other) noexcept
Definition IRCore.h:87
PyOpAdaptor(nanobind::list operands, PyOpAttributeMap attributes)
Definition IRCore.h:2043
PyOpAdaptor(nanobind::list operands, PyOpView &opView)
Definition IRCore.h:2045
Sliceable< PyOpOperandList, PyValue > SliceableT
Definition IRCore.h:1896
static constexpr std::array< const char *, 1 > typeParams
Definition IRCore.h:1895
PyOpOperandList(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:2255
void dunderSetItem(intptr_t index, PyValue value)
Definition IRCore.cpp:2263
Sliceable< PyOpResultList, PyOpResult > SliceableT
Definition IRCore.h:1819
static constexpr std::array< const char *, 1 > typeParams
Definition IRCore.h:1818
PyOpResultList(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:1417
static constexpr IsAFunctionTy isaFunction
Definition IRCore.h:1803
PyOpSuccessors(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:2327
void dunderSetItem(intptr_t index, PyBlock block)
Definition IRCore.cpp:2335
A PyOpView is equivalent to the C++ "Op" wrappers: these are the basis for providing more instance-sp...
Definition IRCore.h:837
PyOpView(const nanobind::object &operationObject)
Definition IRCore.cpp:1757
PyOperation & getOperation() override
Each must provide access to the raw Operation.
Definition IRCore.h:840
Base class for PyOperation and PyOpView which exposes the primary, user visible methods for manipulat...
Definition IRCore.h:672
bool isBeforeInBlock(PyOperationBase &other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
Definition IRCore.cpp:1165
bool isProperAncestor(PyOperationBase &other)
Return whether the current operation is a proper ancestor of 'other', i.e., whether it contains 'othe...
Definition IRCore.cpp:1181
nanobind::object getAsm(bool binary, std::optional< int64_t > largeElementsLimit, std::optional< int64_t > largeResourceLimit, bool enableDebugInfo, bool prettyDebugInfo, bool printGenericOpForm, bool useLocalScope, bool useNameLocAsPrefix, bool assumeVerified, bool skipRegions)
Definition IRCore.cpp:1119
void writeBytecode(const nanobind::object &fileObject, std::optional< int64_t > bytecodeVersion)
Definition IRCore.cpp:1066
bool isAncestor(PyOperationBase &other)
Return whether the current operation is an ancestor of 'other', i.e., whether it contains 'other' or ...
Definition IRCore.cpp:1173
virtual PyOperation & getOperation()=0
Each must provide access to the raw Operation.
void moveAfter(PyOperationBase &other)
Moves the operation before or after the other operation.
Definition IRCore.cpp:1147
void walk(std::function< PyWalkResult(MlirOperation)> callback, PyWalkOrder walkOrder)
Definition IRCore.cpp:1087
PyOperationIterator(PyOperationRef parentOperation, MlirOperation next)
Definition IRCore.h:1662
PyOperationList(PyOperationRef parentOperation, MlirBlock block)
Definition IRCore.h:1682
void setInvalid()
Invalidate the operation.
Definition IRCore.h:804
PyOperation & getOperation() override
Each must provide access to the raw Operation.
Definition IRCore.h:737
PyOperation(PyMlirContextRef contextRef, MlirOperation operation)
Definition IRCore.cpp:916
PyRegionList(PyOperationRef operation, intptr_t startIndex=0, intptr_t length=-1, intptr_t step=1)
Definition IRCore.cpp:194
PyRegion(PyOperationRef parentOperation, MlirRegion region)
Definition IRCore.h:875
static constexpr GetTypeIDFunctionTy getTypeIdFunction
Definition IRCore.h:1250
PySymbolTable(PyOperationBase &operation)
Constructs a symbol table for the given operation.
Definition IRCore.cpp:2040
Tracks an entry in the thread context stack.
Definition IRCore.h:138
PyThreadContextEntry(FrameKind frameKind, nanobind::object context, nanobind::object insertionPoint, nanobind::object location)
Definition IRCore.h:146
A TypeID provides an efficient and unique identifier for a specific C++ type.
Definition IRCore.h:1003
Wrapper around the generic MlirType.
Definition IRCore.h:977
PyType(PyMlirContextRef contextRef, MlirType type)
Definition IRCore.h:979
nanobind::typed< nanobind::object, PyType > maybeDownCast()
Definition IRCore.cpp:1952
static constexpr GetTypeIDFunctionTy getTypeIdFunction
Definition IRCore.h:1328
PyValue(PyOperationRef parentOperation, MlirValue value)
Definition IRCore.h:1396
Safely calls Python initialization code on first use, avoiding deadlocks.
MlirDiagnosticSeverity
Severity of a diagnostic.
Definition Diagnostics.h:32
@ MlirDiagnosticNote
Definition Diagnostics.h:35
@ MlirDiagnosticRemark
Definition Diagnostics.h:36
@ MlirDiagnosticWarning
Definition Diagnostics.h:34
@ MlirDiagnosticError
Definition Diagnostics.h:33
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.
Definition Diagnostics.h:41
MLIR_CAPI_EXPORTED MlirTypeID mlirStringAttrGetTypeID(void)
Returns the typeID of a String attribute.
MLIR_CAPI_EXPORTED bool mlirAttributeIsAString(MlirAttribute attr)
Checks whether the given attribute is a string attribute.
MLIR_CAPI_EXPORTED MlirStringRef mlirStringAttrGetName(void)
@ MlirWalkPreOrder
Definition IR.h:929
@ MlirWalkPostOrder
Definition IR.h:930
MLIR_CAPI_EXPORTED bool mlirLocationIsAUnknown(MlirLocation location)
Checks whether the given location is an Unknown.
Definition IR.cpp:428
MLIR_CAPI_EXPORTED MlirTypeID mlirLocationUnknownGetTypeID(void)
TypeID Getter for Unknown.
Definition IR.cpp:424
MLIR_CAPI_EXPORTED void mlirDialectRegistryDestroy(MlirDialectRegistry registry)
Takes a dialect registry owned by the caller and destroys it.
Definition IR.cpp:166
MLIR_CAPI_EXPORTED bool mlirLocationIsAFileLineColRange(MlirLocation location)
Checks whether the given location is an FileLineColRange.
Definition IR.cpp:338
MLIR_CAPI_EXPORTED void mlirAttributePrint(MlirAttribute attr, MlirStringCallback callback, void *userData)
Prints a location by sending chunks of the string representation and forwarding userData to callback`...
Definition IR.cpp:1385
@ MlirWalkResultInterrupt
Definition IR.h:923
@ MlirWalkResultSkip
Definition IR.h:924
@ MlirWalkResultAdvance
Definition IR.h:922
MLIR_CAPI_EXPORTED bool mlirLocationIsACallSite(MlirLocation location)
Checks whether the given location is an CallSite.
Definition IR.cpp:360
static bool mlirBlockIsNull(MlirBlock block)
Checks whether a block is null.
Definition IR.h:1021
MLIR_CAPI_EXPORTED bool mlirLocationIsAFused(MlirLocation location)
Checks whether the given location is an Fused.
Definition IR.cpp:392
MLIR_CAPI_EXPORTED void mlirSymbolTableDestroy(MlirSymbolTable symbolTable)
Destroys the symbol table created with mlirSymbolTableCreate.
Definition IR.cpp:1439
MLIR_CAPI_EXPORTED bool mlirLocationIsAName(MlirLocation location)
Checks whether the given location is an Name.
Definition IR.cpp:416
static bool mlirDialectRegistryIsNull(MlirDialectRegistry registry)
Checks if the dialect registry is null.
Definition IR.h:266
MLIR_CAPI_EXPORTED MlirTypeID mlirLocationFileLineColRangeGetTypeID(void)
TypeID Getter for FileLineColRange.
Definition IR.cpp:334
static bool mlirRegionIsNull(MlirRegion region)
Checks whether a region is null.
Definition IR.h:960
MLIR_CAPI_EXPORTED MlirTypeID mlirLocationCallSiteGetTypeID(void)
TypeID Getter for CallSite.
Definition IR.cpp:356
MLIR_CAPI_EXPORTED MlirDialectRegistry mlirDialectRegistryCreate(void)
Creates a dialect registry and transfers its ownership to the caller.
Definition IR.cpp:162
MLIR_CAPI_EXPORTED MlirTypeID mlirLocationNameGetTypeID(void)
TypeID Getter for Name.
Definition IR.cpp:414
MLIR_CAPI_EXPORTED MlirTypeID mlirLocationFusedGetTypeID(void)
TypeID Getter for Fused.
Definition IR.cpp:390
MLIR_CAPI_EXPORTED void mlirValuePrint(MlirValue value, MlirStringCallback callback, void *userData)
Prints a block by sending chunks of the string representation and forwarding userData to callback`.
Definition IR.cpp:1230
@ MlirRemarkFileFormatBitstream
Definition Remarks.h:64
@ MlirRemarkFileFormatYAML
Definition Remarks.h:63
@ MlirRemarkPolicyFinal
Postpone remarks and report the final set when the engine is finalized, grouping related remarks unde...
Definition Remarks.h:57
@ MlirRemarkPolicyAll
Report every remark as it is emitted.
Definition Remarks.h:54
@ MlirRemarkKindFailure
The optimization was attempted but failed.
Definition Remarks.h:45
@ MlirRemarkKindAnalysis
Informational context without a pass/fail outcome.
Definition Remarks.h:47
@ MlirRemarkKindMissed
A profitable optimization opportunity was found but not applied.
Definition Remarks.h:43
@ MlirRemarkKindUnknown
Definition Remarks.h:39
@ MlirRemarkKindPassed
An optimization was applied.
Definition Remarks.h:41
static MlirStringRef mlirStringRefCreate(const char *str, size_t length)
Constructs a string reference from the pointer and length.
Definition Support.h:87
#define MLIR_PYTHON_API_EXPORTED
Definition Support.h:49
MLIR_PYTHON_API_EXPORTED MlirValue getUniqueResult(MlirOperation operation)
Definition IRCore.cpp:1546
PyOperationEquivalenceFlags
Flags controlling structural operation equivalence and hashing.
Definition IRCore.h:411
MLIR_PYTHON_API_EXPORTED void populateRoot(nanobind::module_ &m)
MLIR_PYTHON_API_EXPORTED void populateIRRemarks(nanobind::module_ &m)
PyObjectRef< PyMlirContext > PyMlirContextRef
Wrapper around MlirContext.
Definition IRCore.h:231
PyObjectRef< PyOperation > PyOperationRef
Definition IRCore.h:732
MlirStringRef toMlirStringRef(const std::string &s)
Definition IRCore.h:1563
PyRemarkKind
The kinds, emitting policies and file formats of the remark engine (mlir-c/Remarks....
Definition IRCore.h:212
PyObjectRef< PyModule > PyModuleRef
Definition IRCore.h:631
MlirBlock MLIR_PYTHON_API_EXPORTED createBlock(const nanobind::typed< nanobind::sequence, PyType > &pyArgTypes, const std::optional< nanobind::typed< nanobind::sequence, PyLocation > > &pyArgLocs)
Create a block, using the current location context if no locations are specified.
PyWalkOrder
Traversal order for operation walk.
Definition IRCore.h:404
MLIR_PYTHON_API_EXPORTED void populateIRCore(nanobind::module_ &m)
nanobind::object classmethod(Func f, Args... args)
Helper for creating an @classmethod.
Definition IRCore.h:2102
Include the generated interface declarations.
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
An opaque reference to a diagnostic, always owned by the diagnostics engine (context).
Definition Diagnostics.h:26
A logical result value, essentially a boolean with named states.
Definition Support.h:121
Named MLIR attribute.
Definition IR.h:77
An opaque reference to a remark.
Definition Remarks.h:32
A pointer to a sized fragment of a string, not necessarily null-terminated.
Definition Support.h:78
Accumulates into a python string from a method that accepts an MlirStringCallback.
MlirStringCallback getCallback()
MLIRError(std::string message, std::vector< PyDiagnostic::DiagnosticInfo > &&errorDiagnostics={})
Definition IRCore.h:1546
std::vector< PyDiagnostic::DiagnosticInfo > errorDiagnostics
Definition IRCore.h:1556
const char * what() const noexcept override
Definition IRCore.h:1550
static bool dunderContains(const std::string &attributeKind)
Definition IRCore.cpp:146
static nanobind::callable dunderGetItemNamed(const std::string &attributeKind)
Definition IRCore.cpp:151
static void dunderSetItemNamed(const std::string &attributeKind, nanobind::callable func, bool replace, bool allow_existing)
Definition IRCore.cpp:158
Wrapper for the global LLVM debugging flag.
Definition IRCore.h:55
static void set(nanobind::object &o, bool enable)
Definition IRCore.cpp:108
std::vector< PyDiagnostic::DiagnosticInfo > take()
Definition IRCore.h:538