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