1 //===- IRModules.h - IR Submodules of pybind module -----------------------===//
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_IRMODULES_H
10 #define MLIR_BINDINGS_PYTHON_IRMODULES_H
11 
12 #include <utility>
13 #include <vector>
14 
15 #include "PybindUtils.h"
16 
17 #include "mlir-c/AffineExpr.h"
18 #include "mlir-c/AffineMap.h"
19 #include "mlir-c/Diagnostics.h"
20 #include "mlir-c/IR.h"
21 #include "mlir-c/IntegerSet.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/Optional.h"
24 
25 namespace mlir {
26 namespace python {
27 
28 class PyBlock;
29 class PyDiagnostic;
30 class PyDiagnosticHandler;
31 class PyInsertionPoint;
32 class PyLocation;
33 class DefaultingPyLocation;
34 class PyMlirContext;
35 class DefaultingPyMlirContext;
36 class PyModule;
37 class PyOperation;
38 class PyType;
39 class PySymbolTable;
40 class PyValue;
41 
42 /// Template for a reference to a concrete type which captures a python
43 /// reference to its underlying python object.
44 template <typename T>
45 class PyObjectRef {
46 public:
47   PyObjectRef(T *referrent, pybind11::object object)
48       : referrent(referrent), object(std::move(object)) {
49     assert(this->referrent &&
50            "cannot construct PyObjectRef with null referrent");
51     assert(this->object && "cannot construct PyObjectRef with null object");
52   }
53   PyObjectRef(PyObjectRef &&other)
54       : referrent(other.referrent), object(std::move(other.object)) {
55     other.referrent = nullptr;
56     assert(!other.object);
57   }
58   PyObjectRef(const PyObjectRef &other)
59       : referrent(other.referrent), object(other.object /* copies */) {}
60   ~PyObjectRef() = default;
61 
62   int getRefCount() {
63     if (!object)
64       return 0;
65     return object.ref_count();
66   }
67 
68   /// Releases the object held by this instance, returning it.
69   /// This is the proper thing to return from a function that wants to return
70   /// the reference. Note that this does not work from initializers.
71   pybind11::object releaseObject() {
72     assert(referrent && object);
73     referrent = nullptr;
74     auto stolen = std::move(object);
75     return stolen;
76   }
77 
78   T *get() { return referrent; }
79   T *operator->() {
80     assert(referrent && object);
81     return referrent;
82   }
83   pybind11::object getObject() {
84     assert(referrent && object);
85     return object;
86   }
87   operator bool() const { return referrent && object; }
88 
89 private:
90   T *referrent;
91   pybind11::object object;
92 };
93 
94 /// Tracks an entry in the thread context stack. New entries are pushed onto
95 /// here for each with block that activates a new InsertionPoint, Context or
96 /// Location.
97 ///
98 /// Pushing either a Location or InsertionPoint also pushes its associated
99 /// Context. Pushing a Context will not modify the Location or InsertionPoint
100 /// unless if they are from a different context, in which case, they are
101 /// cleared.
102 class PyThreadContextEntry {
103 public:
104   enum class FrameKind {
105     Context,
106     InsertionPoint,
107     Location,
108   };
109 
110   PyThreadContextEntry(FrameKind frameKind, pybind11::object context,
111                        pybind11::object insertionPoint,
112                        pybind11::object location)
113       : context(std::move(context)), insertionPoint(std::move(insertionPoint)),
114         location(std::move(location)), frameKind(frameKind) {}
115 
116   /// Gets the top of stack context and return nullptr if not defined.
117   static PyMlirContext *getDefaultContext();
118 
119   /// Gets the top of stack insertion point and return nullptr if not defined.
120   static PyInsertionPoint *getDefaultInsertionPoint();
121 
122   /// Gets the top of stack location and returns nullptr if not defined.
123   static PyLocation *getDefaultLocation();
124 
125   PyMlirContext *getContext();
126   PyInsertionPoint *getInsertionPoint();
127   PyLocation *getLocation();
128   FrameKind getFrameKind() { return frameKind; }
129 
130   /// Stack management.
131   static PyThreadContextEntry *getTopOfStack();
132   static pybind11::object pushContext(PyMlirContext &context);
133   static void popContext(PyMlirContext &context);
134   static pybind11::object pushInsertionPoint(PyInsertionPoint &insertionPoint);
135   static void popInsertionPoint(PyInsertionPoint &insertionPoint);
136   static pybind11::object pushLocation(PyLocation &location);
137   static void popLocation(PyLocation &location);
138 
139   /// Gets the thread local stack.
140   static std::vector<PyThreadContextEntry> &getStack();
141 
142 private:
143   static void push(FrameKind frameKind, pybind11::object context,
144                    pybind11::object insertionPoint, pybind11::object location);
145 
146   /// An object reference to the PyContext.
147   pybind11::object context;
148   /// An object reference to the current insertion point.
149   pybind11::object insertionPoint;
150   /// An object reference to the current location.
151   pybind11::object location;
152   // The kind of push that was performed.
153   FrameKind frameKind;
154 };
155 
156 /// Wrapper around MlirContext.
157 using PyMlirContextRef = PyObjectRef<PyMlirContext>;
158 class PyMlirContext {
159 public:
160   PyMlirContext() = delete;
161   PyMlirContext(const PyMlirContext &) = delete;
162   PyMlirContext(PyMlirContext &&) = delete;
163 
164   /// For the case of a python __init__ (py::init) method, pybind11 is quite
165   /// strict about needing to return a pointer that is not yet associated to
166   /// an py::object. Since the forContext() method acts like a pool, possibly
167   /// returning a recycled context, it does not satisfy this need. The usual
168   /// way in python to accomplish such a thing is to override __new__, but
169   /// that is also not supported by pybind11. Instead, we use this entry
170   /// point which always constructs a fresh context (which cannot alias an
171   /// existing one because it is fresh).
172   static PyMlirContext *createNewContextForInit();
173 
174   /// Returns a context reference for the singleton PyMlirContext wrapper for
175   /// the given context.
176   static PyMlirContextRef forContext(MlirContext context);
177   ~PyMlirContext();
178 
179   /// Accesses the underlying MlirContext.
180   MlirContext get() { return context; }
181 
182   /// Gets a strong reference to this context, which will ensure it is kept
183   /// alive for the life of the reference.
184   PyMlirContextRef getRef() {
185     return PyMlirContextRef(this, pybind11::cast(this));
186   }
187 
188   /// Gets a capsule wrapping the void* within the MlirContext.
189   pybind11::object getCapsule();
190 
191   /// Creates a PyMlirContext from the MlirContext wrapped by a capsule.
192   /// Note that PyMlirContext instances are uniqued, so the returned object
193   /// may be a pre-existing object. Ownership of the underlying MlirContext
194   /// is taken by calling this function.
195   static pybind11::object createFromCapsule(pybind11::object capsule);
196 
197   /// Gets the count of live context objects. Used for testing.
198   static size_t getLiveCount();
199 
200   /// Gets the count of live operations associated with this context.
201   /// Used for testing.
202   size_t getLiveOperationCount();
203 
204   /// Clears the live operations map, returning the number of entries which were
205   /// invalidated. To be used as a safety mechanism so that API end-users can't
206   /// corrupt by holding references they shouldn't have accessed in the first
207   /// place.
208   size_t clearLiveOperations();
209 
210   /// Gets the count of live modules associated with this context.
211   /// Used for testing.
212   size_t getLiveModuleCount();
213 
214   /// Enter and exit the context manager.
215   pybind11::object contextEnter();
216   void contextExit(const pybind11::object &excType,
217                    const pybind11::object &excVal,
218                    const pybind11::object &excTb);
219 
220   /// Attaches a Python callback as a diagnostic handler, returning a
221   /// registration object (internally a PyDiagnosticHandler).
222   pybind11::object attachDiagnosticHandler(pybind11::object callback);
223 
224 private:
225   PyMlirContext(MlirContext context);
226   // Interns the mapping of live MlirContext::ptr to PyMlirContext instances,
227   // preserving the relationship that an MlirContext maps to a single
228   // PyMlirContext wrapper. This could be replaced in the future with an
229   // extension mechanism on the MlirContext for stashing user pointers.
230   // Note that this holds a handle, which does not imply ownership.
231   // Mappings will be removed when the context is destructed.
232   using LiveContextMap = llvm::DenseMap<void *, PyMlirContext *>;
233   static LiveContextMap &getLiveContexts();
234 
235   // Interns all live modules associated with this context. Modules tracked
236   // in this map are valid. When a module is invalidated, it is removed
237   // from this map, and while it still exists as an instance, any
238   // attempt to access it will raise an error.
239   using LiveModuleMap =
240       llvm::DenseMap<const void *, std::pair<pybind11::handle, PyModule *>>;
241   LiveModuleMap liveModules;
242 
243   // Interns all live operations associated with this context. Operations
244   // tracked in this map are valid. When an operation is invalidated, it is
245   // removed from this map, and while it still exists as an instance, any
246   // attempt to access it will raise an error.
247   using LiveOperationMap =
248       llvm::DenseMap<void *, std::pair<pybind11::handle, PyOperation *>>;
249   LiveOperationMap liveOperations;
250 
251   MlirContext context;
252   friend class PyModule;
253   friend class PyOperation;
254 };
255 
256 /// Used in function arguments when None should resolve to the current context
257 /// manager set instance.
258 class DefaultingPyMlirContext
259     : public Defaulting<DefaultingPyMlirContext, PyMlirContext> {
260 public:
261   using Defaulting::Defaulting;
262   static constexpr const char kTypeDescription[] = "mlir.ir.Context";
263   static PyMlirContext &resolve();
264 };
265 
266 /// Base class for all objects that directly or indirectly depend on an
267 /// MlirContext. The lifetime of the context will extend at least to the
268 /// lifetime of these instances.
269 /// Immutable objects that depend on a context extend this directly.
270 class BaseContextObject {
271 public:
272   BaseContextObject(PyMlirContextRef ref) : contextRef(std::move(ref)) {
273     assert(this->contextRef &&
274            "context object constructed with null context ref");
275   }
276 
277   /// Accesses the context reference.
278   PyMlirContextRef &getContext() { return contextRef; }
279 
280 private:
281   PyMlirContextRef contextRef;
282 };
283 
284 /// Python class mirroring the C MlirDiagnostic struct. Note that these structs
285 /// are only valid for the duration of a diagnostic callback and attempting
286 /// to access them outside of that will raise an exception. This applies to
287 /// nested diagnostics (in the notes) as well.
288 class PyDiagnostic {
289 public:
290   PyDiagnostic(MlirDiagnostic diagnostic) : diagnostic(diagnostic) {}
291   void invalidate();
292   bool isValid() { return valid; }
293   MlirDiagnosticSeverity getSeverity();
294   PyLocation getLocation();
295   pybind11::str getMessage();
296   pybind11::tuple getNotes();
297 
298 private:
299   MlirDiagnostic diagnostic;
300 
301   void checkValid();
302   /// If notes have been materialized from the diagnostic, then this will
303   /// be populated with the corresponding objects (all castable to
304   /// PyDiagnostic).
305   llvm::Optional<pybind11::tuple> materializedNotes;
306   bool valid = true;
307 };
308 
309 /// Represents a diagnostic handler attached to the context. The handler's
310 /// callback will be invoked with PyDiagnostic instances until the detach()
311 /// method is called or the context is destroyed. A diagnostic handler can be
312 /// the subject of a `with` block, which will detach it when the block exits.
313 ///
314 /// Since diagnostic handlers can call back into Python code which can do
315 /// unsafe things (i.e. recursively emitting diagnostics, raising exceptions,
316 /// etc), this is generally not deemed to be a great user-level API. Users
317 /// should generally use some form of DiagnosticCollector. If the handler raises
318 /// any exceptions, they will just be emitted to stderr and dropped.
319 ///
320 /// The unique usage of this class means that its lifetime management is
321 /// different from most other parts of the API. Instances are always created
322 /// in an attached state and can transition to a detached state by either:
323 ///   a) The context being destroyed and unregistering all handlers.
324 ///   b) An explicit call to detach().
325 /// The object may remain live from a Python perspective for an arbitrary time
326 /// after detachment, but there is nothing the user can do with it (since there
327 /// is no way to attach an existing handler object).
328 class PyDiagnosticHandler {
329 public:
330   PyDiagnosticHandler(MlirContext context, pybind11::object callback);
331   ~PyDiagnosticHandler();
332 
333   bool isAttached() { return registeredID.hasValue(); }
334   bool getHadError() { return hadError; }
335 
336   /// Detaches the handler. Does nothing if not attached.
337   void detach();
338 
339   pybind11::object contextEnter() { return pybind11::cast(this); }
340   void contextExit(const pybind11::object &excType,
341                    const pybind11::object &excVal,
342                    const pybind11::object &excTb) {
343     detach();
344   }
345 
346 private:
347   MlirContext context;
348   pybind11::object callback;
349   llvm::Optional<MlirDiagnosticHandlerID> registeredID;
350   bool hadError = false;
351   friend class PyMlirContext;
352 };
353 
354 /// Wrapper around an MlirDialect. This is exported as `DialectDescriptor` in
355 /// order to differentiate it from the `Dialect` base class which is extended by
356 /// plugins which extend dialect functionality through extension python code.
357 /// This should be seen as the "low-level" object and `Dialect` as the
358 /// high-level, user facing object.
359 class PyDialectDescriptor : public BaseContextObject {
360 public:
361   PyDialectDescriptor(PyMlirContextRef contextRef, MlirDialect dialect)
362       : BaseContextObject(std::move(contextRef)), dialect(dialect) {}
363 
364   MlirDialect get() { return dialect; }
365 
366 private:
367   MlirDialect dialect;
368 };
369 
370 /// User-level object for accessing dialects with dotted syntax such as:
371 ///   ctx.dialect.std
372 class PyDialects : public BaseContextObject {
373 public:
374   PyDialects(PyMlirContextRef contextRef)
375       : BaseContextObject(std::move(contextRef)) {}
376 
377   MlirDialect getDialectForKey(const std::string &key, bool attrError);
378 };
379 
380 /// User-level dialect object. For dialects that have a registered extension,
381 /// this will be the base class of the extension dialect type. For un-extended,
382 /// objects of this type will be returned directly.
383 class PyDialect {
384 public:
385   PyDialect(pybind11::object descriptor) : descriptor(std::move(descriptor)) {}
386 
387   pybind11::object getDescriptor() { return descriptor; }
388 
389 private:
390   pybind11::object descriptor;
391 };
392 
393 /// Wrapper around an MlirLocation.
394 class PyLocation : public BaseContextObject {
395 public:
396   PyLocation(PyMlirContextRef contextRef, MlirLocation loc)
397       : BaseContextObject(std::move(contextRef)), loc(loc) {}
398 
399   operator MlirLocation() const { return loc; }
400   MlirLocation get() const { return loc; }
401 
402   /// Enter and exit the context manager.
403   pybind11::object contextEnter();
404   void contextExit(const pybind11::object &excType,
405                    const pybind11::object &excVal,
406                    const pybind11::object &excTb);
407 
408   /// Gets a capsule wrapping the void* within the MlirLocation.
409   pybind11::object getCapsule();
410 
411   /// Creates a PyLocation from the MlirLocation wrapped by a capsule.
412   /// Note that PyLocation instances are uniqued, so the returned object
413   /// may be a pre-existing object. Ownership of the underlying MlirLocation
414   /// is taken by calling this function.
415   static PyLocation createFromCapsule(pybind11::object capsule);
416 
417 private:
418   MlirLocation loc;
419 };
420 
421 /// Used in function arguments when None should resolve to the current context
422 /// manager set instance.
423 class DefaultingPyLocation
424     : public Defaulting<DefaultingPyLocation, PyLocation> {
425 public:
426   using Defaulting::Defaulting;
427   static constexpr const char kTypeDescription[] = "mlir.ir.Location";
428   static PyLocation &resolve();
429 
430   operator MlirLocation() const { return *get(); }
431 };
432 
433 /// Wrapper around MlirModule.
434 /// This is the top-level, user-owned object that contains regions/ops/blocks.
435 class PyModule;
436 using PyModuleRef = PyObjectRef<PyModule>;
437 class PyModule : public BaseContextObject {
438 public:
439   /// Returns a PyModule reference for the given MlirModule. This may return
440   /// a pre-existing or new object.
441   static PyModuleRef forModule(MlirModule module);
442   PyModule(PyModule &) = delete;
443   PyModule(PyMlirContext &&) = delete;
444   ~PyModule();
445 
446   /// Gets the backing MlirModule.
447   MlirModule get() { return module; }
448 
449   /// Gets a strong reference to this module.
450   PyModuleRef getRef() {
451     return PyModuleRef(this,
452                        pybind11::reinterpret_borrow<pybind11::object>(handle));
453   }
454 
455   /// Gets a capsule wrapping the void* within the MlirModule.
456   /// Note that the module does not (yet) provide a corresponding factory for
457   /// constructing from a capsule as that would require uniquing PyModule
458   /// instances, which is not currently done.
459   pybind11::object getCapsule();
460 
461   /// Creates a PyModule from the MlirModule wrapped by a capsule.
462   /// Note that PyModule instances are uniqued, so the returned object
463   /// may be a pre-existing object. Ownership of the underlying MlirModule
464   /// is taken by calling this function.
465   static pybind11::object createFromCapsule(pybind11::object capsule);
466 
467 private:
468   PyModule(PyMlirContextRef contextRef, MlirModule module);
469   MlirModule module;
470   pybind11::handle handle;
471 };
472 
473 /// Base class for PyOperation and PyOpView which exposes the primary, user
474 /// visible methods for manipulating it.
475 class PyOperationBase {
476 public:
477   virtual ~PyOperationBase() = default;
478   /// Implements the bound 'print' method and helps with others.
479   void print(pybind11::object fileObject, bool binary,
480              llvm::Optional<int64_t> largeElementsLimit, bool enableDebugInfo,
481              bool prettyDebugInfo, bool printGenericOpForm, bool useLocalScope,
482              bool assumeVerified);
483   pybind11::object getAsm(bool binary,
484                           llvm::Optional<int64_t> largeElementsLimit,
485                           bool enableDebugInfo, bool prettyDebugInfo,
486                           bool printGenericOpForm, bool useLocalScope,
487                           bool assumeVerified);
488 
489   /// Moves the operation before or after the other operation.
490   void moveAfter(PyOperationBase &other);
491   void moveBefore(PyOperationBase &other);
492 
493   /// Each must provide access to the raw Operation.
494   virtual PyOperation &getOperation() = 0;
495 };
496 
497 /// Wrapper around PyOperation.
498 /// Operations exist in either an attached (dependent) or detached (top-level)
499 /// state. In the detached state (as on creation), an operation is owned by
500 /// the creator and its lifetime extends either until its reference count
501 /// drops to zero or it is attached to a parent, at which point its lifetime
502 /// is bounded by its top-level parent reference.
503 class PyOperation;
504 using PyOperationRef = PyObjectRef<PyOperation>;
505 class PyOperation : public PyOperationBase, public BaseContextObject {
506 public:
507   ~PyOperation() override;
508   PyOperation &getOperation() override { return *this; }
509 
510   /// Returns a PyOperation for the given MlirOperation, optionally associating
511   /// it with a parentKeepAlive.
512   static PyOperationRef
513   forOperation(PyMlirContextRef contextRef, MlirOperation operation,
514                pybind11::object parentKeepAlive = pybind11::object());
515 
516   /// Creates a detached operation. The operation must not be associated with
517   /// any existing live operation.
518   static PyOperationRef
519   createDetached(PyMlirContextRef contextRef, MlirOperation operation,
520                  pybind11::object parentKeepAlive = pybind11::object());
521 
522   /// Detaches the operation from its parent block and updates its state
523   /// accordingly.
524   void detachFromParent() {
525     mlirOperationRemoveFromParent(getOperation());
526     setDetached();
527     parentKeepAlive = pybind11::object();
528   }
529 
530   /// Gets the backing operation.
531   operator MlirOperation() const { return get(); }
532   MlirOperation get() const {
533     checkValid();
534     return operation;
535   }
536 
537   PyOperationRef getRef() {
538     return PyOperationRef(
539         this, pybind11::reinterpret_borrow<pybind11::object>(handle));
540   }
541 
542   bool isAttached() { return attached; }
543   void setAttached(const pybind11::object &parent = pybind11::object()) {
544     assert(!attached && "operation already attached");
545     attached = true;
546   }
547   void setDetached() {
548     assert(attached && "operation already detached");
549     attached = false;
550   }
551   void checkValid() const;
552 
553   /// Gets the owning block or raises an exception if the operation has no
554   /// owning block.
555   PyBlock getBlock();
556 
557   /// Gets the parent operation or raises an exception if the operation has
558   /// no parent.
559   llvm::Optional<PyOperationRef> getParentOperation();
560 
561   /// Gets a capsule wrapping the void* within the MlirOperation.
562   pybind11::object getCapsule();
563 
564   /// Creates a PyOperation from the MlirOperation wrapped by a capsule.
565   /// Ownership of the underlying MlirOperation is taken by calling this
566   /// function.
567   static pybind11::object createFromCapsule(pybind11::object capsule);
568 
569   /// Creates an operation. See corresponding python docstring.
570   static pybind11::object
571   create(const std::string &name, llvm::Optional<std::vector<PyType *>> results,
572          llvm::Optional<std::vector<PyValue *>> operands,
573          llvm::Optional<pybind11::dict> attributes,
574          llvm::Optional<std::vector<PyBlock *>> successors, int regions,
575          DefaultingPyLocation location, const pybind11::object &ip);
576 
577   /// Creates an OpView suitable for this operation.
578   pybind11::object createOpView();
579 
580   /// Erases the underlying MlirOperation, removes its pointer from the
581   /// parent context's live operations map, and sets the valid bit false.
582   void erase();
583 
584   /// Invalidate the operation.
585   void setInvalid() { valid = false; }
586 
587   /// Clones this operation.
588   pybind11::object clone(const pybind11::object &ip);
589 
590 private:
591   PyOperation(PyMlirContextRef contextRef, MlirOperation operation);
592   static PyOperationRef createInstance(PyMlirContextRef contextRef,
593                                        MlirOperation operation,
594                                        pybind11::object parentKeepAlive);
595 
596   MlirOperation operation;
597   pybind11::handle handle;
598   // Keeps the parent alive, regardless of whether it is an Operation or
599   // Module.
600   // TODO: As implemented, this facility is only sufficient for modeling the
601   // trivial module parent back-reference. Generalize this to also account for
602   // transitions from detached to attached and address TODOs in the
603   // ir_operation.py regarding testing corresponding lifetime guarantees.
604   pybind11::object parentKeepAlive;
605   bool attached = true;
606   bool valid = true;
607 
608   friend class PyOperationBase;
609   friend class PySymbolTable;
610 };
611 
612 /// A PyOpView is equivalent to the C++ "Op" wrappers: these are the basis for
613 /// providing more instance-specific accessors and serve as the base class for
614 /// custom ODS-style operation classes. Since this class is subclass on the
615 /// python side, it must present an __init__ method that operates in pure
616 /// python types.
617 class PyOpView : public PyOperationBase {
618 public:
619   PyOpView(const pybind11::object &operationObject);
620   PyOperation &getOperation() override { return operation; }
621 
622   static pybind11::object createRawSubclass(const pybind11::object &userClass);
623 
624   pybind11::object getOperationObject() { return operationObject; }
625 
626   static pybind11::object
627   buildGeneric(const pybind11::object &cls, pybind11::list resultTypeList,
628                pybind11::list operandList,
629                llvm::Optional<pybind11::dict> attributes,
630                llvm::Optional<std::vector<PyBlock *>> successors,
631                llvm::Optional<int> regions, DefaultingPyLocation location,
632                const pybind11::object &maybeIp);
633 
634 private:
635   PyOperation &operation;           // For efficient, cast-free access from C++
636   pybind11::object operationObject; // Holds the reference.
637 };
638 
639 /// Wrapper around an MlirRegion.
640 /// Regions are managed completely by their containing operation. Unlike the
641 /// C++ API, the python API does not support detached regions.
642 class PyRegion {
643 public:
644   PyRegion(PyOperationRef parentOperation, MlirRegion region)
645       : parentOperation(std::move(parentOperation)), region(region) {
646     assert(!mlirRegionIsNull(region) && "python region cannot be null");
647   }
648   operator MlirRegion() const { return region; }
649 
650   MlirRegion get() { return region; }
651   PyOperationRef &getParentOperation() { return parentOperation; }
652 
653   void checkValid() { return parentOperation->checkValid(); }
654 
655 private:
656   PyOperationRef parentOperation;
657   MlirRegion region;
658 };
659 
660 /// Wrapper around an MlirBlock.
661 /// Blocks are managed completely by their containing operation. Unlike the
662 /// C++ API, the python API does not support detached blocks.
663 class PyBlock {
664 public:
665   PyBlock(PyOperationRef parentOperation, MlirBlock block)
666       : parentOperation(std::move(parentOperation)), block(block) {
667     assert(!mlirBlockIsNull(block) && "python block cannot be null");
668   }
669 
670   MlirBlock get() { return block; }
671   PyOperationRef &getParentOperation() { return parentOperation; }
672 
673   void checkValid() { return parentOperation->checkValid(); }
674 
675 private:
676   PyOperationRef parentOperation;
677   MlirBlock block;
678 };
679 
680 /// An insertion point maintains a pointer to a Block and a reference operation.
681 /// Calls to insert() will insert a new operation before the
682 /// reference operation. If the reference operation is null, then appends to
683 /// the end of the block.
684 class PyInsertionPoint {
685 public:
686   /// Creates an insertion point positioned after the last operation in the
687   /// block, but still inside the block.
688   PyInsertionPoint(PyBlock &block);
689   /// Creates an insertion point positioned before a reference operation.
690   PyInsertionPoint(PyOperationBase &beforeOperationBase);
691 
692   /// Shortcut to create an insertion point at the beginning of the block.
693   static PyInsertionPoint atBlockBegin(PyBlock &block);
694   /// Shortcut to create an insertion point before the block terminator.
695   static PyInsertionPoint atBlockTerminator(PyBlock &block);
696 
697   /// Inserts an operation.
698   void insert(PyOperationBase &operationBase);
699 
700   /// Enter and exit the context manager.
701   pybind11::object contextEnter();
702   void contextExit(const pybind11::object &excType,
703                    const pybind11::object &excVal,
704                    const pybind11::object &excTb);
705 
706   PyBlock &getBlock() { return block; }
707 
708 private:
709   // Trampoline constructor that avoids null initializing members while
710   // looking up parents.
711   PyInsertionPoint(PyBlock block, llvm::Optional<PyOperationRef> refOperation)
712       : refOperation(std::move(refOperation)), block(std::move(block)) {}
713 
714   llvm::Optional<PyOperationRef> refOperation;
715   PyBlock block;
716 };
717 /// Wrapper around the generic MlirType.
718 /// The lifetime of a type is bound by the PyContext that created it.
719 class PyType : public BaseContextObject {
720 public:
721   PyType(PyMlirContextRef contextRef, MlirType type)
722       : BaseContextObject(std::move(contextRef)), type(type) {}
723   bool operator==(const PyType &other);
724   operator MlirType() const { return type; }
725   MlirType get() const { return type; }
726 
727   /// Gets a capsule wrapping the void* within the MlirType.
728   pybind11::object getCapsule();
729 
730   /// Creates a PyType from the MlirType wrapped by a capsule.
731   /// Note that PyType instances are uniqued, so the returned object
732   /// may be a pre-existing object. Ownership of the underlying MlirType
733   /// is taken by calling this function.
734   static PyType createFromCapsule(pybind11::object capsule);
735 
736 private:
737   MlirType type;
738 };
739 
740 /// CRTP base classes for Python types that subclass Type and should be
741 /// castable from it (i.e. via something like IntegerType(t)).
742 /// By default, type class hierarchies are one level deep (i.e. a
743 /// concrete type class extends PyType); however, intermediate python-visible
744 /// base classes can be modeled by specifying a BaseTy.
745 template <typename DerivedTy, typename BaseTy = PyType>
746 class PyConcreteType : public BaseTy {
747 public:
748   // Derived classes must define statics for:
749   //   IsAFunctionTy isaFunction
750   //   const char *pyClassName
751   using ClassTy = pybind11::class_<DerivedTy, BaseTy>;
752   using IsAFunctionTy = bool (*)(MlirType);
753 
754   PyConcreteType() = default;
755   PyConcreteType(PyMlirContextRef contextRef, MlirType t)
756       : BaseTy(std::move(contextRef), t) {}
757   PyConcreteType(PyType &orig)
758       : PyConcreteType(orig.getContext(), castFrom(orig)) {}
759 
760   static MlirType castFrom(PyType &orig) {
761     if (!DerivedTy::isaFunction(orig)) {
762       auto origRepr = pybind11::repr(pybind11::cast(orig)).cast<std::string>();
763       throw SetPyError(PyExc_ValueError, llvm::Twine("Cannot cast type to ") +
764                                              DerivedTy::pyClassName +
765                                              " (from " + origRepr + ")");
766     }
767     return orig;
768   }
769 
770   static void bind(pybind11::module &m) {
771     auto cls = ClassTy(m, DerivedTy::pyClassName, pybind11::module_local());
772     cls.def(pybind11::init<PyType &>(), pybind11::keep_alive<0, 1>(),
773             pybind11::arg("cast_from_type"));
774     cls.def_static(
775         "isinstance",
776         [](PyType &otherType) -> bool {
777           return DerivedTy::isaFunction(otherType);
778         },
779         pybind11::arg("other"));
780     DerivedTy::bindDerived(cls);
781   }
782 
783   /// Implemented by derived classes to add methods to the Python subclass.
784   static void bindDerived(ClassTy &m) {}
785 };
786 
787 /// Wrapper around the generic MlirAttribute.
788 /// The lifetime of a type is bound by the PyContext that created it.
789 class PyAttribute : public BaseContextObject {
790 public:
791   PyAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
792       : BaseContextObject(std::move(contextRef)), attr(attr) {}
793   bool operator==(const PyAttribute &other);
794   operator MlirAttribute() const { return attr; }
795   MlirAttribute get() const { return attr; }
796 
797   /// Gets a capsule wrapping the void* within the MlirAttribute.
798   pybind11::object getCapsule();
799 
800   /// Creates a PyAttribute from the MlirAttribute wrapped by a capsule.
801   /// Note that PyAttribute instances are uniqued, so the returned object
802   /// may be a pre-existing object. Ownership of the underlying MlirAttribute
803   /// is taken by calling this function.
804   static PyAttribute createFromCapsule(pybind11::object capsule);
805 
806 private:
807   MlirAttribute attr;
808 };
809 
810 /// Represents a Python MlirNamedAttr, carrying an optional owned name.
811 /// TODO: Refactor this and the C-API to be based on an Identifier owned
812 /// by the context so as to avoid ownership issues here.
813 class PyNamedAttribute {
814 public:
815   /// Constructs a PyNamedAttr that retains an owned name. This should be
816   /// used in any code that originates an MlirNamedAttribute from a python
817   /// string.
818   /// The lifetime of the PyNamedAttr must extend to the lifetime of the
819   /// passed attribute.
820   PyNamedAttribute(MlirAttribute attr, std::string ownedName);
821 
822   MlirNamedAttribute namedAttr;
823 
824 private:
825   // Since the MlirNamedAttr contains an internal pointer to the actual
826   // memory of the owned string, it must be heap allocated to remain valid.
827   // Otherwise, strings that fit within the small object optimization threshold
828   // will have their memory address change as the containing object is moved,
829   // resulting in an invalid aliased pointer.
830   std::unique_ptr<std::string> ownedName;
831 };
832 
833 /// CRTP base classes for Python attributes that subclass Attribute and should
834 /// be castable from it (i.e. via something like StringAttr(attr)).
835 /// By default, attribute class hierarchies are one level deep (i.e. a
836 /// concrete attribute class extends PyAttribute); however, intermediate
837 /// python-visible base classes can be modeled by specifying a BaseTy.
838 template <typename DerivedTy, typename BaseTy = PyAttribute>
839 class PyConcreteAttribute : public BaseTy {
840 public:
841   // Derived classes must define statics for:
842   //   IsAFunctionTy isaFunction
843   //   const char *pyClassName
844   using ClassTy = pybind11::class_<DerivedTy, BaseTy>;
845   using IsAFunctionTy = bool (*)(MlirAttribute);
846 
847   PyConcreteAttribute() = default;
848   PyConcreteAttribute(PyMlirContextRef contextRef, MlirAttribute attr)
849       : BaseTy(std::move(contextRef), attr) {}
850   PyConcreteAttribute(PyAttribute &orig)
851       : PyConcreteAttribute(orig.getContext(), castFrom(orig)) {}
852 
853   static MlirAttribute castFrom(PyAttribute &orig) {
854     if (!DerivedTy::isaFunction(orig)) {
855       auto origRepr = pybind11::repr(pybind11::cast(orig)).cast<std::string>();
856       throw SetPyError(PyExc_ValueError,
857                        llvm::Twine("Cannot cast attribute to ") +
858                            DerivedTy::pyClassName + " (from " + origRepr + ")");
859     }
860     return orig;
861   }
862 
863   static void bind(pybind11::module &m) {
864     auto cls = ClassTy(m, DerivedTy::pyClassName, pybind11::buffer_protocol(),
865                        pybind11::module_local());
866     cls.def(pybind11::init<PyAttribute &>(), pybind11::keep_alive<0, 1>(),
867             pybind11::arg("cast_from_attr"));
868     cls.def_static(
869         "isinstance",
870         [](PyAttribute &otherAttr) -> bool {
871           return DerivedTy::isaFunction(otherAttr);
872         },
873         pybind11::arg("other"));
874     cls.def_property_readonly("type", [](PyAttribute &attr) {
875       return PyType(attr.getContext(), mlirAttributeGetType(attr));
876     });
877     DerivedTy::bindDerived(cls);
878   }
879 
880   /// Implemented by derived classes to add methods to the Python subclass.
881   static void bindDerived(ClassTy &m) {}
882 };
883 
884 /// Wrapper around the generic MlirValue.
885 /// Values are managed completely by the operation that resulted in their
886 /// definition. For op result value, this is the operation that defines the
887 /// value. For block argument values, this is the operation that contains the
888 /// block to which the value is an argument (blocks cannot be detached in Python
889 /// bindings so such operation always exists).
890 class PyValue {
891 public:
892   PyValue(PyOperationRef parentOperation, MlirValue value)
893       : parentOperation(std::move(parentOperation)), value(value) {}
894   operator MlirValue() const { return value; }
895 
896   MlirValue get() { return value; }
897   PyOperationRef &getParentOperation() { return parentOperation; }
898 
899   void checkValid() { return parentOperation->checkValid(); }
900 
901   /// Gets a capsule wrapping the void* within the MlirValue.
902   pybind11::object getCapsule();
903 
904   /// Creates a PyValue from the MlirValue wrapped by a capsule. Ownership of
905   /// the underlying MlirValue is still tied to the owning operation.
906   static PyValue createFromCapsule(pybind11::object capsule);
907 
908 private:
909   PyOperationRef parentOperation;
910   MlirValue value;
911 };
912 
913 /// Wrapper around MlirAffineExpr. Affine expressions are owned by the context.
914 class PyAffineExpr : public BaseContextObject {
915 public:
916   PyAffineExpr(PyMlirContextRef contextRef, MlirAffineExpr affineExpr)
917       : BaseContextObject(std::move(contextRef)), affineExpr(affineExpr) {}
918   bool operator==(const PyAffineExpr &other);
919   operator MlirAffineExpr() const { return affineExpr; }
920   MlirAffineExpr get() const { return affineExpr; }
921 
922   /// Gets a capsule wrapping the void* within the MlirAffineExpr.
923   pybind11::object getCapsule();
924 
925   /// Creates a PyAffineExpr from the MlirAffineExpr wrapped by a capsule.
926   /// Note that PyAffineExpr instances are uniqued, so the returned object
927   /// may be a pre-existing object. Ownership of the underlying MlirAffineExpr
928   /// is taken by calling this function.
929   static PyAffineExpr createFromCapsule(pybind11::object capsule);
930 
931   PyAffineExpr add(const PyAffineExpr &other) const;
932   PyAffineExpr mul(const PyAffineExpr &other) const;
933   PyAffineExpr floorDiv(const PyAffineExpr &other) const;
934   PyAffineExpr ceilDiv(const PyAffineExpr &other) const;
935   PyAffineExpr mod(const PyAffineExpr &other) const;
936 
937 private:
938   MlirAffineExpr affineExpr;
939 };
940 
941 class PyAffineMap : public BaseContextObject {
942 public:
943   PyAffineMap(PyMlirContextRef contextRef, MlirAffineMap affineMap)
944       : BaseContextObject(std::move(contextRef)), affineMap(affineMap) {}
945   bool operator==(const PyAffineMap &other);
946   operator MlirAffineMap() const { return affineMap; }
947   MlirAffineMap get() const { return affineMap; }
948 
949   /// Gets a capsule wrapping the void* within the MlirAffineMap.
950   pybind11::object getCapsule();
951 
952   /// Creates a PyAffineMap from the MlirAffineMap wrapped by a capsule.
953   /// Note that PyAffineMap instances are uniqued, so the returned object
954   /// may be a pre-existing object. Ownership of the underlying MlirAffineMap
955   /// is taken by calling this function.
956   static PyAffineMap createFromCapsule(pybind11::object capsule);
957 
958 private:
959   MlirAffineMap affineMap;
960 };
961 
962 class PyIntegerSet : public BaseContextObject {
963 public:
964   PyIntegerSet(PyMlirContextRef contextRef, MlirIntegerSet integerSet)
965       : BaseContextObject(std::move(contextRef)), integerSet(integerSet) {}
966   bool operator==(const PyIntegerSet &other);
967   operator MlirIntegerSet() const { return integerSet; }
968   MlirIntegerSet get() const { return integerSet; }
969 
970   /// Gets a capsule wrapping the void* within the MlirIntegerSet.
971   pybind11::object getCapsule();
972 
973   /// Creates a PyIntegerSet from the MlirAffineMap wrapped by a capsule.
974   /// Note that PyIntegerSet instances may be uniqued, so the returned object
975   /// may be a pre-existing object. Integer sets are owned by the context.
976   static PyIntegerSet createFromCapsule(pybind11::object capsule);
977 
978 private:
979   MlirIntegerSet integerSet;
980 };
981 
982 /// Bindings for MLIR symbol tables.
983 class PySymbolTable {
984 public:
985   /// Constructs a symbol table for the given operation.
986   explicit PySymbolTable(PyOperationBase &operation);
987 
988   /// Destroys the symbol table.
989   ~PySymbolTable() { mlirSymbolTableDestroy(symbolTable); }
990 
991   /// Returns the symbol (opview) with the given name, throws if there is no
992   /// such symbol in the table.
993   pybind11::object dunderGetItem(const std::string &name);
994 
995   /// Removes the given operation from the symbol table and erases it.
996   void erase(PyOperationBase &symbol);
997 
998   /// Removes the operation with the given name from the symbol table and erases
999   /// it, throws if there is no such symbol in the table.
1000   void dunderDel(const std::string &name);
1001 
1002   /// Inserts the given operation into the symbol table. The operation must have
1003   /// the symbol trait.
1004   PyAttribute insert(PyOperationBase &symbol);
1005 
1006   /// Gets and sets the name of a symbol op.
1007   static PyAttribute getSymbolName(PyOperationBase &symbol);
1008   static void setSymbolName(PyOperationBase &symbol, const std::string &name);
1009 
1010   /// Gets and sets the visibility of a symbol op.
1011   static PyAttribute getVisibility(PyOperationBase &symbol);
1012   static void setVisibility(PyOperationBase &symbol,
1013                             const std::string &visibility);
1014 
1015   /// Replaces all symbol uses within an operation. See the API
1016   /// mlirSymbolTableReplaceAllSymbolUses for all caveats.
1017   static void replaceAllSymbolUses(const std::string &oldSymbol,
1018                                    const std::string &newSymbol,
1019                                    PyOperationBase &from);
1020 
1021   /// Walks all symbol tables under and including 'from'.
1022   static void walkSymbolTables(PyOperationBase &from, bool allSymUsesVisible,
1023                                pybind11::object callback);
1024 
1025   /// Casts the bindings class into the C API structure.
1026   operator MlirSymbolTable() { return symbolTable; }
1027 
1028 private:
1029   PyOperationRef operation;
1030   MlirSymbolTable symbolTable;
1031 };
1032 
1033 void populateIRAffine(pybind11::module &m);
1034 void populateIRAttributes(pybind11::module &m);
1035 void populateIRCore(pybind11::module &m);
1036 void populateIRInterfaces(pybind11::module &m);
1037 void populateIRTypes(pybind11::module &m);
1038 
1039 } // namespace python
1040 } // namespace mlir
1041 
1042 namespace pybind11 {
1043 namespace detail {
1044 
1045 template <>
1046 struct type_caster<mlir::python::DefaultingPyMlirContext>
1047     : MlirDefaultingCaster<mlir::python::DefaultingPyMlirContext> {};
1048 template <>
1049 struct type_caster<mlir::python::DefaultingPyLocation>
1050     : MlirDefaultingCaster<mlir::python::DefaultingPyLocation> {};
1051 
1052 } // namespace detail
1053 } // namespace pybind11
1054 
1055 #endif // MLIR_BINDINGS_PYTHON_IRMODULES_H
1056