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