MLIR 24.0.0git
Operation.h
Go to the documentation of this file.
1//===- Operation.h - MLIR Operation Class -----------------------*- C++ -*-===//
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// This file defines the Operation class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_IR_OPERATION_H
14#define MLIR_IR_OPERATION_H
15
16#include "mlir/IR/Block.h"
18#include "mlir/IR/Diagnostics.h"
20#include "mlir/IR/Region.h"
21#include <optional>
22
23namespace mlir {
24namespace detail {
25/// This is a "tag" used for mapping the properties storage in
26/// llvm::TrailingObjects.
27enum class OpProperties : char {};
28} // namespace detail
29
30/// Operation is the basic unit of execution within MLIR.
31///
32/// The following documentations are recommended to understand this class:
33/// - https://mlir.llvm.org/docs/LangRef/#operations
34/// - https://mlir.llvm.org/docs/Tutorials/UnderstandingTheIRStructure/
35///
36/// An Operation is defined first by its name, which is a unique string. The
37/// name is interpreted so that if it contains a '.' character, the part before
38/// is the dialect name this operation belongs to, and everything that follows
39/// is this operation name within the dialect.
40///
41/// An Operation defines zero or more SSA `Value` that we refer to as the
42/// Operation results. This array of Value is actually stored in memory before
43/// the Operation itself in reverse order. That is for an Operation with 3
44/// results we allocate the following memory layout:
45///
46/// [Result2, Result1, Result0, Operation]
47/// ^ this is where `Operation*` pointer points to.
48///
49/// A consequence of this is that this class must be heap allocated, which is
50/// handled by the various `create` methods. Each result contains:
51/// - one pointer to the first use (see `OpOperand`)
52/// - the type of the SSA Value this result defines.
53/// - the index for this result in the array.
54/// The results are defined as subclass of `ValueImpl`, and more precisely as
55/// the only two subclasses of `OpResultImpl`: `InlineOpResult` and
56/// `OutOfLineOpResult`. The former is used for the first 5 results and the
57/// latter for the subsequent ones. They differ in how they store their index:
58/// the first 5 results only need 3 bits and thus are packed with the Type
59/// pointer, while the subsequent one have an extra `unsigned` value and thus
60/// need more space.
61///
62/// An Operation also has zero or more operands: these are uses of SSA Value,
63/// which can be the results of other operations or Block arguments. Each of
64/// these uses is an instance of `OpOperand`. This optional array is initially
65/// tail allocated with the operation class itself, but can be dynamically moved
66/// out-of-line in a dynamic allocation as needed.
67///
68/// An Operation may optionally contain one or multiple Regions, stored in a
69/// tail allocated array. Each `Region` is a list of Blocks. Each `Block` is
70/// itself a list of Operations. This structure is effectively forming a tree.
71///
72/// Some operations like branches also refer to other Block, in which case they
73/// would have an array of `BlockOperand`.
74///
75/// An Operation may optionally contain a "Properties" object: this is a
76/// pre-defined C++ object with a fixed size. This object is owned by the
77/// operation and deleted with the operation. It can be converted to an
78/// Attribute on demand, or loaded from an Attribute.
79///
80///
81/// Finally an Operation also contain an optional `DictionaryAttr`, a Location,
82/// and a pointer to its parent Block (if any).
83class alignas(8) Operation final
84 : public llvm::ilist_node_with_parent<Operation, Block>,
85 private llvm::TrailingObjects<Operation, detail::OperandStorage,
86 detail::OpProperties, BlockOperand, Region,
87 OpOperand> {
88public:
89 /// Create a new Operation with the specific fields. This constructor
90 /// populates the provided attribute list with default attributes if
91 /// necessary.
92 static Operation *create(Location location, OperationName name,
93 TypeRange resultTypes, ValueRange operands,
94 NamedAttrList &&attributes, PropertyRef properties,
95 BlockRange successors, unsigned numRegions);
96
97 /// Create a new Operation with the specific fields. This constructor uses an
98 /// existing attribute dictionary to avoid uniquing a list of attributes.
99 static Operation *create(Location location, OperationName name,
100 TypeRange resultTypes, ValueRange operands,
101 DictionaryAttr attributes, PropertyRef properties,
102 BlockRange successors, unsigned numRegions);
103
104 /// Create a new Operation from the fields stored in `state`.
105 static Operation *create(const OperationState &state);
106
107 /// Create a new Operation with the specific fields.
108 static Operation *create(Location location, OperationName name,
109 TypeRange resultTypes, ValueRange operands,
110 NamedAttrList &&attributes, PropertyRef properties,
111 BlockRange successors = {},
112 RegionRange regions = {});
113
114 /// The name of an operation is the key identifier for it.
115 OperationName getName() { return name; }
116
117 /// If this operation has a registered operation description, return it.
118 /// Otherwise return std::nullopt.
119 std::optional<RegisteredOperationName> getRegisteredInfo() {
120 return getName().getRegisteredInfo();
121 }
122
123 /// Returns true if this operation has a registered operation description,
124 /// otherwise false.
125 bool isRegistered() { return getName().isRegistered(); }
126
127 /// Remove this operation from its parent block and delete it.
128 void erase();
129
130 /// Remove the operation from its parent block, but don't delete it.
131 void remove();
132
133 /// Class encompassing various options related to cloning an operation. Users
134 /// of this class should pass it to Operation's 'clone' methods.
135 /// Current options include:
136 /// * Whether cloning should recursively traverse into the regions of the
137 /// operation or not.
138 /// * Whether cloning should also clone the operands of the operation.
139 /// * Whether to use different result types or clone them.
141 public:
142 /// Default constructs an option with all flags set to false. That means all
143 /// parts of an operation that may optionally not be cloned, are not cloned.
144 CloneOptions();
145
146 /// Constructs an instance with the options set accordingly.
148 std::optional<SmallVector<Type>> resultTypes);
149
150 /// Returns an instance such that all elements of the operation are cloned.
151 /// This is the default when using the clone method and clones all parts of
152 /// the operation.
153 static CloneOptions all();
154
155 /// Configures whether cloning should traverse into any of the regions of
156 /// the operation. If set to true, the operation's regions are recursively
157 /// cloned. If set to false, cloned operations will have the same number of
158 /// regions, but they will be empty.
159 /// Cloning of nested operations in the operation's regions are currently
160 /// unaffected by other flags.
161 CloneOptions &cloneRegions(bool enable = true);
162
163 /// Returns whether regions of the operation should be cloned as well.
164 bool shouldCloneRegions() const { return cloneRegionsFlag; }
165
166 /// Configures whether operation' operands should be cloned. Otherwise the
167 /// resulting clones will simply have zero operands.
168 CloneOptions &cloneOperands(bool enable = true);
169
170 /// Returns whether operands should be cloned as well.
171 bool shouldCloneOperands() const { return cloneOperandsFlag; }
172
173 /// Configures different result types to use for the cloned operation.
174 /// If an empty optional, the result types are cloned from the original
175 /// operation.
176 CloneOptions &withResultTypes(std::optional<SmallVector<Type>> resultTypes);
177
178 /// Returns true if the results are cloned from the operation.
179 bool shouldCloneResults() const { return !resultTypes.has_value(); }
180
181 /// Returns the result types that should be used for the created operation
182 /// or `defaultResultTypes` if none were set.
183 TypeRange resultTypesOr(TypeRange defaultResultTypes) const {
184 if (resultTypes)
185 return *resultTypes;
186 return defaultResultTypes;
187 }
188
189 private:
190 /// Whether regions should be cloned.
191 bool cloneRegionsFlag : 1;
192 /// Whether operands should be cloned.
193 bool cloneOperandsFlag : 1;
194 /// New result types to use in the cloned operation.
195 std::optional<SmallVector<Type>> resultTypes;
196 };
197
198 /// Create a deep copy of this operation, remapping any operands that use
199 /// values outside of the operation using the map that is provided (leaving
200 /// them alone if no entry is present). Replaces references to cloned
201 /// sub-operations to the corresponding operation that is copied, and adds
202 /// those mappings to the map.
203 /// Optionally, one may configure what parts of the operation to clone using
204 /// the options parameter. If parts of the operation (e.g. results or regions)
205 /// are not cloned, they will not appear in the mapper.
206 ///
207 /// Calling this method from multiple threads is generally safe if through the
208 /// process of cloning no new uses of 'Value's from outside the operation are
209 /// created. Cloning an isolated-from-above operation with no operands, such
210 /// as top level function operations, is therefore always safe. Using the
211 /// mapper, it is possible to avoid adding uses to outside operands by
212 /// remapping them to 'Value's owned by the caller thread.
213 Operation *clone(IRMapping &mapper,
214 const CloneOptions &options = CloneOptions::all());
215 Operation *clone(const CloneOptions &options = CloneOptions::all());
216
217 /// Create a partial copy of this operation without traversing into attached
218 /// regions. The new operation will have the same number of regions as the
219 /// original one, but they will be left empty.
220 /// Operands are remapped using `mapper` (if present), and `mapper` is updated
221 /// to contain the results.
223
224 /// Create a partial copy of this operation without traversing into attached
225 /// regions. The new operation will have the same number of regions as the
226 /// original one, but they will be left empty.
228
229 /// Returns the operation block that contains this operation.
230 Block *getBlock() { return block; }
231
232 /// Return the context this operation is associated with.
233 MLIRContext *getContext() { return location->getContext(); }
234
235 /// Return the dialect this operation is associated with, or nullptr if the
236 /// associated dialect is not loaded.
238
239 /// The source location the operation was defined or derived from.
240 Location getLoc() { return location; }
241
242 /// Set the source location the operation was defined or derived from.
243 void setLoc(Location loc) { location = loc; }
244
245 /// Returns the region to which the instruction belongs. Returns nullptr if
246 /// the instruction is unlinked.
247 Region *getParentRegion() { return block ? block->getParent() : nullptr; }
248
249 /// Returns the closest surrounding operation that contains this operation
250 /// or nullptr if this is a top-level operation.
251 Operation *getParentOp() { return block ? block->getParentOp() : nullptr; }
252
253 /// Return the closest surrounding parent operation that is of type 'OpTy'.
254 template <typename OpTy>
256 auto *op = this;
257 while ((op = op->getParentOp()))
258 if (auto parentOp = dyn_cast<OpTy>(op))
259 return parentOp;
260 return OpTy();
261 }
262 template <typename... OpTy>
263 std::enable_if_t<(sizeof...(OpTy) > 1), Operation *> getParentOfType() {
264 auto *op = this;
265 while ((op = op->getParentOp()))
266 if (isa<OpTy...>(op))
267 return op;
268 return nullptr;
269 }
270
271 /// Returns the closest surrounding parent operation with trait `Trait`.
272 template <template <typename T> class Trait>
273 Operation *getParentWithTrait() {
274 Operation *op = this;
275 while ((op = op->getParentOp()))
276 if (op->hasTrait<Trait>())
277 return op;
278 return nullptr;
279 }
280
281 /// Return true if this operation is a proper ancestor of the `other`
282 /// operation.
283 bool isProperAncestor(Operation *other);
284
285 /// Return true if this operation is an ancestor of the `other` operation. An
286 /// operation is considered as its own ancestor, use `isProperAncestor` to
287 /// avoid this.
288 bool isAncestor(Operation *other) {
289 return this == other || isProperAncestor(other);
290 }
291
292 /// Replace any uses of 'from' with 'to' within this operation.
293 void replaceUsesOfWith(Value from, Value to);
294
295 /// Replace all uses of results of this operation with the provided 'values'.
296 template <typename ValuesT>
297 void replaceAllUsesWith(ValuesT &&values) {
298 getResults().replaceAllUsesWith(std::forward<ValuesT>(values));
299 }
300
301 /// Replace uses of results of this operation with the provided `values` if
302 /// the given callback returns true. Returns whether any uses were replaced.
303 template <typename ValuesT>
304 bool replaceUsesWithIf(ValuesT &&values,
305 function_ref<bool(OpOperand &)> shouldReplace) {
306 return getResults().replaceUsesWithIf(std::forward<ValuesT>(values),
307 shouldReplace);
308 }
309
310 /// Destroys this operation and its subclass data.
311 void destroy();
312
313 /// This drops all operand uses from this operation, which is an essential
314 /// step in breaking cyclic dependencies between references when they are to
315 /// be deleted.
316 void dropAllReferences();
317
318 /// Drop uses of all values defined by this operation or its nested regions.
320
321 /// Unlink this operation from its current block and insert it right before
322 /// `existingOp` which may be in the same or another block in the same
323 /// function.
324 void moveBefore(Operation *existingOp);
325
326 /// Unlink this operation from its current block and insert it right before
327 /// `iterator` in the specified block.
328 void moveBefore(Block *block, llvm::iplist<Operation>::iterator iterator);
329
330 /// Unlink this operation from its current block and insert it right after
331 /// `existingOp` which may be in the same or another block in the same
332 /// function.
333 void moveAfter(Operation *existingOp);
334
335 /// Unlink this operation from its current block and insert it right after
336 /// `iterator` in the specified block.
337 void moveAfter(Block *block, llvm::iplist<Operation>::iterator iterator);
338
339 /// Given an operation 'other' that is within the same parent block, return
340 /// whether the current operation is before 'other' in the operation list
341 /// of the parent block.
342 /// Note: This function has an average complexity of O(1), but worst case may
343 /// take O(N) where N is the number of operations within the parent block.
344 bool isBeforeInBlock(Operation *other);
345
346 void print(raw_ostream &os, const OpPrintingFlags &flags = {});
347 void print(raw_ostream &os, AsmState &state);
348#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
349 LLVM_DUMP_METHOD void dump();
350#endif
351
352 // Dump pretty printed IR. This method is helpful for better readability if
353 // the Operation is not verified because it won't disable custom printers to
354 // fall back to the generic one.
355 LLVM_DUMP_METHOD void dumpPretty();
356
357 //===--------------------------------------------------------------------===//
358 // Operands
359 //===--------------------------------------------------------------------===//
360
361 /// Replace the current operands of this operation with the ones provided in
362 /// 'operands'.
363 void setOperands(ValueRange operands);
364
365 /// Replace the operands beginning at 'start' and ending at 'start' + 'length'
366 /// with the ones provided in 'operands'. 'operands' may be smaller or larger
367 /// than the range pointed to by 'start'+'length'.
368 void setOperands(unsigned start, unsigned length, ValueRange operands);
369
370 /// Insert the given operands into the operand list at the given 'index'.
371 void insertOperands(unsigned index, ValueRange operands);
372
373 unsigned getNumOperands() {
374 return LLVM_LIKELY(hasOperandStorage) ? getOperandStorage().size() : 0;
375 }
376
377 Value getOperand(unsigned idx) { return getOpOperand(idx).get(); }
378 void setOperand(unsigned idx, Value value) {
379 return getOpOperand(idx).set(value);
380 }
381
382 /// Erase the operand at position `idx`.
383 void eraseOperand(unsigned idx) { eraseOperands(idx); }
384
385 /// Erase the operands starting at position `idx` and ending at position
386 /// 'idx'+'length'.
387 void eraseOperands(unsigned idx, unsigned length = 1) {
388 getOperandStorage().eraseOperands(idx, length);
389 }
390
391 /// Erases the operands that have their corresponding bit set in
392 /// `eraseIndices` and removes them from the operand list.
393 void eraseOperands(const BitVector &eraseIndices) {
394 getOperandStorage().eraseOperands(eraseIndices);
395 }
396
397 // Support operand iteration.
399 using operand_iterator = operand_range::iterator;
400
403
404 /// Returns an iterator on the underlying Value's.
407 return OperandRange(operands.data(), operands.size());
408 }
409
411 return LLVM_LIKELY(hasOperandStorage) ? getOperandStorage().getOperands()
413 }
414
415 OpOperand &getOpOperand(unsigned idx) {
416 return getOperandStorage().getOperands()[idx];
417 }
418
419 // Support operand type iteration.
425
426 //===--------------------------------------------------------------------===//
427 // Results
428 //===--------------------------------------------------------------------===//
429
430 /// Return the number of results held by this operation.
431 unsigned getNumResults() { return numResults; }
432
433 /// Get the 'idx'th result of this operation.
434 OpResult getResult(unsigned idx) { return OpResult(getOpResultImpl(idx)); }
435
436 /// Support result iteration.
438 using result_iterator = result_range::iterator;
439
443 return numResults == 0 ? result_range(nullptr, 0)
444 : result_range(getInlineOpResult(0), numResults);
445 }
446
448 OpResult getOpResult(unsigned idx) { return getResult(idx); }
449
450 /// Support result type iteration.
456
457 //===--------------------------------------------------------------------===//
458 // Attributes
459 //===--------------------------------------------------------------------===//
460
461 // Operations may optionally carry a list of attributes that associate
462 // constants to names. Attributes may be dynamically added and removed over
463 // the lifetime of an operation.
464
465 /// Access an inherent attribute by name: returns an empty optional if there
466 /// is no inherent attribute with this name.
467 ///
468 /// This method is available as a transient facility in the migration process
469 /// to use Properties instead.
470 std::optional<Attribute> getInherentAttr(StringRef name);
471
472 /// Access an inherent attribute by name and cast it to `AttrClass`.
473 template <typename AttrClass>
474 AttrClass getInherentAttrOfType(StringRef name) {
475 return llvm::dyn_cast_or_null<AttrClass>(
476 getInherentAttr(name).value_or(Attribute{}));
477 }
478
479 /// Set an inherent attribute by name.
480 ///
481 /// This method is available as a transient facility in the migration process
482 /// to use Properties instead.
483 void setInherentAttr(StringAttr name, Attribute value);
484
485 /// Access a discardable attribute by name, returns a null Attribute if the
486 /// discardable attribute does not exist.
487 Attribute getDiscardableAttr(StringRef name) { return attrs.get(name); }
488
489 /// Access a discardable attribute by name, returns a null Attribute if the
490 /// discardable attribute does not exist.
491 Attribute getDiscardableAttr(StringAttr name) { return attrs.get(name); }
492
493 /// Access a discardable attribute by name and cast it to `AttrClass`.
494 template <typename AttrClass>
495 AttrClass getDiscardableAttrOfType(StringRef name) {
496 return llvm::dyn_cast_or_null<AttrClass>(getDiscardableAttr(name));
497 }
498 template <typename AttrClass>
499 AttrClass getDiscardableAttrOfType(StringAttr name) {
500 return llvm::dyn_cast_or_null<AttrClass>(getDiscardableAttr(name));
501 }
502
503 /// Return true if this operation has a discardable attribute with the
504 /// provided name.
505 bool hasDiscardableAttr(StringRef name) { return bool(attrs.get(name)); }
506 bool hasDiscardableAttr(StringAttr name) { return bool(attrs.get(name)); }
507 template <typename AttrClass, typename NameT>
508 bool hasDiscardableAttrOfType(NameT &&name) {
509 return static_cast<bool>(
510 getDiscardableAttrOfType<AttrClass>(std::forward<NameT>(name)));
511 }
512
513 /// Set a discardable attribute by name.
514 void setDiscardableAttr(StringAttr name, Attribute value) {
515 NamedAttrList attributes(attrs);
516 if (attributes.set(name, value) != value)
517 attrs = attributes.getDictionary(getContext());
518 }
519 void setDiscardableAttr(StringRef name, Attribute value) {
520 setDiscardableAttr(StringAttr::get(getContext(), name), value);
521 }
522
523 /// Remove the discardable attribute with the specified name if it exists.
524 /// Return the attribute that was erased, or nullptr if there was no attribute
525 /// with such name.
527 NamedAttrList attributes(attrs);
528 Attribute removedAttr = attributes.erase(name);
529 if (removedAttr)
530 attrs = attributes.getDictionary(getContext());
531 return removedAttr;
532 }
534 return removeDiscardableAttr(StringAttr::get(getContext(), name));
535 }
536
537 /// Return a range of all of discardable attributes on this operation. Note
538 /// that for unregistered operations that are not storing inherent attributes
539 /// as properties, all attributes are considered discardable.
541 std::optional<RegisteredOperationName> opName = getRegisteredInfo();
542 ArrayRef<StringAttr> attributeNames =
543 opName ? getRegisteredInfo()->getAttributeNames()
545 return llvm::make_filter_range(
546 attrs.getValue(),
547 [this, attributeNames](const NamedAttribute attribute) {
548 return getPropertiesStorage() ||
549 !llvm::is_contained(attributeNames, attribute.getName());
550 });
551 }
552
553 /// Return all of the discardable attributes on this operation as a
554 /// DictionaryAttr.
557 return attrs;
558 return DictionaryAttr::get(getContext(),
559 llvm::to_vector(getDiscardableAttrs()));
560 }
561
562 /// Return all attributes that are not stored as properties.
563 DictionaryAttr getRawDictionaryAttrs() { return attrs; }
564
565 /// Return all of the attributes on this operation.
567
568 /// Return all of the attributes on this operation as a DictionaryAttr.
569 DictionaryAttr getAttrDictionary();
570
571 /// Set the attributes from a dictionary on this operation.
572 /// These methods are expensive: if the dictionary only contains discardable
573 /// attributes, `setDiscardableAttrs` is more efficient.
574 void setAttrs(DictionaryAttr newAttrs);
575 void setAttrs(ArrayRef<NamedAttribute> newAttrs);
576 /// Set the discardable attribute dictionary on this operation.
577 void setDiscardableAttrs(DictionaryAttr newAttrs) {
578 assert(newAttrs && "expected valid attribute dictionary");
579 attrs = newAttrs;
580 }
582 setDiscardableAttrs(DictionaryAttr::get(getContext(), newAttrs));
583 }
584
585 /// Return the specified attribute if present, null otherwise.
586 /// These methods are expensive: if the dictionary only contains discardable
587 /// attributes, `getDiscardableAttr` is more efficient.
588 Attribute getAttr(StringAttr name) {
590 if (std::optional<Attribute> inherentAttr = getInherentAttr(name))
591 return *inherentAttr;
592 }
593 return attrs.get(name);
594 }
595 Attribute getAttr(StringRef name) {
597 if (std::optional<Attribute> inherentAttr = getInherentAttr(name))
598 return *inherentAttr;
599 }
600 return attrs.get(name);
601 }
602
603 template <typename AttrClass>
604 AttrClass getAttrOfType(StringAttr name) {
605 return llvm::dyn_cast_or_null<AttrClass>(getAttr(name));
606 }
607 template <typename AttrClass>
608 AttrClass getAttrOfType(StringRef name) {
609 return llvm::dyn_cast_or_null<AttrClass>(getAttr(name));
610 }
611
612 /// Return true if the operation has an attribute with the provided name,
613 /// false otherwise.
614 bool hasAttr(StringAttr name) {
616 if (std::optional<Attribute> inherentAttr = getInherentAttr(name))
617 return (bool)*inherentAttr;
618 }
619 return attrs.contains(name);
620 }
621 bool hasAttr(StringRef name) {
623 if (std::optional<Attribute> inherentAttr = getInherentAttr(name))
624 return (bool)*inherentAttr;
625 }
626 return attrs.contains(name);
627 }
628 template <typename AttrClass, typename NameT>
629 bool hasAttrOfType(NameT &&name) {
630 return static_cast<bool>(
631 getAttrOfType<AttrClass>(std::forward<NameT>(name)));
632 }
633
634 /// If the an attribute exists with the specified name, change it to the new
635 /// value. Otherwise, add a new attribute with the specified name/value.
636 void setAttr(StringAttr name, Attribute value) {
638 if (getInherentAttr(name)) {
639 setInherentAttr(name, value);
640 return;
641 }
642 }
643 NamedAttrList attributes(attrs);
644 if (attributes.set(name, value) != value)
645 attrs = attributes.getDictionary(getContext());
646 }
647 void setAttr(StringRef name, Attribute value) {
648 setAttr(StringAttr::get(getContext(), name), value);
649 }
650
651 /// Remove the attribute with the specified name if it exists. Return the
652 /// attribute that was erased, or nullptr if there was no attribute with such
653 /// name.
654 Attribute removeAttr(StringAttr name) {
656 if (std::optional<Attribute> inherentAttr = getInherentAttr(name)) {
657 setInherentAttr(name, {});
658 return *inherentAttr;
659 }
660 }
661 NamedAttrList attributes(attrs);
662 Attribute removedAttr = attributes.erase(name);
663 if (removedAttr)
664 attrs = attributes.getDictionary(getContext());
665 return removedAttr;
666 }
667 Attribute removeAttr(StringRef name) {
668 return removeAttr(StringAttr::get(getContext(), name));
669 }
670
671 /// A utility iterator that filters out non-dialect attributes.
672 class dialect_attr_iterator
673 : public llvm::filter_iterator<ArrayRef<NamedAttribute>::iterator,
674 bool (*)(NamedAttribute)> {
675 static bool filter(NamedAttribute attr) {
676 // Dialect attributes are prefixed by the dialect name, like operations.
677 return attr.getName().strref().count('.');
678 }
679
680 explicit dialect_attr_iterator(ArrayRef<NamedAttribute>::iterator it,
682 : llvm::filter_iterator<ArrayRef<NamedAttribute>::iterator,
683 bool (*)(NamedAttribute)>(it, end, &filter) {}
684
685 // Allow access to the constructor.
686 friend Operation;
687 };
689
690 /// Return a range corresponding to the dialect attributes for this operation.
693 return {dialect_attr_iterator(attrs.begin(), attrs.end()),
694 dialect_attr_iterator(attrs.end(), attrs.end())};
695 }
698 return dialect_attr_iterator(attrs.begin(), attrs.end());
699 }
702 return dialect_attr_iterator(attrs.end(), attrs.end());
703 }
704
705 /// Set the dialect attributes for this operation, and preserve all inherent.
706 template <typename DialectAttrT>
707 void setDialectAttrs(DialectAttrT &&dialectAttrs) {
708 NamedAttrList attrs;
709 attrs.append(std::begin(dialectAttrs), std::end(dialectAttrs));
710 for (auto attr : getAttrs())
711 if (!attr.getName().strref().contains('.'))
712 attrs.push_back(attr);
713 setAttrs(attrs.getDictionary(getContext()));
714 }
715
716 /// Sets default attributes on unset attributes.
719 name.populateDefaultAttrs(attrs);
720 setAttrs(attrs.getDictionary(getContext()));
721 }
722
723 //===--------------------------------------------------------------------===//
724 // Blocks
725 //===--------------------------------------------------------------------===//
726
727 /// Returns the number of regions held by this operation.
728 unsigned getNumRegions() { return numRegions; }
729
730 /// Returns the regions held by this operation.
732 // Check the count first, as computing the trailing objects can be slow.
733 if (numRegions == 0)
735
736 return getTrailingObjects<Region>(numRegions);
737 }
738
739 /// Returns the region held by this operation at position 'index'.
740 Region &getRegion(unsigned index) {
741 assert(index < numRegions && "invalid region index");
742 return getRegions()[index];
743 }
744
745 //===--------------------------------------------------------------------===//
746 // Successors
747 //===--------------------------------------------------------------------===//
748
750 return getTrailingObjects<BlockOperand>(numSuccs);
751 }
752
753 // Successor iteration.
754 using succ_iterator = SuccessorRange::iterator;
758
759 bool hasSuccessors() { return numSuccs != 0; }
760 unsigned getNumSuccessors() { return numSuccs; }
761
763 assert(index < getNumSuccessors());
764 return getBlockOperands()[index].get();
765 }
766 void setSuccessor(Block *block, unsigned index);
767
768 //===--------------------------------------------------------------------===//
769 // Accessors for various properties of operations
770 //===--------------------------------------------------------------------===//
771
772 /// Attempt to fold this operation with the specified constant operand values
773 /// - the elements in "operands" will correspond directly to the operands of
774 /// the operation, but may be null if non-constant.
775 ///
776 /// If folding was successful, this function returns "success".
777 /// * If this operation was modified in-place (but not folded away),
778 /// `results` is empty.
779 /// * Otherwise, `results` is filled with the folded results.
780 /// If folding was unsuccessful, this function returns "failure".
781 LogicalResult fold(ArrayRef<Attribute> operands,
783
784 /// Attempt to fold this operation.
785 ///
786 /// If folding was successful, this function returns "success".
787 /// * If this operation was modified in-place (but not folded away),
788 /// `results` is empty.
789 /// * Otherwise, `results` is filled with the folded results.
790 /// If folding was unsuccessful, this function returns "failure".
791 LogicalResult fold(SmallVectorImpl<OpFoldResult> &results);
792
793 /// Returns true if `InterfaceT` has been promised by the dialect or
794 /// implemented.
795 template <typename InterfaceT>
797 return name.hasPromiseOrImplementsInterface<InterfaceT>();
798 }
799
800 /// Returns true if the operation was registered with a particular trait, e.g.
801 /// hasTrait<OperandsAreSignlessIntegerLike>().
802 template <template <typename T> class Trait>
803 bool hasTrait() {
804 return name.hasTrait<Trait>();
805 }
806
807 /// Returns true if the operation *might* have the provided trait. This
808 /// means that either the operation is unregistered, or it was registered with
809 /// the provide trait.
810 template <template <typename T> class Trait>
812 return name.mightHaveTrait<Trait>();
813 }
814
815 //===--------------------------------------------------------------------===//
816 // Operation Walkers
817 //===--------------------------------------------------------------------===//
818
819 /// Walk the operation by calling the callback for each nested operation
820 /// (including this one), block or region, depending on the callback provided.
821 /// The order in which regions, blocks and operations at the same nesting
822 /// level are visited (e.g., lexicographical or reverse lexicographical order)
823 /// is determined by 'Iterator'. The walk order for enclosing regions, blocks
824 /// and operations with respect to their nested ones is specified by 'Order'
825 /// (post-order by default). A callback on a block or operation is allowed to
826 /// erase that block or operation if either:
827 /// * the walk is in post-order, or
828 /// * the walk is in pre-order and the walk is skipped after the erasure.
829 ///
830 /// The callback method can take any of the following forms:
831 /// void(Operation*) : Walk all operations opaquely.
832 /// * op->walk([](Operation *nestedOp) { ...});
833 /// void(OpT) : Walk all operations of the given derived type.
834 /// * op->walk([](ReturnOp returnOp) { ...});
835 /// WalkResult(Operation*|OpT) : Walk operations, but allow for
836 /// interruption/skipping.
837 /// * op->walk([](... op) {
838 /// // Skip the walk of this op based on some invariant.
839 /// if (some_invariant)
840 /// return WalkResult::skip();
841 /// // Interrupt, i.e cancel, the walk based on some invariant.
842 /// if (another_invariant)
843 /// return WalkResult::interrupt();
844 /// return WalkResult::advance();
845 /// });
846 template <WalkOrder Order = WalkOrder::PostOrder,
847 typename Iterator = ForwardIterator, typename FnT,
848 typename RetT = detail::walkResultType<FnT>>
849 std::enable_if_t<llvm::function_traits<std::decay_t<FnT>>::num_args == 1,
850 RetT>
851 walk(FnT &&callback) {
852 return detail::walk<Order, Iterator>(this, std::forward<FnT>(callback));
853 }
854
855 /// Generic walker with a stage aware callback. Walk the operation by calling
856 /// the callback for each nested operation (including this one) N+1 times,
857 /// where N is the number of regions attached to that operation.
858 ///
859 /// The callback method can take any of the following forms:
860 /// void(Operation *, const WalkStage &) : Walk all operation opaquely
861 /// * op->walk([](Operation *nestedOp, const WalkStage &stage) { ...});
862 /// void(OpT, const WalkStage &) : Walk all operations of the given derived
863 /// type.
864 /// * op->walk([](ReturnOp returnOp, const WalkStage &stage) { ...});
865 /// WalkResult(Operation*|OpT, const WalkStage &stage) : Walk operations,
866 /// but allow for interruption/skipping.
867 /// * op->walk([](... op, const WalkStage &stage) {
868 /// // Skip the walk of this op based on some invariant.
869 /// if (some_invariant)
870 /// return WalkResult::skip();
871 /// // Interrupt, i.e cancel, the walk based on some invariant.
872 /// if (another_invariant)
873 /// return WalkResult::interrupt();
874 /// return WalkResult::advance();
875 /// });
876 template <typename FnT, typename RetT = detail::walkResultType<FnT>>
877 std::enable_if_t<llvm::function_traits<std::decay_t<FnT>>::num_args == 2,
878 RetT>
879 walk(FnT &&callback) {
880 return detail::walk(this, std::forward<FnT>(callback));
881 }
882
883 //===--------------------------------------------------------------------===//
884 // Uses
885 //===--------------------------------------------------------------------===//
886
887 /// Drop all uses of results of this operation.
888 void dropAllUses() {
890 result.dropAllUses();
891 }
892
895
898
899 /// Returns a range of all uses, which is useful for iterating over all uses.
901
902 /// Returns true if this operation has exactly one use.
903 bool hasOneUse() { return llvm::hasSingleElement(getUses()); }
904
905 /// Returns true if this operation has no uses.
906 bool use_empty() { return getResults().use_empty(); }
907
908 /// Returns true if the results of this operation are used outside of the
909 /// given block.
911 return llvm::any_of(getOpResults(), [block](OpResult result) {
912 return result.isUsedOutsideOfBlock(block);
913 });
914 }
915
916 //===--------------------------------------------------------------------===//
917 // Users
918 //===--------------------------------------------------------------------===//
919
922
925
926 /// Returns a range of all users.
928
929 //===--------------------------------------------------------------------===//
930 // Other
931 //===--------------------------------------------------------------------===//
932
933 /// Emit an error with the op name prefixed, like "'dim' op " which is
934 /// convenient for verifiers.
935 InFlightDiagnostic emitOpError(const Twine &message = {});
936
937 /// Emit an error about fatal conditions with this operation, reporting up to
938 /// any diagnostic handlers that may be listening.
939 InFlightDiagnostic emitError(const Twine &message = {});
940
941 /// Emit a warning about this operation, reporting up to any diagnostic
942 /// handlers that may be listening.
943 InFlightDiagnostic emitWarning(const Twine &message = {});
944
945 /// Emit a remark about this operation, reporting up to any diagnostic
946 /// handlers that may be listening.
947 InFlightDiagnostic emitRemark(const Twine &message = {});
948
949 /// Returns the properties storage size.
951 return ((int)propertiesStorageSize) * 8;
952 }
953
954 /// Return a generic (but typed) reference to the property type storage.
956 if (propertiesStorageSize)
957 return PropertyRef(name.getOpPropertiesTypeID(),
959 return {};
960 }
961
963 if (propertiesStorageSize)
964 return PropertyRef(
965 name.getOpPropertiesTypeID(),
966 reinterpret_cast<void *>(const_cast<detail::OpProperties *>(
967 getTrailingObjects<detail::OpProperties>())));
968 return {};
969 }
970
971 /// Returns a pointer to the properties storage (if it exists) with no type
972 /// information.
974 return reinterpret_cast<void *>(const_cast<detail::OpProperties *>(
975 getTrailingObjects<detail::OpProperties>()));
976 }
977
978 /// Return the properties converted to an attribute.
979 /// This is expensive, and mostly useful when dealing with unregistered
980 /// operation. Returns an empty attribute if no properties are present.
982
983 /// Set the properties from the provided attribute.
984 /// This is an expensive operation that can fail if the attribute is not
985 /// matching the expectations of the properties for this operation. This is
986 /// mostly useful for unregistered operations or used when parsing the
987 /// generic format. An optional diagnostic emitter can be passed in for richer
988 /// errors, if none is passed then behavior is undefined in error case.
989 LogicalResult
992
993 /// Copy properties from an existing other properties object. The two objects
994 /// must be the same type.
995 void copyProperties(PropertyRef rhs);
996
997 /// Compute a hash for the op properties (if any).
998 llvm::hash_code hashProperties();
999
1000private:
1001 //===--------------------------------------------------------------------===//
1002 // Ordering
1003 //===--------------------------------------------------------------------===//
1004
1005 /// This value represents an invalid index ordering for an operation within a
1006 /// block.
1007 static constexpr unsigned kInvalidOrderIdx = -1;
1008
1009 /// This value represents the stride to use when computing a new order for an
1010 /// operation.
1011 static constexpr unsigned kOrderStride = 5;
1012
1013 /// Update the order index of this operation if necessary,
1014 /// potentially recomputing the order of the parent block.
1015 void updateOrderIfNecessary();
1016
1017 /// Returns true if this operation has a valid order.
1018 bool hasValidOrder() { return orderIndex != kInvalidOrderIdx; }
1019
1020private:
1021 Operation(Location location, OperationName name, unsigned numResults,
1022 unsigned numSuccessors, unsigned numRegions,
1023 int propertiesStorageSize, DictionaryAttr attributes,
1024 PropertyRef properties, bool hasOperandStorage);
1025
1026 // Operations are deleted through the destroy() member because they are
1027 // allocated with malloc.
1028 ~Operation();
1029
1030 /// Returns the additional size necessary for allocating the given objects
1031 /// before an Operation in-memory.
1032 static size_t prefixAllocSize(unsigned numOutOfLineResults,
1033 unsigned numInlineResults) {
1034 return sizeof(detail::OutOfLineOpResult) * numOutOfLineResults +
1035 sizeof(detail::InlineOpResult) * numInlineResults;
1036 }
1037 /// Returns the additional size allocated before this Operation in-memory.
1038 size_t prefixAllocSize() {
1039 unsigned numResults = getNumResults();
1040 unsigned numOutOfLineResults = OpResult::getNumTrailing(numResults);
1041 unsigned numInlineResults = OpResult::getNumInline(numResults);
1042 return prefixAllocSize(numOutOfLineResults, numInlineResults);
1043 }
1044
1045 /// Returns the operand storage object.
1046 detail::OperandStorage &getOperandStorage() {
1047 assert(hasOperandStorage && "expected operation to have operand storage");
1048 return *getTrailingObjects<detail::OperandStorage>();
1049 }
1050
1051 /// Returns a pointer to the use list for the given out-of-line result.
1052 detail::OutOfLineOpResult *getOutOfLineOpResult(unsigned resultNumber) {
1053 // Out-of-line results are stored in reverse order after (before in memory)
1054 // the inline results.
1055 return reinterpret_cast<detail::OutOfLineOpResult *>(getInlineOpResult(
1057 ++resultNumber;
1058 }
1059
1060 /// Returns a pointer to the use list for the given inline result.
1061 detail::InlineOpResult *getInlineOpResult(unsigned resultNumber) {
1062 // Inline results are stored in reverse order before the operation in
1063 // memory.
1064 return reinterpret_cast<detail::InlineOpResult *>(this) - ++resultNumber;
1065 }
1066
1067 /// Returns a pointer to the use list for the given result, which may be
1068 /// either inline or out-of-line.
1069 detail::OpResultImpl *getOpResultImpl(unsigned resultNumber) {
1070 assert(resultNumber < getNumResults() &&
1071 "Result number is out of range for operation");
1072 unsigned maxInlineResults = detail::OpResultImpl::getMaxInlineResults();
1073 if (resultNumber < maxInlineResults)
1074 return getInlineOpResult(resultNumber);
1075 return getOutOfLineOpResult(resultNumber - maxInlineResults);
1076 }
1077
1078 /// Provide a 'getParent' method for ilist_node_with_parent methods.
1079 /// We mark it as a const function because ilist_node_with_parent specifically
1080 /// requires a 'getParent() const' method. Once ilist_node removes this
1081 /// constraint, we should drop the const to fit the rest of the MLIR const
1082 /// model.
1083 Block *getParent() const { return block; }
1084
1085 /// Expose a few methods explicitly for the debugger to call for
1086 /// visualization.
1087#ifndef NDEBUG
1088 LLVM_DUMP_METHOD operand_range debug_getOperands() { return getOperands(); }
1089 LLVM_DUMP_METHOD result_range debug_getResults() { return getResults(); }
1090 LLVM_DUMP_METHOD SuccessorRange debug_getSuccessors() {
1091 return getSuccessors();
1092 }
1093 LLVM_DUMP_METHOD MutableArrayRef<Region> debug_getRegions() {
1094 return getRegions();
1095 }
1096#endif
1097
1098 /// The operation block that contains this operation.
1099 Block *block = nullptr;
1100
1101 /// This holds information about the source location the operation was defined
1102 /// or derived from.
1103 Location location;
1104
1105 /// Relative order of this operation in its parent block. Used for
1106 /// O(1) local dominance checks between operations.
1107 mutable unsigned orderIndex = 0;
1108
1109 const unsigned numResults;
1110 const unsigned numSuccs;
1111 const unsigned numRegions : 23;
1112
1113 /// This bit signals whether this operation has an operand storage or not. The
1114 /// operand storage may be elided for operations that are known to never have
1115 /// operands.
1116 bool hasOperandStorage : 1;
1117
1118 /// The size of the storage for properties (if any), divided by 8: since the
1119 /// Properties storage will always be rounded up to the next multiple of 8 we
1120 /// save some bits here.
1121 unsigned char propertiesStorageSize : 8;
1122 /// This is the maximum size we support to allocate properties inline with an
1123 /// operation: this must match the bitwidth above.
1124 static constexpr int64_t propertiesCapacity = 8 * 256;
1125
1126 /// This holds the name of the operation.
1127 OperationName name;
1128
1129 /// This holds general named attributes for the operation.
1130 DictionaryAttr attrs;
1131
1132 // allow ilist_traits access to 'block' field.
1133 friend struct llvm::ilist_traits<Operation>;
1134
1135 // allow block to access the 'orderIndex' field.
1136 friend class Block;
1137
1138 // allow value to access the 'ResultStorage' methods.
1139 friend class Value;
1140
1141 // allow ilist_node_with_parent to access the 'getParent' method.
1142 friend class llvm::ilist_node_with_parent<Operation, Block>;
1143
1144 // This stuff is used by the TrailingObjects template.
1145 friend llvm::TrailingObjects<Operation, detail::OperandStorage,
1147 OpOperand>;
1148 size_t numTrailingObjects(OverloadToken<detail::OperandStorage>) const {
1149 return hasOperandStorage ? 1 : 0;
1150 }
1151 size_t numTrailingObjects(OverloadToken<BlockOperand>) const {
1152 return numSuccs;
1153 }
1154 size_t numTrailingObjects(OverloadToken<Region>) const { return numRegions; }
1155 size_t numTrailingObjects(OverloadToken<detail::OpProperties>) const {
1156 return getPropertiesStorageSize();
1157 }
1158};
1159
1161 const_cast<Operation &>(op).print(os, OpPrintingFlags().useLocalScope());
1162 return os;
1163}
1164
1165/// A wrapper class that allows for printing an operation with a set of flags,
1166/// useful to act as a "stream modifier" to customize printing an operation
1167/// with a stream using the operator<< overload, e.g.:
1168/// llvm::dbgs() << OpWithFlags(op, OpPrintingFlags().skipRegions());
1169/// This always prints the operation with the local scope, to avoid introducing
1170/// spurious newlines in the stream.
1172public:
1174 : op(op), theFlags(flags) {}
1175 OpPrintingFlags &flags() { return theFlags; }
1176 const OpPrintingFlags &flags() const { return theFlags; }
1177 Operation *getOperation() const { return op; }
1178
1179private:
1180 Operation *op;
1181 OpPrintingFlags theFlags;
1183};
1184
1186 opWithFlags.flags().useLocalScope();
1187 opWithFlags.op->print(os, opWithFlags.flags());
1188 return os;
1189}
1190
1191/// A wrapper class that allows for printing an operation with a custom
1192/// AsmState, useful to act as a "stream modifier" to customize printing an
1193/// operation with a stream using the operator<< overload, e.g.:
1194/// llvm::dbgs() << OpWithState(op, OpPrintingFlags().skipRegions());
1196public:
1197 OpWithState(Operation *op, AsmState &state) : op(op), theState(state) {}
1198
1199private:
1200 Operation *op;
1201 AsmState &theState;
1202 friend raw_ostream &operator<<(raw_ostream &os, const OpWithState &op);
1203};
1204
1206 const OpWithState &opWithState) {
1207 opWithState.op->print(os, const_cast<OpWithState &>(opWithState).theState);
1208 return os;
1209}
1210
1211} // namespace mlir
1212
1213namespace llvm {
1214/// Cast from an (const) Operation * to a derived operation type.
1215template <typename T>
1217 : public ValueFromPointerCast<T, ::mlir::Operation,
1218 CastInfo<T, ::mlir::Operation *>> {
1219 static bool isPossible(::mlir::Operation *op) { return T::classof(op); }
1220};
1221template <typename T>
1222struct CastInfo<T, const ::mlir::Operation *>
1223 : public ConstStrippingForwardingCast<T, const ::mlir::Operation *,
1224 CastInfo<T, ::mlir::Operation *>> {};
1225
1226/// Cast from an (const) Operation & to a derived operation type.
1227template <typename T>
1229 : public NullableValueCastFailed<T>,
1230 public DefaultDoCastIfPossible<T, ::mlir::Operation &,
1231 CastInfo<T, ::mlir::Operation>> {
1232 // Provide isPossible here because here we have the const-stripping from
1233 // ConstStrippingCast.
1234 static bool isPossible(::mlir::Operation &val) { return T::classof(&val); }
1235 static T doCast(::mlir::Operation &val) { return T(&val); }
1236};
1237template <typename T>
1238struct CastInfo<T, const ::mlir::Operation>
1239 : public ConstStrippingForwardingCast<T, const ::mlir::Operation,
1240 CastInfo<T, ::mlir::Operation>> {};
1241
1242/// Cast (const) Operation * to itself. This is helpful to avoid SFINAE in
1243/// templated implementations that should work on both base and derived
1244/// operation types.
1245template <>
1247 : public NullableValueCastFailed<::mlir::Operation *>,
1249 ::mlir::Operation *, ::mlir::Operation *,
1250 CastInfo<::mlir::Operation *, ::mlir::Operation *>> {
1251 static bool isPossible(::mlir::Operation *op) { return true; }
1252 static ::mlir::Operation *doCast(::mlir::Operation *op) { return op; }
1253};
1254template <>
1257 const ::mlir::Operation *, const ::mlir::Operation *,
1258 CastInfo<::mlir::Operation *, ::mlir::Operation *>> {};
1259} // namespace llvm
1260
1261#endif // MLIR_IR_OPERATION_H
static llvm::ManagedStatic< PassManagerOptions > options
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
This class provides management for the lifetime of the state used when printing the IR.
Definition AsmState.h:542
Attributes are known-constant values of operations.
Definition Attributes.h:25
A block operand represents an operand that holds a reference to a Block, e.g.
This class provides an abstraction over the different types of ranges over Blocks.
Block represents an ordered list of Operations.
Definition Block.h:34
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Definition Dialect.h:38
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
IRValueT get() const
Return the current value being used by this operand.
void set(IRValueT newValue)
Set the current value being used by this operand.
This class represents a diagnostic that is inflight and set to be reported.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
DictionaryAttr getDictionary(MLIRContext *context) const
Return a dictionary attribute for the underlying dictionary.
Attribute erase(StringAttr name)
Erase the attribute with the given name from the list.
void append(StringRef name, Attribute attr)
Add an attribute with the specified name.
Attribute set(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
StringAttr getName() const
Return the name of the attribute.
This class represents an operand of an operation.
Definition Value.h:256
Set of flags used to control the behavior of the various IR print methods (e.g.
OpPrintingFlags & useLocalScope(bool enable=true)
Use local scope when printing the operation.
This is a value defined by a result of an operation.
Definition Value.h:456
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Definition Operation.h:1171
OpWithFlags(Operation *op, OpPrintingFlags flags={})
Definition Operation.h:1173
friend raw_ostream & operator<<(raw_ostream &os, OpWithFlags op)
Definition Operation.h:1185
const OpPrintingFlags & flags() const
Definition Operation.h:1176
Operation * getOperation() const
Definition Operation.h:1177
OpPrintingFlags & flags()
Definition Operation.h:1175
A wrapper class that allows for printing an operation with a custom AsmState, useful to act as a "str...
Definition Operation.h:1195
OpWithState(Operation *op, AsmState &state)
Definition Operation.h:1197
friend raw_ostream & operator<<(raw_ostream &os, const OpWithState &op)
Definition Operation.h:1205
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
type_range getTypes() const
ValueTypeRange< OperandRange > type_range
Definition ValueRange.h:50
ValueTypeIterator< iterator > type_iterator
Returns the types of the values within this range.
Definition ValueRange.h:49
Dialect * getDialect() const
Return the dialect this operation is registered to if the dialect is loaded in the context,...
std::optional< RegisteredOperationName > getRegisteredInfo() const
If this operation is registered, returns the registered information, std::nullopt otherwise.
bool isRegistered() const
Return if this operation is registered.
Class encompassing various options related to cloning an operation.
Definition Operation.h:140
bool shouldCloneResults() const
Returns true if the results are cloned from the operation.
Definition Operation.h:179
bool shouldCloneRegions() const
Returns whether regions of the operation should be cloned as well.
Definition Operation.h:164
CloneOptions()
Default constructs an option with all flags set to false.
static CloneOptions all()
Returns an instance such that all elements of the operation are cloned.
bool shouldCloneOperands() const
Returns whether operands should be cloned as well.
Definition Operation.h:171
TypeRange resultTypesOr(TypeRange defaultResultTypes) const
Returns the result types that should be used for the created operation or defaultResultTypes if none ...
Definition Operation.h:183
CloneOptions & cloneRegions(bool enable=true)
Configures whether cloning should traverse into any of the regions of the operation.
CloneOptions & withResultTypes(std::optional< SmallVector< Type > > resultTypes)
Configures different result types to use for the cloned operation.
CloneOptions & cloneOperands(bool enable=true)
Configures whether operation' operands should be cloned.
A utility iterator that filters out non-dialect attributes.
Definition Operation.h:674
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
PropertyRef getPropertiesStorage()
Return a generic (but typed) reference to the property type storage.
Definition Operation.h:955
AttrClass getAttrOfType(StringRef name)
Definition Operation.h:608
void setLoc(Location loc)
Set the source location the operation was defined or derived from.
Definition Operation.h:243
bool hasDiscardableAttrOfType(NameT &&name)
Definition Operation.h:508
void setInherentAttr(StringAttr name, Attribute value)
Set an inherent attribute by name.
void eraseOperands(const BitVector &eraseIndices)
Erases the operands that have their corresponding bit set in eraseIndices and removes them from the o...
Definition Operation.h:393
Attribute getDiscardableAttr(StringRef name)
Access a discardable attribute by name, returns a null Attribute if the discardable attribute does no...
Definition Operation.h:487
void replaceUsesOfWith(Value from, Value to)
Replace any uses of 'from' with 'to' within this operation.
PropertyRef getPropertiesStorage() const
Definition Operation.h:962
void copyProperties(PropertyRef rhs)
Copy properties from an existing other properties object.
MutableArrayRef< BlockOperand > getBlockOperands()
Definition Operation.h:749
DictionaryAttr getAttrDictionary()
Return all of the attributes on this operation as a DictionaryAttr.
ResultRange result_range
Support result iteration.
Definition Operation.h:437
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Definition Operation.h:237
LogicalResult fold(ArrayRef< Attribute > operands, SmallVectorImpl< OpFoldResult > &results)
Attempt to fold this operation with the specified constant operand values.
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==2, RetT > walk(FnT &&callback)
Generic walker with a stage aware callback.
Definition Operation.h:879
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition Operation.h:740
bool use_empty()
Returns true if this operation has no uses.
Definition Operation.h:906
Value getOperand(unsigned idx)
Definition Operation.h:377
std::enable_if_t<(sizeof...(OpTy) > 1), Operation * > getParentOfType()
Definition Operation.h:263
OpResult getOpResult(unsigned idx)
Definition Operation.h:448
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
Operation * cloneWithoutRegions()
Create a partial copy of this operation without traversing into attached regions.
void insertOperands(unsigned index, ValueRange operands)
Insert the given operands into the operand list at the given 'index'.
void dropAllUses()
Drop all uses of results of this operation.
Definition Operation.h:888
AttrClass getAttrOfType(StringAttr name)
Definition Operation.h:604
Attribute getAttr(StringAttr name)
Return the specified attribute if present, null otherwise.
Definition Operation.h:588
bool hasAttr(StringRef name)
Definition Operation.h:621
operand_range::type_range operand_type_range
Definition Operation.h:421
bool hasAttrOfType(NameT &&name)
Definition Operation.h:629
void setOperand(unsigned idx, Value value)
Definition Operation.h:378
void setAttrs(DictionaryAttr newAttrs)
Set the attributes from a dictionary on this operation.
bool hasAttr(StringAttr name)
Return true if the operation has an attribute with the provided name, false otherwise.
Definition Operation.h:614
unsigned getNumSuccessors()
Definition Operation.h:760
bool isBeforeInBlock(Operation *other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
result_iterator result_begin()
Definition Operation.h:440
void eraseOperands(unsigned idx, unsigned length=1)
Erase the operands starting at position idx and ending at position 'idx'+'length'.
Definition Operation.h:387
void dropAllReferences()
This drops all operand uses from this operation, which is an essential step in breaking cyclic depend...
bool isRegistered()
Returns true if this operation has a registered operation description, otherwise false.
Definition Operation.h:125
InFlightDiagnostic emitWarning(const Twine &message={})
Emit a warning about this operation, reporting up to any diagnostic handlers that may be listening.
result_range::iterator result_iterator
Definition Operation.h:438
ArrayRef< NamedAttribute > getAttrs()
Return all of the attributes on this operation.
Definition Operation.h:566
operand_iterator operand_begin()
Definition Operation.h:401
bool replaceUsesWithIf(ValuesT &&values, function_ref< bool(OpOperand &)> shouldReplace)
Replace uses of results of this operation with the provided values if the given callback returns true...
Definition Operation.h:304
bool mightHaveTrait()
Returns true if the operation might have the provided trait.
Definition Operation.h:811
result_range::use_iterator use_iterator
Definition Operation.h:893
bool hasOneUse()
Returns true if this operation has exactly one use.
Definition Operation.h:903
dialect_attr_iterator dialect_attr_begin()
Definition Operation.h:696
Attribute getAttr(StringRef name)
Definition Operation.h:595
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
user_iterator user_end()
Definition Operation.h:924
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
Definition Operation.h:514
Attribute removeAttr(StringRef name)
Definition Operation.h:667
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
use_iterator use_begin()
Definition Operation.h:896
std::optional< Attribute > getInherentAttr(StringRef name)
Access an inherent attribute by name: returns an empty optional if there is no inherent attribute wit...
Operation * getParentWithTrait()
Returns the closest surrounding parent operation with trait Trait.
Definition Operation.h:273
operand_range::type_iterator operand_type_iterator
Definition Operation.h:420
operand_type_iterator operand_type_end()
Definition Operation.h:423
Attribute removeDiscardableAttr(StringRef name)
Definition Operation.h:533
result_range::type_range result_type_range
Definition Operation.h:452
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition Operation.h:728
void setDialectAttrs(DialectAttrT &&dialectAttrs)
Set the dialect attributes for this operation, and preserve all inherent.
Definition Operation.h:707
AttrClass getInherentAttrOfType(StringRef name)
Access an inherent attribute by name and cast it to AttrClass.
Definition Operation.h:474
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
LLVM_DUMP_METHOD void dump()
MutableArrayRef< OpOperand > getOpOperands()
Definition Operation.h:410
std::optional< RegisteredOperationName > getRegisteredInfo()
If this operation has a registered operation description, return it.
Definition Operation.h:119
void eraseOperand(unsigned idx)
Erase the operand at position idx.
Definition Operation.h:383
bool hasPromiseOrImplementsInterface() const
Returns true if InterfaceT has been promised by the dialect or implemented.
Definition Operation.h:796
DictionaryAttr getRawDictionaryAttrs()
Return all attributes that are not stored as properties.
Definition Operation.h:563
void dropAllDefinedValueUses()
Drop uses of all values defined by this operation or its nested regions.
iterator_range< user_iterator > user_range
Definition Operation.h:921
iterator_range< dialect_attr_iterator > dialect_attr_range
Definition Operation.h:688
unsigned getNumOperands()
Definition Operation.h:373
result_type_iterator result_type_end()
Definition Operation.h:454
Attribute getPropertiesAsAttribute()
Return the properties converted to an attribute.
OperandRange operand_range
Definition Operation.h:398
void populateDefaultAttrs()
Sets default attributes on unset attributes.
Definition Operation.h:717
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
ValueUserIterator< use_iterator, OpOperand > user_iterator
Definition Operation.h:920
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition Operation.h:255
result_range::type_iterator result_type_iterator
Support result type iteration.
Definition Operation.h:451
operand_iterator operand_end()
Definition Operation.h:402
Attribute getDiscardableAttr(StringAttr name)
Access a discardable attribute by name, returns a null Attribute if the discardable attribute does no...
Definition Operation.h:491
bool isUsedOutsideOfBlock(Block *block)
Returns true if the results of this operation are used outside of the given block.
Definition Operation.h:910
result_type_iterator result_type_begin()
Definition Operation.h:453
void setAttr(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
Definition Operation.h:636
void destroy()
Destroys this operation and its subclass data.
bool hasDiscardableAttr(StringRef name)
Return true if this operation has a discardable attribute with the provided name.
Definition Operation.h:505
auto getDiscardableAttrs()
Return a range of all of discardable attributes on this operation.
Definition Operation.h:540
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
Definition Operation.h:555
void remove()
Remove the operation from its parent block, but don't delete it.
void print(raw_ostream &os, const OpPrintingFlags &flags={})
void setDiscardableAttrs(ArrayRef< NamedAttribute > newAttrs)
Definition Operation.h:581
dialect_attr_range getDialectAttrs()
Return a range corresponding to the dialect attributes for this operation.
Definition Operation.h:691
LogicalResult setPropertiesFromAttribute(Attribute attr, function_ref< InFlightDiagnostic()> emitError)
Set the properties from the provided attribute.
bool hasSuccessors()
Definition Operation.h:759
operand_type_range getOperandTypes()
Definition Operation.h:424
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:731
result_iterator result_end()
Definition Operation.h:441
AttrClass getDiscardableAttrOfType(StringAttr name)
Definition Operation.h:499
static Operation * create(Location location, OperationName name, TypeRange resultTypes, ValueRange operands, NamedAttrList &&attributes, PropertyRef properties, BlockRange successors, unsigned numRegions)
Create a new Operation with the specific fields.
Definition Operation.cpp:65
friend class Block
Definition Operation.h:1136
result_type_range getResultTypes()
Definition Operation.h:455
Attribute removeDiscardableAttr(StringAttr name)
Remove the discardable attribute with the specified name if it exists.
Definition Operation.h:526
LLVM_DUMP_METHOD void dumpPretty()
void setDiscardableAttr(StringRef name, Attribute value)
Definition Operation.h:519
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
void setSuccessor(Block *block, unsigned index)
void moveBefore(Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
Definition Operation.h:288
void replaceAllUsesWith(ValuesT &&values)
Replace all uses of results of this operation with the provided 'values'.
Definition Operation.h:297
void setOperands(ValueRange operands)
Replace the current operands of this operation with the ones provided in 'operands'.
result_range::use_range use_range
Definition Operation.h:894
bool hasDiscardableAttr(StringAttr name)
Definition Operation.h:506
void * getRawPropertiesStorageUnsafe()
Returns a pointer to the properties storage (if it exists) with no type information.
Definition Operation.h:973
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
AttrClass getDiscardableAttrOfType(StringRef name)
Access a discardable attribute by name and cast it to AttrClass.
Definition Operation.h:495
Block * getSuccessor(unsigned index)
Definition Operation.h:762
user_range getUsers()
Returns a range of all users.
Definition Operation.h:927
SuccessorRange getSuccessors()
Definition Operation.h:757
result_range getOpResults()
Definition Operation.h:447
result_range getResults()
Definition Operation.h:442
int getPropertiesStorageSize() const
Returns the properties storage size.
Definition Operation.h:950
Operation * clone(IRMapping &mapper, const CloneOptions &options=CloneOptions::all())
Create a deep copy of this operation, remapping any operands that use values outside of the operation...
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition Operation.h:247
Attribute removeAttr(StringAttr name)
Remove the attribute with the specified name if it exists.
Definition Operation.h:654
SuccessorRange::iterator succ_iterator
Definition Operation.h:754
dialect_attr_iterator dialect_attr_end()
Definition Operation.h:700
bool isProperAncestor(Operation *other)
Return true if this operation is a proper ancestor of the other operation.
OpOperand & getOpOperand(unsigned idx)
Definition Operation.h:415
use_range getUses()
Returns a range of all uses, which is useful for iterating over all uses.
Definition Operation.h:900
void setAttr(StringRef name, Attribute value)
Definition Operation.h:647
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
InFlightDiagnostic emitRemark(const Twine &message={})
Emit a remark about this operation, reporting up to any diagnostic handlers that may be listening.
operand_range::iterator operand_iterator
Definition Operation.h:399
user_iterator user_begin()
Definition Operation.h:923
friend class Value
Definition Operation.h:1139
void setDiscardableAttrs(DictionaryAttr newAttrs)
Set the discardable attribute dictionary on this operation.
Definition Operation.h:577
void moveAfter(Operation *existingOp)
Unlink this operation from its current block and insert it right after existingOp which may be in the...
llvm::hash_code hashProperties()
Compute a hash for the op properties (if any).
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
succ_iterator successor_end()
Definition Operation.h:756
use_iterator use_end()
Definition Operation.h:897
void erase()
Remove this operation from its parent block and delete it.
succ_iterator successor_begin()
Definition Operation.h:755
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
operand_type_iterator operand_type_begin()
Definition Operation.h:422
Type-safe wrapper around a void* for passing properties, including the properties structs of operatio...
This class provides an abstraction over the different types of ranges over Regions.
Definition Region.h:363
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
This class implements the result iterators for the Operation class.
Definition ValueRange.h:248
use_range getUses() const
Returns a range of all uses of results within this range, which is useful for iterating over all uses...
bool use_empty() const
Returns true if no results in this range have uses.
Definition ValueRange.h:278
ValueTypeRange< ResultRange > type_range
Definition ValueRange.h:259
use_iterator use_begin() const
ValueTypeIterator< iterator > type_iterator
Returns the types of the values within this range.
Definition ValueRange.h:258
use_iterator use_end() const
type_range getTypes() const
iterator_range< use_iterator > use_range
Definition ValueRange.h:269
std::enable_if_t<!std::is_convertible< ValuesT, Operation * >::value, bool > replaceUsesWithIf(ValuesT &&values, function_ref< bool(OpOperand &)> shouldReplace)
Replace uses of results of this range with the provided 'values' if the given callback returns true.
Definition ValueRange.h:304
UseIterator use_iterator
Definition ValueRange.h:268
std::enable_if_t<!std::is_convertible< ValuesT, Operation * >::value > replaceAllUsesWith(ValuesT &&values)
Replace all uses of results of this range with the provided 'values'.
Definition ValueRange.h:287
This class implements the successor iterators for Block.
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
An iterator over the users of an IRObject.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
static unsigned getMaxInlineResults()
Returns the maximum number of results that can be stored inline.
Definition Value.h:379
This class handles the management of operation operands.
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
AttrTypeReplacer.
void walk(Operation *op, function_ref< void(Region *)> callback, WalkOrder order)
Walk all of the regions, blocks, or operations nested under (and including) the given operation.
Definition Visitors.h:102
OpProperties
This is a "tag" used for mapping the properties storage in llvm::TrailingObjects.
Definition Operation.h:27
decltype(walk(nullptr, std::declval< FnT >())) walkResultType
Utility to provide the return type of a templated walk method.
Definition Visitors.h:433
Include the generated interface declarations.
raw_ostream & operator<<(raw_ostream &os, const AliasResult &result)
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
WalkOrder
Traversal order for region, block and operation walk utilities.
Definition Visitors.h:28
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
static T doCast(::mlir::Operation &val)
Definition Operation.h:1235
static bool isPossible(::mlir::Operation &val)
Definition Operation.h:1234
static bool isPossible(::mlir::Operation *op)
Definition Operation.h:1219
::mlir::Operation * doCast(::mlir::Operation *op)
Definition Operation.h:1252
This iterator enumerates the elements in "forward" order.
Definition Visitors.h:31
This represents an operation in an abstracted form, suitable for use with the builder APIs.