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