[llvm] [SimpleLoopUnswitch] Allow trivial unswitch when exit LCSSA is a header PHI (PR #222962)

Ehsan Amiri via llvm-commits llvm-commits at lists.llvm.org
Sat Sep 12 15:13:11 PDT 2026


================
@@ -647,8 +657,14 @@ static bool unswitchTrivialBranch(Loop &L, CondBrInst &BI, DominatorTree &DT,
   }
   auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
   auto *ParentBB = BI.getParent();
-  if (!ModifiedBranch &&
-      !areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB)) {
+
+  // If the exit incomings aren't loop-invariant, the unswitch is still trivial
+  // when branch dominates the latch and every non-invariant incoming is a
+  // header PHI. Those incomings are repaired after unswitching.
+  // Branch always dominates the latch as guaranteed by the caller.
+  bool TrivialFromHeader = false;
+  if (!ModifiedBranch && !areLoopExitPHIsLoopInvariant(
----------------
amehsan wrote:

> `areLoopExitPHIsLoopInvariant(L, *LoopLatch, *ULExit)` guard redirecting the branch's latch edge to the unique latch exit. The value that must appear on the bypass edge is the one at the last iteration, loop-invariance is exactly what makes that equal to the value at entry. Relaxing this to accept a header PHI would substitute the entry value and would be incorrect.

Makes sense. Let me do one final round of detailed review, so that we can approve it next time. 

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


More information about the llvm-commits mailing list