xref: /llvm-project/mlir/lib/IR/Block.cpp (revision 7b06786de239a4ab7d53ee8ca0b2f5a9b15a871a)
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) {
142   BlockArgument arg = BlockArgument::create(type, this, arguments.size());
143   arguments.push_back(arg);
144   return arg;
145 }
146 
147 /// Add one argument to the argument list for each type specified in the list.
148 auto Block::addArguments(TypeRange types) -> iterator_range<args_iterator> {
149   size_t initialSize = arguments.size();
150   arguments.reserve(initialSize + types.size());
151   for (auto type : types)
152     addArgument(type);
153   return {arguments.data() + initialSize, arguments.data() + arguments.size()};
154 }
155 
156 BlockArgument Block::insertArgument(unsigned index, Type type) {
157   auto arg = BlockArgument::create(type, this, index);
158   assert(index <= arguments.size());
159   arguments.insert(arguments.begin() + index, arg);
160   // Update the cached position for all the arguments after the newly inserted
161   // one.
162   ++index;
163   for (BlockArgument arg : llvm::drop_begin(arguments, index))
164     arg.setArgNumber(index++);
165   return arg;
166 }
167 
168 /// Insert one value to the given position of the argument list. The existing
169 /// arguments are shifted. The block is expected not to have predecessors.
170 BlockArgument Block::insertArgument(args_iterator it, Type type) {
171   assert(llvm::empty(getPredecessors()) &&
172          "cannot insert arguments to blocks with predecessors");
173   return insertArgument(it->getArgNumber(), type);
174 }
175 
176 void Block::eraseArgument(unsigned index) {
177   assert(index < arguments.size());
178   arguments[index].destroy();
179   arguments.erase(arguments.begin() + index);
180   for (BlockArgument arg : llvm::drop_begin(arguments, index))
181     arg.setArgNumber(index++);
182 }
183 
184 void Block::eraseArguments(ArrayRef<unsigned> argIndices) {
185   llvm::BitVector eraseIndices(getNumArguments());
186   for (unsigned i : argIndices)
187     eraseIndices.set(i);
188   eraseArguments(eraseIndices);
189 }
190 
191 void Block::eraseArguments(llvm::BitVector eraseIndices) {
192   // We do this in reverse so that we erase later indices before earlier
193   // indices, to avoid shifting the later indices.
194   unsigned originalNumArgs = getNumArguments();
195   for (unsigned i = 0; i < originalNumArgs; ++i) {
196     int64_t currentPos = originalNumArgs - i - 1;
197     if (eraseIndices.test(currentPos)) {
198       arguments[currentPos].destroy();
199       arguments.erase(arguments.begin() + currentPos);
200     }
201   }
202   // Update the cached position for the arguments after the first erased one.
203   int64_t index = eraseIndices.find_first();
204   for (BlockArgument arg : llvm::drop_begin(arguments, index))
205     arg.setArgNumber(index++);
206 }
207 
208 //===----------------------------------------------------------------------===//
209 // Terminator management
210 //===----------------------------------------------------------------------===//
211 
212 /// Get the terminator operation of this block. This function asserts that
213 /// the block has a valid terminator operation.
214 Operation *Block::getTerminator() {
215   assert(!empty() && back().mightHaveTrait<OpTrait::IsTerminator>());
216   return &back();
217 }
218 
219 // Indexed successor access.
220 unsigned Block::getNumSuccessors() {
221   return empty() ? 0 : back().getNumSuccessors();
222 }
223 
224 Block *Block::getSuccessor(unsigned i) {
225   assert(i < getNumSuccessors());
226   return getTerminator()->getSuccessor(i);
227 }
228 
229 /// If this block has exactly one predecessor, return it.  Otherwise, return
230 /// null.
231 ///
232 /// Note that multiple edges from a single block (e.g. if you have a cond
233 /// branch with the same block as the true/false destinations) is not
234 /// considered to be a single predecessor.
235 Block *Block::getSinglePredecessor() {
236   auto it = pred_begin();
237   if (it == pred_end())
238     return nullptr;
239   auto *firstPred = *it;
240   ++it;
241   return it == pred_end() ? firstPred : nullptr;
242 }
243 
244 /// If this block has a unique predecessor, i.e., all incoming edges originate
245 /// from one block, return it. Otherwise, return null.
246 Block *Block::getUniquePredecessor() {
247   auto it = pred_begin(), e = pred_end();
248   if (it == e)
249     return nullptr;
250 
251   // Check for any conflicting predecessors.
252   auto *firstPred = *it;
253   for (++it; it != e; ++it)
254     if (*it != firstPred)
255       return nullptr;
256   return firstPred;
257 }
258 
259 //===----------------------------------------------------------------------===//
260 // Other
261 //===----------------------------------------------------------------------===//
262 
263 /// Split the block into two blocks before the specified operation or
264 /// iterator.
265 ///
266 /// Note that all operations BEFORE the specified iterator stay as part of
267 /// the original basic block, and the rest of the operations in the original
268 /// block are moved to the new block, including the old terminator.  The
269 /// original block is left without a terminator.
270 ///
271 /// The newly formed Block is returned, and the specified iterator is
272 /// invalidated.
273 Block *Block::splitBlock(iterator splitBefore) {
274   // Start by creating a new basic block, and insert it immediate after this
275   // one in the containing region.
276   auto newBB = new Block();
277   getParent()->getBlocks().insert(std::next(Region::iterator(this)), newBB);
278 
279   // Move all of the operations from the split point to the end of the region
280   // into the new block.
281   newBB->getOperations().splice(newBB->end(), getOperations(), splitBefore,
282                                 end());
283   return newBB;
284 }
285 
286 //===----------------------------------------------------------------------===//
287 // Predecessors
288 //===----------------------------------------------------------------------===//
289 
290 Block *PredecessorIterator::unwrap(BlockOperand &value) {
291   return value.getOwner()->getBlock();
292 }
293 
294 /// Get the successor number in the predecessor terminator.
295 unsigned PredecessorIterator::getSuccessorIndex() const {
296   return I->getOperandNumber();
297 }
298 
299 //===----------------------------------------------------------------------===//
300 // SuccessorRange
301 //===----------------------------------------------------------------------===//
302 
303 SuccessorRange::SuccessorRange() : SuccessorRange(nullptr, 0) {}
304 
305 SuccessorRange::SuccessorRange(Block *block) : SuccessorRange() {
306   if (Operation *term = block->getTerminator())
307     if ((count = term->getNumSuccessors()))
308       base = term->getBlockOperands().data();
309 }
310 
311 SuccessorRange::SuccessorRange(Operation *term) : SuccessorRange() {
312   if ((count = term->getNumSuccessors()))
313     base = term->getBlockOperands().data();
314 }
315 
316 //===----------------------------------------------------------------------===//
317 // BlockRange
318 //===----------------------------------------------------------------------===//
319 
320 BlockRange::BlockRange(ArrayRef<Block *> blocks) : BlockRange(nullptr, 0) {
321   if ((count = blocks.size()))
322     base = blocks.data();
323 }
324 
325 BlockRange::BlockRange(SuccessorRange successors)
326     : BlockRange(successors.begin().getBase(), successors.size()) {}
327 
328 /// See `llvm::detail::indexed_accessor_range_base` for details.
329 BlockRange::OwnerT BlockRange::offset_base(OwnerT object, ptrdiff_t index) {
330   if (auto *operand = object.dyn_cast<BlockOperand *>())
331     return {operand + index};
332   return {object.dyn_cast<Block *const *>() + index};
333 }
334 
335 /// See `llvm::detail::indexed_accessor_range_base` for details.
336 Block *BlockRange::dereference_iterator(OwnerT object, ptrdiff_t index) {
337   if (const auto *operand = object.dyn_cast<BlockOperand *>())
338     return operand[index].get();
339   return object.dyn_cast<Block *const *>()[index];
340 }
341