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