[llvm] [LoopInfo] Derive Loop::contains(BlockT*) from the block-to-loop map (PR #207613)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Wed Jul 22 00:51:53 PDT 2026


================
@@ -121,20 +123,35 @@ template <class BlockT, class LoopT> class LoopBase {
     ParentLoop = L;
   }
 
-  /// Return true if the specified loop is contained within in this loop.
+  /// Return true if the specified loop is contained within this loop.
+  ///
+  /// This walks the parent chain and is O(depth). Deep nesting is not a
+  /// performance target (yet).
   bool contains(const LoopT *L) const {
     assert(!isInvalid() && "Loop not in a valid state!");
-    if (L == this)
-      return true;
-    if (!L)
-      return false;
-    return contains(L->getParentLoop());
+    for (;;) {
+      if (L == this)
+        return true;
+      if (!L)
+        return false;
+      L = L->getParentLoop();
+    }
   }
 
-  /// Return true if the specified basic block is in this loop.
+  /// Return true if the specified basic block is in this loop, using LoopInfo's
+  /// block-to-loop map.
+  ///
+  /// This is only valid when that map agrees with the block lists. Avoid when
+  /// the loop nest is being restructured, when a block may appear in a loop's
+  /// block list before it is mapped to that loop. Code in such a transient
+  /// state must scan getBlocks() directly instead.
   bool contains(const BlockT *BB) const {
     assert(!isInvalid() && "Loop not in a valid state!");
-    return DenseBlockSet.count(BB);
+    // A block from another function is never contained, and its number would
+    // otherwise index this function's map.
+    if (BB->getParent() != LI->ParentPtr)
----------------
nikic wrote:

This should probably be an assertion -- shouldn't be doing cross-function LoopInfo queries...

https://github.com/llvm/llvm-project/pull/207613


More information about the llvm-commits mailing list