xref: /llvm-project/mlir/lib/IR/Block.cpp (revision 066b3207234d098b6bf25d7c55e47c5a7b8dcfc7)
1 //===- Block.cpp - MLIR Block Class ---------------------------------------===//
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 #include "mlir/IR/Block.h"
10 #include "mlir/IR/Builders.h"
11 #include "mlir/IR/Operation.h"
12 #include "llvm/ADT/BitVector.h"
13 using namespace mlir;
14 
15 //===----------------------------------------------------------------------===//
16 // Block
17 //===----------------------------------------------------------------------===//
18 
19 Block::~Block() {
20   assert(!verifyOpOrder() && "Expected valid operation ordering.");
21   clear();
22   for (BlockArgument arg : arguments)
23     arg.destroy();
24 }
25 
26 Region *Block::getParent() const { return parentValidOpOrderPair.getPointer(); }
27 
28 /// Returns the closest surrounding operation that contains this block or
29 /// nullptr if this block is unlinked.
30 Operation *Block::getParentOp() {
31   return getParent() ? getParent()->getParentOp() : nullptr;
32 }
33 
34 /// Return if this block is the entry block in the parent region.
35 bool Block::isEntryBlock() { return this == &getParent()->front(); }
36 
37 /// Insert this block (which must not already be in a region) right before the
38 /// specified block.
39 void Block::insertBefore(Block *block) {
40   assert(!getParent() && "already inserted into a block!");
41   assert(block->getParent() && "cannot insert before a block without a parent");
42   block->getParent()->getBlocks().insert(block->getIterator(), this);
43 }
44 
45 /// Unlink this block from its current region and insert it right before the
46 /// specific block.
47 void Block::moveBefore(Block *block) {
48   assert(block->getParent() && "cannot insert before a block without a parent");
49   block->getParent()->getBlocks().splice(
50       block->getIterator(), getParent()->getBlocks(), getIterator());
51 }
52 
53 /// Unlink this Block from its parent Region and delete it.
54 void Block::erase() {
55   assert(getParent() && "Block has no parent");
56   getParent()->getBlocks().erase(this);
57 }
58 
59 /// Returns 'op' if 'op' lies in this block, or otherwise finds the
60 /// ancestor operation of 'op' that lies in this block. Returns nullptr if
61 /// the latter fails.
62 Operation *Block::findAncestorOpInBlock(Operation &op) {
63   // Traverse up the operation hierarchy starting from the owner of operand to
64   // find the ancestor operation that resides in the block of 'forOp'.
65   auto *currOp = &op;
66   while (currOp->getBlock() != this) {
67     currOp = currOp->getParentOp();
68     if (!currOp)
69       return nullptr;
70   }
71   return currOp;
72 }
73 
74 /// This drops all operand uses from operations within this block, which is
75 /// an essential step in breaking cyclic dependences between references when
76 /// they are to be deleted.
77 void Block::dropAllReferences() {
78   for (Operation &i : *this)
79     i.dropAllReferences();
80 }
81 
82 void Block::dropAllDefinedValueUses() {
83   for (auto arg : getArguments())
84     arg.dropAllUses();
85   for (auto &op : *this)
86     op.dropAllDefinedValueUses();
87   dropAllUses();
88 }
89 
90 /// Returns true if the ordering of the child operations is valid, false
91 /// otherwise.
92 bool Block::isOpOrderValid() { return parentValidOpOrderPair.getInt(); }
93 
94 /// Invalidates the current ordering of operations.
95 void Block::invalidateOpOrder() {
96   // Validate the current ordering.
97   assert(!verifyOpOrder());
98   parentValidOpOrderPair.setInt(false);
99 }
100 
101 /// Verifies the current ordering of child operations. Returns false if the
102 /// order is valid, true otherwise.
103 bool Block::verifyOpOrder() {
104   // The order is already known to be invalid.
105   if (!isOpOrderValid())
106     return false;
107   // The order is valid if there are less than 2 operations.
108   if (operations.empty() || std::next(operations.begin()) == operations.end())
109     return false;
110 
111   Operation *prev = nullptr;
112   for (auto &i : *this) {
113     // The previous operation must have a smaller order index than the next as
114     // it appears earlier in the list.
115     if (prev && prev->orderIndex != Operation::kInvalidOrderIdx &&
116         prev->orderIndex >= i.orderIndex)
117       return true;
118     prev = &i;
119   }
120   return false;
121 }
122 
123 /// Recomputes the ordering of child operations within the block.
124 void Block::recomputeOpOrder() {
125   parentValidOpOrderPair.setInt(true);
126 
127   unsigned orderIndex = 0;
128   for (auto &op : *this)
129     op.orderIndex = (orderIndex += Operation::kOrderStride);
130 }
131 
132 //===----------------------------------------------------------------------===//
133 // Argument list management.
134 //===----------------------------------------------------------------------===//
135 
136 /// Return a range containing the types of the arguments for this block.
137 auto Block::getArgumentTypes() -> ValueTypeRange<BlockArgListType> {
138   return ValueTypeRange<BlockArgListType>(getArguments());
139 }
140 
141 BlockArgument Block::addArgument(Type type, Optional<Location> loc) {
142   // TODO: Require locations for BlockArguments.
143   if (!loc.hasValue()) {
144     // Use the location of the parent operation if the block is attached.
145     if (Operation *parentOp = getParentOp())
146       loc = parentOp->getLoc();
147     else
148       loc = UnknownLoc::get(type.getContext());
149   }
150 
151   BlockArgument arg = BlockArgument::create(type, this, arguments.size(), *loc);
152   arguments.push_back(arg);
153   return arg;
154 }
155 
156 /// Add one argument to the argument list for each type specified in the list.
157 auto Block::addArguments(TypeRange types, ArrayRef<Location> locs)
158     -> iterator_range<args_iterator> {
159   // TODO: Require locations for BlockArguments.
160   assert((locs.empty() || types.size() == locs.size()) &&
161          "incorrect number of block argument locations");
162   size_t initialSize = arguments.size();
163 
164   arguments.reserve(initialSize + types.size());
165 
166   // TODO: Require locations for BlockArguments.
167   if (locs.empty()) {
168     for (auto type : types)
169       addArgument(type);
170   } else {
171     for (auto typeAndLoc : llvm::zip(types, locs))
172       addArgument(std::get<0>(typeAndLoc), std::get<1>(typeAndLoc));
173   }
174   return {arguments.data() + initialSize, arguments.data() + arguments.size()};
175 }
176 
177 BlockArgument Block::insertArgument(unsigned index, Type type,
178                                     Optional<Location> loc) {
179   // TODO: Require locations for BlockArguments.
180   if (!loc.hasValue()) {
181     // Use the location of the parent operation if the block is attached.
182     if (Operation *parentOp = getParentOp())
183       loc = parentOp->getLoc();
184     else
185       loc = UnknownLoc::get(type.getContext());
186   }
187 
188   auto arg = BlockArgument::create(type, this, index, *loc);
189   assert(index <= arguments.size());
190   arguments.insert(arguments.begin() + index, arg);
191   // Update the cached position for all the arguments after the newly inserted
192   // one.
193   ++index;
194   for (BlockArgument arg : llvm::drop_begin(arguments, index))
195     arg.setArgNumber(index++);
196   return arg;
197 }
198 
199 /// Insert one value to the given position of the argument list. The existing
200 /// arguments are shifted. The block is expected not to have predecessors.
201 BlockArgument Block::insertArgument(args_iterator it, Type type,
202                                     Optional<Location> loc) {
203   assert(llvm::empty(getPredecessors()) &&
204          "cannot insert arguments to blocks with predecessors");
205   return insertArgument(it->getArgNumber(), type, loc);
206 }
207 
208 void Block::eraseArgument(unsigned index) {
209   assert(index < arguments.size());
210   arguments[index].destroy();
211   arguments.erase(arguments.begin() + index);
212   for (BlockArgument arg : llvm::drop_begin(arguments, index))
213     arg.setArgNumber(index++);
214 }
215 
216 void Block::eraseArguments(ArrayRef<unsigned> argIndices) {
217   llvm::BitVector eraseIndices(getNumArguments());
218   for (unsigned i : argIndices)
219     eraseIndices.set(i);
220   eraseArguments(eraseIndices);
221 }
222 
223 void Block::eraseArguments(const llvm::BitVector &eraseIndices) {
224   eraseArguments(
225       [&](BlockArgument arg) { return eraseIndices.test(arg.getArgNumber()); });
226 }
227 
228 void Block::eraseArguments(function_ref<bool(BlockArgument)> shouldEraseFn) {
229   auto firstDead = llvm::find_if(arguments, shouldEraseFn);
230   if (firstDead == arguments.end())
231     return;
232 
233   // Destroy the first dead argument, this avoids reapplying the predicate to
234   // it.
235   unsigned index = firstDead->getArgNumber();
236   firstDead->destroy();
237 
238   // Iterate the remaining arguments to remove any that are now dead.
239   for (auto it = std::next(firstDead), e = arguments.end(); it != e; ++it) {
240     // Destroy dead arguments, and shift those that are still live.
241     if (shouldEraseFn(*it)) {
242       it->destroy();
243     } else {
244       it->setArgNumber(index++);
245       *firstDead++ = *it;
246     }
247   }
248   arguments.erase(firstDead, arguments.end());
249 }
250 
251 //===----------------------------------------------------------------------===//
252 // Terminator management
253 //===----------------------------------------------------------------------===//
254 
255 /// Get the terminator operation of this block. This function asserts that
256 /// the block has a valid terminator operation.
257 Operation *Block::getTerminator() {
258   assert(!empty() && back().mightHaveTrait<OpTrait::IsTerminator>());
259   return &back();
260 }
261 
262 // Indexed successor access.
263 unsigned Block::getNumSuccessors() {
264   return empty() ? 0 : back().getNumSuccessors();
265 }
266 
267 Block *Block::getSuccessor(unsigned i) {
268   assert(i < getNumSuccessors());
269   return getTerminator()->getSuccessor(i);
270 }
271 
272 /// If this block has exactly one predecessor, return it.  Otherwise, return
273 /// null.
274 ///
275 /// Note that multiple edges from a single block (e.g. if you have a cond
276 /// branch with the same block as the true/false destinations) is not
277 /// considered to be a single predecessor.
278 Block *Block::getSinglePredecessor() {
279   auto it = pred_begin();
280   if (it == pred_end())
281     return nullptr;
282   auto *firstPred = *it;
283   ++it;
284   return it == pred_end() ? firstPred : nullptr;
285 }
286 
287 /// If this block has a unique predecessor, i.e., all incoming edges originate
288 /// from one block, return it. Otherwise, return null.
289 Block *Block::getUniquePredecessor() {
290   auto it = pred_begin(), e = pred_end();
291   if (it == e)
292     return nullptr;
293 
294   // Check for any conflicting predecessors.
295   auto *firstPred = *it;
296   for (++it; it != e; ++it)
297     if (*it != firstPred)
298       return nullptr;
299   return firstPred;
300 }
301 
302 //===----------------------------------------------------------------------===//
303 // Other
304 //===----------------------------------------------------------------------===//
305 
306 /// Split the block into two blocks before the specified operation or
307 /// iterator.
308 ///
309 /// Note that all operations BEFORE the specified iterator stay as part of
310 /// the original basic block, and the rest of the operations in the original
311 /// block are moved to the new block, including the old terminator.  The
312 /// original block is left without a terminator.
313 ///
314 /// The newly formed Block is returned, and the specified iterator is
315 /// invalidated.
316 Block *Block::splitBlock(iterator splitBefore) {
317   // Start by creating a new basic block, and insert it immediate after this
318   // one in the containing region.
319   auto newBB = new Block();
320   getParent()->getBlocks().insert(std::next(Region::iterator(this)), newBB);
321 
322   // Move all of the operations from the split point to the end of the region
323   // into the new block.
324   newBB->getOperations().splice(newBB->end(), getOperations(), splitBefore,
325                                 end());
326   return newBB;
327 }
328 
329 //===----------------------------------------------------------------------===//
330 // Predecessors
331 //===----------------------------------------------------------------------===//
332 
333 Block *PredecessorIterator::unwrap(BlockOperand &value) {
334   return value.getOwner()->getBlock();
335 }
336 
337 /// Get the successor number in the predecessor terminator.
338 unsigned PredecessorIterator::getSuccessorIndex() const {
339   return I->getOperandNumber();
340 }
341 
342 //===----------------------------------------------------------------------===//
343 // SuccessorRange
344 //===----------------------------------------------------------------------===//
345 
346 SuccessorRange::SuccessorRange() : SuccessorRange(nullptr, 0) {}
347 
348 SuccessorRange::SuccessorRange(Block *block) : SuccessorRange() {
349  if (block->empty() || llvm::hasSingleElement(*block->getParent()))
350   return;
351  Operation *term = &block->back();
352  if ((count = term->getNumSuccessors()))
353    base = term->getBlockOperands().data();
354 }
355 
356 SuccessorRange::SuccessorRange(Operation *term) : SuccessorRange() {
357   if ((count = term->getNumSuccessors()))
358     base = term->getBlockOperands().data();
359 }
360 
361 //===----------------------------------------------------------------------===//
362 // BlockRange
363 //===----------------------------------------------------------------------===//
364 
365 BlockRange::BlockRange(ArrayRef<Block *> blocks) : BlockRange(nullptr, 0) {
366   if ((count = blocks.size()))
367     base = blocks.data();
368 }
369 
370 BlockRange::BlockRange(SuccessorRange successors)
371     : BlockRange(successors.begin().getBase(), successors.size()) {}
372 
373 /// See `llvm::detail::indexed_accessor_range_base` for details.
374 BlockRange::OwnerT BlockRange::offset_base(OwnerT object, ptrdiff_t index) {
375   if (auto *operand = object.dyn_cast<BlockOperand *>())
376     return {operand + index};
377   return {object.dyn_cast<Block *const *>() + index};
378 }
379 
380 /// See `llvm::detail::indexed_accessor_range_base` for details.
381 Block *BlockRange::dereference_iterator(OwnerT object, ptrdiff_t index) {
382   if (const auto *operand = object.dyn_cast<BlockOperand *>())
383     return operand[index].get();
384   return object.dyn_cast<Block *const *>()[index];
385 }
386