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 Attribute
154 NamedAttrList::eraseImpl(SmallVectorImpl<NamedAttribute>::iterator it) {
155   if (it == attrs.end())
156     return nullptr;
157 
158   // Erasing does not affect the sorted property.
159   Attribute attr = it->second;
160   attrs.erase(it);
161   dictionarySorted.setPointer(nullptr);
162   return attr;
163 }
164 
165 Attribute NamedAttrList::erase(Identifier name) {
166   return eraseImpl(findAttr(attrs, name, isSorted()));
167 }
168 
169 Attribute NamedAttrList::erase(StringRef name) {
170   return eraseImpl(findAttr(attrs, name, isSorted()));
171 }
172 
173 NamedAttrList &
174 NamedAttrList::operator=(const SmallVectorImpl<NamedAttribute> &rhs) {
175   assign(rhs.begin(), rhs.end());
176   return *this;
177 }
178 
179 NamedAttrList::operator ArrayRef<NamedAttribute>() const { return attrs; }
180 
181 //===----------------------------------------------------------------------===//
182 // OperationState
183 //===----------------------------------------------------------------------===//
184 
185 OperationState::OperationState(Location location, StringRef name)
186     : location(location), name(name, location->getContext()) {}
187 
188 OperationState::OperationState(Location location, OperationName name)
189     : location(location), name(name) {}
190 
191 OperationState::OperationState(Location location, StringRef name,
192                                ValueRange operands, TypeRange types,
193                                ArrayRef<NamedAttribute> attributes,
194                                BlockRange successors,
195                                MutableArrayRef<std::unique_ptr<Region>> regions)
196     : location(location), name(name, location->getContext()),
197       operands(operands.begin(), operands.end()),
198       types(types.begin(), types.end()),
199       attributes(attributes.begin(), attributes.end()),
200       successors(successors.begin(), successors.end()) {
201   for (std::unique_ptr<Region> &r : regions)
202     this->regions.push_back(std::move(r));
203 }
204 
205 void OperationState::addOperands(ValueRange newOperands) {
206   operands.append(newOperands.begin(), newOperands.end());
207 }
208 
209 void OperationState::addSuccessors(BlockRange newSuccessors) {
210   successors.append(newSuccessors.begin(), newSuccessors.end());
211 }
212 
213 Region *OperationState::addRegion() {
214   regions.emplace_back(new Region);
215   return regions.back().get();
216 }
217 
218 void OperationState::addRegion(std::unique_ptr<Region> &&region) {
219   regions.push_back(std::move(region));
220 }
221 
222 void OperationState::addRegions(
223     MutableArrayRef<std::unique_ptr<Region>> regions) {
224   for (std::unique_ptr<Region> &region : regions)
225     addRegion(std::move(region));
226 }
227 
228 //===----------------------------------------------------------------------===//
229 // OperandStorage
230 //===----------------------------------------------------------------------===//
231 
232 detail::OperandStorage::OperandStorage(Operation *owner, ValueRange values)
233     : representation(0) {
234   auto &inlineStorage = getInlineStorage();
235   inlineStorage.numOperands = inlineStorage.capacity = values.size();
236   auto *operandPtrBegin = getTrailingObjects<OpOperand>();
237   for (unsigned i = 0, e = inlineStorage.numOperands; i < e; ++i)
238     new (&operandPtrBegin[i]) OpOperand(owner, values[i]);
239 }
240 
241 detail::OperandStorage::~OperandStorage() {
242   // Destruct the current storage container.
243   if (isDynamicStorage()) {
244     TrailingOperandStorage &storage = getDynamicStorage();
245     storage.~TrailingOperandStorage();
246     free(&storage);
247   } else {
248     getInlineStorage().~TrailingOperandStorage();
249   }
250 }
251 
252 /// Replace the operands contained in the storage with the ones provided in
253 /// 'values'.
254 void detail::OperandStorage::setOperands(Operation *owner, ValueRange values) {
255   MutableArrayRef<OpOperand> storageOperands = resize(owner, values.size());
256   for (unsigned i = 0, e = values.size(); i != e; ++i)
257     storageOperands[i].set(values[i]);
258 }
259 
260 /// Replace the operands beginning at 'start' and ending at 'start' + 'length'
261 /// with the ones provided in 'operands'. 'operands' may be smaller or larger
262 /// than the range pointed to by 'start'+'length'.
263 void detail::OperandStorage::setOperands(Operation *owner, unsigned start,
264                                          unsigned length, ValueRange operands) {
265   // If the new size is the same, we can update inplace.
266   unsigned newSize = operands.size();
267   if (newSize == length) {
268     MutableArrayRef<OpOperand> storageOperands = getOperands();
269     for (unsigned i = 0, e = length; i != e; ++i)
270       storageOperands[start + i].set(operands[i]);
271     return;
272   }
273   // If the new size is greater, remove the extra operands and set the rest
274   // inplace.
275   if (newSize < length) {
276     eraseOperands(start + operands.size(), length - newSize);
277     setOperands(owner, start, newSize, operands);
278     return;
279   }
280   // Otherwise, the new size is greater so we need to grow the storage.
281   auto storageOperands = resize(owner, size() + (newSize - length));
282 
283   // Shift operands to the right to make space for the new operands.
284   unsigned rotateSize = storageOperands.size() - (start + length);
285   auto rbegin = storageOperands.rbegin();
286   std::rotate(rbegin, std::next(rbegin, newSize - length), rbegin + rotateSize);
287 
288   // Update the operands inplace.
289   for (unsigned i = 0, e = operands.size(); i != e; ++i)
290     storageOperands[start + i].set(operands[i]);
291 }
292 
293 /// Erase an operand held by the storage.
294 void detail::OperandStorage::eraseOperands(unsigned start, unsigned length) {
295   TrailingOperandStorage &storage = getStorage();
296   MutableArrayRef<OpOperand> operands = storage.getOperands();
297   assert((start + length) <= operands.size());
298   storage.numOperands -= length;
299 
300   // Shift all operands down if the operand to remove is not at the end.
301   if (start != storage.numOperands) {
302     auto *indexIt = std::next(operands.begin(), start);
303     std::rotate(indexIt, std::next(indexIt, length), operands.end());
304   }
305   for (unsigned i = 0; i != length; ++i)
306     operands[storage.numOperands + i].~OpOperand();
307 }
308 
309 /// Resize the storage to the given size. Returns the array containing the new
310 /// operands.
311 MutableArrayRef<OpOperand> detail::OperandStorage::resize(Operation *owner,
312                                                           unsigned newSize) {
313   TrailingOperandStorage &storage = getStorage();
314 
315   // If the number of operands is less than or equal to the current amount, we
316   // can just update in place.
317   unsigned &numOperands = storage.numOperands;
318   MutableArrayRef<OpOperand> operands = storage.getOperands();
319   if (newSize <= numOperands) {
320     // If the number of new size is less than the current, remove any extra
321     // operands.
322     for (unsigned i = newSize; i != numOperands; ++i)
323       operands[i].~OpOperand();
324     numOperands = newSize;
325     return operands.take_front(newSize);
326   }
327 
328   // If the new size is within the original inline capacity, grow inplace.
329   if (newSize <= storage.capacity) {
330     OpOperand *opBegin = operands.data();
331     for (unsigned e = newSize; numOperands != e; ++numOperands)
332       new (&opBegin[numOperands]) OpOperand(owner);
333     return MutableArrayRef<OpOperand>(opBegin, newSize);
334   }
335 
336   // Otherwise, we need to allocate a new storage.
337   unsigned newCapacity =
338       std::max(unsigned(llvm::NextPowerOf2(storage.capacity + 2)), newSize);
339   auto *newStorageMem =
340       malloc(TrailingOperandStorage::totalSizeToAlloc<OpOperand>(newCapacity));
341   auto *newStorage = ::new (newStorageMem) TrailingOperandStorage();
342   newStorage->numOperands = newSize;
343   newStorage->capacity = newCapacity;
344 
345   // Move the current operands to the new storage.
346   MutableArrayRef<OpOperand> newOperands = newStorage->getOperands();
347   std::uninitialized_copy(std::make_move_iterator(operands.begin()),
348                           std::make_move_iterator(operands.end()),
349                           newOperands.begin());
350 
351   // Destroy the original operands.
352   for (auto &operand : operands)
353     operand.~OpOperand();
354 
355   // Initialize any new operands.
356   for (unsigned e = newSize; numOperands != e; ++numOperands)
357     new (&newOperands[numOperands]) OpOperand(owner);
358 
359   // If the current storage is also dynamic, free it.
360   if (isDynamicStorage())
361     free(&storage);
362 
363   // Update the storage representation to use the new dynamic storage.
364   representation = reinterpret_cast<intptr_t>(newStorage);
365   representation |= DynamicStorageBit;
366   return newOperands;
367 }
368 
369 //===----------------------------------------------------------------------===//
370 // ResultStorage
371 //===----------------------------------------------------------------------===//
372 
373 /// Returns the parent operation of this trailing result.
374 Operation *detail::TrailingOpResult::getOwner() {
375   // We need to do some arithmetic to get the operation pointer. Move the
376   // trailing owner to the start of the array.
377   TrailingOpResult *trailingIt = this - trailingResultNumber;
378 
379   // Move the owner past the inline op results to get to the operation.
380   auto *inlineResultIt = reinterpret_cast<InLineOpResult *>(trailingIt) -
381                          OpResult::getMaxInlineResults();
382   return reinterpret_cast<Operation *>(inlineResultIt) - 1;
383 }
384 
385 //===----------------------------------------------------------------------===//
386 // Operation Value-Iterators
387 //===----------------------------------------------------------------------===//
388 
389 //===----------------------------------------------------------------------===//
390 // OperandRange
391 
392 OperandRange::OperandRange(Operation *op)
393     : OperandRange(op->getOpOperands().data(), op->getNumOperands()) {}
394 
395 /// Return the operand index of the first element of this range. The range
396 /// must not be empty.
397 unsigned OperandRange::getBeginOperandIndex() const {
398   assert(!empty() && "range must not be empty");
399   return base->getOperandNumber();
400 }
401 
402 //===----------------------------------------------------------------------===//
403 // MutableOperandRange
404 
405 /// Construct a new mutable range from the given operand, operand start index,
406 /// and range length.
407 MutableOperandRange::MutableOperandRange(
408     Operation *owner, unsigned start, unsigned length,
409     ArrayRef<OperandSegment> operandSegments)
410     : owner(owner), start(start), length(length),
411       operandSegments(operandSegments.begin(), operandSegments.end()) {
412   assert((start + length) <= owner->getNumOperands() && "invalid range");
413 }
414 MutableOperandRange::MutableOperandRange(Operation *owner)
415     : MutableOperandRange(owner, /*start=*/0, owner->getNumOperands()) {}
416 
417 /// Slice this range into a sub range, with the additional operand segment.
418 MutableOperandRange
419 MutableOperandRange::slice(unsigned subStart, unsigned subLen,
420                            Optional<OperandSegment> segment) {
421   assert((subStart + subLen) <= length && "invalid sub-range");
422   MutableOperandRange subSlice(owner, start + subStart, subLen,
423                                operandSegments);
424   if (segment)
425     subSlice.operandSegments.push_back(*segment);
426   return subSlice;
427 }
428 
429 /// Append the given values to the range.
430 void MutableOperandRange::append(ValueRange values) {
431   if (values.empty())
432     return;
433   owner->insertOperands(start + length, values);
434   updateLength(length + values.size());
435 }
436 
437 /// Assign this range to the given values.
438 void MutableOperandRange::assign(ValueRange values) {
439   owner->setOperands(start, length, values);
440   if (length != values.size())
441     updateLength(/*newLength=*/values.size());
442 }
443 
444 /// Assign the range to the given value.
445 void MutableOperandRange::assign(Value value) {
446   if (length == 1) {
447     owner->setOperand(start, value);
448   } else {
449     owner->setOperands(start, length, value);
450     updateLength(/*newLength=*/1);
451   }
452 }
453 
454 /// Erase the operands within the given sub-range.
455 void MutableOperandRange::erase(unsigned subStart, unsigned subLen) {
456   assert((subStart + subLen) <= length && "invalid sub-range");
457   if (length == 0)
458     return;
459   owner->eraseOperands(start + subStart, subLen);
460   updateLength(length - subLen);
461 }
462 
463 /// Clear this range and erase all of the operands.
464 void MutableOperandRange::clear() {
465   if (length != 0) {
466     owner->eraseOperands(start, length);
467     updateLength(/*newLength=*/0);
468   }
469 }
470 
471 /// Allow implicit conversion to an OperandRange.
472 MutableOperandRange::operator OperandRange() const {
473   return owner->getOperands().slice(start, length);
474 }
475 
476 /// Update the length of this range to the one provided.
477 void MutableOperandRange::updateLength(unsigned newLength) {
478   int32_t diff = int32_t(newLength) - int32_t(length);
479   length = newLength;
480 
481   // Update any of the provided segment attributes.
482   for (OperandSegment &segment : operandSegments) {
483     auto attr = segment.second.second.cast<DenseIntElementsAttr>();
484     SmallVector<int32_t, 8> segments(attr.getValues<int32_t>());
485     segments[segment.first] += diff;
486     segment.second.second = DenseIntElementsAttr::get(attr.getType(), segments);
487     owner->setAttr(segment.second.first, segment.second.second);
488   }
489 }
490 
491 //===----------------------------------------------------------------------===//
492 // ResultRange
493 
494 ResultRange::ResultRange(Operation *op)
495     : ResultRange(op, /*startIndex=*/0, op->getNumResults()) {}
496 
497 ArrayRef<Type> ResultRange::getTypes() const {
498   return getBase()->getResultTypes().slice(getStartIndex(), size());
499 }
500 
501 /// See `llvm::indexed_accessor_range` for details.
502 OpResult ResultRange::dereference(Operation *op, ptrdiff_t index) {
503   return op->getResult(index);
504 }
505 
506 //===----------------------------------------------------------------------===//
507 // ValueRange
508 
509 ValueRange::ValueRange(ArrayRef<Value> values)
510     : ValueRange(values.data(), values.size()) {}
511 ValueRange::ValueRange(OperandRange values)
512     : ValueRange(values.begin().getBase(), values.size()) {}
513 ValueRange::ValueRange(ResultRange values)
514     : ValueRange(
515           {values.getBase(), static_cast<unsigned>(values.getStartIndex())},
516           values.size()) {}
517 
518 /// See `llvm::detail::indexed_accessor_range_base` for details.
519 ValueRange::OwnerT ValueRange::offset_base(const OwnerT &owner,
520                                            ptrdiff_t index) {
521   if (auto *value = owner.ptr.dyn_cast<const Value *>())
522     return {value + index};
523   if (auto *operand = owner.ptr.dyn_cast<OpOperand *>())
524     return {operand + index};
525   Operation *operation = reinterpret_cast<Operation *>(owner.ptr.get<void *>());
526   return {operation, owner.startIndex + static_cast<unsigned>(index)};
527 }
528 /// See `llvm::detail::indexed_accessor_range_base` for details.
529 Value ValueRange::dereference_iterator(const OwnerT &owner, ptrdiff_t index) {
530   if (auto *value = owner.ptr.dyn_cast<const Value *>())
531     return value[index];
532   if (auto *operand = owner.ptr.dyn_cast<OpOperand *>())
533     return operand[index].get();
534   Operation *operation = reinterpret_cast<Operation *>(owner.ptr.get<void *>());
535   return operation->getResult(owner.startIndex + index);
536 }
537 
538 //===----------------------------------------------------------------------===//
539 // Operation Equivalency
540 //===----------------------------------------------------------------------===//
541 
542 llvm::hash_code OperationEquivalence::computeHash(Operation *op, Flags flags) {
543   // Hash operations based upon their:
544   //   - Operation Name
545   //   - Attributes
546   llvm::hash_code hash =
547       llvm::hash_combine(op->getName(), op->getMutableAttrDict());
548 
549   //   - Result Types
550   ArrayRef<Type> resultTypes = op->getResultTypes();
551   switch (resultTypes.size()) {
552   case 0:
553     // We don't need to add anything to the hash.
554     break;
555   case 1:
556     // Add in the result type.
557     hash = llvm::hash_combine(hash, resultTypes.front());
558     break;
559   default:
560     // Use the type buffer as the hash, as we can guarantee it is the same for
561     // any given range of result types. This takes advantage of the fact the
562     // result types >1 are stored in a TupleType and uniqued.
563     hash = llvm::hash_combine(hash, resultTypes.data());
564     break;
565   }
566 
567   //   - Operands
568   bool ignoreOperands = flags & Flags::IgnoreOperands;
569   if (!ignoreOperands) {
570     // TODO: Allow commutative operations to have different ordering.
571     hash = llvm::hash_combine(
572         hash, llvm::hash_combine_range(op->operand_begin(), op->operand_end()));
573   }
574   return hash;
575 }
576 
577 bool OperationEquivalence::isEquivalentTo(Operation *lhs, Operation *rhs,
578                                           Flags flags) {
579   if (lhs == rhs)
580     return true;
581 
582   // Compare the operation name.
583   if (lhs->getName() != rhs->getName())
584     return false;
585   // Check operand counts.
586   if (lhs->getNumOperands() != rhs->getNumOperands())
587     return false;
588   // Compare attributes.
589   if (lhs->getMutableAttrDict() != rhs->getMutableAttrDict())
590     return false;
591   // Compare result types.
592   ArrayRef<Type> lhsResultTypes = lhs->getResultTypes();
593   ArrayRef<Type> rhsResultTypes = rhs->getResultTypes();
594   if (lhsResultTypes.size() != rhsResultTypes.size())
595     return false;
596   switch (lhsResultTypes.size()) {
597   case 0:
598     break;
599   case 1:
600     // Compare the single result type.
601     if (lhsResultTypes.front() != rhsResultTypes.front())
602       return false;
603     break;
604   default:
605     // Use the type buffer for the comparison, as we can guarantee it is the
606     // same for any given range of result types. This takes advantage of the
607     // fact the result types >1 are stored in a TupleType and uniqued.
608     if (lhsResultTypes.data() != rhsResultTypes.data())
609       return false;
610     break;
611   }
612   // Compare operands.
613   bool ignoreOperands = flags & Flags::IgnoreOperands;
614   if (ignoreOperands)
615     return true;
616   // TODO: Allow commutative operations to have different ordering.
617   return std::equal(lhs->operand_begin(), lhs->operand_end(),
618                     rhs->operand_begin());
619 }
620