1 //===- Operation.cpp - Operation support code -----------------------------===//
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 #include "mlir/IR/Operation.h"
10 #include "mlir/IR/BlockAndValueMapping.h"
11 #include "mlir/IR/Dialect.h"
12 #include "mlir/IR/OpImplementation.h"
13 #include "mlir/IR/PatternMatch.h"
14 #include "mlir/IR/StandardTypes.h"
15 #include "mlir/IR/TypeUtilities.h"
16 #include <numeric>
17 
18 using namespace mlir;
19 
20 OpAsmParser::~OpAsmParser() {}
21 
22 //===----------------------------------------------------------------------===//
23 // OperationName
24 //===----------------------------------------------------------------------===//
25 
26 /// Form the OperationName for an op with the specified string.  This either is
27 /// a reference to an AbstractOperation if one is known, or a uniqued Identifier
28 /// if not.
29 OperationName::OperationName(StringRef name, MLIRContext *context) {
30   if (auto *op = AbstractOperation::lookup(name, context))
31     representation = op;
32   else
33     representation = Identifier::get(name, context);
34 }
35 
36 /// Return the name of the dialect this operation is registered to.
37 StringRef OperationName::getDialect() const {
38   return getStringRef().split('.').first;
39 }
40 
41 /// Return the name of this operation.  This always succeeds.
42 StringRef OperationName::getStringRef() const {
43   if (auto *op = representation.dyn_cast<const AbstractOperation *>())
44     return op->name;
45   return representation.get<Identifier>().strref();
46 }
47 
48 const AbstractOperation *OperationName::getAbstractOperation() const {
49   return representation.dyn_cast<const AbstractOperation *>();
50 }
51 
52 OperationName OperationName::getFromOpaquePointer(void *pointer) {
53   return OperationName(RepresentationUnion::getFromOpaqueValue(pointer));
54 }
55 
56 //===----------------------------------------------------------------------===//
57 // Operation
58 //===----------------------------------------------------------------------===//
59 
60 /// Create a new Operation with the specific fields.
61 Operation *Operation::create(Location location, OperationName name,
62                              ArrayRef<Type> resultTypes,
63                              ArrayRef<Value> operands,
64                              ArrayRef<NamedAttribute> attributes,
65                              ArrayRef<Block *> successors,
66                              unsigned numRegions) {
67   return create(location, name, resultTypes, operands,
68                 MutableDictionaryAttr(attributes), successors, numRegions);
69 }
70 
71 /// Create a new Operation from operation state.
72 Operation *Operation::create(const OperationState &state) {
73   return Operation::create(state.location, state.name, state.types,
74                            state.operands, state.attributes, state.successors,
75                            state.regions);
76 }
77 
78 /// Create a new Operation with the specific fields.
79 Operation *Operation::create(Location location, OperationName name,
80                              ArrayRef<Type> resultTypes,
81                              ArrayRef<Value> operands,
82                              MutableDictionaryAttr attributes,
83                              ArrayRef<Block *> successors,
84                              RegionRange regions) {
85   unsigned numRegions = regions.size();
86   Operation *op = create(location, name, resultTypes, operands, attributes,
87                          successors, numRegions);
88   for (unsigned i = 0; i < numRegions; ++i)
89     if (regions[i])
90       op->getRegion(i).takeBody(*regions[i]);
91   return op;
92 }
93 
94 /// Overload of create that takes an existing MutableDictionaryAttr to avoid
95 /// unnecessarily uniquing a list of attributes.
96 Operation *Operation::create(Location location, OperationName name,
97                              ArrayRef<Type> resultTypes,
98                              ArrayRef<Value> operands,
99                              MutableDictionaryAttr attributes,
100                              ArrayRef<Block *> successors,
101                              unsigned numRegions) {
102   // We only need to allocate additional memory for a subset of results.
103   unsigned numTrailingResults = OpResult::getNumTrailing(resultTypes.size());
104   unsigned numInlineResults = OpResult::getNumInline(resultTypes.size());
105   unsigned numSuccessors = successors.size();
106   unsigned numOperands = operands.size();
107 
108   // If the operation is known to have no operands, don't allocate an operand
109   // storage.
110   bool needsOperandStorage = true;
111   if (operands.empty()) {
112     if (const AbstractOperation *abstractOp = name.getAbstractOperation())
113       needsOperandStorage = !abstractOp->hasTrait<OpTrait::ZeroOperands>();
114   }
115 
116   // Compute the byte size for the operation and the operand storage.
117   auto byteSize =
118       totalSizeToAlloc<detail::InLineOpResult, detail::TrailingOpResult,
119                        BlockOperand, Region, detail::OperandStorage>(
120           numInlineResults, numTrailingResults, numSuccessors, numRegions,
121           needsOperandStorage ? 1 : 0);
122   byteSize +=
123       llvm::alignTo(detail::OperandStorage::additionalAllocSize(numOperands),
124                     alignof(Operation));
125   void *rawMem = malloc(byteSize);
126 
127   // Create the new Operation.
128   Operation *op =
129       ::new (rawMem) Operation(location, name, resultTypes, numSuccessors,
130                                numRegions, attributes, needsOperandStorage);
131 
132   assert((numSuccessors == 0 || !op->isKnownNonTerminator()) &&
133          "unexpected successors in a non-terminator operation");
134 
135   // Initialize the results.
136   for (unsigned i = 0; i < numInlineResults; ++i)
137     new (op->getInlineResult(i)) detail::InLineOpResult();
138   for (unsigned i = 0; i < numTrailingResults; ++i)
139     new (op->getTrailingResult(i)) detail::TrailingOpResult(i);
140 
141   // Initialize the regions.
142   for (unsigned i = 0; i != numRegions; ++i)
143     new (&op->getRegion(i)) Region(op);
144 
145   // Initialize the operands.
146   if (needsOperandStorage)
147     new (&op->getOperandStorage()) detail::OperandStorage(op, operands);
148 
149   // Initialize the successors.
150   auto blockOperands = op->getBlockOperands();
151   for (unsigned i = 0; i != numSuccessors; ++i)
152     new (&blockOperands[i]) BlockOperand(op, successors[i]);
153 
154   return op;
155 }
156 
157 Operation::Operation(Location location, OperationName name,
158                      ArrayRef<Type> resultTypes, unsigned numSuccessors,
159                      unsigned numRegions,
160                      const MutableDictionaryAttr &attributes,
161                      bool hasOperandStorage)
162     : location(location), numSuccs(numSuccessors), numRegions(numRegions),
163       hasOperandStorage(hasOperandStorage), hasSingleResult(false), name(name),
164       attrs(attributes) {
165   if (!resultTypes.empty()) {
166     // If there is a single result it is stored in-place, otherwise use a tuple.
167     hasSingleResult = resultTypes.size() == 1;
168     if (hasSingleResult)
169       resultType = resultTypes.front();
170     else
171       resultType = TupleType::get(resultTypes, location->getContext());
172   }
173 }
174 
175 // Operations are deleted through the destroy() member because they are
176 // allocated via malloc.
177 Operation::~Operation() {
178   assert(block == nullptr && "operation destroyed but still in a block");
179 
180   // Explicitly run the destructors for the operands.
181   if (hasOperandStorage)
182     getOperandStorage().~OperandStorage();
183 
184   // Explicitly run the destructors for the successors.
185   for (auto &successor : getBlockOperands())
186     successor.~BlockOperand();
187 
188   // Explicitly destroy the regions.
189   for (auto &region : getRegions())
190     region.~Region();
191 }
192 
193 /// Destroy this operation or one of its subclasses.
194 void Operation::destroy() {
195   this->~Operation();
196   free(this);
197 }
198 
199 /// Return the context this operation is associated with.
200 MLIRContext *Operation::getContext() { return location->getContext(); }
201 
202 /// Return the dialect this operation is associated with, or nullptr if the
203 /// associated dialect is not registered.
204 Dialect *Operation::getDialect() {
205   if (auto *abstractOp = getAbstractOperation())
206     return &abstractOp->dialect;
207 
208   // If this operation hasn't been registered or doesn't have abstract
209   // operation, try looking up the dialect name in the context.
210   return getContext()->getRegisteredDialect(getName().getDialect());
211 }
212 
213 Region *Operation::getParentRegion() {
214   return block ? block->getParent() : nullptr;
215 }
216 
217 Operation *Operation::getParentOp() {
218   return block ? block->getParentOp() : nullptr;
219 }
220 
221 /// Return true if this operation is a proper ancestor of the `other`
222 /// operation.
223 bool Operation::isProperAncestor(Operation *other) {
224   while ((other = other->getParentOp()))
225     if (this == other)
226       return true;
227   return false;
228 }
229 
230 /// Replace any uses of 'from' with 'to' within this operation.
231 void Operation::replaceUsesOfWith(Value from, Value to) {
232   if (from == to)
233     return;
234   for (auto &operand : getOpOperands())
235     if (operand.get() == from)
236       operand.set(to);
237 }
238 
239 /// Replace the current operands of this operation with the ones provided in
240 /// 'operands'.
241 void Operation::setOperands(ValueRange operands) {
242   if (LLVM_LIKELY(hasOperandStorage))
243     return getOperandStorage().setOperands(this, operands);
244   assert(operands.empty() && "setting operands without an operand storage");
245 }
246 
247 /// Replace the operands beginning at 'start' and ending at 'start' + 'length'
248 /// with the ones provided in 'operands'. 'operands' may be smaller or larger
249 /// than the range pointed to by 'start'+'length'.
250 void Operation::setOperands(unsigned start, unsigned length,
251                             ValueRange operands) {
252   assert((start + length) <= getNumOperands() &&
253          "invalid operand range specified");
254   if (LLVM_LIKELY(hasOperandStorage))
255     return getOperandStorage().setOperands(this, start, length, operands);
256   assert(operands.empty() && "setting operands without an operand storage");
257 }
258 
259 /// Insert the given operands into the operand list at the given 'index'.
260 void Operation::insertOperands(unsigned index, ValueRange operands) {
261   if (LLVM_LIKELY(hasOperandStorage))
262     return setOperands(index, /*length=*/0, operands);
263   assert(operands.empty() && "inserting operands without an operand storage");
264 }
265 
266 //===----------------------------------------------------------------------===//
267 // Diagnostics
268 //===----------------------------------------------------------------------===//
269 
270 /// Emit an error about fatal conditions with this operation, reporting up to
271 /// any diagnostic handlers that may be listening.
272 InFlightDiagnostic Operation::emitError(const Twine &message) {
273   InFlightDiagnostic diag = mlir::emitError(getLoc(), message);
274   if (getContext()->shouldPrintOpOnDiagnostic()) {
275     // Print out the operation explicitly here so that we can print the generic
276     // form.
277     // TODO(riverriddle) It would be nice if we could instead provide the
278     // specific printing flags when adding the operation as an argument to the
279     // diagnostic.
280     std::string printedOp;
281     {
282       llvm::raw_string_ostream os(printedOp);
283       print(os, OpPrintingFlags().printGenericOpForm().useLocalScope());
284     }
285     diag.attachNote(getLoc()) << "see current operation: " << printedOp;
286   }
287   return diag;
288 }
289 
290 /// Emit a warning about this operation, reporting up to any diagnostic
291 /// handlers that may be listening.
292 InFlightDiagnostic Operation::emitWarning(const Twine &message) {
293   InFlightDiagnostic diag = mlir::emitWarning(getLoc(), message);
294   if (getContext()->shouldPrintOpOnDiagnostic())
295     diag.attachNote(getLoc()) << "see current operation: " << *this;
296   return diag;
297 }
298 
299 /// Emit a remark about this operation, reporting up to any diagnostic
300 /// handlers that may be listening.
301 InFlightDiagnostic Operation::emitRemark(const Twine &message) {
302   InFlightDiagnostic diag = mlir::emitRemark(getLoc(), message);
303   if (getContext()->shouldPrintOpOnDiagnostic())
304     diag.attachNote(getLoc()) << "see current operation: " << *this;
305   return diag;
306 }
307 
308 //===----------------------------------------------------------------------===//
309 // Operation Ordering
310 //===----------------------------------------------------------------------===//
311 
312 constexpr unsigned Operation::kInvalidOrderIdx;
313 constexpr unsigned Operation::kOrderStride;
314 
315 /// Given an operation 'other' that is within the same parent block, return
316 /// whether the current operation is before 'other' in the operation list
317 /// of the parent block.
318 /// Note: This function has an average complexity of O(1), but worst case may
319 /// take O(N) where N is the number of operations within the parent block.
320 bool Operation::isBeforeInBlock(Operation *other) {
321   assert(block && "Operations without parent blocks have no order.");
322   assert(other && other->block == block &&
323          "Expected other operation to have the same parent block.");
324   // If the order of the block is already invalid, directly recompute the
325   // parent.
326   if (!block->isOpOrderValid()) {
327     block->recomputeOpOrder();
328   } else {
329     // Update the order either operation if necessary.
330     updateOrderIfNecessary();
331     other->updateOrderIfNecessary();
332   }
333 
334   return orderIndex < other->orderIndex;
335 }
336 
337 /// Update the order index of this operation of this operation if necessary,
338 /// potentially recomputing the order of the parent block.
339 void Operation::updateOrderIfNecessary() {
340   assert(block && "expected valid parent");
341 
342   // If the order is valid for this operation there is nothing to do.
343   if (hasValidOrder())
344     return;
345   Operation *blockFront = &block->front();
346   Operation *blockBack = &block->back();
347 
348   // This method is expected to only be invoked on blocks with more than one
349   // operation.
350   assert(blockFront != blockBack && "expected more than one operation");
351 
352   // If the operation is at the end of the block.
353   if (this == blockBack) {
354     Operation *prevNode = getPrevNode();
355     if (!prevNode->hasValidOrder())
356       return block->recomputeOpOrder();
357 
358     // Add the stride to the previous operation.
359     orderIndex = prevNode->orderIndex + kOrderStride;
360     return;
361   }
362 
363   // If this is the first operation try to use the next operation to compute the
364   // ordering.
365   if (this == blockFront) {
366     Operation *nextNode = getNextNode();
367     if (!nextNode->hasValidOrder())
368       return block->recomputeOpOrder();
369     // There is no order to give this operation.
370     if (nextNode->orderIndex == 0)
371       return block->recomputeOpOrder();
372 
373     // If we can't use the stride, just take the middle value left. This is safe
374     // because we know there is at least one valid index to assign to.
375     if (nextNode->orderIndex <= kOrderStride)
376       orderIndex = (nextNode->orderIndex / 2);
377     else
378       orderIndex = kOrderStride;
379     return;
380   }
381 
382   // Otherwise, this operation is between two others. Place this operation in
383   // the middle of the previous and next if possible.
384   Operation *prevNode = getPrevNode(), *nextNode = getNextNode();
385   if (!prevNode->hasValidOrder() || !nextNode->hasValidOrder())
386     return block->recomputeOpOrder();
387   unsigned prevOrder = prevNode->orderIndex, nextOrder = nextNode->orderIndex;
388 
389   // Check to see if there is a valid order between the two.
390   if (prevOrder + 1 == nextOrder)
391     return block->recomputeOpOrder();
392   orderIndex = prevOrder + 1 + ((nextOrder - prevOrder) / 2);
393 }
394 
395 //===----------------------------------------------------------------------===//
396 // ilist_traits for Operation
397 //===----------------------------------------------------------------------===//
398 
399 auto llvm::ilist_detail::SpecificNodeAccess<
400     typename llvm::ilist_detail::compute_node_options<
401         ::mlir::Operation>::type>::getNodePtr(pointer N) -> node_type * {
402   return NodeAccess::getNodePtr<OptionsT>(N);
403 }
404 
405 auto llvm::ilist_detail::SpecificNodeAccess<
406     typename llvm::ilist_detail::compute_node_options<
407         ::mlir::Operation>::type>::getNodePtr(const_pointer N)
408     -> const node_type * {
409   return NodeAccess::getNodePtr<OptionsT>(N);
410 }
411 
412 auto llvm::ilist_detail::SpecificNodeAccess<
413     typename llvm::ilist_detail::compute_node_options<
414         ::mlir::Operation>::type>::getValuePtr(node_type *N) -> pointer {
415   return NodeAccess::getValuePtr<OptionsT>(N);
416 }
417 
418 auto llvm::ilist_detail::SpecificNodeAccess<
419     typename llvm::ilist_detail::compute_node_options<
420         ::mlir::Operation>::type>::getValuePtr(const node_type *N)
421     -> const_pointer {
422   return NodeAccess::getValuePtr<OptionsT>(N);
423 }
424 
425 void llvm::ilist_traits<::mlir::Operation>::deleteNode(Operation *op) {
426   op->destroy();
427 }
428 
429 Block *llvm::ilist_traits<::mlir::Operation>::getContainingBlock() {
430   size_t Offset(size_t(&((Block *)nullptr->*Block::getSublistAccess(nullptr))));
431   iplist<Operation> *Anchor(static_cast<iplist<Operation> *>(this));
432   return reinterpret_cast<Block *>(reinterpret_cast<char *>(Anchor) - Offset);
433 }
434 
435 /// This is a trait method invoked when an operation is added to a block.  We
436 /// keep the block pointer up to date.
437 void llvm::ilist_traits<::mlir::Operation>::addNodeToList(Operation *op) {
438   assert(!op->getBlock() && "already in an operation block!");
439   op->block = getContainingBlock();
440 
441   // Invalidate the order on the operation.
442   op->orderIndex = Operation::kInvalidOrderIdx;
443 }
444 
445 /// This is a trait method invoked when an operation is removed from a block.
446 /// We keep the block pointer up to date.
447 void llvm::ilist_traits<::mlir::Operation>::removeNodeFromList(Operation *op) {
448   assert(op->block && "not already in an operation block!");
449   op->block = nullptr;
450 }
451 
452 /// This is a trait method invoked when an operation is moved from one block
453 /// to another.  We keep the block pointer up to date.
454 void llvm::ilist_traits<::mlir::Operation>::transferNodesFromList(
455     ilist_traits<Operation> &otherList, op_iterator first, op_iterator last) {
456   Block *curParent = getContainingBlock();
457 
458   // Invalidate the ordering of the parent block.
459   curParent->invalidateOpOrder();
460 
461   // If we are transferring operations within the same block, the block
462   // pointer doesn't need to be updated.
463   if (curParent == otherList.getContainingBlock())
464     return;
465 
466   // Update the 'block' member of each operation.
467   for (; first != last; ++first)
468     first->block = curParent;
469 }
470 
471 /// Remove this operation (and its descendants) from its Block and delete
472 /// all of them.
473 void Operation::erase() {
474   if (auto *parent = getBlock())
475     parent->getOperations().erase(this);
476   else
477     destroy();
478 }
479 
480 /// Unlink this operation from its current block and insert it right before
481 /// `existingOp` which may be in the same or another block in the same
482 /// function.
483 void Operation::moveBefore(Operation *existingOp) {
484   moveBefore(existingOp->getBlock(), existingOp->getIterator());
485 }
486 
487 /// Unlink this operation from its current basic block and insert it right
488 /// before `iterator` in the specified basic block.
489 void Operation::moveBefore(Block *block,
490                            llvm::iplist<Operation>::iterator iterator) {
491   block->getOperations().splice(iterator, getBlock()->getOperations(),
492                                 getIterator());
493 }
494 
495 /// Unlink this operation from its current block and insert it right after
496 /// `existingOp` which may be in the same or another block in the same function.
497 void Operation::moveAfter(Operation *existingOp) {
498   moveAfter(existingOp->getBlock(), existingOp->getIterator());
499 }
500 
501 /// Unlink this operation from its current block and insert it right after
502 /// `iterator` in the specified block.
503 void Operation::moveAfter(Block *block,
504                           llvm::iplist<Operation>::iterator iterator) {
505   assert(iterator != block->end() && "cannot move after end of block");
506   moveBefore(&*std::next(iterator));
507 }
508 
509 /// This drops all operand uses from this operation, which is an essential
510 /// step in breaking cyclic dependences between references when they are to
511 /// be deleted.
512 void Operation::dropAllReferences() {
513   for (auto &op : getOpOperands())
514     op.drop();
515 
516   for (auto &region : getRegions())
517     region.dropAllReferences();
518 
519   for (auto &dest : getBlockOperands())
520     dest.drop();
521 }
522 
523 /// This drops all uses of any values defined by this operation or its nested
524 /// regions, wherever they are located.
525 void Operation::dropAllDefinedValueUses() {
526   dropAllUses();
527 
528   for (auto &region : getRegions())
529     for (auto &block : region)
530       block.dropAllDefinedValueUses();
531 }
532 
533 /// Return the number of results held by this operation.
534 unsigned Operation::getNumResults() {
535   if (!resultType)
536     return 0;
537   return hasSingleResult ? 1 : resultType.cast<TupleType>().size();
538 }
539 
540 auto Operation::getResultTypes() -> result_type_range {
541   if (!resultType)
542     return llvm::None;
543   if (hasSingleResult)
544     return resultType;
545   return resultType.cast<TupleType>().getTypes();
546 }
547 
548 void Operation::setSuccessor(Block *block, unsigned index) {
549   assert(index < getNumSuccessors());
550   getBlockOperands()[index].set(block);
551 }
552 
553 /// Attempt to fold this operation using the Op's registered foldHook.
554 LogicalResult Operation::fold(ArrayRef<Attribute> operands,
555                               SmallVectorImpl<OpFoldResult> &results) {
556   // If we have a registered operation definition matching this one, use it to
557   // try to constant fold the operation.
558   auto *abstractOp = getAbstractOperation();
559   if (abstractOp && succeeded(abstractOp->foldHook(this, operands, results)))
560     return success();
561 
562   // Otherwise, fall back on the dialect hook to handle it.
563   Dialect *dialect = getDialect();
564   if (!dialect)
565     return failure();
566 
567   SmallVector<Attribute, 8> constants;
568   if (failed(dialect->constantFoldHook(this, operands, constants)))
569     return failure();
570   results.assign(constants.begin(), constants.end());
571   return success();
572 }
573 
574 /// Emit an error with the op name prefixed, like "'dim' op " which is
575 /// convenient for verifiers.
576 InFlightDiagnostic Operation::emitOpError(const Twine &message) {
577   return emitError() << "'" << getName() << "' op " << message;
578 }
579 
580 //===----------------------------------------------------------------------===//
581 // Operation Cloning
582 //===----------------------------------------------------------------------===//
583 
584 /// Create a deep copy of this operation but keep the operation regions empty.
585 /// Operands are remapped using `mapper` (if present), and `mapper` is updated
586 /// to contain the results.
587 Operation *Operation::cloneWithoutRegions(BlockAndValueMapping &mapper) {
588   SmallVector<Value, 8> operands;
589   SmallVector<Block *, 2> successors;
590 
591   // Remap the operands.
592   operands.reserve(getNumOperands());
593   for (auto opValue : getOperands())
594     operands.push_back(mapper.lookupOrDefault(opValue));
595 
596   // Remap the successors.
597   successors.reserve(getNumSuccessors());
598   for (Block *successor : getSuccessors())
599     successors.push_back(mapper.lookupOrDefault(successor));
600 
601   // Create the new operation.
602   auto *newOp = Operation::create(getLoc(), getName(), getResultTypes(),
603                                   operands, attrs, successors, getNumRegions());
604 
605   // Remember the mapping of any results.
606   for (unsigned i = 0, e = getNumResults(); i != e; ++i)
607     mapper.map(getResult(i), newOp->getResult(i));
608 
609   return newOp;
610 }
611 
612 Operation *Operation::cloneWithoutRegions() {
613   BlockAndValueMapping mapper;
614   return cloneWithoutRegions(mapper);
615 }
616 
617 /// Create a deep copy of this operation, remapping any operands that use
618 /// values outside of the operation using the map that is provided (leaving
619 /// them alone if no entry is present).  Replaces references to cloned
620 /// sub-operations to the corresponding operation that is copied, and adds
621 /// those mappings to the map.
622 Operation *Operation::clone(BlockAndValueMapping &mapper) {
623   auto *newOp = cloneWithoutRegions(mapper);
624 
625   // Clone the regions.
626   for (unsigned i = 0; i != numRegions; ++i)
627     getRegion(i).cloneInto(&newOp->getRegion(i), mapper);
628 
629   return newOp;
630 }
631 
632 Operation *Operation::clone() {
633   BlockAndValueMapping mapper;
634   return clone(mapper);
635 }
636 
637 //===----------------------------------------------------------------------===//
638 // OpState trait class.
639 //===----------------------------------------------------------------------===//
640 
641 // The fallback for the parser is to reject the custom assembly form.
642 ParseResult OpState::parse(OpAsmParser &parser, OperationState &result) {
643   return parser.emitError(parser.getNameLoc(), "has no custom assembly form");
644 }
645 
646 // The fallback for the printer is to print in the generic assembly form.
647 void OpState::print(OpAsmPrinter &p) { p.printGenericOp(getOperation()); }
648 
649 /// Emit an error about fatal conditions with this operation, reporting up to
650 /// any diagnostic handlers that may be listening.
651 InFlightDiagnostic OpState::emitError(const Twine &message) {
652   return getOperation()->emitError(message);
653 }
654 
655 /// Emit an error with the op name prefixed, like "'dim' op " which is
656 /// convenient for verifiers.
657 InFlightDiagnostic OpState::emitOpError(const Twine &message) {
658   return getOperation()->emitOpError(message);
659 }
660 
661 /// Emit a warning about this operation, reporting up to any diagnostic
662 /// handlers that may be listening.
663 InFlightDiagnostic OpState::emitWarning(const Twine &message) {
664   return getOperation()->emitWarning(message);
665 }
666 
667 /// Emit a remark about this operation, reporting up to any diagnostic
668 /// handlers that may be listening.
669 InFlightDiagnostic OpState::emitRemark(const Twine &message) {
670   return getOperation()->emitRemark(message);
671 }
672 
673 //===----------------------------------------------------------------------===//
674 // Op Trait implementations
675 //===----------------------------------------------------------------------===//
676 
677 LogicalResult OpTrait::impl::verifyZeroOperands(Operation *op) {
678   if (op->getNumOperands() != 0)
679     return op->emitOpError() << "requires zero operands";
680   return success();
681 }
682 
683 LogicalResult OpTrait::impl::verifyOneOperand(Operation *op) {
684   if (op->getNumOperands() != 1)
685     return op->emitOpError() << "requires a single operand";
686   return success();
687 }
688 
689 LogicalResult OpTrait::impl::verifyNOperands(Operation *op,
690                                              unsigned numOperands) {
691   if (op->getNumOperands() != numOperands) {
692     return op->emitOpError() << "expected " << numOperands
693                              << " operands, but found " << op->getNumOperands();
694   }
695   return success();
696 }
697 
698 LogicalResult OpTrait::impl::verifyAtLeastNOperands(Operation *op,
699                                                     unsigned numOperands) {
700   if (op->getNumOperands() < numOperands)
701     return op->emitOpError()
702            << "expected " << numOperands << " or more operands";
703   return success();
704 }
705 
706 /// If this is a vector type, or a tensor type, return the scalar element type
707 /// that it is built around, otherwise return the type unmodified.
708 static Type getTensorOrVectorElementType(Type type) {
709   if (auto vec = type.dyn_cast<VectorType>())
710     return vec.getElementType();
711 
712   // Look through tensor<vector<...>> to find the underlying element type.
713   if (auto tensor = type.dyn_cast<TensorType>())
714     return getTensorOrVectorElementType(tensor.getElementType());
715   return type;
716 }
717 
718 LogicalResult
719 OpTrait::impl::verifyOperandsAreSignlessIntegerLike(Operation *op) {
720   for (auto opType : op->getOperandTypes()) {
721     auto type = getTensorOrVectorElementType(opType);
722     if (!type.isSignlessIntOrIndex())
723       return op->emitOpError() << "requires an integer or index type";
724   }
725   return success();
726 }
727 
728 LogicalResult OpTrait::impl::verifyOperandsAreFloatLike(Operation *op) {
729   for (auto opType : op->getOperandTypes()) {
730     auto type = getTensorOrVectorElementType(opType);
731     if (!type.isa<FloatType>())
732       return op->emitOpError("requires a float type");
733   }
734   return success();
735 }
736 
737 LogicalResult OpTrait::impl::verifySameTypeOperands(Operation *op) {
738   // Zero or one operand always have the "same" type.
739   unsigned nOperands = op->getNumOperands();
740   if (nOperands < 2)
741     return success();
742 
743   auto type = op->getOperand(0).getType();
744   for (auto opType : llvm::drop_begin(op->getOperandTypes(), 1))
745     if (opType != type)
746       return op->emitOpError() << "requires all operands to have the same type";
747   return success();
748 }
749 
750 LogicalResult OpTrait::impl::verifyZeroRegion(Operation *op) {
751   if (op->getNumRegions() != 0)
752     return op->emitOpError() << "requires zero regions";
753   return success();
754 }
755 
756 LogicalResult OpTrait::impl::verifyOneRegion(Operation *op) {
757   if (op->getNumRegions() != 1)
758     return op->emitOpError() << "requires one region";
759   return success();
760 }
761 
762 LogicalResult OpTrait::impl::verifyNRegions(Operation *op,
763                                             unsigned numRegions) {
764   if (op->getNumRegions() != numRegions)
765     return op->emitOpError() << "expected " << numRegions << " regions";
766   return success();
767 }
768 
769 LogicalResult OpTrait::impl::verifyAtLeastNRegions(Operation *op,
770                                                    unsigned numRegions) {
771   if (op->getNumRegions() < numRegions)
772     return op->emitOpError() << "expected " << numRegions << " or more regions";
773   return success();
774 }
775 
776 LogicalResult OpTrait::impl::verifyZeroResult(Operation *op) {
777   if (op->getNumResults() != 0)
778     return op->emitOpError() << "requires zero results";
779   return success();
780 }
781 
782 LogicalResult OpTrait::impl::verifyOneResult(Operation *op) {
783   if (op->getNumResults() != 1)
784     return op->emitOpError() << "requires one result";
785   return success();
786 }
787 
788 LogicalResult OpTrait::impl::verifyNResults(Operation *op,
789                                             unsigned numOperands) {
790   if (op->getNumResults() != numOperands)
791     return op->emitOpError() << "expected " << numOperands << " results";
792   return success();
793 }
794 
795 LogicalResult OpTrait::impl::verifyAtLeastNResults(Operation *op,
796                                                    unsigned numOperands) {
797   if (op->getNumResults() < numOperands)
798     return op->emitOpError()
799            << "expected " << numOperands << " or more results";
800   return success();
801 }
802 
803 LogicalResult OpTrait::impl::verifySameOperandsShape(Operation *op) {
804   if (failed(verifyAtLeastNOperands(op, 1)))
805     return failure();
806 
807   auto type = op->getOperand(0).getType();
808   for (auto opType : llvm::drop_begin(op->getOperandTypes(), 1)) {
809     if (failed(verifyCompatibleShape(opType, type)))
810       return op->emitOpError() << "requires the same shape for all operands";
811   }
812   return success();
813 }
814 
815 LogicalResult OpTrait::impl::verifySameOperandsAndResultShape(Operation *op) {
816   if (failed(verifyAtLeastNOperands(op, 1)) ||
817       failed(verifyAtLeastNResults(op, 1)))
818     return failure();
819 
820   auto type = op->getOperand(0).getType();
821   for (auto resultType : op->getResultTypes()) {
822     if (failed(verifyCompatibleShape(resultType, type)))
823       return op->emitOpError()
824              << "requires the same shape for all operands and results";
825   }
826   for (auto opType : llvm::drop_begin(op->getOperandTypes(), 1)) {
827     if (failed(verifyCompatibleShape(opType, type)))
828       return op->emitOpError()
829              << "requires the same shape for all operands and results";
830   }
831   return success();
832 }
833 
834 LogicalResult OpTrait::impl::verifySameOperandsElementType(Operation *op) {
835   if (failed(verifyAtLeastNOperands(op, 1)))
836     return failure();
837   auto elementType = getElementTypeOrSelf(op->getOperand(0));
838 
839   for (auto operand : llvm::drop_begin(op->getOperands(), 1)) {
840     if (getElementTypeOrSelf(operand) != elementType)
841       return op->emitOpError("requires the same element type for all operands");
842   }
843 
844   return success();
845 }
846 
847 LogicalResult
848 OpTrait::impl::verifySameOperandsAndResultElementType(Operation *op) {
849   if (failed(verifyAtLeastNOperands(op, 1)) ||
850       failed(verifyAtLeastNResults(op, 1)))
851     return failure();
852 
853   auto elementType = getElementTypeOrSelf(op->getResult(0));
854 
855   // Verify result element type matches first result's element type.
856   for (auto result : llvm::drop_begin(op->getResults(), 1)) {
857     if (getElementTypeOrSelf(result) != elementType)
858       return op->emitOpError(
859           "requires the same element type for all operands and results");
860   }
861 
862   // Verify operand's element type matches first result's element type.
863   for (auto operand : op->getOperands()) {
864     if (getElementTypeOrSelf(operand) != elementType)
865       return op->emitOpError(
866           "requires the same element type for all operands and results");
867   }
868 
869   return success();
870 }
871 
872 LogicalResult OpTrait::impl::verifySameOperandsAndResultType(Operation *op) {
873   if (failed(verifyAtLeastNOperands(op, 1)) ||
874       failed(verifyAtLeastNResults(op, 1)))
875     return failure();
876 
877   auto type = op->getResult(0).getType();
878   auto elementType = getElementTypeOrSelf(type);
879   for (auto resultType : op->getResultTypes().drop_front(1)) {
880     if (getElementTypeOrSelf(resultType) != elementType ||
881         failed(verifyCompatibleShape(resultType, type)))
882       return op->emitOpError()
883              << "requires the same type for all operands and results";
884   }
885   for (auto opType : op->getOperandTypes()) {
886     if (getElementTypeOrSelf(opType) != elementType ||
887         failed(verifyCompatibleShape(opType, type)))
888       return op->emitOpError()
889              << "requires the same type for all operands and results";
890   }
891   return success();
892 }
893 
894 LogicalResult OpTrait::impl::verifyIsTerminator(Operation *op) {
895   Block *block = op->getBlock();
896   // Verify that the operation is at the end of the respective parent block.
897   if (!block || &block->back() != op)
898     return op->emitOpError("must be the last operation in the parent block");
899   return success();
900 }
901 
902 static LogicalResult verifyTerminatorSuccessors(Operation *op) {
903   auto *parent = op->getParentRegion();
904 
905   // Verify that the operands lines up with the BB arguments in the successor.
906   for (Block *succ : op->getSuccessors())
907     if (succ->getParent() != parent)
908       return op->emitError("reference to block defined in another region");
909   return success();
910 }
911 
912 LogicalResult OpTrait::impl::verifyZeroSuccessor(Operation *op) {
913   if (op->getNumSuccessors() != 0) {
914     return op->emitOpError("requires 0 successors but found ")
915            << op->getNumSuccessors();
916   }
917   return success();
918 }
919 
920 LogicalResult OpTrait::impl::verifyOneSuccessor(Operation *op) {
921   if (op->getNumSuccessors() != 1) {
922     return op->emitOpError("requires 1 successor but found ")
923            << op->getNumSuccessors();
924   }
925   return verifyTerminatorSuccessors(op);
926 }
927 LogicalResult OpTrait::impl::verifyNSuccessors(Operation *op,
928                                                unsigned numSuccessors) {
929   if (op->getNumSuccessors() != numSuccessors) {
930     return op->emitOpError("requires ")
931            << numSuccessors << " successors but found "
932            << op->getNumSuccessors();
933   }
934   return verifyTerminatorSuccessors(op);
935 }
936 LogicalResult OpTrait::impl::verifyAtLeastNSuccessors(Operation *op,
937                                                       unsigned numSuccessors) {
938   if (op->getNumSuccessors() < numSuccessors) {
939     return op->emitOpError("requires at least ")
940            << numSuccessors << " successors but found "
941            << op->getNumSuccessors();
942   }
943   return verifyTerminatorSuccessors(op);
944 }
945 
946 LogicalResult OpTrait::impl::verifyResultsAreBoolLike(Operation *op) {
947   for (auto resultType : op->getResultTypes()) {
948     auto elementType = getTensorOrVectorElementType(resultType);
949     bool isBoolType = elementType.isInteger(1);
950     if (!isBoolType)
951       return op->emitOpError() << "requires a bool result type";
952   }
953 
954   return success();
955 }
956 
957 LogicalResult OpTrait::impl::verifyResultsAreFloatLike(Operation *op) {
958   for (auto resultType : op->getResultTypes())
959     if (!getTensorOrVectorElementType(resultType).isa<FloatType>())
960       return op->emitOpError() << "requires a floating point type";
961 
962   return success();
963 }
964 
965 LogicalResult
966 OpTrait::impl::verifyResultsAreSignlessIntegerLike(Operation *op) {
967   for (auto resultType : op->getResultTypes())
968     if (!getTensorOrVectorElementType(resultType).isSignlessIntOrIndex())
969       return op->emitOpError() << "requires an integer or index type";
970   return success();
971 }
972 
973 static LogicalResult verifyValueSizeAttr(Operation *op, StringRef attrName,
974                                          bool isOperand) {
975   auto sizeAttr = op->getAttrOfType<DenseIntElementsAttr>(attrName);
976   if (!sizeAttr)
977     return op->emitOpError("requires 1D vector attribute '") << attrName << "'";
978 
979   auto sizeAttrType = sizeAttr.getType().dyn_cast<VectorType>();
980   if (!sizeAttrType || sizeAttrType.getRank() != 1)
981     return op->emitOpError("requires 1D vector attribute '") << attrName << "'";
982 
983   if (llvm::any_of(sizeAttr.getIntValues(), [](const APInt &element) {
984         return !element.isNonNegative();
985       }))
986     return op->emitOpError("'")
987            << attrName << "' attribute cannot have negative elements";
988 
989   size_t totalCount = std::accumulate(
990       sizeAttr.begin(), sizeAttr.end(), 0,
991       [](unsigned all, APInt one) { return all + one.getZExtValue(); });
992 
993   if (isOperand && totalCount != op->getNumOperands())
994     return op->emitOpError("operand count (")
995            << op->getNumOperands() << ") does not match with the total size ("
996            << totalCount << ") specified in attribute '" << attrName << "'";
997   else if (!isOperand && totalCount != op->getNumResults())
998     return op->emitOpError("result count (")
999            << op->getNumResults() << ") does not match with the total size ("
1000            << totalCount << ") specified in attribute '" << attrName << "'";
1001   return success();
1002 }
1003 
1004 LogicalResult OpTrait::impl::verifyOperandSizeAttr(Operation *op,
1005                                                    StringRef attrName) {
1006   return verifyValueSizeAttr(op, attrName, /*isOperand=*/true);
1007 }
1008 
1009 LogicalResult OpTrait::impl::verifyResultSizeAttr(Operation *op,
1010                                                   StringRef attrName) {
1011   return verifyValueSizeAttr(op, attrName, /*isOperand=*/false);
1012 }
1013 
1014 //===----------------------------------------------------------------------===//
1015 // BinaryOp implementation
1016 //===----------------------------------------------------------------------===//
1017 
1018 // These functions are out-of-line implementations of the methods in BinaryOp,
1019 // which avoids them being template instantiated/duplicated.
1020 
1021 void impl::buildBinaryOp(OpBuilder &builder, OperationState &result, Value lhs,
1022                          Value rhs) {
1023   assert(lhs.getType() == rhs.getType());
1024   result.addOperands({lhs, rhs});
1025   result.types.push_back(lhs.getType());
1026 }
1027 
1028 ParseResult impl::parseOneResultSameOperandTypeOp(OpAsmParser &parser,
1029                                                   OperationState &result) {
1030   SmallVector<OpAsmParser::OperandType, 2> ops;
1031   Type type;
1032   return failure(parser.parseOperandList(ops) ||
1033                  parser.parseOptionalAttrDict(result.attributes) ||
1034                  parser.parseColonType(type) ||
1035                  parser.resolveOperands(ops, type, result.operands) ||
1036                  parser.addTypeToList(type, result.types));
1037 }
1038 
1039 void impl::printOneResultOp(Operation *op, OpAsmPrinter &p) {
1040   assert(op->getNumResults() == 1 && "op should have one result");
1041 
1042   // If not all the operand and result types are the same, just use the
1043   // generic assembly form to avoid omitting information in printing.
1044   auto resultType = op->getResult(0).getType();
1045   if (llvm::any_of(op->getOperandTypes(),
1046                    [&](Type type) { return type != resultType; })) {
1047     p.printGenericOp(op);
1048     return;
1049   }
1050 
1051   p << op->getName() << ' ';
1052   p.printOperands(op->getOperands());
1053   p.printOptionalAttrDict(op->getAttrs());
1054   // Now we can output only one type for all operands and the result.
1055   p << " : " << resultType;
1056 }
1057 
1058 //===----------------------------------------------------------------------===//
1059 // CastOp implementation
1060 //===----------------------------------------------------------------------===//
1061 
1062 void impl::buildCastOp(OpBuilder &builder, OperationState &result, Value source,
1063                        Type destType) {
1064   result.addOperands(source);
1065   result.addTypes(destType);
1066 }
1067 
1068 ParseResult impl::parseCastOp(OpAsmParser &parser, OperationState &result) {
1069   OpAsmParser::OperandType srcInfo;
1070   Type srcType, dstType;
1071   return failure(parser.parseOperand(srcInfo) ||
1072                  parser.parseOptionalAttrDict(result.attributes) ||
1073                  parser.parseColonType(srcType) ||
1074                  parser.resolveOperand(srcInfo, srcType, result.operands) ||
1075                  parser.parseKeywordType("to", dstType) ||
1076                  parser.addTypeToList(dstType, result.types));
1077 }
1078 
1079 void impl::printCastOp(Operation *op, OpAsmPrinter &p) {
1080   p << op->getName() << ' ' << op->getOperand(0);
1081   p.printOptionalAttrDict(op->getAttrs());
1082   p << " : " << op->getOperand(0).getType() << " to "
1083     << op->getResult(0).getType();
1084 }
1085 
1086 Value impl::foldCastOp(Operation *op) {
1087   // Identity cast
1088   if (op->getOperand(0).getType() == op->getResult(0).getType())
1089     return op->getOperand(0);
1090   return nullptr;
1091 }
1092 
1093 //===----------------------------------------------------------------------===//
1094 // Misc. utils
1095 //===----------------------------------------------------------------------===//
1096 
1097 /// Insert an operation, generated by `buildTerminatorOp`, at the end of the
1098 /// region's only block if it does not have a terminator already. If the region
1099 /// is empty, insert a new block first. `buildTerminatorOp` should return the
1100 /// terminator operation to insert.
1101 void impl::ensureRegionTerminator(
1102     Region &region, OpBuilder &builder, Location loc,
1103     function_ref<Operation *(OpBuilder &, Location)> buildTerminatorOp) {
1104   OpBuilder::InsertionGuard guard(builder);
1105   if (region.empty())
1106     builder.createBlock(&region);
1107 
1108   Block &block = region.back();
1109   if (!block.empty() && block.back().isKnownTerminator())
1110     return;
1111 
1112   builder.setInsertionPointToEnd(&block);
1113   builder.insert(buildTerminatorOp(builder, loc));
1114 }
1115 
1116 /// Create a simple OpBuilder and forward to the OpBuilder version of this
1117 /// function.
1118 void impl::ensureRegionTerminator(
1119     Region &region, Builder &builder, Location loc,
1120     function_ref<Operation *(OpBuilder &, Location)> buildTerminatorOp) {
1121   OpBuilder opBuilder(builder.getContext());
1122   ensureRegionTerminator(region, opBuilder, loc, buildTerminatorOp);
1123 }
1124 
1125 //===----------------------------------------------------------------------===//
1126 // UseIterator
1127 //===----------------------------------------------------------------------===//
1128 
1129 Operation::UseIterator::UseIterator(Operation *op, bool end)
1130     : op(op), res(end ? op->result_end() : op->result_begin()) {
1131   // Only initialize current use if there are results/can be uses.
1132   if (op->getNumResults())
1133     skipOverResultsWithNoUsers();
1134 }
1135 
1136 Operation::UseIterator &Operation::UseIterator::operator++() {
1137   // We increment over uses, if we reach the last use then move to next
1138   // result.
1139   if (use != (*res).use_end())
1140     ++use;
1141   if (use == (*res).use_end()) {
1142     ++res;
1143     skipOverResultsWithNoUsers();
1144   }
1145   return *this;
1146 }
1147 
1148 void Operation::UseIterator::skipOverResultsWithNoUsers() {
1149   while (res != op->result_end() && (*res).use_empty())
1150     ++res;
1151 
1152   // If we are at the last result, then set use to first use of
1153   // first result (sentinel value used for end).
1154   if (res == op->result_end())
1155     use = {};
1156   else
1157     use = (*res).use_begin();
1158 }
1159