[llvm] [RegAlloc] Consider rematerialization over CSR use (PR #206756)

Lucas Ramirez via llvm-commits llvm-commits at lists.llvm.org
Mon Jul 20 05:03:12 PDT 2026


================
@@ -2372,6 +2372,87 @@ BlockFrequency RAGreedy::calcSpillCost(const LiveInterval &LI) {
   return BlockFrequency(SpillCost);
 }
 
+bool RAGreedy::shouldAvoidCSRForRemat(const LiveInterval &VirtReg,
+                                      AllocationOrder &Order) const {
+  if (!VirtReg.isSpillable())
+    return false;
+
+  // This logic is intentionally narrow: handle a single concrete value
+  // whose def can be cheaply rematerialized at every use.
+  const VNInfo *OnlyVNI = nullptr;
+  for (const VNInfo *VNI : VirtReg.vnis()) {
+    if (!VNI || VNI->isUnused())
+      continue;
+    if (VNI->isPHIDef())
+      return false;
+    if (OnlyVNI)
+      return false;
+    OnlyVNI = VNI;
+  }
+  if (!OnlyVNI)
+    return false;
+
+  MachineInstr *DefMI = LIS->getInstructionFromIndex(OnlyVNI->def);
+  if (!DefMI || DefMI->isImplicitDef() || !TII->isReMaterializable(*DefMI) ||
+      !TII->isAsCheapAsAMove(*DefMI))
+    return false;
+
+  // This logic aims to address a specific problem: The first use of CSR for
+  // cheap-to-rematerialize live ranges because they cross calls, not because
+  // pressure requires it. With this check and the check for an available for a
+  // register that is not a first-use CSR below, we can scope this.
+  if (!Matrix->checkRegMaskInterference(VirtReg))
+    return false;
+
+  SmallPtrSet<MachineInstr *, 8> VisitedUses;
+  unsigned NumUses = 0;
+  for (MachineOperand &MO : MRI->use_nodbg_operands(VirtReg.reg())) {
+    if (MO.isUndef())
+      continue;
+
+    MachineInstr *UseMI = MO.getParent();
+    if (!VisitedUses.insert(UseMI).second)
+      continue;
+
+    SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI).getRegSlot(true);
+    if (!VirtRegAuxInfo::allUsesAvailableAt(DefMI, UseIdx, *LIS, *MRI, *TII))
+      return false;
+
+    // Check if any register that is not a first-use CSR is available as
+    // destination for the rematerialization.
+    SlotIndex PrevIdx = UseIdx.getPrevSlot();
+    bool HasNoFirstCSRReg = false;
+    for (MCRegister RematPhysReg : Order) {
+      if (EvictAdvisor->isUnusedCalleeSavedReg(RematPhysReg))
----------------
lucas-rami wrote:

Do we really care that the register used for the rematerialization is not a CSR? If we rematerialize across the call then we won't need a push/pop for it in the callee so there is no penalty for using a CSR over the live-range `[PrevIdx,UseIdx]`.

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


More information about the llvm-commits mailing list