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/Block.h"
16 #include "mlir/IR/BuiltinTypes.h"
17 #include "mlir/IR/OpDefinition.h"
18 #include "mlir/IR/Operation.h"
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(attrs, context));
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> &&region) {
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> &region : 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 /// Resize the storage to the given size. Returns the array containing the new
304 /// operands.
305 MutableArrayRef<OpOperand> detail::OperandStorage::resize(Operation *owner,
306                                                           unsigned newSize) {
307   TrailingOperandStorage &storage = getStorage();
308 
309   // If the number of operands is less than or equal to the current amount, we
310   // can just update in place.
311   unsigned &numOperands = storage.numOperands;
312   MutableArrayRef<OpOperand> operands = storage.getOperands();
313   if (newSize <= numOperands) {
314     // If the number of new size is less than the current, remove any extra
315     // operands.
316     for (unsigned i = newSize; i != numOperands; ++i)
317       operands[i].~OpOperand();
318     numOperands = newSize;
319     return operands.take_front(newSize);
320   }
321 
322   // If the new size is within the original inline capacity, grow inplace.
323   if (newSize <= storage.capacity) {
324     OpOperand *opBegin = operands.data();
325     for (unsigned e = newSize; numOperands != e; ++numOperands)
326       new (&opBegin[numOperands]) OpOperand(owner);
327     return MutableArrayRef<OpOperand>(opBegin, newSize);
328   }
329 
330   // Otherwise, we need to allocate a new storage.
331   unsigned newCapacity =
332       std::max(unsigned(llvm::NextPowerOf2(storage.capacity + 2)), newSize);
333   auto *newStorageMem =
334       malloc(TrailingOperandStorage::totalSizeToAlloc<OpOperand>(newCapacity));
335   auto *newStorage = ::new (newStorageMem) TrailingOperandStorage();
336   newStorage->numOperands = newSize;
337   newStorage->capacity = newCapacity;
338 
339   // Move the current operands to the new storage.
340   MutableArrayRef<OpOperand> newOperands = newStorage->getOperands();
341   std::uninitialized_copy(std::make_move_iterator(operands.begin()),
342                           std::make_move_iterator(operands.end()),
343                           newOperands.begin());
344 
345   // Destroy the original operands.
346   for (auto &operand : operands)
347     operand.~OpOperand();
348 
349   // Initialize any new operands.
350   for (unsigned e = newSize; numOperands != e; ++numOperands)
351     new (&newOperands[numOperands]) OpOperand(owner);
352 
353   // If the current storage is also dynamic, free it.
354   if (isDynamicStorage())
355     free(&storage);
356 
357   // Update the storage representation to use the new dynamic storage.
358   representation = reinterpret_cast<intptr_t>(newStorage);
359   representation |= DynamicStorageBit;
360   return newOperands;
361 }
362 
363 //===----------------------------------------------------------------------===//
364 // ResultStorage
365 //===----------------------------------------------------------------------===//
366 
367 /// Returns the parent operation of this trailing result.
368 Operation *detail::TrailingOpResult::getOwner() {
369   // We need to do some arithmetic to get the operation pointer. Trailing
370   // results are stored in reverse order before the inline results of the
371   // operation, so move the trailing owner up to the start of the array.
372   TrailingOpResult *trailingIt = this + (trailingResultNumber + 1);
373 
374   // Move the owner past the inline op results to get to the operation.
375   auto *inlineResultIt = reinterpret_cast<InLineOpResult *>(trailingIt) +
376                          OpResult::getMaxInlineResults();
377   return reinterpret_cast<Operation *>(inlineResultIt);
378 }
379 
380 //===----------------------------------------------------------------------===//
381 // Operation Value-Iterators
382 //===----------------------------------------------------------------------===//
383 
384 //===----------------------------------------------------------------------===//
385 // OperandRange
386 
387 OperandRange::OperandRange(Operation *op)
388     : OperandRange(op->getOpOperands().data(), op->getNumOperands()) {}
389 
390 /// Return the operand index of the first element of this range. The range
391 /// must not be empty.
392 unsigned OperandRange::getBeginOperandIndex() const {
393   assert(!empty() && "range must not be empty");
394   return base->getOperandNumber();
395 }
396 
397 //===----------------------------------------------------------------------===//
398 // MutableOperandRange
399 
400 /// Construct a new mutable range from the given operand, operand start index,
401 /// and range length.
402 MutableOperandRange::MutableOperandRange(
403     Operation *owner, unsigned start, unsigned length,
404     ArrayRef<OperandSegment> operandSegments)
405     : owner(owner), start(start), length(length),
406       operandSegments(operandSegments.begin(), operandSegments.end()) {
407   assert((start + length) <= owner->getNumOperands() && "invalid range");
408 }
409 MutableOperandRange::MutableOperandRange(Operation *owner)
410     : MutableOperandRange(owner, /*start=*/0, owner->getNumOperands()) {}
411 
412 /// Slice this range into a sub range, with the additional operand segment.
413 MutableOperandRange
414 MutableOperandRange::slice(unsigned subStart, unsigned subLen,
415                            Optional<OperandSegment> segment) {
416   assert((subStart + subLen) <= length && "invalid sub-range");
417   MutableOperandRange subSlice(owner, start + subStart, subLen,
418                                operandSegments);
419   if (segment)
420     subSlice.operandSegments.push_back(*segment);
421   return subSlice;
422 }
423 
424 /// Append the given values to the range.
425 void MutableOperandRange::append(ValueRange values) {
426   if (values.empty())
427     return;
428   owner->insertOperands(start + length, values);
429   updateLength(length + values.size());
430 }
431 
432 /// Assign this range to the given values.
433 void MutableOperandRange::assign(ValueRange values) {
434   owner->setOperands(start, length, values);
435   if (length != values.size())
436     updateLength(/*newLength=*/values.size());
437 }
438 
439 /// Assign the range to the given value.
440 void MutableOperandRange::assign(Value value) {
441   if (length == 1) {
442     owner->setOperand(start, value);
443   } else {
444     owner->setOperands(start, length, value);
445     updateLength(/*newLength=*/1);
446   }
447 }
448 
449 /// Erase the operands within the given sub-range.
450 void MutableOperandRange::erase(unsigned subStart, unsigned subLen) {
451   assert((subStart + subLen) <= length && "invalid sub-range");
452   if (length == 0)
453     return;
454   owner->eraseOperands(start + subStart, subLen);
455   updateLength(length - subLen);
456 }
457 
458 /// Clear this range and erase all of the operands.
459 void MutableOperandRange::clear() {
460   if (length != 0) {
461     owner->eraseOperands(start, length);
462     updateLength(/*newLength=*/0);
463   }
464 }
465 
466 /// Allow implicit conversion to an OperandRange.
467 MutableOperandRange::operator OperandRange() const {
468   return owner->getOperands().slice(start, length);
469 }
470 
471 /// Update the length of this range to the one provided.
472 void MutableOperandRange::updateLength(unsigned newLength) {
473   int32_t diff = int32_t(newLength) - int32_t(length);
474   length = newLength;
475 
476   // Update any of the provided segment attributes.
477   for (OperandSegment &segment : operandSegments) {
478     auto attr = segment.second.second.cast<DenseIntElementsAttr>();
479     SmallVector<int32_t, 8> segments(attr.getValues<int32_t>());
480     segments[segment.first] += diff;
481     segment.second.second = DenseIntElementsAttr::get(attr.getType(), segments);
482     owner->setAttr(segment.second.first, segment.second.second);
483   }
484 }
485 
486 //===----------------------------------------------------------------------===//
487 // ResultRange
488 
489 ResultRange::ResultRange(Operation *op)
490     : ResultRange(op, /*startIndex=*/0, op->getNumResults()) {}
491 
492 ArrayRef<Type> ResultRange::getTypes() const {
493   return getBase()->getResultTypes().slice(getStartIndex(), size());
494 }
495 
496 /// See `llvm::indexed_accessor_range` for details.
497 OpResult ResultRange::dereference(Operation *op, ptrdiff_t index) {
498   return op->getResult(index);
499 }
500 
501 //===----------------------------------------------------------------------===//
502 // ValueRange
503 
504 ValueRange::ValueRange(ArrayRef<Value> values)
505     : ValueRange(values.data(), values.size()) {}
506 ValueRange::ValueRange(OperandRange values)
507     : ValueRange(values.begin().getBase(), values.size()) {}
508 ValueRange::ValueRange(ResultRange values)
509     : ValueRange(
510           {values.getBase(), static_cast<unsigned>(values.getStartIndex())},
511           values.size()) {}
512 
513 /// See `llvm::detail::indexed_accessor_range_base` for details.
514 ValueRange::OwnerT ValueRange::offset_base(const OwnerT &owner,
515                                            ptrdiff_t index) {
516   if (auto *value = owner.ptr.dyn_cast<const Value *>())
517     return {value + index};
518   if (auto *operand = owner.ptr.dyn_cast<OpOperand *>())
519     return {operand + index};
520   Operation *operation = reinterpret_cast<Operation *>(owner.ptr.get<void *>());
521   return {operation, owner.startIndex + static_cast<unsigned>(index)};
522 }
523 /// See `llvm::detail::indexed_accessor_range_base` for details.
524 Value ValueRange::dereference_iterator(const OwnerT &owner, ptrdiff_t index) {
525   if (auto *value = owner.ptr.dyn_cast<const Value *>())
526     return value[index];
527   if (auto *operand = owner.ptr.dyn_cast<OpOperand *>())
528     return operand[index].get();
529   Operation *operation = reinterpret_cast<Operation *>(owner.ptr.get<void *>());
530   return operation->getResult(owner.startIndex + index);
531 }
532 
533 //===----------------------------------------------------------------------===//
534 // Operation Equivalency
535 //===----------------------------------------------------------------------===//
536 
537 llvm::hash_code OperationEquivalence::computeHash(Operation *op, Flags flags) {
538   // Hash operations based upon their:
539   //   - Operation Name
540   //   - Attributes
541   llvm::hash_code hash =
542       llvm::hash_combine(op->getName(), op->getAttrDictionary());
543 
544   //   - Result Types
545   ArrayRef<Type> resultTypes = op->getResultTypes();
546   switch (resultTypes.size()) {
547   case 0:
548     // We don't need to add anything to the hash.
549     break;
550   case 1:
551     // Add in the result type.
552     hash = llvm::hash_combine(hash, resultTypes.front());
553     break;
554   default:
555     // Use the type buffer as the hash, as we can guarantee it is the same for
556     // any given range of result types. This takes advantage of the fact the
557     // result types >1 are stored in a TupleType and uniqued.
558     hash = llvm::hash_combine(hash, resultTypes.data());
559     break;
560   }
561 
562   //   - Operands
563   bool ignoreOperands = flags & Flags::IgnoreOperands;
564   if (!ignoreOperands) {
565     // TODO: Allow commutative operations to have different ordering.
566     hash = llvm::hash_combine(
567         hash, llvm::hash_combine_range(op->operand_begin(), op->operand_end()));
568   }
569   return hash;
570 }
571 
572 bool OperationEquivalence::isEquivalentTo(Operation *lhs, Operation *rhs,
573                                           Flags flags) {
574   if (lhs == rhs)
575     return true;
576 
577   // Compare the operation name.
578   if (lhs->getName() != rhs->getName())
579     return false;
580   // Check operand counts.
581   if (lhs->getNumOperands() != rhs->getNumOperands())
582     return false;
583   // Compare attributes.
584   if (lhs->getAttrDictionary() != rhs->getAttrDictionary())
585     return false;
586   // Compare result types.
587   ArrayRef<Type> lhsResultTypes = lhs->getResultTypes();
588   ArrayRef<Type> rhsResultTypes = rhs->getResultTypes();
589   if (lhsResultTypes.size() != rhsResultTypes.size())
590     return false;
591   switch (lhsResultTypes.size()) {
592   case 0:
593     break;
594   case 1:
595     // Compare the single result type.
596     if (lhsResultTypes.front() != rhsResultTypes.front())
597       return false;
598     break;
599   default:
600     // Use the type buffer for the comparison, as we can guarantee it is the
601     // same for any given range of result types. This takes advantage of the
602     // fact the result types >1 are stored in a TupleType and uniqued.
603     if (lhsResultTypes.data() != rhsResultTypes.data())
604       return false;
605     break;
606   }
607   // Compare operands.
608   bool ignoreOperands = flags & Flags::IgnoreOperands;
609   if (ignoreOperands)
610     return true;
611   // TODO: Allow commutative operations to have different ordering.
612   return std::equal(lhs->operand_begin(), lhs->operand_end(),
613                     rhs->operand_begin());
614 }
615