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