1 //===- OperationSupport.cpp -----------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains out-of-line implementations of the support types that 10 // Operation and related classes build on top of. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "mlir/IR/OperationSupport.h" 15 #include "mlir/IR/BuiltinAttributes.h" 16 #include "mlir/IR/BuiltinTypes.h" 17 #include "mlir/IR/OpDefinition.h" 18 #include "llvm/ADT/BitVector.h" 19 #include <numeric> 20 21 using namespace mlir; 22 23 //===----------------------------------------------------------------------===// 24 // NamedAttrList 25 //===----------------------------------------------------------------------===// 26 27 NamedAttrList::NamedAttrList(ArrayRef<NamedAttribute> attributes) { 28 assign(attributes.begin(), attributes.end()); 29 } 30 31 NamedAttrList::NamedAttrList(DictionaryAttr attributes) 32 : NamedAttrList(attributes ? attributes.getValue() 33 : ArrayRef<NamedAttribute>()) { 34 dictionarySorted.setPointerAndInt(attributes, true); 35 } 36 37 NamedAttrList::NamedAttrList(const_iterator in_start, const_iterator in_end) { 38 assign(in_start, in_end); 39 } 40 41 ArrayRef<NamedAttribute> NamedAttrList::getAttrs() const { return attrs; } 42 43 Optional<NamedAttribute> NamedAttrList::findDuplicate() const { 44 Optional<NamedAttribute> duplicate = 45 DictionaryAttr::findDuplicate(attrs, isSorted()); 46 // DictionaryAttr::findDuplicate will sort the list, so reset the sorted 47 // state. 48 if (!isSorted()) 49 dictionarySorted.setPointerAndInt(nullptr, true); 50 return duplicate; 51 } 52 53 DictionaryAttr NamedAttrList::getDictionary(MLIRContext *context) const { 54 if (!isSorted()) { 55 DictionaryAttr::sortInPlace(attrs); 56 dictionarySorted.setPointerAndInt(nullptr, true); 57 } 58 if (!dictionarySorted.getPointer()) 59 dictionarySorted.setPointer(DictionaryAttr::getWithSorted(context, attrs)); 60 return dictionarySorted.getPointer().cast<DictionaryAttr>(); 61 } 62 63 /// Add an attribute with the specified name. 64 void NamedAttrList::append(StringRef name, Attribute attr) { 65 append(StringAttr::get(attr.getContext(), name), attr); 66 } 67 68 /// Replaces the attributes with new list of attributes. 69 void NamedAttrList::assign(const_iterator in_start, const_iterator in_end) { 70 DictionaryAttr::sort(ArrayRef<NamedAttribute>{in_start, in_end}, attrs); 71 dictionarySorted.setPointerAndInt(nullptr, true); 72 } 73 74 void NamedAttrList::push_back(NamedAttribute newAttribute) { 75 if (isSorted()) 76 dictionarySorted.setInt(attrs.empty() || attrs.back() < newAttribute); 77 dictionarySorted.setPointer(nullptr); 78 attrs.push_back(newAttribute); 79 } 80 81 /// Return the specified attribute if present, null otherwise. 82 Attribute NamedAttrList::get(StringRef name) const { 83 auto it = findAttr(*this, name); 84 return it.second ? it.first->getValue() : Attribute(); 85 } 86 Attribute NamedAttrList::get(StringAttr name) const { 87 auto it = findAttr(*this, name); 88 return it.second ? it.first->getValue() : Attribute(); 89 } 90 91 /// Return the specified named attribute if present, None otherwise. 92 Optional<NamedAttribute> NamedAttrList::getNamed(StringRef name) const { 93 auto it = findAttr(*this, name); 94 return it.second ? *it.first : Optional<NamedAttribute>(); 95 } 96 Optional<NamedAttribute> NamedAttrList::getNamed(StringAttr name) const { 97 auto it = findAttr(*this, name); 98 return it.second ? *it.first : Optional<NamedAttribute>(); 99 } 100 101 /// If the an attribute exists with the specified name, change it to the new 102 /// value. Otherwise, add a new attribute with the specified name/value. 103 Attribute NamedAttrList::set(StringAttr name, Attribute value) { 104 assert(value && "attributes may never be null"); 105 106 // Look for an existing attribute with the given name, and set its value 107 // in-place. Return the previous value of the attribute, if there was one. 108 auto it = findAttr(*this, name); 109 if (it.second) { 110 // Update the existing attribute by swapping out the old value for the new 111 // value. Return the old value. 112 Attribute oldValue = it.first->getValue(); 113 if (it.first->getValue() != value) { 114 it.first->setValue(value); 115 116 // If the attributes have changed, the dictionary is invalidated. 117 dictionarySorted.setPointer(nullptr); 118 } 119 return oldValue; 120 } 121 // Perform a string lookup to insert the new attribute into its sorted 122 // position. 123 if (isSorted()) 124 it = findAttr(*this, name.strref()); 125 attrs.insert(it.first, {name, value}); 126 // Invalidate the dictionary. Return null as there was no previous value. 127 dictionarySorted.setPointer(nullptr); 128 return Attribute(); 129 } 130 131 Attribute NamedAttrList::set(StringRef name, Attribute value) { 132 assert(value && "attributes may never be null"); 133 return set(mlir::StringAttr::get(value.getContext(), name), value); 134 } 135 136 Attribute 137 NamedAttrList::eraseImpl(SmallVectorImpl<NamedAttribute>::iterator it) { 138 // Erasing does not affect the sorted property. 139 Attribute attr = it->getValue(); 140 attrs.erase(it); 141 dictionarySorted.setPointer(nullptr); 142 return attr; 143 } 144 145 Attribute NamedAttrList::erase(StringAttr name) { 146 auto it = findAttr(*this, name); 147 return it.second ? eraseImpl(it.first) : Attribute(); 148 } 149 150 Attribute NamedAttrList::erase(StringRef name) { 151 auto it = findAttr(*this, name); 152 return it.second ? eraseImpl(it.first) : Attribute(); 153 } 154 155 NamedAttrList & 156 NamedAttrList::operator=(const SmallVectorImpl<NamedAttribute> &rhs) { 157 assign(rhs.begin(), rhs.end()); 158 return *this; 159 } 160 161 NamedAttrList::operator ArrayRef<NamedAttribute>() const { return attrs; } 162 163 //===----------------------------------------------------------------------===// 164 // OperationState 165 //===----------------------------------------------------------------------===// 166 167 OperationState::OperationState(Location location, StringRef name) 168 : location(location), name(name, location->getContext()) {} 169 170 OperationState::OperationState(Location location, OperationName name) 171 : location(location), name(name) {} 172 173 OperationState::OperationState(Location location, StringRef name, 174 ValueRange operands, TypeRange types, 175 ArrayRef<NamedAttribute> attributes, 176 BlockRange successors, 177 MutableArrayRef<std::unique_ptr<Region>> regions) 178 : location(location), name(name, location->getContext()), 179 operands(operands.begin(), operands.end()), 180 types(types.begin(), types.end()), 181 attributes(attributes.begin(), attributes.end()), 182 successors(successors.begin(), successors.end()) { 183 for (std::unique_ptr<Region> &r : regions) 184 this->regions.push_back(std::move(r)); 185 } 186 187 void OperationState::addOperands(ValueRange newOperands) { 188 operands.append(newOperands.begin(), newOperands.end()); 189 } 190 191 void OperationState::addSuccessors(BlockRange newSuccessors) { 192 successors.append(newSuccessors.begin(), newSuccessors.end()); 193 } 194 195 Region *OperationState::addRegion() { 196 regions.emplace_back(new Region); 197 return regions.back().get(); 198 } 199 200 void OperationState::addRegion(std::unique_ptr<Region> &®ion) { 201 regions.push_back(std::move(region)); 202 } 203 204 void OperationState::addRegions( 205 MutableArrayRef<std::unique_ptr<Region>> regions) { 206 for (std::unique_ptr<Region> ®ion : regions) 207 addRegion(std::move(region)); 208 } 209 210 //===----------------------------------------------------------------------===// 211 // OperandStorage 212 //===----------------------------------------------------------------------===// 213 214 detail::OperandStorage::OperandStorage(Operation *owner, 215 OpOperand *trailingOperands, 216 ValueRange values) 217 : isStorageDynamic(false), operandStorage(trailingOperands) { 218 numOperands = capacity = values.size(); 219 for (unsigned i = 0; i < numOperands; ++i) 220 new (&operandStorage[i]) OpOperand(owner, values[i]); 221 } 222 223 detail::OperandStorage::~OperandStorage() { 224 for (auto &operand : getOperands()) 225 operand.~OpOperand(); 226 227 // If the storage is dynamic, deallocate it. 228 if (isStorageDynamic) 229 free(operandStorage); 230 } 231 232 /// Replace the operands contained in the storage with the ones provided in 233 /// 'values'. 234 void detail::OperandStorage::setOperands(Operation *owner, ValueRange values) { 235 MutableArrayRef<OpOperand> storageOperands = resize(owner, values.size()); 236 for (unsigned i = 0, e = values.size(); i != e; ++i) 237 storageOperands[i].set(values[i]); 238 } 239 240 /// Replace the operands beginning at 'start' and ending at 'start' + 'length' 241 /// with the ones provided in 'operands'. 'operands' may be smaller or larger 242 /// than the range pointed to by 'start'+'length'. 243 void detail::OperandStorage::setOperands(Operation *owner, unsigned start, 244 unsigned length, ValueRange operands) { 245 // If the new size is the same, we can update inplace. 246 unsigned newSize = operands.size(); 247 if (newSize == length) { 248 MutableArrayRef<OpOperand> storageOperands = getOperands(); 249 for (unsigned i = 0, e = length; i != e; ++i) 250 storageOperands[start + i].set(operands[i]); 251 return; 252 } 253 // If the new size is greater, remove the extra operands and set the rest 254 // inplace. 255 if (newSize < length) { 256 eraseOperands(start + operands.size(), length - newSize); 257 setOperands(owner, start, newSize, operands); 258 return; 259 } 260 // Otherwise, the new size is greater so we need to grow the storage. 261 auto storageOperands = resize(owner, size() + (newSize - length)); 262 263 // Shift operands to the right to make space for the new operands. 264 unsigned rotateSize = storageOperands.size() - (start + length); 265 auto rbegin = storageOperands.rbegin(); 266 std::rotate(rbegin, std::next(rbegin, newSize - length), rbegin + rotateSize); 267 268 // Update the operands inplace. 269 for (unsigned i = 0, e = operands.size(); i != e; ++i) 270 storageOperands[start + i].set(operands[i]); 271 } 272 273 /// Erase an operand held by the storage. 274 void detail::OperandStorage::eraseOperands(unsigned start, unsigned length) { 275 MutableArrayRef<OpOperand> operands = getOperands(); 276 assert((start + length) <= operands.size()); 277 numOperands -= length; 278 279 // Shift all operands down if the operand to remove is not at the end. 280 if (start != numOperands) { 281 auto *indexIt = std::next(operands.begin(), start); 282 std::rotate(indexIt, std::next(indexIt, length), operands.end()); 283 } 284 for (unsigned i = 0; i != length; ++i) 285 operands[numOperands + i].~OpOperand(); 286 } 287 288 void detail::OperandStorage::eraseOperands( 289 const llvm::BitVector &eraseIndices) { 290 MutableArrayRef<OpOperand> operands = getOperands(); 291 assert(eraseIndices.size() == operands.size()); 292 293 // Check that at least one operand is erased. 294 int firstErasedIndice = eraseIndices.find_first(); 295 if (firstErasedIndice == -1) 296 return; 297 298 // Shift all of the removed operands to the end, and destroy them. 299 numOperands = firstErasedIndice; 300 for (unsigned i = firstErasedIndice + 1, e = operands.size(); i < e; ++i) 301 if (!eraseIndices.test(i)) 302 operands[numOperands++] = std::move(operands[i]); 303 for (OpOperand &operand : operands.drop_front(numOperands)) 304 operand.~OpOperand(); 305 } 306 307 /// Resize the storage to the given size. Returns the array containing the new 308 /// operands. 309 MutableArrayRef<OpOperand> detail::OperandStorage::resize(Operation *owner, 310 unsigned newSize) { 311 // If the number of operands is less than or equal to the current amount, we 312 // can just update in place. 313 MutableArrayRef<OpOperand> origOperands = getOperands(); 314 if (newSize <= numOperands) { 315 // If the number of new size is less than the current, remove any extra 316 // operands. 317 for (unsigned i = newSize; i != numOperands; ++i) 318 origOperands[i].~OpOperand(); 319 numOperands = newSize; 320 return origOperands.take_front(newSize); 321 } 322 323 // If the new size is within the original inline capacity, grow inplace. 324 if (newSize <= capacity) { 325 OpOperand *opBegin = origOperands.data(); 326 for (unsigned e = newSize; numOperands != e; ++numOperands) 327 new (&opBegin[numOperands]) OpOperand(owner); 328 return MutableArrayRef<OpOperand>(opBegin, newSize); 329 } 330 331 // Otherwise, we need to allocate a new storage. 332 unsigned newCapacity = 333 std::max(unsigned(llvm::NextPowerOf2(capacity + 2)), newSize); 334 OpOperand *newOperandStorage = 335 reinterpret_cast<OpOperand *>(malloc(sizeof(OpOperand) * newCapacity)); 336 337 // Move the current operands to the new storage. 338 MutableArrayRef<OpOperand> newOperands(newOperandStorage, newSize); 339 std::uninitialized_copy(std::make_move_iterator(origOperands.begin()), 340 std::make_move_iterator(origOperands.end()), 341 newOperands.begin()); 342 343 // Destroy the original operands. 344 for (auto &operand : origOperands) 345 operand.~OpOperand(); 346 347 // Initialize any new operands. 348 for (unsigned e = newSize; numOperands != e; ++numOperands) 349 new (&newOperands[numOperands]) OpOperand(owner); 350 351 // If the current storage is dynamic, free it. 352 if (isStorageDynamic) 353 free(operandStorage); 354 355 // Update the storage representation to use the new dynamic storage. 356 operandStorage = newOperandStorage; 357 capacity = newCapacity; 358 isStorageDynamic = true; 359 return newOperands; 360 } 361 362 //===----------------------------------------------------------------------===// 363 // Operation Value-Iterators 364 //===----------------------------------------------------------------------===// 365 366 //===----------------------------------------------------------------------===// 367 // OperandRange 368 369 unsigned OperandRange::getBeginOperandIndex() const { 370 assert(!empty() && "range must not be empty"); 371 return base->getOperandNumber(); 372 } 373 374 OperandRangeRange OperandRange::split(ElementsAttr segmentSizes) const { 375 return OperandRangeRange(*this, segmentSizes); 376 } 377 378 //===----------------------------------------------------------------------===// 379 // OperandRangeRange 380 381 OperandRangeRange::OperandRangeRange(OperandRange operands, 382 Attribute operandSegments) 383 : OperandRangeRange(OwnerT(operands.getBase(), operandSegments), 0, 384 operandSegments.cast<DenseElementsAttr>().size()) {} 385 386 OperandRange OperandRangeRange::join() const { 387 const OwnerT &owner = getBase(); 388 auto sizeData = owner.second.cast<DenseElementsAttr>().getValues<uint32_t>(); 389 return OperandRange(owner.first, 390 std::accumulate(sizeData.begin(), sizeData.end(), 0)); 391 } 392 393 OperandRange OperandRangeRange::dereference(const OwnerT &object, 394 ptrdiff_t index) { 395 auto sizeData = object.second.cast<DenseElementsAttr>().getValues<uint32_t>(); 396 uint32_t startIndex = 397 std::accumulate(sizeData.begin(), sizeData.begin() + index, 0); 398 return OperandRange(object.first + startIndex, *(sizeData.begin() + index)); 399 } 400 401 //===----------------------------------------------------------------------===// 402 // MutableOperandRange 403 404 /// Construct a new mutable range from the given operand, operand start index, 405 /// and range length. 406 MutableOperandRange::MutableOperandRange( 407 Operation *owner, unsigned start, unsigned length, 408 ArrayRef<OperandSegment> operandSegments) 409 : owner(owner), start(start), length(length), 410 operandSegments(operandSegments.begin(), operandSegments.end()) { 411 assert((start + length) <= owner->getNumOperands() && "invalid range"); 412 } 413 MutableOperandRange::MutableOperandRange(Operation *owner) 414 : MutableOperandRange(owner, /*start=*/0, owner->getNumOperands()) {} 415 416 /// Slice this range into a sub range, with the additional operand segment. 417 MutableOperandRange 418 MutableOperandRange::slice(unsigned subStart, unsigned subLen, 419 Optional<OperandSegment> segment) const { 420 assert((subStart + subLen) <= length && "invalid sub-range"); 421 MutableOperandRange subSlice(owner, start + subStart, subLen, 422 operandSegments); 423 if (segment) 424 subSlice.operandSegments.push_back(*segment); 425 return subSlice; 426 } 427 428 /// Append the given values to the range. 429 void MutableOperandRange::append(ValueRange values) { 430 if (values.empty()) 431 return; 432 owner->insertOperands(start + length, values); 433 updateLength(length + values.size()); 434 } 435 436 /// Assign this range to the given values. 437 void MutableOperandRange::assign(ValueRange values) { 438 owner->setOperands(start, length, values); 439 if (length != values.size()) 440 updateLength(/*newLength=*/values.size()); 441 } 442 443 /// Assign the range to the given value. 444 void MutableOperandRange::assign(Value value) { 445 if (length == 1) { 446 owner->setOperand(start, value); 447 } else { 448 owner->setOperands(start, length, value); 449 updateLength(/*newLength=*/1); 450 } 451 } 452 453 /// Erase the operands within the given sub-range. 454 void MutableOperandRange::erase(unsigned subStart, unsigned subLen) { 455 assert((subStart + subLen) <= length && "invalid sub-range"); 456 if (length == 0) 457 return; 458 owner->eraseOperands(start + subStart, subLen); 459 updateLength(length - subLen); 460 } 461 462 /// Clear this range and erase all of the operands. 463 void MutableOperandRange::clear() { 464 if (length != 0) { 465 owner->eraseOperands(start, length); 466 updateLength(/*newLength=*/0); 467 } 468 } 469 470 /// Allow implicit conversion to an OperandRange. 471 MutableOperandRange::operator OperandRange() const { 472 return owner->getOperands().slice(start, length); 473 } 474 475 MutableOperandRangeRange 476 MutableOperandRange::split(NamedAttribute segmentSizes) const { 477 return MutableOperandRangeRange(*this, segmentSizes); 478 } 479 480 /// Update the length of this range to the one provided. 481 void MutableOperandRange::updateLength(unsigned newLength) { 482 int32_t diff = int32_t(newLength) - int32_t(length); 483 length = newLength; 484 485 // Update any of the provided segment attributes. 486 for (OperandSegment &segment : operandSegments) { 487 auto attr = segment.second.getValue().cast<DenseIntElementsAttr>(); 488 SmallVector<int32_t, 8> segments(attr.getValues<int32_t>()); 489 segments[segment.first] += diff; 490 segment.second.setValue( 491 DenseIntElementsAttr::get(attr.getType(), segments)); 492 owner->setAttr(segment.second.getName(), segment.second.getValue()); 493 } 494 } 495 496 //===----------------------------------------------------------------------===// 497 // MutableOperandRangeRange 498 499 MutableOperandRangeRange::MutableOperandRangeRange( 500 const MutableOperandRange &operands, NamedAttribute operandSegmentAttr) 501 : MutableOperandRangeRange( 502 OwnerT(operands, operandSegmentAttr), 0, 503 operandSegmentAttr.getValue().cast<DenseElementsAttr>().size()) {} 504 505 MutableOperandRange MutableOperandRangeRange::join() const { 506 return getBase().first; 507 } 508 509 MutableOperandRangeRange::operator OperandRangeRange() const { 510 return OperandRangeRange( 511 getBase().first, getBase().second.getValue().cast<DenseElementsAttr>()); 512 } 513 514 MutableOperandRange MutableOperandRangeRange::dereference(const OwnerT &object, 515 ptrdiff_t index) { 516 auto sizeData = 517 object.second.getValue().cast<DenseElementsAttr>().getValues<uint32_t>(); 518 uint32_t startIndex = 519 std::accumulate(sizeData.begin(), sizeData.begin() + index, 0); 520 return object.first.slice( 521 startIndex, *(sizeData.begin() + index), 522 MutableOperandRange::OperandSegment(index, object.second)); 523 } 524 525 //===----------------------------------------------------------------------===// 526 // ResultRange 527 528 ResultRange::ResultRange(OpResult result) 529 : ResultRange(static_cast<detail::OpResultImpl *>(Value(result).getImpl()), 530 1) {} 531 532 ResultRange::use_range ResultRange::getUses() const { 533 return {use_begin(), use_end()}; 534 } 535 ResultRange::use_iterator ResultRange::use_begin() const { 536 return use_iterator(*this); 537 } 538 ResultRange::use_iterator ResultRange::use_end() const { 539 return use_iterator(*this, /*end=*/true); 540 } 541 ResultRange::user_range ResultRange::getUsers() { 542 return {user_begin(), user_end()}; 543 } 544 ResultRange::user_iterator ResultRange::user_begin() { 545 return user_iterator(use_begin()); 546 } 547 ResultRange::user_iterator ResultRange::user_end() { 548 return user_iterator(use_end()); 549 } 550 551 ResultRange::UseIterator::UseIterator(ResultRange results, bool end) 552 : it(end ? results.end() : results.begin()), endIt(results.end()) { 553 // Only initialize current use if there are results/can be uses. 554 if (it != endIt) 555 skipOverResultsWithNoUsers(); 556 } 557 558 ResultRange::UseIterator &ResultRange::UseIterator::operator++() { 559 // We increment over uses, if we reach the last use then move to next 560 // result. 561 if (use != (*it).use_end()) 562 ++use; 563 if (use == (*it).use_end()) { 564 ++it; 565 skipOverResultsWithNoUsers(); 566 } 567 return *this; 568 } 569 570 void ResultRange::UseIterator::skipOverResultsWithNoUsers() { 571 while (it != endIt && (*it).use_empty()) 572 ++it; 573 574 // If we are at the last result, then set use to first use of 575 // first result (sentinel value used for end). 576 if (it == endIt) 577 use = {}; 578 else 579 use = (*it).use_begin(); 580 } 581 582 void ResultRange::replaceAllUsesWith(Operation *op) { 583 replaceAllUsesWith(op->getResults()); 584 } 585 586 //===----------------------------------------------------------------------===// 587 // ValueRange 588 589 ValueRange::ValueRange(ArrayRef<Value> values) 590 : ValueRange(values.data(), values.size()) {} 591 ValueRange::ValueRange(OperandRange values) 592 : ValueRange(values.begin().getBase(), values.size()) {} 593 ValueRange::ValueRange(ResultRange values) 594 : ValueRange(values.getBase(), values.size()) {} 595 596 /// See `llvm::detail::indexed_accessor_range_base` for details. 597 ValueRange::OwnerT ValueRange::offset_base(const OwnerT &owner, 598 ptrdiff_t index) { 599 if (const auto *value = owner.dyn_cast<const Value *>()) 600 return {value + index}; 601 if (auto *operand = owner.dyn_cast<OpOperand *>()) 602 return {operand + index}; 603 return owner.get<detail::OpResultImpl *>()->getNextResultAtOffset(index); 604 } 605 /// See `llvm::detail::indexed_accessor_range_base` for details. 606 Value ValueRange::dereference_iterator(const OwnerT &owner, ptrdiff_t index) { 607 if (const auto *value = owner.dyn_cast<const Value *>()) 608 return value[index]; 609 if (auto *operand = owner.dyn_cast<OpOperand *>()) 610 return operand[index].get(); 611 return owner.get<detail::OpResultImpl *>()->getNextResultAtOffset(index); 612 } 613 614 //===----------------------------------------------------------------------===// 615 // Operation Equivalency 616 //===----------------------------------------------------------------------===// 617 618 llvm::hash_code OperationEquivalence::computeHash( 619 Operation *op, function_ref<llvm::hash_code(Value)> hashOperands, 620 function_ref<llvm::hash_code(Value)> hashResults, Flags flags) { 621 // Hash operations based upon their: 622 // - Operation Name 623 // - Attributes 624 // - Result Types 625 llvm::hash_code hash = llvm::hash_combine( 626 op->getName(), op->getAttrDictionary(), op->getResultTypes()); 627 628 // - Operands 629 for (Value operand : op->getOperands()) 630 hash = llvm::hash_combine(hash, hashOperands(operand)); 631 // - Operands 632 for (Value result : op->getResults()) 633 hash = llvm::hash_combine(hash, hashResults(result)); 634 return hash; 635 } 636 637 static bool 638 isRegionEquivalentTo(Region *lhs, Region *rhs, 639 function_ref<LogicalResult(Value, Value)> mapOperands, 640 function_ref<LogicalResult(Value, Value)> mapResults, 641 OperationEquivalence::Flags flags) { 642 DenseMap<Block *, Block *> blocksMap; 643 auto blocksEquivalent = [&](Block &lBlock, Block &rBlock) { 644 // Check block arguments. 645 if (lBlock.getNumArguments() != rBlock.getNumArguments()) 646 return false; 647 648 // Map the two blocks. 649 auto insertion = blocksMap.insert({&lBlock, &rBlock}); 650 if (insertion.first->getSecond() != &rBlock) 651 return false; 652 653 for (auto argPair : 654 llvm::zip(lBlock.getArguments(), rBlock.getArguments())) { 655 Value curArg = std::get<0>(argPair); 656 Value otherArg = std::get<1>(argPair); 657 if (curArg.getType() != otherArg.getType()) 658 return false; 659 if (!(flags & OperationEquivalence::IgnoreLocations) && 660 curArg.getLoc() != otherArg.getLoc()) 661 return false; 662 // Check if this value was already mapped to another value. 663 if (failed(mapOperands(curArg, otherArg))) 664 return false; 665 } 666 667 auto opsEquivalent = [&](Operation &lOp, Operation &rOp) { 668 // Check for op equality (recursively). 669 if (!OperationEquivalence::isEquivalentTo(&lOp, &rOp, mapOperands, 670 mapResults, flags)) 671 return false; 672 // Check successor mapping. 673 for (auto successorsPair : 674 llvm::zip(lOp.getSuccessors(), rOp.getSuccessors())) { 675 Block *curSuccessor = std::get<0>(successorsPair); 676 Block *otherSuccessor = std::get<1>(successorsPair); 677 auto insertion = blocksMap.insert({curSuccessor, otherSuccessor}); 678 if (insertion.first->getSecond() != otherSuccessor) 679 return false; 680 } 681 return true; 682 }; 683 return llvm::all_of_zip(lBlock, rBlock, opsEquivalent); 684 }; 685 return llvm::all_of_zip(*lhs, *rhs, blocksEquivalent); 686 } 687 688 bool OperationEquivalence::isEquivalentTo( 689 Operation *lhs, Operation *rhs, 690 function_ref<LogicalResult(Value, Value)> mapOperands, 691 function_ref<LogicalResult(Value, Value)> mapResults, Flags flags) { 692 if (lhs == rhs) 693 return true; 694 695 // Compare the operation properties. 696 if (lhs->getName() != rhs->getName() || 697 lhs->getAttrDictionary() != rhs->getAttrDictionary() || 698 lhs->getNumRegions() != rhs->getNumRegions() || 699 lhs->getNumSuccessors() != rhs->getNumSuccessors() || 700 lhs->getNumOperands() != rhs->getNumOperands() || 701 lhs->getNumResults() != rhs->getNumResults()) 702 return false; 703 if (!(flags & IgnoreLocations) && lhs->getLoc() != rhs->getLoc()) 704 return false; 705 706 auto checkValueRangeMapping = 707 [](ValueRange lhs, ValueRange rhs, 708 function_ref<LogicalResult(Value, Value)> mapValues) { 709 for (auto operandPair : llvm::zip(lhs, rhs)) { 710 Value curArg = std::get<0>(operandPair); 711 Value otherArg = std::get<1>(operandPair); 712 if (curArg.getType() != otherArg.getType()) 713 return false; 714 if (failed(mapValues(curArg, otherArg))) 715 return false; 716 } 717 return true; 718 }; 719 // Check mapping of operands and results. 720 if (!checkValueRangeMapping(lhs->getOperands(), rhs->getOperands(), 721 mapOperands)) 722 return false; 723 if (!checkValueRangeMapping(lhs->getResults(), rhs->getResults(), mapResults)) 724 return false; 725 for (auto regionPair : llvm::zip(lhs->getRegions(), rhs->getRegions())) 726 if (!isRegionEquivalentTo(&std::get<0>(regionPair), 727 &std::get<1>(regionPair), mapOperands, mapResults, 728 flags)) 729 return false; 730 return true; 731 } 732