[llvm] [IVDescriptors] Implement MonotonicDescriptor (PR #214490)

Luke Lau via llvm-commits llvm-commits at lists.llvm.org
Tue Aug 25 08:52:14 PDT 2026


================
@@ -1696,3 +1696,88 @@ bool InductionDescriptor::isInductionPHI(
                           /*InductionBinOp=*/nullptr, /*Casts=*/nullptr, Preds);
   return true;
 }
+
+// Recognize monotonic phi variable by matching the following pattern:
+// loop_header:
+//   %monotonic_phi = phi [ %start, %preheader ], [ %chain_phi0, %latch ]
+//   br i1 %do_step, label %step_bb, label %latch
+//
+// step_bb:
+//   %step = add/gep %monotonic_phi, %step_val
+//   br label %latch
+//
+// latch:
+//   %chain_phi0 = phi [ %monotonic_phi, %loop_header ], [ %step, %step_bb ]
+//   br label %loop_header
+//
+// For this pattern, monotonic phi is described by {%start, +, %step}
+// recurrence and predicate is CFG edge %step_bb -> %latch.
+bool MonotonicDescriptor::isMonotonicPHI(PHINode *HeaderPHI, const Loop *L,
+                                         MonotonicDescriptor &Desc,
+                                         ScalarEvolution &SE) {
+  if (!L->getLoopPreheader() || !HeaderPHI->getType()->isIntOrPtrTy() ||
+      HeaderPHI->getParent() != L->getHeader())
+    return false;
+  auto *BackedgePHI =
+      dyn_cast<PHINode>(HeaderPHI->getIncomingValueForBlock(L->getLoopLatch()));
+  if (!BackedgePHI)
+    return false;
+
+  // Ensure the only users of the backedge PHI are outside the loop or the
+  // header PHI.
+  bool BackedgeValueUsesValid = all_of(BackedgePHI->users(), [&](User *U) {
+    auto *UI = dyn_cast<Instruction>(U);
+    return UI == HeaderPHI || (UI && !L->contains(UI));
+  });
+  if (!BackedgeValueUsesValid)
+    return false;
----------------
lukel97 wrote:

Can this just be a for loop?
```suggestion
  for (User *U : BackedgePHI->users()) {
    auto *UI = dyn_cast<Instruction>(U);
    if (UI && UI != HeaderPHI && L->contains(UI))
      return false;
  }
```

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


More information about the llvm-commits mailing list