[LLVM] Fix Maintainers.md formatting (NFC)
[llvm-project.git] / mlir / lib / IR / Dominance.cpp
blob406e0f2d62d640102effd59f8fff66012c71aea9
1 //===- Dominance.cpp - Dominator analysis for CFGs ------------------------===//
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 // Implementation of dominance related classes and instantiations of extern
10 // templates.
12 //===----------------------------------------------------------------------===//
14 #include "mlir/IR/Dominance.h"
15 #include "mlir/IR/Operation.h"
16 #include "mlir/IR/RegionKindInterface.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/Support/GenericDomTreeConstruction.h"
20 using namespace mlir;
21 using namespace mlir::detail;
23 template class llvm::DominatorTreeBase<Block, /*IsPostDom=*/false>;
24 template class llvm::DominatorTreeBase<Block, /*IsPostDom=*/true>;
25 template class llvm::DomTreeNodeBase<Block>;
27 //===----------------------------------------------------------------------===//
28 // DominanceInfoBase
29 //===----------------------------------------------------------------------===//
31 template <bool IsPostDom>
32 DominanceInfoBase<IsPostDom>::~DominanceInfoBase() {
33 for (auto entry : dominanceInfos)
34 delete entry.second.getPointer();
37 template <bool IsPostDom>
38 void DominanceInfoBase<IsPostDom>::invalidate() {
39 for (auto entry : dominanceInfos)
40 delete entry.second.getPointer();
41 dominanceInfos.clear();
44 template <bool IsPostDom>
45 void DominanceInfoBase<IsPostDom>::invalidate(Region *region) {
46 auto it = dominanceInfos.find(region);
47 if (it != dominanceInfos.end()) {
48 delete it->second.getPointer();
49 dominanceInfos.erase(it);
53 /// Return the dom tree and "hasSSADominance" bit for the given region. The
54 /// DomTree will be null for single-block regions. This lazily constructs the
55 /// DomTree on demand when needsDomTree=true.
56 template <bool IsPostDom>
57 auto DominanceInfoBase<IsPostDom>::getDominanceInfo(Region *region,
58 bool needsDomTree) const
59 -> llvm::PointerIntPair<DomTree *, 1, bool> {
60 // Check to see if we already have this information.
61 auto itAndInserted = dominanceInfos.insert({region, {nullptr, true}});
62 auto &entry = itAndInserted.first->second;
64 // This method builds on knowledge that multi-block regions always have
65 // SSADominance. Graph regions are only allowed to be single-block regions,
66 // but of course single-block regions may also have SSA dominance.
67 if (!itAndInserted.second) {
68 // We do have it, so we know the 'hasSSADominance' bit is correct, but we
69 // may not have constructed a DominatorTree yet. If we need it, build it.
70 if (needsDomTree && !entry.getPointer() && !region->hasOneBlock()) {
71 auto *domTree = new DomTree();
72 domTree->recalculate(*region);
73 entry.setPointer(domTree);
75 return entry;
78 // Nope, lazily construct it. Create a DomTree if this is a multi-block
79 // region.
80 if (!region->hasOneBlock()) {
81 auto *domTree = new DomTree();
82 domTree->recalculate(*region);
83 entry.setPointer(domTree);
84 // Multiblock regions always have SSA dominance, leave `second` set to true.
85 return entry;
88 // Single block regions have a more complicated predicate.
89 if (Operation *parentOp = region->getParentOp()) {
90 if (!parentOp->isRegistered()) { // We don't know about unregistered ops.
91 entry.setInt(false);
92 } else if (auto regionKindItf = dyn_cast<RegionKindInterface>(parentOp)) {
93 // Registered ops can opt-out of SSA dominance with
94 // RegionKindInterface.
95 entry.setInt(regionKindItf.hasSSADominance(region->getRegionNumber()));
99 return entry;
102 /// Return the ancestor block enclosing the specified block. This returns null
103 /// if we reach the top of the hierarchy.
104 static Block *getAncestorBlock(Block *block) {
105 if (Operation *ancestorOp = block->getParentOp())
106 return ancestorOp->getBlock();
107 return nullptr;
110 /// Walks up the list of containers of the given block and calls the
111 /// user-defined traversal function for every pair of a region and block that
112 /// could be found during traversal. If the user-defined function returns true
113 /// for a given pair, traverseAncestors will return the current block. Nullptr
114 /// otherwise.
115 template <typename FuncT>
116 static Block *traverseAncestors(Block *block, const FuncT &func) {
117 do {
118 // Invoke the user-defined traversal function for each block.
119 if (func(block))
120 return block;
121 } while ((block = getAncestorBlock(block)));
122 return nullptr;
125 /// Tries to update the given block references to live in the same region by
126 /// exploring the relationship of both blocks with respect to their regions.
127 static bool tryGetBlocksInSameRegion(Block *&a, Block *&b) {
128 // If both block do not live in the same region, we will have to check their
129 // parent operations.
130 Region *aRegion = a->getParent();
131 Region *bRegion = b->getParent();
132 if (aRegion == bRegion)
133 return true;
135 // Iterate over all ancestors of `a`, counting the depth of `a`. If one of
136 // `a`s ancestors are in the same region as `b`, then we stop early because we
137 // found our NCA.
138 size_t aRegionDepth = 0;
139 if (Block *aResult = traverseAncestors(a, [&](Block *block) {
140 ++aRegionDepth;
141 return block->getParent() == bRegion;
142 })) {
143 a = aResult;
144 return true;
147 // Iterate over all ancestors of `b`, counting the depth of `b`. If one of
148 // `b`s ancestors are in the same region as `a`, then we stop early because
149 // we found our NCA.
150 size_t bRegionDepth = 0;
151 if (Block *bResult = traverseAncestors(b, [&](Block *block) {
152 ++bRegionDepth;
153 return block->getParent() == aRegion;
154 })) {
155 b = bResult;
156 return true;
159 // Otherwise we found two blocks that are siblings at some level. Walk the
160 // deepest one up until we reach the top or find an NCA.
161 while (true) {
162 if (aRegionDepth > bRegionDepth) {
163 a = getAncestorBlock(a);
164 --aRegionDepth;
165 } else if (aRegionDepth < bRegionDepth) {
166 b = getAncestorBlock(b);
167 --bRegionDepth;
168 } else {
169 break;
173 // If we found something with the same level, then we can march both up at the
174 // same time from here on out.
175 while (a) {
176 // If they are at the same level, and have the same parent region then we
177 // succeeded.
178 if (a->getParent() == b->getParent())
179 return true;
181 a = getAncestorBlock(a);
182 b = getAncestorBlock(b);
185 // They don't share an NCA, perhaps they are in different modules or
186 // something.
187 return false;
190 template <bool IsPostDom>
191 Block *
192 DominanceInfoBase<IsPostDom>::findNearestCommonDominator(Block *a,
193 Block *b) const {
194 // If either a or b are null, then conservatively return nullptr.
195 if (!a || !b)
196 return nullptr;
198 // If they are the same block, then we are done.
199 if (a == b)
200 return a;
202 // Try to find blocks that are in the same region.
203 if (!tryGetBlocksInSameRegion(a, b))
204 return nullptr;
206 // If the common ancestor in a common region is the same block, then return
207 // it.
208 if (a == b)
209 return a;
211 // Otherwise, there must be multiple blocks in the region, check the
212 // DomTree.
213 return getDomTree(a->getParent()).findNearestCommonDominator(a, b);
216 /// Return true if the specified block A properly dominates block B.
217 template <bool IsPostDom>
218 bool DominanceInfoBase<IsPostDom>::properlyDominatesImpl(Block *a,
219 Block *b) const {
220 assert(a && b && "null blocks not allowed");
222 // A block dominates, but does not properly dominate, itself unless this
223 // is a graph region.
224 if (a == b)
225 return !hasSSADominance(a);
227 // If both blocks are not in the same region, `a` properly dominates `b` if
228 // `b` is defined in an operation region that (recursively) ends up being
229 // dominated by `a`. Walk up the list of containers enclosing B.
230 Region *regionA = a->getParent();
231 if (regionA != b->getParent()) {
232 b = regionA ? regionA->findAncestorBlockInRegion(*b) : nullptr;
233 // If we could not find a valid block b then it is a not a dominator.
234 if (!b)
235 return false;
237 // Check to see if the ancestor of `b` is the same block as `a`. A properly
238 // dominates B if it contains an op that contains the B block.
239 if (a == b)
240 return true;
243 // Otherwise, they are two different blocks in the same region, use DomTree.
244 return getDomTree(regionA).properlyDominates(a, b);
247 template <bool IsPostDom>
248 bool DominanceInfoBase<IsPostDom>::properlyDominatesImpl(
249 Operation *a, Operation *b, bool enclosingOpOk) const {
250 Block *aBlock = a->getBlock(), *bBlock = b->getBlock();
251 assert(aBlock && bBlock && "operations must be in a block");
253 // An operation (pos)dominates, but does not properly (pos)dominate, itself
254 // unless this is a graph region.
255 if (a == b)
256 return !hasSSADominance(aBlock);
258 // If these ops are in different regions, then normalize one into the other.
259 Region *aRegion = aBlock->getParent();
260 if (aRegion != bBlock->getParent()) {
261 // Scoot up b's region tree until we find an operation in A's region that
262 // encloses it. If this fails, then we know there is no (post)dom relation.
263 b = aRegion ? aRegion->findAncestorOpInRegion(*b) : nullptr;
264 if (!b)
265 return false;
266 bBlock = b->getBlock();
267 assert(bBlock->getParent() == aRegion);
269 // If 'a' encloses 'b', then we consider it to (post)dominate.
270 if (a == b && enclosingOpOk)
271 return true;
274 // Ok, they are in the same region now.
275 if (aBlock == bBlock) {
276 // Dominance changes based on the region type. In a region with SSA
277 // dominance, uses inside the same block must follow defs. In other
278 // regions kinds, uses and defs can come in any order inside a block.
279 if (!hasSSADominance(aBlock))
280 return true;
281 if constexpr (IsPostDom) {
282 return b->isBeforeInBlock(a);
283 } else {
284 return a->isBeforeInBlock(b);
288 // If the blocks are different, use DomTree to resolve the query.
289 return getDomTree(aRegion).properlyDominates(aBlock, bBlock);
292 /// Return true if the specified block is reachable from the entry block of
293 /// its region.
294 template <bool IsPostDom>
295 bool DominanceInfoBase<IsPostDom>::isReachableFromEntry(Block *a) const {
296 // If this is the first block in its region, then it is obviously reachable.
297 Region *region = a->getParent();
298 if (&region->front() == a)
299 return true;
301 // Otherwise this is some block in a multi-block region. Check DomTree.
302 return getDomTree(region).isReachableFromEntry(a);
305 template class detail::DominanceInfoBase</*IsPostDom=*/true>;
306 template class detail::DominanceInfoBase</*IsPostDom=*/false>;
308 //===----------------------------------------------------------------------===//
309 // DominanceInfo
310 //===----------------------------------------------------------------------===//
312 /// Return true if the `a` value properly dominates operation `b`, i.e if the
313 /// operation that defines `a` properlyDominates `b` and the operation that
314 /// defines `a` does not contain `b`.
315 bool DominanceInfo::properlyDominates(Value a, Operation *b) const {
316 // block arguments properly dominate all operations in their own block, so
317 // we use a dominates check here, not a properlyDominates check.
318 if (auto blockArg = dyn_cast<BlockArgument>(a))
319 return dominates(blockArg.getOwner(), b->getBlock());
321 // `a` properlyDominates `b` if the operation defining `a` properlyDominates
322 // `b`, but `a` does not itself enclose `b` in one of its regions.
323 return properlyDominates(a.getDefiningOp(), b, /*enclosingOpOk=*/false);