[llvm] [polly] [SimpleLoopUnswitch] Generalize the notion of trivial unswitching (PR #193989)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Fri Jun 12 09:24:43 PDT 2026


================
@@ -591,6 +592,48 @@ static bool unswitchTrivialBranch(Loop &L, CondBrInst &BI, DominatorTree &DT,
     }
   }
 
+  std::optional<int> LatchIdx = std::nullopt;
+  if (FullUnswitch && L.getUniqueLatchExitBlock() != nullptr)
+    if (BI.getSuccessor(0) == L.getLoopLatch() &&
+        L.contains(BI.getSuccessor(1)))
+      LatchIdx = 0;
+    else if (BI.getSuccessor(1) == L.getLoopLatch() &&
+             L.contains(BI.getSuccessor(0)))
+      LatchIdx = 1;
+
+  bool ModifiedBranch = false;
+  if (LatchIdx &&
+      areLoopExitPHIsLoopInvariant(L, *L.getLoopLatch(),
+                                   *L.getUniqueLatchExitBlock()) &&
+      !llvm::any_of(*L.getLoopLatch(),
+                    [](Instruction &I) { return I.mayHaveSideEffects(); })) {
+
+    // We need to prove the loop is finite, otherwise this change will convert
+    // it to a finite loop. This conservative check is good enough as we are
+    // mostly interested in perfect countable loop nests that perform
+    // calculations on arrays.
+    const SCEV *MaxBECount = SE->getConstantMaxBackedgeTakenCount(&L);
----------------
nikic wrote:

It looks like SE is supposed to be optional in this function (see function comment and null checks below).

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


More information about the llvm-commits mailing list