[llvm] [AMDGPU][CodeGen] Preserve debug value locations across multi-stage register allocation (PR #187237)

Teja Alaghari via llvm-commits llvm-commits at lists.llvm.org
Thu May 7 00:50:23 PDT 2026


https://github.com/TejaX-Alaghari updated https://github.com/llvm/llvm-project/pull/187237

>From 74bf5977d17d12d0559b03ac2d6dcd190efe2c82 Mon Sep 17 00:00:00 2001
From: tmahatej_amdeng <teja.alaghari at amd.com>
Date: Wed, 18 Mar 2026 14:42:08 +0530
Subject: [PATCH 1/4] Add tests to prove loss of debug info (missing SGPRs)

---
 .../AMDGPU/dbg-phi-sgpr-multi-stage-ra.ll     | 116 ++++++++++++++++++
 .../AMDGPU/dbg-value-sgpr-multi-stage-ra.ll   |  99 +++++++++++++++
 2 files changed, 215 insertions(+)
 create mode 100644 llvm/test/CodeGen/AMDGPU/dbg-phi-sgpr-multi-stage-ra.ll
 create mode 100644 llvm/test/CodeGen/AMDGPU/dbg-value-sgpr-multi-stage-ra.ll

diff --git a/llvm/test/CodeGen/AMDGPU/dbg-phi-sgpr-multi-stage-ra.ll b/llvm/test/CodeGen/AMDGPU/dbg-phi-sgpr-multi-stage-ra.ll
new file mode 100644
index 0000000000000..d6af44ec7e0d6
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/dbg-phi-sgpr-multi-stage-ra.ll
@@ -0,0 +1,116 @@
+; Verifies that DBG_PHI instructions referencing SGPR virtual registers are
+; correctly resolved to physical registers through the AMDGPU multi-stage
+; register allocation pipeline in instruction-referencing mode.
+;
+; AMDGPU does NOT use instruction-referencing mode by default — only x86_64
+; does (see debuginfoShouldUseDebugInstrRef() in LiveDebugValues.cpp). This
+; test uses -experimental-debug-variable-locations=true to explicitly enable
+; it, exercising the DBG_PHI / DBG_INSTR_REF code paths that would otherwise
+; be dormant on AMDGPU. These paths become relevant if instr-ref mode is
+; enabled for AMDGPU in the future.
+;
+; In instr-ref mode, PHI node debug info is tracked via DBG_PHI + DBG_INSTR_REF
+; pairs. PHIElimination records debug PHI positions (mapping instruction numbers
+; to their destination vregs). LDV stashes these in PHIValToPos and emits
+; DBG_PHI instructions with resolved physregs at final emission.
+;
+; Without resolveAssignedLocations(), the SGPR vreg-to-physreg mapping from the
+; first RA stage is lost when VRM is re-initialized for subsequent stages,
+; causing DBG_PHI to emit $noreg instead of the correct $sgprN.
+;
+; The test also includes a DIArgList-based debug value that, in instr-ref mode,
+; is translated by ISel into DBG_PHI + DBG_INSTR_REF pairs. This exercises the
+; same PHIValToPos resolution path for multi-operand debug expressions.
+;
+; RUN: llc -mtriple=amdgcn-amd-amdhsa -mcpu=gfx1030 -O1 \
+; RUN:   -experimental-debug-variable-locations=true \
+; RUN:   -print-after=virtregrewriter -o /dev/null < %s 2>&1 | \
+; RUN:   FileCheck %s
+
+; --- Function 1: SGPR PHI resolved via DBG_PHI ---
+; The PHI result (uniform add across a uniform branch) lives in an SGPR vreg.
+; After the fix, resolveAssignedLocations() pre-resolves it before VRM reset.
+; CHECK: Machine code for function test_sgpr_phi:{{.*}}NoVRegs
+; CHECK: DBG_PHI $sgpr{{[0-9]+}}, 1
+; CHECK: DBG_INSTR_REF !"phi_result", !DIExpression(DW_OP_LLVM_arg, 0), dbg-instr-ref(1, 0)
+
+; --- Function 2: DIArgList → DBG_PHI pair (SGPR + VGPR) ---
+; In instr-ref mode, ISel lowers DIArgList into two DBG_PHI entries and a
+; DBG_INSTR_REF that references both. The SGPR and VGPR entries must both
+; carry physical registers, not $noreg.
+; CHECK: Machine code for function test_diarglist_instr_ref:{{.*}}NoVRegs
+; CHECK-DAG: DBG_PHI $sgpr{{[0-9]+}},
+; CHECK-DAG: DBG_PHI $vgpr{{[0-9]+}},
+; CHECK: DBG_INSTR_REF !"combined"
+
+; Uniform branch with inline-asm side effects prevents if-conversion,
+; preserving the SGPR PHI across register allocation.
+define void @test_sgpr_phi(
+    i32 inreg %cond,
+    i32 inreg %a,
+    i32 inreg %b,
+    ptr addrspace(1) %out
+) #0 !dbg !6 {
+entry:
+  %cmp = icmp sgt i32 %cond, 0
+  br i1 %cmp, label %if.then, label %if.else
+
+if.then:
+  call void asm sideeffect "", "~{s0}"()
+  %va = add i32 %a, 10
+  br label %if.end
+
+if.else:
+  call void asm sideeffect "", "~{s0}"()
+  %vb = add i32 %b, 20
+  br label %if.end
+
+if.end:
+  %result = phi i32 [%va, %if.then], [%vb, %if.else]
+  call void @llvm.dbg.value(metadata i32 %result, metadata !9, metadata !DIExpression()), !dbg !11
+  store i32 %result, ptr addrspace(1) %out
+  ret void
+}
+
+; Non-kernel function: inreg → SGPR, normal arg → VGPR.
+; In instr-ref mode, DIArgList is lowered to DBG_PHI + DBG_INSTR_REF.
+define void @test_diarglist_instr_ref(
+    i32 inreg %sgpr_arg,
+    i32 %vgpr_arg,
+    ptr addrspace(1) %out
+) #0 !dbg !20 {
+entry:
+  call void @llvm.dbg.value(metadata !DIArgList(i32 %sgpr_arg, i32 %vgpr_arg), metadata !22, metadata !DIExpression(DW_OP_LLVM_arg, 0, DW_OP_LLVM_arg, 1, DW_OP_plus, DW_OP_stack_value)), !dbg !24
+  %sum = add i32 %sgpr_arg, %vgpr_arg
+  store i32 %sum, ptr addrspace(1) %out
+  ret void
+}
+
+declare void @llvm.dbg.value(metadata, metadata, metadata) #1
+
+attributes #0 = { nounwind "amdgpu-flat-work-group-size"="64,256" }
+attributes #1 = { nounwind readnone speculatable willreturn }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
+!1 = !DIFile(filename: "test.cl", directory: "/tmp")
+!2 = !{}
+!3 = !{i32 7, !"Dwarf Version", i32 5}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 4}
+
+; Metadata for test_sgpr_phi
+!6 = distinct !DISubprogram(name: "test_sgpr_phi", scope: !1, file: !1, line: 1, type: !7, scopeLine: 1, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !8)
+!7 = !DISubroutineType(types: !2)
+!8 = !{!9}
+!9 = !DILocalVariable(name: "phi_result", scope: !6, file: !1, line: 2, type: !12)
+!11 = !DILocation(line: 2, column: 1, scope: !6)
+!12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+
+; Metadata for test_diarglist_instr_ref
+!20 = distinct !DISubprogram(name: "test_diarglist_instr_ref", scope: !1, file: !1, line: 10, type: !7, scopeLine: 10, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !21)
+!21 = !{!22}
+!22 = !DILocalVariable(name: "combined", scope: !20, file: !1, line: 11, type: !12)
+!24 = !DILocation(line: 11, column: 1, scope: !20)
diff --git a/llvm/test/CodeGen/AMDGPU/dbg-value-sgpr-multi-stage-ra.ll b/llvm/test/CodeGen/AMDGPU/dbg-value-sgpr-multi-stage-ra.ll
new file mode 100644
index 0000000000000..52faff34d6f18
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/dbg-value-sgpr-multi-stage-ra.ll
@@ -0,0 +1,99 @@
+; Verifies that debug variable locations for both SGPR and VGPR register
+; classes are preserved through the AMDGPU multi-stage register allocation
+; pipeline in non-instruction-referencing mode.
+;
+; The AMDGPU backend allocates registers in three stages: SGPR → WWM → VGPR.
+; Each stage has its own Greedy Allocator and VirtRegRewriter. Previously,
+; VRM mappings from the SGPR stage were lost before the final emission because
+; intervening passes (e.g. StackSlotColoring) did not preserve VRM. The fix
+; adds resolveAssignedLocations() calls at intermediate VirtRegRewriter passes,
+; capturing assigned physregs into LDV's UserValue data before VRM is cleared.
+;
+; AMDGPU does NOT use instruction-referencing mode by default — only x86_64
+; does (see debuginfoShouldUseDebugInstrRef() in LiveDebugValues.cpp). This
+; means ALL DBG_VALUE and DBG_VALUE_LIST instructions on AMDGPU are routed
+; through LDV's UserValue path, making them directly susceptible to VRM loss
+; across RA stages. The fix is therefore critical for all debug values on
+; AMDGPU, not just edge cases.
+;
+; The -experimental-debug-variable-locations=false flag explicitly forces
+; non-instr-ref mode, matching AMDGPU's actual default behavior. This routes
+; ALL DBG_VALUE instructions through UserValue (not stashing).
+;
+; RUN: llc -mtriple=amdgcn-amd-amdhsa -mcpu=gfx1030 -O1 \
+; RUN:   -experimental-debug-variable-locations=false \
+; RUN:   -print-after=virtregrewriter -o /dev/null < %s 2>&1 | \
+; RUN:   FileCheck %s
+
+; --- Function 1: DBG_VALUE for separate SGPR and VGPR variables ---
+; The NoVRegs flag distinguishes the final (VGPR) VirtRegRewriter dump.
+; CHECK: Machine code for function test_sgpr_vgpr_dbg_value:{{.*}}NoVRegs
+; CHECK: DBG_VALUE $sgpr{{[0-9]+}}, $noreg, !"uniform_val"
+; CHECK: DBG_VALUE $vgpr{{[0-9]+}}, $noreg, !"divergent_val"
+
+; --- Function 2: DBG_VALUE_LIST with mixed SGPR + VGPR operands ---
+; CHECK: Machine code for function test_dbg_value_list_mixed:{{.*}}NoVRegs
+; CHECK: DBG_VALUE_LIST !"combined", !DIExpression(DW_OP_LLVM_arg, 0, DW_OP_LLVM_arg, 1, DW_OP_plus, DW_OP_stack_value), $sgpr{{[0-9]+}}, $vgpr{{[0-9]+}}
+
+define amdgpu_kernel void @test_sgpr_vgpr_dbg_value(
+    ptr addrspace(1) %out,
+    i32 %uniform_arg
+) #0 !dbg !6 {
+entry:
+  %tid = call i32 @llvm.amdgcn.workitem.id.x()
+
+  %uniform_val = add i32 %uniform_arg, 42
+  call void @llvm.dbg.value(metadata i32 %uniform_val, metadata !9, metadata !DIExpression()), !dbg !14
+
+  %divergent_val = add i32 %tid, %uniform_val
+  call void @llvm.dbg.value(metadata i32 %divergent_val, metadata !10, metadata !DIExpression()), !dbg !14
+
+  %gep = getelementptr i32, ptr addrspace(1) %out, i32 %tid
+  store i32 %divergent_val, ptr addrspace(1) %gep, align 4
+  ret void
+}
+
+; Non-kernel function: inreg → SGPR, normal arg → VGPR.
+; DIArgList produces a DBG_VALUE_LIST referencing both register classes.
+define void @test_dbg_value_list_mixed(
+    i32 inreg %sgpr_arg,
+    i32 %vgpr_arg,
+    ptr addrspace(1) %out
+) #0 !dbg !20 {
+entry:
+  call void @llvm.dbg.value(metadata !DIArgList(i32 %sgpr_arg, i32 %vgpr_arg), metadata !22, metadata !DIExpression(DW_OP_LLVM_arg, 0, DW_OP_LLVM_arg, 1, DW_OP_plus, DW_OP_stack_value)), !dbg !24
+  %sum = add i32 %sgpr_arg, %vgpr_arg
+  store i32 %sum, ptr addrspace(1) %out
+  ret void
+}
+
+declare i32 @llvm.amdgcn.workitem.id.x() #1
+declare void @llvm.dbg.value(metadata, metadata, metadata) #1
+
+attributes #0 = { nounwind "amdgpu-flat-work-group-size"="64,256" }
+attributes #1 = { nounwind readnone speculatable willreturn }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
+!1 = !DIFile(filename: "test.cl", directory: "/tmp")
+!2 = !{}
+!3 = !{i32 7, !"Dwarf Version", i32 5}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 4}
+
+; Metadata for test_sgpr_vgpr_dbg_value
+!6 = distinct !DISubprogram(name: "test_sgpr_vgpr_dbg_value", scope: !1, file: !1, line: 1, type: !7, scopeLine: 1, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !8)
+!7 = !DISubroutineType(types: !2)
+!8 = !{!9, !10}
+!9 = !DILocalVariable(name: "uniform_val", scope: !6, file: !1, line: 2, type: !12)
+!10 = !DILocalVariable(name: "divergent_val", scope: !6, file: !1, line: 3, type: !12)
+!12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!14 = !DILocation(line: 2, column: 1, scope: !6)
+
+; Metadata for test_dbg_value_list_mixed
+!20 = distinct !DISubprogram(name: "test_dbg_value_list_mixed", scope: !1, file: !1, line: 10, type: !7, scopeLine: 10, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !21)
+!21 = !{!22}
+!22 = !DILocalVariable(name: "combined", scope: !20, file: !1, line: 11, type: !12)
+!24 = !DILocation(line: 11, column: 1, scope: !20)

>From e07023218aec18a267a8b9b4046aeb230499c828 Mon Sep 17 00:00:00 2001
From: tmahatej_amdeng <teja.alaghari at amd.com>
Date: Wed, 18 Mar 2026 14:44:19 +0530
Subject: [PATCH 2/4] Add mechanism to partially resolve debug value locations
 with  after its RA

---
 .../include/llvm/CodeGen/LiveDebugVariables.h |  7 +++
 llvm/lib/CodeGen/LiveDebugVariables.cpp       | 62 +++++++++++++++++--
 llvm/lib/CodeGen/VirtRegMap.cpp               |  6 ++
 3 files changed, 71 insertions(+), 4 deletions(-)

diff --git a/llvm/include/llvm/CodeGen/LiveDebugVariables.h b/llvm/include/llvm/CodeGen/LiveDebugVariables.h
index 419b60e4e38a5..4adaa37f700f3 100644
--- a/llvm/include/llvm/CodeGen/LiveDebugVariables.h
+++ b/llvm/include/llvm/CodeGen/LiveDebugVariables.h
@@ -52,6 +52,13 @@ class LiveDebugVariables {
   /// @param VRM Rename virtual registers according to map.
   void emitDebugValues(VirtRegMap *VRM);
 
+  /// In multi-stage register allocation pipelines (e.g. AMDGPU's
+  /// SGPR → WWM → VGPR), VRM is re-initialized between stages, losing
+  /// mappings from earlier stages. This method captures those mappings into
+  /// the internal UserValue data before VRM is cleared, so that the final
+  /// emitDebugValues only needs to resolve remaining (later-stage) vregs.
+  void resolveAssignedLocations(VirtRegMap *VRM);
+
 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
   /// dump - Print data structures to dbgs().
   void dump() const;
diff --git a/llvm/lib/CodeGen/LiveDebugVariables.cpp b/llvm/lib/CodeGen/LiveDebugVariables.cpp
index fb90032131491..2707e13d6becf 100644
--- a/llvm/lib/CodeGen/LiveDebugVariables.cpp
+++ b/llvm/lib/CodeGen/LiveDebugVariables.cpp
@@ -478,10 +478,16 @@ class UserValue {
   /// Rewrite virtual register locations according to the provided virtual
   /// register map. Record the stack slot offsets for the locations that
   /// were spilled.
+  ///
+  /// If \p KeepUnassigned is true, virtual registers not present in \p VRM
+  /// are left as-is rather than being set to $noreg. This supports
+  /// incremental resolution across multi-stage register allocation where
+  /// not all register classes have been allocated yet.
   void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
                         const TargetInstrInfo &TII,
                         const TargetRegisterInfo &TRI,
-                        SpillOffsetMap &SpillOffsets);
+                        SpillOffsetMap &SpillOffsets,
+                        bool KeepUnassigned = false);
 
   /// Recreate DBG_VALUE instruction from data structures.
   void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
@@ -671,6 +677,10 @@ class LiveDebugVariables::LDVImpl {
   /// Recreate DBG_VALUE instruction from data structures.
   void emitDebugValues(VirtRegMap *VRM);
 
+  /// Resolve assigned virtual register locations in \p VRM, leaving
+  /// unassigned vregs intact for later allocation stages.
+  void resolveAssignedLocations(VirtRegMap &VRM);
+
   void print(raw_ostream&);
 };
 
@@ -1555,7 +1565,8 @@ splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) {
 void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
                                  const TargetInstrInfo &TII,
                                  const TargetRegisterInfo &TRI,
-                                 SpillOffsetMap &SpillOffsets) {
+                                 SpillOffsetMap &SpillOffsets,
+                                 bool KeepUnassigned) {
   // Build a set of new locations with new numbers so we can coalesce our
   // IntervalMap if two vreg intervals collapse to the same physical location.
   // Use MapVector instead of SetVector because MapVector::insert returns the
@@ -1591,7 +1602,7 @@ void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
 
         Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
         Spilled = true;
-      } else {
+      } else if (!KeepUnassigned) {
         Loc.setReg(0);
         Loc.setSubReg(0);
       }
@@ -1883,7 +1894,13 @@ void LiveDebugVariables::LDVImpl::emitDebugValues(VirtRegMap *VRM) {
     unsigned SubReg = It.second.SubReg;
 
     MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(Slot);
-    if (VRM->isAssignedReg(Reg) && VRM->hasPhys(Reg)) {
+    if (Reg.isPhysical()) {
+      // Already resolved by resolveAssignedLocations at an earlier RA stage.
+      auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
+                             TII->get(TargetOpcode::DBG_PHI));
+      Builder.addReg(Reg);
+      Builder.addImm(InstNum);
+    } else if (VRM->isAssignedReg(Reg) && VRM->hasPhys(Reg)) {
       unsigned PhysReg = VRM->getPhys(Reg);
       if (SubReg != 0)
         PhysReg = TRI->getSubReg(PhysReg, SubReg);
@@ -2004,6 +2021,43 @@ void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
     PImpl->emitDebugValues(VRM);
 }
 
+void LiveDebugVariables::LDVImpl::resolveAssignedLocations(VirtRegMap &VRM) {
+  LLVM_DEBUG(
+      dbgs() << "********** RESOLVING ASSIGNED DEBUG LOCATIONS **********\n");
+  if (!MF)
+    return;
+
+  const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
+  SpillOffsetMap SpillOffsets;
+  for (auto &UV : userValues) {
+    LLVM_DEBUG(UV->print(dbgs(), TRI));
+    UV->rewriteLocations(VRM, *MF, *TII, *TRI, SpillOffsets,
+                         /*KeepUnassigned=*/true);
+  }
+
+  // Pre-resolve PHI entries whose vregs have been assigned in this stage.
+  // Replacing the vreg with its physreg here ensures the mapping survives
+  // VRM re-initialization before the next allocation stage.
+  for (auto &It : PHIValToPos) {
+    Register &Reg = It.second.Reg;
+    if (!Reg.isVirtual())
+      continue;
+    if (VRM.isAssignedReg(Reg) && VRM.hasPhys(Reg)) {
+      unsigned SubReg = It.second.SubReg;
+      Register PhysReg = VRM.getPhys(Reg);
+      if (SubReg != 0)
+        PhysReg = TRI->getSubReg(PhysReg, SubReg);
+      Reg = PhysReg;
+      It.second.SubReg = 0;
+    }
+  }
+}
+
+void LiveDebugVariables::resolveAssignedLocations(VirtRegMap *VRM) {
+  if (PImpl)
+    PImpl->resolveAssignedLocations(*VRM);
+}
+
 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
 LLVM_DUMP_METHOD void LiveDebugVariables::dump() const { print(dbgs()); }
 #endif
diff --git a/llvm/lib/CodeGen/VirtRegMap.cpp b/llvm/lib/CodeGen/VirtRegMap.cpp
index 972bd8f550e8b..07430556eef53 100644
--- a/llvm/lib/CodeGen/VirtRegMap.cpp
+++ b/llvm/lib/CodeGen/VirtRegMap.cpp
@@ -356,6 +356,12 @@ bool VirtRegRewriter::run(MachineFunction &fn) {
     // replaced. Remove the virtual registers and release all the transient data.
     VRM->clearAllVirt();
     MRI->clearVirtRegs();
+  } else {
+    // Capture the current VRM mappings into LDV's internal data at intermediate
+    // rewriter passes in multi-stage RA pipelines. This pre-resolves debug
+    // locations for register classes allocated in this stage before VRM is
+    // potentially re-initialized by subsequent allocation stages.
+    DebugVars->resolveAssignedLocations(VRM);
   }
 
   return true;

>From 9ef10d1062e98d2fc8e652742f026314b94b84c3 Mon Sep 17 00:00:00 2001
From: tmahatej_amdeng <teja.alaghari at amd.com>
Date: Wed, 18 Mar 2026 15:06:43 +0530
Subject: [PATCH 3/4] Add mechanism to skip resolving debug info in LDV after
 WWM RA

---
 llvm/include/llvm/CodeGen/Passes.h            |  3 +-
 llvm/include/llvm/CodeGen/VirtRegMap.h        |  5 ++--
 llvm/lib/CodeGen/VirtRegMap.cpp               | 28 +++++++++++--------
 .../lib/Target/AMDGPU/AMDGPUTargetMachine.cpp |  5 +++-
 4 files changed, 26 insertions(+), 15 deletions(-)

diff --git a/llvm/include/llvm/CodeGen/Passes.h b/llvm/include/llvm/CodeGen/Passes.h
index be344c6aaf40e..c0860fc7447b5 100644
--- a/llvm/include/llvm/CodeGen/Passes.h
+++ b/llvm/include/llvm/CodeGen/Passes.h
@@ -206,7 +206,8 @@ LLVM_ABI extern char &RABasicID;
 /// VirtRegRewriter pass. Rewrite virtual registers to physical registers as
 /// assigned in VirtRegMap.
 LLVM_ABI extern char &VirtRegRewriterID;
-LLVM_ABI FunctionPass *createVirtRegRewriter(bool ClearVirtRegs = true);
+LLVM_ABI FunctionPass *createVirtRegRewriter(bool ClearVirtRegs = true,
+                                             bool ResolveDebugLocs = true);
 
 /// UnreachableMachineBlockElimination - This pass removes unreachable
 /// machine basic blocks.
diff --git a/llvm/include/llvm/CodeGen/VirtRegMap.h b/llvm/include/llvm/CodeGen/VirtRegMap.h
index c75b3eda00622..2d93bec4b5aa3 100644
--- a/llvm/include/llvm/CodeGen/VirtRegMap.h
+++ b/llvm/include/llvm/CodeGen/VirtRegMap.h
@@ -240,10 +240,11 @@ class VirtRegMapPrinterPass
 
 class VirtRegRewriterPass : public RequiredPassInfoMixin<VirtRegRewriterPass> {
   bool ClearVirtRegs = true;
+  bool ResolveDebugLocs = true;
 
 public:
-  VirtRegRewriterPass(bool ClearVirtRegs = true)
-      : ClearVirtRegs(ClearVirtRegs) {}
+  VirtRegRewriterPass(bool ClearVirtRegs = true, bool ResolveDebugLocs = true)
+      : ClearVirtRegs(ClearVirtRegs), ResolveDebugLocs(ResolveDebugLocs) {}
   LLVM_ABI PreservedAnalyses run(MachineFunction &MF,
                                  MachineFunctionAnalysisManager &MFAM);
 
diff --git a/llvm/lib/CodeGen/VirtRegMap.cpp b/llvm/lib/CodeGen/VirtRegMap.cpp
index 07430556eef53..02abf55196008 100644
--- a/llvm/lib/CodeGen/VirtRegMap.cpp
+++ b/llvm/lib/CodeGen/VirtRegMap.cpp
@@ -209,6 +209,7 @@ class VirtRegRewriter {
   LiveDebugVariables *DebugVars = nullptr;
   DenseSet<Register> RewriteRegs;
   bool ClearVirtRegs;
+  bool ResolveDebugLocs;
 
   void rewrite();
   void addMBBLiveIns();
@@ -222,11 +223,11 @@ class VirtRegRewriter {
       MCRegister PhysReg, const MachineInstr &MI) const;
 
 public:
-  VirtRegRewriter(bool ClearVirtRegs, SlotIndexes *Indexes, LiveIntervals *LIS,
-                  LiveRegMatrix *LRM, VirtRegMap *VRM,
-                  LiveDebugVariables *DebugVars)
+  VirtRegRewriter(bool ClearVirtRegs, bool ResolveDebugLocs,
+                  SlotIndexes *Indexes, LiveIntervals *LIS, LiveRegMatrix *LRM,
+                  VirtRegMap *VRM, LiveDebugVariables *DebugVars)
       : Indexes(Indexes), LIS(LIS), LRM(LRM), VRM(VRM), DebugVars(DebugVars),
-        ClearVirtRegs(ClearVirtRegs) {}
+        ClearVirtRegs(ClearVirtRegs), ResolveDebugLocs(ResolveDebugLocs) {}
 
   bool run(MachineFunction &);
 };
@@ -235,8 +236,10 @@ class VirtRegRewriterLegacy : public MachineFunctionPass {
 public:
   static char ID;
   bool ClearVirtRegs;
-  VirtRegRewriterLegacy(bool ClearVirtRegs = true)
-      : MachineFunctionPass(ID), ClearVirtRegs(ClearVirtRegs) {}
+  bool ResolveDebugLocs;
+  VirtRegRewriterLegacy(bool ClearVirtRegs = true, bool ResolveDebugLocs = true)
+      : MachineFunctionPass(ID), ClearVirtRegs(ClearVirtRegs),
+        ResolveDebugLocs(ResolveDebugLocs) {}
 
   void getAnalysisUsage(AnalysisUsage &AU) const override;
 
@@ -294,7 +297,8 @@ bool VirtRegRewriterLegacy::runOnMachineFunction(MachineFunction &MF) {
   LiveDebugVariables &DebugVars =
       getAnalysis<LiveDebugVariablesWrapperLegacy>().getLDV();
 
-  VirtRegRewriter R(ClearVirtRegs, &Indexes, &LIS, &LRM, &VRM, &DebugVars);
+  VirtRegRewriter R(ClearVirtRegs, ResolveDebugLocs, &Indexes, &LIS, &LRM, &VRM,
+                    &DebugVars);
   return R.run(MF);
 }
 
@@ -310,7 +314,8 @@ VirtRegRewriterPass::run(MachineFunction &MF,
   LiveDebugVariables &DebugVars =
       MFAM.getResult<LiveDebugVariablesAnalysis>(MF);
 
-  VirtRegRewriter R(ClearVirtRegs, &Indexes, &LIS, &LRM, &VRM, &DebugVars);
+  VirtRegRewriter R(ClearVirtRegs, ResolveDebugLocs, &Indexes, &LIS, &LRM, &VRM,
+                    &DebugVars);
   if (!R.run(MF))
     return PreservedAnalyses::all();
 
@@ -356,7 +361,7 @@ bool VirtRegRewriter::run(MachineFunction &fn) {
     // replaced. Remove the virtual registers and release all the transient data.
     VRM->clearAllVirt();
     MRI->clearVirtRegs();
-  } else {
+  } else if (ResolveDebugLocs) {
     // Capture the current VRM mappings into LDV's internal data at intermediate
     // rewriter passes in multi-stage RA pipelines. This pre-resolves debug
     // locations for register classes allocated in this stage before VRM is
@@ -785,6 +790,7 @@ void VirtRegRewriterPass::printPipeline(
     OS << "<no-clear-vregs>";
 }
 
-FunctionPass *llvm::createVirtRegRewriter(bool ClearVirtRegs) {
-  return new VirtRegRewriterLegacy(ClearVirtRegs);
+FunctionPass *llvm::createVirtRegRewriter(bool ClearVirtRegs,
+                                          bool ResolveDebugLocs) {
+  return new VirtRegRewriterLegacy(ClearVirtRegs, ResolveDebugLocs);
 }
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp b/llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp
index 65317016c6390..3cf41f0c24bc8 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp
@@ -1865,7 +1865,10 @@ bool GCNPassConfig::addRegAssignAndRewriteOptimized() {
   // For allocating other whole wave mode registers.
   addPass(createWWMRegAllocPass(true));
   addPass(&SILowerWWMCopiesLegacyID);
-  addPass(createVirtRegRewriter(false));
+  // Skip the LDV resolution as no source-level debug variables reference WWM
+  // vregs.
+  addPass(createVirtRegRewriter(/*ClearVirtRegs=*/false,
+                                /*ResolveDebugLocs=*/false));
   addPass(&AMDGPUReserveWWMRegsLegacyID);
 
   // For allocating per-thread VGPRs.

>From 1356881a08b771bbb67ffbe66c7e946541d60659 Mon Sep 17 00:00:00 2001
From: tmahatej_amdeng <teja.alaghari at amd.com>
Date: Wed, 18 Mar 2026 15:50:37 +0530
Subject: [PATCH 4/4] Skip iterating through the UserValues with no VirtRegs
 during rewriteLocations and emitDebugValues

---
 llvm/lib/CodeGen/LiveDebugVariables.cpp | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/CodeGen/LiveDebugVariables.cpp b/llvm/lib/CodeGen/LiveDebugVariables.cpp
index 2707e13d6becf..0a7cbbf87a333 100644
--- a/llvm/lib/CodeGen/LiveDebugVariables.cpp
+++ b/llvm/lib/CodeGen/LiveDebugVariables.cpp
@@ -499,6 +499,13 @@ class UserValue {
   /// Return DebugLoc of this UserValue.
   const DebugLoc &getDebugLoc() { return dl; }
 
+  /// Return true if any numbered location is a virtual register.
+  bool hasVirtualRegLocations() const {
+    return any_of(locations, [](const MachineOperand &Loc) {
+      return Loc.isReg() && Loc.getReg().isVirtual();
+    });
+  }
+
   void print(raw_ostream &, const TargetRegisterInfo *);
 };
 
@@ -1872,7 +1879,10 @@ void LiveDebugVariables::LDVImpl::emitDebugValues(VirtRegMap *VRM) {
   SpillOffsetMap SpillOffsets;
   for (auto &userValue : userValues) {
     LLVM_DEBUG(userValue->print(dbgs(), TRI));
-    userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
+    if (userValue->hasVirtualRegLocations())
+      userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
+    else
+      SpillOffsets.clear();
     userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets,
                                BBSkipInstsMap);
   }
@@ -2030,6 +2040,8 @@ void LiveDebugVariables::LDVImpl::resolveAssignedLocations(VirtRegMap &VRM) {
   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
   SpillOffsetMap SpillOffsets;
   for (auto &UV : userValues) {
+    if (!UV->hasVirtualRegLocations())
+      continue;
     LLVM_DEBUG(UV->print(dbgs(), TRI));
     UV->rewriteLocations(VRM, *MF, *TII, *TRI, SpillOffsets,
                          /*KeepUnassigned=*/true);



More information about the llvm-commits mailing list