[llvm] [AMDGPU] Eliminate redundant SGPR restores (PR #222680)

Matt Arsenault via llvm-commits llvm-commits at lists.llvm.org
Fri Sep 11 05:06:19 PDT 2026


================
@@ -121,6 +129,59 @@ INITIALIZE_PASS_END(SILowerSGPRSpillsLegacy, DEBUG_TYPE,
 
 char &llvm::SILowerSGPRSpillsLegacyID = SILowerSGPRSpillsLegacy::ID;
 
+/// Remove a restore which immediately reads back the value just saved from the
+/// same SGPR. Keep the save, since a later restore may still need it.
+bool SILowerSGPRSpills::eliminateRedundantRestores(
+    MachineFunction &MF, ArrayRef<int> CalleeSavedFIs) {
+  bool Changed = false;
+
+  for (MachineBasicBlock &MBB : MF) {
+    for (MachineInstr &Restore : llvm::make_early_inc_range(MBB)) {
+      if (!TII->isSGPRSpill(Restore) || !Restore.mayLoad() ||
+          Restore.isBundled() || Restore.getFlag(MachineInstr::FrameSetup) ||
+          Restore.getFlag(MachineInstr::FrameDestroy))
+        continue;
+
+      auto RestoreIt = Restore.getIterator();
+      if (RestoreIt == MBB.begin())
+        continue;
+      MachineInstr &Save = *prev_nodbg(RestoreIt, MBB.instr_begin(),
+                                       /*SkipPseudoOp=*/false);
+      if (!TII->isSGPRSpill(Save) || !Save.mayStore() || Save.isBundled() ||
+          Save.getFlag(MachineInstr::FrameSetup) ||
+          Save.getFlag(MachineInstr::FrameDestroy))
+        continue;
+
+      int RestoreFI, SaveFI;
+      TypeSize RestoreSize = TypeSize::getZero();
+      TypeSize SaveSize = TypeSize::getZero();
+      Register RestoreReg =
+          TII->isLoadFromStackSlot(Restore, RestoreFI, RestoreSize);
+      Register SaveReg = TII->isStoreToStackSlot(Save, SaveFI, SaveSize);
+      const MachineOperand *SaveData =
+          TII->getNamedOperand(Save, AMDGPU::OpName::data);
+      if (!RestoreReg.isPhysical() || RestoreReg != SaveReg || !RestoreSize ||
+          RestoreSize != SaveSize || RestoreFI != SaveFI ||
+          llvm::is_contained(CalleeSavedFIs, SaveFI) ||
+          MF.getFrameInfo().getStackID(SaveFI) != TargetStackID::SGPRSpill ||
+          !SaveData || SaveData->isUndef() ||
+          hasVolatileOrAtomicMemOperand(Save) ||
+          hasVolatileOrAtomicMemOperand(Restore))
----------------
arsenm wrote:

We don't ever emit an atomic or volatile spill

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


More information about the llvm-commits mailing list