[llvm] [CodeGen] Keep physreg copies when successors use-before-def (PR #182732)

via llvm-commits llvm-commits at lists.llvm.org
Sun Feb 22 00:30:39 PST 2026


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-regalloc

Author: Sightem (Sightem)

<details>
<summary>Changes</summary>

Addresses #<!-- -->182731

---
Full diff: https://github.com/llvm/llvm-project/pull/182732.diff


3 Files Affected:

- (modified) llvm/lib/CodeGen/MachineCopyPropagation.cpp (+31-3) 
- (modified) llvm/unittests/CodeGen/CMakeLists.txt (+1) 
- (added) llvm/unittests/CodeGen/MachineCopyPropagationTest.cpp (+145) 


``````````diff
diff --git a/llvm/lib/CodeGen/MachineCopyPropagation.cpp b/llvm/lib/CodeGen/MachineCopyPropagation.cpp
index 2a344b40c30c1..a4fc55027f5a7 100644
--- a/llvm/lib/CodeGen/MachineCopyPropagation.cpp
+++ b/llvm/lib/CodeGen/MachineCopyPropagation.cpp
@@ -563,6 +563,26 @@ void MachineCopyPropagation::readSuccessorLiveIns(
   }
 }
 
+// Conservatively detect a physical-register use in a successor block before
+// the register is redefined there. This guards against stale/incomplete
+// live-in information, which can otherwise make a required copy look
+// dead at block exit
+static bool hasUseBeforeDefInSuccessor(const MachineBasicBlock &MBB,
+                                       MCRegister Reg,
+                                       const TargetRegisterInfo &TRI) {
+  for (const MachineBasicBlock *Succ : MBB.successors()) {
+    for (const MachineInstr &MI : *Succ) {
+      if (MI.isPHI())
+        continue;
+      if (MI.readsRegister(Reg, &TRI))
+        return true;
+      if (MI.modifiesRegister(Reg, &TRI))
+        break;
+    }
+  }
+  return false;
+}
+
 /// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
 /// This fact may have been obscured by sub register usage or may not be true at
 /// all even though Src and Def are subregisters of the registers used in
@@ -1047,9 +1067,6 @@ void MachineCopyPropagation::ForwardCopyPropagateBlock(MachineBasicBlock &MBB) {
   // use liveness information from successors to confirm they are really dead.
   if (MBB.succ_empty() || TracksLiveness) {
     for (MachineInstr *MaybeDead : MaybeDeadCopies) {
-      LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
-                 MaybeDead->dump());
-
       std::optional<DestSourcePair> CopyOperands =
           isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
       assert(CopyOperands);
@@ -1058,6 +1075,17 @@ void MachineCopyPropagation::ForwardCopyPropagateBlock(MachineBasicBlock &MBB) {
       Register DestReg = CopyOperands->Destination->getReg();
       assert(!MRI->isReserved(DestReg));
 
+      if (!MBB.succ_empty() && DestReg.isPhysical() &&
+          hasUseBeforeDefInSuccessor(MBB, DestReg.asMCReg(), *TRI)) {
+        LLVM_DEBUG(dbgs() << "MCP: Keeping copy due to successor use-before-"
+                             "def: ";
+                   MaybeDead->dump());
+        continue;
+      }
+
+      LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
+                 MaybeDead->dump());
+
       // Update matching debug values, if any.
       const auto &DbgUsers = CopyDbgUsers[MaybeDead];
       SmallVector<MachineInstr *> MaybeDeadDbgUsers(DbgUsers.begin(),
diff --git a/llvm/unittests/CodeGen/CMakeLists.txt b/llvm/unittests/CodeGen/CMakeLists.txt
index 709017380fa4e..eb22080ddb423 100644
--- a/llvm/unittests/CodeGen/CMakeLists.txt
+++ b/llvm/unittests/CodeGen/CMakeLists.txt
@@ -33,6 +33,7 @@ add_llvm_unittest(CodeGenTests
   LowLevelTypeTest.cpp
   LexicalScopesTest.cpp
   MachineBasicBlockTest.cpp
+  MachineCopyPropagationTest.cpp
   MachineDomTreeUpdaterTest.cpp
   MachineInstrBundleIteratorTest.cpp
   MachineInstrTest.cpp
diff --git a/llvm/unittests/CodeGen/MachineCopyPropagationTest.cpp b/llvm/unittests/CodeGen/MachineCopyPropagationTest.cpp
new file mode 100644
index 0000000000000..cd6f9449e6456
--- /dev/null
+++ b/llvm/unittests/CodeGen/MachineCopyPropagationTest.cpp
@@ -0,0 +1,145 @@
+//===- MachineCopyPropagationTest.cpp - MCP unit tests --------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/CodeGen/MIRParser/MIRParser.h"
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/CodeGen/MachineInstr.h"
+#include "llvm/CodeGen/MachineModuleInfo.h"
+#include "llvm/CodeGen/Passes.h"
+#include "llvm/IR/LegacyPassManager.h"
+#include "llvm/IR/Module.h"
+#include "llvm/MC/TargetRegistry.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/TargetSelect.h"
+#include "llvm/Target/TargetMachine.h"
+#include "llvm/TargetParser/Triple.h"
+#include "gtest/gtest.h"
+
+using namespace llvm;
+
+namespace {
+
+class NoInitMachineModuleInfoWrapperPass : public MachineModuleInfoWrapperPass {
+public:
+  explicit NoInitMachineModuleInfoWrapperPass(const TargetMachine *TM)
+      : MachineModuleInfoWrapperPass(TM) {}
+
+  bool doInitialization(Module &M) override { return false; }
+  bool doFinalization(Module &M) override { return false; }
+};
+
+class MachineCopyPropagationTest : public testing::Test {
+protected:
+  static void SetUpTestCase() {
+    InitializeAllTargets();
+    InitializeAllTargetMCs();
+  }
+
+  void SetUp() override {
+    Triple TargetTriple("x86_64-unknown-linux-gnu");
+    std::string Error;
+    const Target *T = TargetRegistry::lookupTarget("", TargetTriple, Error);
+    if (!T)
+      GTEST_SKIP() << Error;
+
+    TargetOptions Options;
+    TM = std::unique_ptr<TargetMachine>(T->createTargetMachine(
+        TargetTriple, "", "", Options, std::nullopt));
+    if (!TM)
+      GTEST_SKIP();
+  }
+
+  bool parseMIR(StringRef MIRCode, MachineModuleInfo &MMI) {
+    std::unique_ptr<MemoryBuffer> MBuffer = MemoryBuffer::getMemBuffer(MIRCode);
+    MIR = createMIRParser(std::move(MBuffer), Context);
+    if (!MIR)
+      return false;
+
+    M = MIR->parseIRModule();
+    if (!M)
+      return false;
+    M->setDataLayout(TM->createDataLayout());
+
+    return !MIR->parseMachineFunctions(*M, MMI);
+  }
+
+  static unsigned countCopies(const MachineBasicBlock &MBB) {
+    return count_if(MBB, [](const MachineInstr &MI) { return MI.isCopy(); });
+  }
+
+  static size_t liveInCount(const MachineBasicBlock &MBB) {
+    return static_cast<size_t>(std::distance(MBB.liveins().begin(),
+                                             MBB.liveins().end()));
+  }
+
+  LLVMContext Context;
+  std::unique_ptr<TargetMachine> TM;
+  std::unique_ptr<Module> M;
+  std::unique_ptr<MIRParser> MIR;
+};
+
+TEST_F(MachineCopyPropagationTest, KeepsCopyWhenSuccessorUsesRegBeforeDef) {
+  StringRef MIRString = R"(
+--- |
+  define void @f() {
+  entry:
+    br label %bb1
+  bb1:
+    ret void
+  }
+...
+---
+name:            f
+tracksRegLiveness: true
+body:             |
+  bb.0.entry:
+    successors: %bb.1.bb1(0x80000000)
+    liveins: $ecx, $edx
+
+    $eax = COPY killed $ecx
+    JMP_1 %bb.1.bb1
+
+  bb.1.bb1:
+    liveins: $eax, $edx
+
+    $eax = ADD32rr killed $eax, killed $edx, implicit-def dead $eflags
+    RET64
+...
+)";
+
+  auto *MMIWP = new NoInitMachineModuleInfoWrapperPass(TM.get());
+  ASSERT_TRUE(parseMIR(MIRString, MMIWP->getMMI()));
+
+  Function *F = M->getFunction("f");
+  ASSERT_NE(F, nullptr);
+  MachineFunction *MF = MMIWP->getMMI().getMachineFunction(*F);
+  ASSERT_NE(MF, nullptr);
+  ASSERT_FALSE(MF->empty());
+
+  MachineBasicBlock &EntryMBB = MF->front();
+  ASSERT_EQ(EntryMBB.succ_size(), 1u);
+  MachineBasicBlock &SuccMBB = **EntryMBB.succ_begin();
+
+  EXPECT_EQ(countCopies(EntryMBB), 1u);
+  ASSERT_EQ(liveInCount(SuccMBB), 2u);
+
+  // simulate stale successor liveness metadata while keeping tracksLiveness on
+  SuccMBB.clearLiveIns();
+  EXPECT_EQ(liveInCount(SuccMBB), 0u);
+
+  legacy::PassManager PM;
+  PM.add(MMIWP);
+  PM.add(createMachineCopyPropagationPass(false));
+  PM.run(*M);
+
+  EXPECT_EQ(countCopies(EntryMBB), 1u);
+}
+
+} // namespace

``````````

</details>


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


More information about the llvm-commits mailing list