[llvm] [AArch64] Reorder callee-saved spills to maximise load/store register groupings (PR #229349)

Kieran B via llvm-commits llvm-commits at lists.llvm.org
Fri Oct 9 01:39:33 PDT 2026


================
@@ -2889,39 +2871,86 @@ static void orderZPRCalleeSavesForPairs(MachineFunction &MF,
   const int LowestOffset =
       (ZPRByteOffset / Scale) - static_cast<int>(ZPRSaves.size());
 
-  // Prefer the highest single otherwise split the highest pair.
-  std::optional<CalleeSavedInfo> AlignmentSingle;
-  if (LowestOffset % 2 != 0) {
-    if (!Singles.empty()) {
-      AlignmentSingle = Singles.pop_back_val();
-    } else {
-      assert(!Pairs.empty() && "Expected a ZPR pair to split");
-      auto [Even, Odd] = Pairs.pop_back_val();
-      AlignmentSingle = Odd;
-      Singles.push_back(Even);
+  int NumToAlign = alignTo(LowestOffset, 4) - LowestOffset;
+  if (NumToAlign > int(ZPRSaves.size()))
+    return;
+
+  sort(ZPRSaves,
+       [](const auto &A, const auto &B) { return A.getReg() < B.getReg(); });
+
+  SmallVector<std::array<CalleeSavedInfo, 4>> Quads;
+  SmallVector<std::array<CalleeSavedInfo, 2>> Pairs;
+  SmallVector<CalleeSavedInfo> Singles;
+
+  int ZPRsNeededForAlignment = NumToAlign;
+  for (size_t i = 0; i < ZPRSaves.size();) {
+    int ZPRsRemaining = int(ZPRSaves.size()) - i;
+    if (i + 3 < ZPRSaves.size() &&
+        (ZPRSaves[i].getReg() - AArch64::Z0) % 4 == 0 &&
+        ZPRSaves[i].getReg() + 3 == ZPRSaves[i + 3].getReg() &&
+        ZPRsRemaining - 4 >= ZPRsNeededForAlignment) {
+      Quads.push_back(
+          {ZPRSaves[i], ZPRSaves[i + 1], ZPRSaves[i + 2], ZPRSaves[i + 3]});
+      i += 4;
+      continue;
     }
+
+    bool MustSplitPairForSingle =
+        ZPRsNeededForAlignment == 1 && Singles.empty() && ZPRsRemaining == 2;
+
+    if (i + 1 < ZPRSaves.size() &&
+        (ZPRSaves[i].getReg() - AArch64::Z0) % 2 == 0 &&
+        ZPRSaves[i].getReg() + 1 == ZPRSaves[i + 1].getReg() &&
+        !MustSplitPairForSingle) {
+      Pairs.push_back({ZPRSaves[i], ZPRSaves[i + 1]});
+
+      if (ZPRsNeededForAlignment >= 2) {
+        ZPRsNeededForAlignment -= 2;
+      } else if (ZPRsNeededForAlignment == 1 && !Singles.empty()) {
+        // In this case, we have already found a single to use for alignment but
+        // we prefer to use this pair instead to align the offset
+        ZPRsNeededForAlignment = 0;
+      }
+
+      i += 2;
+      continue;
+    }
+
+    Singles.push_back(ZPRSaves[i++]);
+    if (ZPRsNeededForAlignment > 0)
+      ZPRsNeededForAlignment--;
----------------
kieroxide wrote:

Done.

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


More information about the llvm-commits mailing list