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/BuiltinTypes.h" 16 #include "mlir/IR/OpDefinition.h" 17 #include "llvm/ADT/BitVector.h" 18 19 using namespace mlir; 20 21 //===----------------------------------------------------------------------===// 22 // NamedAttrList 23 //===----------------------------------------------------------------------===// 24 25 NamedAttrList::NamedAttrList(ArrayRef<NamedAttribute> attributes) { 26 assign(attributes.begin(), attributes.end()); 27 } 28 29 NamedAttrList::NamedAttrList(DictionaryAttr attributes) 30 : NamedAttrList(attributes ? attributes.getValue() 31 : ArrayRef<NamedAttribute>()) { 32 dictionarySorted.setPointerAndInt(attributes, true); 33 } 34 35 NamedAttrList::NamedAttrList(const_iterator in_start, const_iterator in_end) { 36 assign(in_start, in_end); 37 } 38 39 ArrayRef<NamedAttribute> NamedAttrList::getAttrs() const { return attrs; } 40 41 Optional<NamedAttribute> NamedAttrList::findDuplicate() const { 42 Optional<NamedAttribute> duplicate = 43 DictionaryAttr::findDuplicate(attrs, isSorted()); 44 // DictionaryAttr::findDuplicate will sort the list, so reset the sorted 45 // state. 46 if (!isSorted()) 47 dictionarySorted.setPointerAndInt(nullptr, true); 48 return duplicate; 49 } 50 51 DictionaryAttr NamedAttrList::getDictionary(MLIRContext *context) const { 52 if (!isSorted()) { 53 DictionaryAttr::sortInPlace(attrs); 54 dictionarySorted.setPointerAndInt(nullptr, true); 55 } 56 if (!dictionarySorted.getPointer()) 57 dictionarySorted.setPointer(DictionaryAttr::getWithSorted(context, attrs)); 58 return dictionarySorted.getPointer().cast<DictionaryAttr>(); 59 } 60 61 /// Add an attribute with the specified name. 62 void NamedAttrList::append(StringRef name, Attribute attr) { 63 append(Identifier::get(name, attr.getContext()), attr); 64 } 65 66 /// Replaces the attributes with new list of attributes. 67 void NamedAttrList::assign(const_iterator in_start, const_iterator in_end) { 68 DictionaryAttr::sort(ArrayRef<NamedAttribute>{in_start, in_end}, attrs); 69 dictionarySorted.setPointerAndInt(nullptr, true); 70 } 71 72 void NamedAttrList::push_back(NamedAttribute newAttribute) { 73 if (isSorted()) 74 dictionarySorted.setInt( 75 attrs.empty() || 76 strcmp(attrs.back().first.data(), newAttribute.first.data()) < 0); 77 dictionarySorted.setPointer(nullptr); 78 attrs.push_back(newAttribute); 79 } 80 81 /// Helper function to find attribute in possible sorted vector of 82 /// NamedAttributes. 83 template <typename T> 84 static auto *findAttr(SmallVectorImpl<NamedAttribute> &attrs, T name, 85 bool sorted) { 86 if (!sorted) { 87 return llvm::find_if( 88 attrs, [name](NamedAttribute attr) { return attr.first == name; }); 89 } 90 91 auto *it = llvm::lower_bound(attrs, name); 92 if (it == attrs.end() || it->first != name) 93 return attrs.end(); 94 return it; 95 } 96 97 /// Return the specified attribute if present, null otherwise. 98 Attribute NamedAttrList::get(StringRef name) const { 99 auto *it = findAttr(attrs, name, isSorted()); 100 return it != attrs.end() ? it->second : nullptr; 101 } 102 103 /// Return the specified attribute if present, null otherwise. 104 Attribute NamedAttrList::get(Identifier name) const { 105 auto *it = findAttr(attrs, name, isSorted()); 106 return it != attrs.end() ? it->second : nullptr; 107 } 108 109 /// Return the specified named attribute if present, None otherwise. 110 Optional<NamedAttribute> NamedAttrList::getNamed(StringRef name) const { 111 auto *it = findAttr(attrs, name, isSorted()); 112 return it != attrs.end() ? *it : Optional<NamedAttribute>(); 113 } 114 Optional<NamedAttribute> NamedAttrList::getNamed(Identifier name) const { 115 auto *it = findAttr(attrs, name, isSorted()); 116 return it != attrs.end() ? *it : Optional<NamedAttribute>(); 117 } 118 119 /// If the an attribute exists with the specified name, change it to the new 120 /// value. Otherwise, add a new attribute with the specified name/value. 121 Attribute NamedAttrList::set(Identifier name, Attribute value) { 122 assert(value && "attributes may never be null"); 123 124 // Look for an existing value for the given name, and set it in-place. 125 auto *it = findAttr(attrs, name, isSorted()); 126 if (it != attrs.end()) { 127 // Only update if the value is different from the existing. 128 Attribute oldValue = it->second; 129 if (oldValue != value) { 130 dictionarySorted.setPointer(nullptr); 131 it->second = value; 132 } 133 return oldValue; 134 } 135 136 // Otherwise, insert the new attribute into its sorted position. 137 it = llvm::lower_bound(attrs, name); 138 dictionarySorted.setPointer(nullptr); 139 attrs.insert(it, {name, value}); 140 return Attribute(); 141 } 142 Attribute NamedAttrList::set(StringRef name, Attribute value) { 143 assert(value && "setting null attribute not supported"); 144 return set(mlir::Identifier::get(name, value.getContext()), value); 145 } 146 147 Attribute 148 NamedAttrList::eraseImpl(SmallVectorImpl<NamedAttribute>::iterator it) { 149 if (it == attrs.end()) 150 return nullptr; 151 152 // Erasing does not affect the sorted property. 153 Attribute attr = it->second; 154 attrs.erase(it); 155 dictionarySorted.setPointer(nullptr); 156 return attr; 157 } 158 159 Attribute NamedAttrList::erase(Identifier name) { 160 return eraseImpl(findAttr(attrs, name, isSorted())); 161 } 162 163 Attribute NamedAttrList::erase(StringRef name) { 164 return eraseImpl(findAttr(attrs, name, isSorted())); 165 } 166 167 NamedAttrList & 168 NamedAttrList::operator=(const SmallVectorImpl<NamedAttribute> &rhs) { 169 assign(rhs.begin(), rhs.end()); 170 return *this; 171 } 172 173 NamedAttrList::operator ArrayRef<NamedAttribute>() const { return attrs; } 174 175 //===----------------------------------------------------------------------===// 176 // OperationState 177 //===----------------------------------------------------------------------===// 178 179 OperationState::OperationState(Location location, StringRef name) 180 : location(location), name(name, location->getContext()) {} 181 182 OperationState::OperationState(Location location, OperationName name) 183 : location(location), name(name) {} 184 185 OperationState::OperationState(Location location, StringRef name, 186 ValueRange operands, TypeRange types, 187 ArrayRef<NamedAttribute> attributes, 188 BlockRange successors, 189 MutableArrayRef<std::unique_ptr<Region>> regions) 190 : location(location), name(name, location->getContext()), 191 operands(operands.begin(), operands.end()), 192 types(types.begin(), types.end()), 193 attributes(attributes.begin(), attributes.end()), 194 successors(successors.begin(), successors.end()) { 195 for (std::unique_ptr<Region> &r : regions) 196 this->regions.push_back(std::move(r)); 197 } 198 199 void OperationState::addOperands(ValueRange newOperands) { 200 operands.append(newOperands.begin(), newOperands.end()); 201 } 202 203 void OperationState::addSuccessors(BlockRange newSuccessors) { 204 successors.append(newSuccessors.begin(), newSuccessors.end()); 205 } 206 207 Region *OperationState::addRegion() { 208 regions.emplace_back(new Region); 209 return regions.back().get(); 210 } 211 212 void OperationState::addRegion(std::unique_ptr<Region> &®ion) { 213 regions.push_back(std::move(region)); 214 } 215 216 void OperationState::addRegions( 217 MutableArrayRef<std::unique_ptr<Region>> regions) { 218 for (std::unique_ptr<Region> ®ion : regions) 219 addRegion(std::move(region)); 220 } 221 222 //===----------------------------------------------------------------------===// 223 // OperandStorage 224 //===----------------------------------------------------------------------===// 225 226 detail::OperandStorage::OperandStorage(Operation *owner, ValueRange values) 227 : representation(0) { 228 auto &inlineStorage = getInlineStorage(); 229 inlineStorage.numOperands = inlineStorage.capacity = values.size(); 230 auto *operandPtrBegin = getTrailingObjects<OpOperand>(); 231 for (unsigned i = 0, e = inlineStorage.numOperands; i < e; ++i) 232 new (&operandPtrBegin[i]) OpOperand(owner, values[i]); 233 } 234 235 detail::OperandStorage::~OperandStorage() { 236 // Destruct the current storage container. 237 if (isDynamicStorage()) { 238 TrailingOperandStorage &storage = getDynamicStorage(); 239 storage.~TrailingOperandStorage(); 240 free(&storage); 241 } else { 242 getInlineStorage().~TrailingOperandStorage(); 243 } 244 } 245 246 /// Replace the operands contained in the storage with the ones provided in 247 /// 'values'. 248 void detail::OperandStorage::setOperands(Operation *owner, ValueRange values) { 249 MutableArrayRef<OpOperand> storageOperands = resize(owner, values.size()); 250 for (unsigned i = 0, e = values.size(); i != e; ++i) 251 storageOperands[i].set(values[i]); 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 detail::OperandStorage::setOperands(Operation *owner, unsigned start, 258 unsigned length, ValueRange operands) { 259 // If the new size is the same, we can update inplace. 260 unsigned newSize = operands.size(); 261 if (newSize == length) { 262 MutableArrayRef<OpOperand> storageOperands = getOperands(); 263 for (unsigned i = 0, e = length; i != e; ++i) 264 storageOperands[start + i].set(operands[i]); 265 return; 266 } 267 // If the new size is greater, remove the extra operands and set the rest 268 // inplace. 269 if (newSize < length) { 270 eraseOperands(start + operands.size(), length - newSize); 271 setOperands(owner, start, newSize, operands); 272 return; 273 } 274 // Otherwise, the new size is greater so we need to grow the storage. 275 auto storageOperands = resize(owner, size() + (newSize - length)); 276 277 // Shift operands to the right to make space for the new operands. 278 unsigned rotateSize = storageOperands.size() - (start + length); 279 auto rbegin = storageOperands.rbegin(); 280 std::rotate(rbegin, std::next(rbegin, newSize - length), rbegin + rotateSize); 281 282 // Update the operands inplace. 283 for (unsigned i = 0, e = operands.size(); i != e; ++i) 284 storageOperands[start + i].set(operands[i]); 285 } 286 287 /// Erase an operand held by the storage. 288 void detail::OperandStorage::eraseOperands(unsigned start, unsigned length) { 289 TrailingOperandStorage &storage = getStorage(); 290 MutableArrayRef<OpOperand> operands = storage.getOperands(); 291 assert((start + length) <= operands.size()); 292 storage.numOperands -= length; 293 294 // Shift all operands down if the operand to remove is not at the end. 295 if (start != storage.numOperands) { 296 auto *indexIt = std::next(operands.begin(), start); 297 std::rotate(indexIt, std::next(indexIt, length), operands.end()); 298 } 299 for (unsigned i = 0; i != length; ++i) 300 operands[storage.numOperands + i].~OpOperand(); 301 } 302 303 void detail::OperandStorage::eraseOperands( 304 const llvm::BitVector &eraseIndices) { 305 TrailingOperandStorage &storage = getStorage(); 306 MutableArrayRef<OpOperand> operands = storage.getOperands(); 307 assert(eraseIndices.size() == operands.size()); 308 309 // Check that at least one operand is erased. 310 int firstErasedIndice = eraseIndices.find_first(); 311 if (firstErasedIndice == -1) 312 return; 313 314 // Shift all of the removed operands to the end, and destroy them. 315 storage.numOperands = firstErasedIndice; 316 for (unsigned i = firstErasedIndice + 1, e = operands.size(); i < e; ++i) 317 if (!eraseIndices.test(i)) 318 operands[storage.numOperands++] = std::move(operands[i]); 319 for (OpOperand &operand : operands.drop_front(storage.numOperands)) 320 operand.~OpOperand(); 321 } 322 323 /// Resize the storage to the given size. Returns the array containing the new 324 /// operands. 325 MutableArrayRef<OpOperand> detail::OperandStorage::resize(Operation *owner, 326 unsigned newSize) { 327 TrailingOperandStorage &storage = getStorage(); 328 329 // If the number of operands is less than or equal to the current amount, we 330 // can just update in place. 331 unsigned &numOperands = storage.numOperands; 332 MutableArrayRef<OpOperand> operands = storage.getOperands(); 333 if (newSize <= numOperands) { 334 // If the number of new size is less than the current, remove any extra 335 // operands. 336 for (unsigned i = newSize; i != numOperands; ++i) 337 operands[i].~OpOperand(); 338 numOperands = newSize; 339 return operands.take_front(newSize); 340 } 341 342 // If the new size is within the original inline capacity, grow inplace. 343 if (newSize <= storage.capacity) { 344 OpOperand *opBegin = operands.data(); 345 for (unsigned e = newSize; numOperands != e; ++numOperands) 346 new (&opBegin[numOperands]) OpOperand(owner); 347 return MutableArrayRef<OpOperand>(opBegin, newSize); 348 } 349 350 // Otherwise, we need to allocate a new storage. 351 unsigned newCapacity = 352 std::max(unsigned(llvm::NextPowerOf2(storage.capacity + 2)), newSize); 353 auto *newStorageMem = 354 malloc(TrailingOperandStorage::totalSizeToAlloc<OpOperand>(newCapacity)); 355 auto *newStorage = ::new (newStorageMem) TrailingOperandStorage(); 356 newStorage->numOperands = newSize; 357 newStorage->capacity = newCapacity; 358 359 // Move the current operands to the new storage. 360 MutableArrayRef<OpOperand> newOperands = newStorage->getOperands(); 361 std::uninitialized_copy(std::make_move_iterator(operands.begin()), 362 std::make_move_iterator(operands.end()), 363 newOperands.begin()); 364 365 // Destroy the original operands. 366 for (auto &operand : operands) 367 operand.~OpOperand(); 368 369 // Initialize any new operands. 370 for (unsigned e = newSize; numOperands != e; ++numOperands) 371 new (&newOperands[numOperands]) OpOperand(owner); 372 373 // If the current storage is also dynamic, free it. 374 if (isDynamicStorage()) 375 free(&storage); 376 377 // Update the storage representation to use the new dynamic storage. 378 representation = reinterpret_cast<intptr_t>(newStorage); 379 representation |= DynamicStorageBit; 380 return newOperands; 381 } 382 383 //===----------------------------------------------------------------------===// 384 // Operation Value-Iterators 385 //===----------------------------------------------------------------------===// 386 387 //===----------------------------------------------------------------------===// 388 // OperandRange 389 390 OperandRange::OperandRange(Operation *op) 391 : OperandRange(op->getOpOperands().data(), op->getNumOperands()) {} 392 393 /// Return the operand index of the first element of this range. The range 394 /// must not be empty. 395 unsigned OperandRange::getBeginOperandIndex() const { 396 assert(!empty() && "range must not be empty"); 397 return base->getOperandNumber(); 398 } 399 400 //===----------------------------------------------------------------------===// 401 // MutableOperandRange 402 403 /// Construct a new mutable range from the given operand, operand start index, 404 /// and range length. 405 MutableOperandRange::MutableOperandRange( 406 Operation *owner, unsigned start, unsigned length, 407 ArrayRef<OperandSegment> operandSegments) 408 : owner(owner), start(start), length(length), 409 operandSegments(operandSegments.begin(), operandSegments.end()) { 410 assert((start + length) <= owner->getNumOperands() && "invalid range"); 411 } 412 MutableOperandRange::MutableOperandRange(Operation *owner) 413 : MutableOperandRange(owner, /*start=*/0, owner->getNumOperands()) {} 414 415 /// Slice this range into a sub range, with the additional operand segment. 416 MutableOperandRange 417 MutableOperandRange::slice(unsigned subStart, unsigned subLen, 418 Optional<OperandSegment> segment) { 419 assert((subStart + subLen) <= length && "invalid sub-range"); 420 MutableOperandRange subSlice(owner, start + subStart, subLen, 421 operandSegments); 422 if (segment) 423 subSlice.operandSegments.push_back(*segment); 424 return subSlice; 425 } 426 427 /// Append the given values to the range. 428 void MutableOperandRange::append(ValueRange values) { 429 if (values.empty()) 430 return; 431 owner->insertOperands(start + length, values); 432 updateLength(length + values.size()); 433 } 434 435 /// Assign this range to the given values. 436 void MutableOperandRange::assign(ValueRange values) { 437 owner->setOperands(start, length, values); 438 if (length != values.size()) 439 updateLength(/*newLength=*/values.size()); 440 } 441 442 /// Assign the range to the given value. 443 void MutableOperandRange::assign(Value value) { 444 if (length == 1) { 445 owner->setOperand(start, value); 446 } else { 447 owner->setOperands(start, length, value); 448 updateLength(/*newLength=*/1); 449 } 450 } 451 452 /// Erase the operands within the given sub-range. 453 void MutableOperandRange::erase(unsigned subStart, unsigned subLen) { 454 assert((subStart + subLen) <= length && "invalid sub-range"); 455 if (length == 0) 456 return; 457 owner->eraseOperands(start + subStart, subLen); 458 updateLength(length - subLen); 459 } 460 461 /// Clear this range and erase all of the operands. 462 void MutableOperandRange::clear() { 463 if (length != 0) { 464 owner->eraseOperands(start, length); 465 updateLength(/*newLength=*/0); 466 } 467 } 468 469 /// Allow implicit conversion to an OperandRange. 470 MutableOperandRange::operator OperandRange() const { 471 return owner->getOperands().slice(start, length); 472 } 473 474 /// Update the length of this range to the one provided. 475 void MutableOperandRange::updateLength(unsigned newLength) { 476 int32_t diff = int32_t(newLength) - int32_t(length); 477 length = newLength; 478 479 // Update any of the provided segment attributes. 480 for (OperandSegment &segment : operandSegments) { 481 auto attr = segment.second.second.cast<DenseIntElementsAttr>(); 482 SmallVector<int32_t, 8> segments(attr.getValues<int32_t>()); 483 segments[segment.first] += diff; 484 segment.second.second = DenseIntElementsAttr::get(attr.getType(), segments); 485 owner->setAttr(segment.second.first, segment.second.second); 486 } 487 } 488 489 //===----------------------------------------------------------------------===// 490 // ValueRange 491 492 ValueRange::ValueRange(ArrayRef<Value> values) 493 : ValueRange(values.data(), values.size()) {} 494 ValueRange::ValueRange(OperandRange values) 495 : ValueRange(values.begin().getBase(), values.size()) {} 496 ValueRange::ValueRange(ResultRange values) 497 : ValueRange(values.getBase(), values.size()) {} 498 499 /// See `llvm::detail::indexed_accessor_range_base` for details. 500 ValueRange::OwnerT ValueRange::offset_base(const OwnerT &owner, 501 ptrdiff_t index) { 502 if (const auto *value = owner.dyn_cast<const Value *>()) 503 return {value + index}; 504 if (auto *operand = owner.dyn_cast<OpOperand *>()) 505 return {operand + index}; 506 return owner.get<detail::OpResultImpl *>()->getNextResultAtOffset(index); 507 } 508 /// See `llvm::detail::indexed_accessor_range_base` for details. 509 Value ValueRange::dereference_iterator(const OwnerT &owner, ptrdiff_t index) { 510 if (const auto *value = owner.dyn_cast<const Value *>()) 511 return value[index]; 512 if (auto *operand = owner.dyn_cast<OpOperand *>()) 513 return operand[index].get(); 514 return owner.get<detail::OpResultImpl *>()->getNextResultAtOffset(index); 515 } 516 517 //===----------------------------------------------------------------------===// 518 // Operation Equivalency 519 //===----------------------------------------------------------------------===// 520 521 llvm::hash_code OperationEquivalence::computeHash(Operation *op, Flags flags) { 522 // Hash operations based upon their: 523 // - Operation Name 524 // - Attributes 525 // - Result Types 526 llvm::hash_code hash = llvm::hash_combine( 527 op->getName(), op->getAttrDictionary(), op->getResultTypes()); 528 529 // - Operands 530 bool ignoreOperands = flags & Flags::IgnoreOperands; 531 if (!ignoreOperands) { 532 // TODO: Allow commutative operations to have different ordering. 533 hash = llvm::hash_combine( 534 hash, llvm::hash_combine_range(op->operand_begin(), op->operand_end())); 535 } 536 return hash; 537 } 538 539 bool OperationEquivalence::isEquivalentTo(Operation *lhs, Operation *rhs, 540 Flags flags) { 541 if (lhs == rhs) 542 return true; 543 544 // Compare the operation name. 545 if (lhs->getName() != rhs->getName()) 546 return false; 547 // Check operand counts. 548 if (lhs->getNumOperands() != rhs->getNumOperands()) 549 return false; 550 // Compare attributes. 551 if (lhs->getAttrDictionary() != rhs->getAttrDictionary()) 552 return false; 553 // Compare result types. 554 if (lhs->getResultTypes() != rhs->getResultTypes()) 555 return false; 556 // Compare operands. 557 bool ignoreOperands = flags & Flags::IgnoreOperands; 558 if (ignoreOperands) 559 return true; 560 // TODO: Allow commutative operations to have different ordering. 561 return std::equal(lhs->operand_begin(), lhs->operand_end(), 562 rhs->operand_begin()); 563 } 564