[llvm] [LoopStrengthReduce] Mitigation of issues introduced by compilation time optimization in SolveRecurse. (PR #147588)

Matt Arsenault via llvm-commits llvm-commits at lists.llvm.org
Fri Aug 1 01:53:07 PDT 2025


================
@@ -5395,6 +5401,58 @@ void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
     NarrowSearchSpaceByPickingWinnerRegs();
 }
 
+/// Sort LSRUses to address side effects of compile time optimization done in
+/// SolveRecurse which filters out formulae not including required registers.
+/// Such optimization makes the found best solution sensitive to the order
+/// of LSRUses processing, hence it's important to ensure that that order
+/// isn't random to avoid fluctuations and sub-optimal results.
+///
+/// Also check that all LSRUses have formulae as otherwise the situation is
+/// unsolvable.
+bool LSRInstance::SortLSRUses() {
+  SmallVector<LSRUse *, 16> NewOrder;
+  for (LSRUse &LU : Uses) {
+    if (LU.Formulae.empty()) {
+      return false;
+    }
+    NewOrder.push_back(&LU);
+  }
+
+  stable_sort(NewOrder, [](const LSRUse *L, const LSRUse *R) {
+    auto CalcKey = [](const LSRUse *LU) {
+      return std::tuple(LU->Regs.size(), LU->Formulae.size(), LU->Kind,
+                        LU->MinOffset.getKnownMinValue(),
+                        LU->MaxOffset.getKnownMinValue(),
+                        LU->AllFixupsOutsideLoop, LU->RigidFormula);
+    };
+
+    bool LExpensive = L->Formulae.size() >= MinExpensiveFromulaeNum;
+    bool RExpensive = R->Formulae.size() >= MinExpensiveFromulaeNum;
+
+    // If there are too many forlmulae then LSRUses w/ less formulae
+    // go first to save compilation time
+    if (LExpensive != RExpensive) {
+      return RExpensive;
+    }
+    if (LExpensive) {
+      return L->Formulae.size() < R->Formulae.size();
+    }
----------------
arsenm wrote:

```suggestion
    if (LExpensive != RExpensive)
      return RExpensive;
    if (LExpensive)
      return L->Formulae.size() < R->Formulae.size();
```

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


More information about the llvm-commits mailing list