Repository navigation
Conversation
All siblings of an original register share one stack slot. Live range splitting can create a sibling that only defines some lanes: undef %new.sub2_sub3:sgpr_128 = COPY %sib.sub2_sub3 When such a sibling is spilled, the store after the copy (or the store that hoistSpillInsideBB moves to the copy source) writes the full register, including lanes that hold no value, into the slot. If the original register is still live in those lanes, a later reload of another sibling reads garbage there. On AMDGPU this corrupted the base address of a loop-carried buffer resource that was spilled before a loop and reloaded on every iteration. The existing subrange checks do not catch this because the new sibling has no subrange at all for the lanes it does not define. When a sibling copy defines only some lanes and the original register is live in the other lanes: - only hoist the spill if the copy source holds those lanes at its def; - otherwise do not fold, but reload the slot into the new register first and let the copy update only its lanes, so that the full-width store after it writes the other lanes back unchanged. Assisted-by: Claude Code Signed-off-by: Chen, Todd <[email protected]>
|
Suggested reviewers, based on the regalloc maintainers list and the history of the spill-hoisting checks: @qcolombet @mshockwave @arsenm cc @xgxanq @PankajDwivedi-25 since #226689 and #232650 address the same issue. Assisted-by: Claude Code |
|
Hello @zhentaocc 👋 Thank you for submitting a Pull Request (PR) to the LLVM Project. Since this is your first PR, here are a few useful links covering our main contribution policies and review practices.
Please reply to this message to confirm that you have read these policies, especially the LLVM AI Tool Use Policy, and that any AI tool usage has been noted in the PR description. Frequently asked questionsHow do I add reviewers? This PR will be automatically labeled, and the relevant teams will be notified. For some parts of the project, reviewers may also be added automatically. You can also add reviewers manually using the Reviewers section on this page. If you cannot use that section, it is probably because you do not have write permissions for the repository. In that case, you can request a review by tagging reviewers in a comment using What if there are no comments? If you have not received any comments on your PR after a week, you can request a review by pinging the PR with a comment such as “Ping”. The common courtesy ping rate is once a week. Please remember that you are asking for volunteer time from other developers. Are any special GitHub settings required to contribute to LLVM? We only require contributors to have a public email address associated with their GitHub commits, see this section of LLVM Developer Policy for details. If you have questions, feel free to leave a comment on this PR, or ask on LLVM Discord or LLVM Discourse. Thank you, |
|
@llvm/pr-subscribers-backend-amdgpu @llvm/pr-subscribers-llvm-regalloc Author: Chen, Zhentao (zhentaocc) ChangesAll siblings of an original register share one stack slot. Live range splitting can create a sibling that only defines some lanes: When such a sibling is spilled, the store after the copy (or the store that The existing subrange checks (#177703) do not catch this because the new sibling has no subrange at all for the lanes it does not define. Fix, when a sibling copy defines only some lanes and the original register is live in the other lanes:
The check is lane-aware (undefined lanes intersected with the lanes of the original that are live at the copy), so nothing changes when the other lanes are dead. The change is target-independent and needs no new target hooks. Test: Testing / measurements:
Related to #225054. Relation to #226689: that PR fixes the same problem more completely for AMDGPU SGPR tuples by storing only the defined lanes through a new lane-aware Assisted-by: Claude Code 2 Files Affected:
diff --git a/llvm/lib/CodeGen/InlineSpiller.cpp b/llvm/lib/CodeGen/InlineSpiller.cpp
index 66f22263c4ded..b411ab5cfeb5d 100644
--- a/llvm/lib/CodeGen/InlineSpiller.cpp
+++ b/llvm/lib/CodeGen/InlineSpiller.cpp
@@ -214,7 +214,8 @@ class InlineSpiller : public Spiller {
bool isRegToSpill(Register Reg) { return is_contained(RegsToSpill, Reg); }
bool isSibling(Register Reg);
- bool hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI);
+ bool hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI,
+ LaneBitmask KeepLanes);
void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
void markValueUsed(LiveInterval *, VNInfo *);
@@ -257,6 +258,20 @@ llvm::createInlineSpiller(const InlineSpiller::RequiredAnalyses &Analyses,
// This minimizes register pressure and maximizes the store-to-load distance for
// spill slots which can be important in tight loops.
+/// Return the lanes of \p LI that are live at \p Idx. A lane without a
+/// subrange is not live.
+static LaneBitmask getLiveLanesAt(const LiveInterval &LI, SlotIndex Idx,
+ const MachineRegisterInfo &MRI) {
+ if (!LI.hasSubRanges())
+ return LI.liveAt(Idx) ? MRI.getMaxLaneMaskForVReg(LI.reg())
+ : LaneBitmask::getNone();
+ LaneBitmask Lanes;
+ for (const LiveInterval::SubRange &SR : LI.subranges())
+ if (SR.liveAt(Idx))
+ Lanes |= SR.LaneMask;
+ return Lanes;
+}
+
/// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
/// otherwise return 0.
static Register isCopyOf(const MachineInstr &MI, Register Reg,
@@ -439,7 +454,8 @@ bool InlineSpiller::isSibling(Register Reg) {
/// This hoist only helps when the copy kills its source.
///
bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
- MachineInstr &CopyMI) {
+ MachineInstr &CopyMI,
+ LaneBitmask KeepLanes) {
SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
#ifndef NDEBUG
VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
@@ -454,6 +470,12 @@ bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
if (DefMBB != CopyMI.getParent() || !SrcQ.isKill())
return false;
+ // The store below writes every lane of SrcReg. The lanes of the slot in
+ // KeepLanes must be preserved, so SrcReg has to hold them where it is
+ // stored.
+ if ((KeepLanes & ~getLiveLanesAt(SrcLI, SrcVNI->def, MRI)).any())
+ return false;
+
MachineBasicBlock *MBB = DefMBB;
MachineBasicBlock::iterator MII;
if (SrcVNI->isPHIDef())
@@ -1350,6 +1372,27 @@ void InlineSpiller::spillAroundUses(Register Reg) {
// Check for a sibling copy.
Register SibReg = isCopyOfBundle(MI, Reg, TII);
+
+ // A split copy can define only some lanes of a sibling, e.g.
+ // undef %new.sub2_sub3 = COPY %sib.sub2_sub3
+ // The other lanes of %new are undefined, but the slot is shared by all
+ // siblings. If the original value is still live in those lanes, the slot
+ // holds them for a later reload, and a full-width store of %new would
+ // overwrite them. Reload the slot first so that the store after the copy
+ // writes those lanes back unchanged.
+ LaneBitmask KeepLanes;
+ if (SibReg && isSibling(SibReg) && RI.Writes && !RI.Reads &&
+ StackInt->liveAt(Idx.getBaseIndex())) {
+ for (const auto &[DefMI, OpIdx] : Ops) {
+ const MachineOperand &MO = DefMI->getOperand(OpIdx);
+ if (MO.isDef() && !MO.isDead() && MO.getSubReg() && MO.isUndef())
+ KeepLanes |= MRI.getMaxLaneMaskForVReg(Reg) &
+ ~TRI.getSubRegIndexLaneMask(MO.getSubReg());
+ }
+ KeepLanes &= getLiveLanesAt(LIS.getInterval(Original), Idx, MRI);
+ }
+ bool PartialSplitDef = KeepLanes.any();
+
if (SibReg && isSibling(SibReg)) {
// This may actually be a copy between snippets.
if (isRegToSpill(SibReg)) {
@@ -1358,7 +1401,7 @@ void InlineSpiller::spillAroundUses(Register Reg) {
continue;
}
if (RI.Writes) {
- if (hoistSpillInsideBB(OldLI, MI)) {
+ if (hoistSpillInsideBB(OldLI, MI, KeepLanes)) {
// This COPY is now dead, the value is already in the stack slot.
MI.getOperand(0).setIsDead();
DeadDefs.push_back(&MI);
@@ -1373,7 +1416,7 @@ void InlineSpiller::spillAroundUses(Register Reg) {
}
// Attempt to fold memory ops.
- if (foldMemoryOperand(Ops))
+ if (!PartialSplitDef && foldMemoryOperand(Ops))
continue;
// Create a new virtual register for spill/fill.
@@ -1382,12 +1425,23 @@ void InlineSpiller::spillAroundUses(Register Reg) {
if (RI.Reads)
insertReload(NewVReg, Idx, &MI);
+ else if (PartialSplitDef) {
+ insertReload(NewVReg, Idx, &MI);
+ // Keep the slot live from the reload to the copy.
+ SlotIndex ReloadIdx =
+ LIS.getInstructionIndex(*std::prev(MI.getIterator())).getRegSlot();
+ StackInt->addSegment(LiveInterval::Segment(ReloadIdx, Idx.getBaseIndex(),
+ StackInt->getValNumInfo(0)));
+ }
// Rewrite instruction operands.
bool hasLiveDef = false;
for (const auto &OpPair : Ops) {
MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
MO.setReg(NewVReg);
+ // The def now updates the reloaded value instead of starting a new one.
+ if (PartialSplitDef && MO.isDef())
+ MO.setIsUndef(false);
if (MO.isDef() && !MO.isDead())
hasLiveDef = true;
}
diff --git a/llvm/test/CodeGen/AMDGPU/inline-spiller-partial-split-def-spill.ll b/llvm/test/CodeGen/AMDGPU/inline-spiller-partial-split-def-spill.ll
new file mode 100644
index 0000000000000..05a0241b464b9
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/inline-spiller-partial-split-def-spill.ll
@@ -0,0 +1,128 @@
+; RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -greedy-compact-slot-indexes=false -split-spill-mode=speed -verify-machineinstrs -stop-after=greedy -o - %s | FileCheck %s
+
+; The buffer resource built from %0 is spilled before the loop and reloaded on
+; every iteration. Live range splitting creates a sibling of it that only defines
+; sub3. All siblings share one stack slot, so the full-width spill of that
+; sibling must not write its undefined lanes over the resource in the slot.
+; Reload the slot before the partial copy so that the spill writes the other
+; lanes back unchanged, and do not hoist the spill to the copy source.
+
+; CHECK-LABEL: name: partial_split_def_spill
+; CHECK: SI_SPILL_S128_SAVE %{{[0-9]+}}, %stack.0
+; CHECK: bb.1
+; CHECK: [[RSRC:%[0-9]+]]:sgpr_128 = SI_SPILL_S128_RESTORE %stack.0
+; CHECK-NEXT: BUFFER_LOAD_DWORDX4_OFFEN %{{[0-9]+}}, [[RSRC]],
+; CHECK-NEXT: undef [[SPLIT:%[0-9]+]].sub3:sgpr_128 = lr-split COPY [[RSRC]].sub3
+; CHECK-NOT: SI_SPILL_S128_SAVE
+; CHECK: [[RMW:%[0-9]+]]:sgpr_128 = SI_SPILL_S128_RESTORE %stack.0
+; CHECK-NEXT: [[RMW]].sub3:sgpr_128 = lr-split COPY [[SPLIT]].sub3
+; CHECK-NEXT: SI_SPILL_S128_SAVE [[RMW]], %stack.0
+
+define amdgpu_kernel void @partial_split_def_spill(ptr addrspace(1) inreg %0, ptr addrspace(1) %1, i32 %2, <4 x float> %3) #0 {
+.lr.ph:
+ %4 = tail call i32 @llvm.amdgcn.workitem.id.x()
+ %5 = insertelement <4 x i32> zeroinitializer, i32 %4, i64 0
+ br label %6
+
+6: ; preds = %6, %.lr.ph
+ %7 = phi i32 [ 1, %.lr.ph ], [ 0, %6 ]
+ %8 = tail call ptr addrspace(8) @llvm.amdgcn.make.buffer.rsrc.p8.p1.i32(ptr addrspace(1) %0, i16 0, i32 2147483646, i32 1)
+ %9 = load <1 x i32>, ptr addrspace(1) null, align 4
+ %10 = extractelement <1 x i32> %9, i64 0
+ %11 = tail call <4 x i32> @llvm.amdgcn.raw.ptr.buffer.load.v4i32(ptr addrspace(8) %8, i32 %10, i32 0, i32 0)
+ %12 = sdiv i32 %7, %2
+ %13 = insertelement <4 x i32> zeroinitializer, i32 %12, i64 0
+ %14 = shufflevector <4 x i32> %13, <4 x i32> zeroinitializer, <4 x i32> zeroinitializer
+ %15 = shufflevector <4 x i32> %5, <4 x i32> zeroinitializer, <4 x i32> zeroinitializer
+ %16 = or <4 x i32> %15, <i32 40, i32 41, i32 42, i32 43>
+ %17 = or <4 x i32> %14, %16
+ %18 = or <4 x i32> %5, <i32 48, i32 49, i32 50, i32 51>
+ %19 = or <4 x i32> %14, %18
+ %20 = or <4 x i32> %15, <i32 56, i32 57, i32 58, i32 59>
+ %21 = or <4 x i32> %14, %20
+ %22 = tail call ptr addrspace(8) @llvm.amdgcn.make.buffer.rsrc.p8.p1.i32(ptr addrspace(1) %1, i16 0, i32 1, i32 0)
+ tail call void @llvm.amdgcn.raw.ptr.buffer.load.async.lds(ptr addrspace(8) %22, ptr addrspace(3) null, i32 1, i32 0, i32 0, i32 0, i32 0)
+ %23 = or <4 x i32> %15, <i32 24, i32 25, i32 26, i32 27>
+ %24 = or <4 x i32> %14, %23
+ %25 = sub <4 x i32> zeroinitializer, %24
+ %26 = icmp ult <4 x i32> %25, splat (i32 101)
+ %27 = or <4 x i32> %15, <i32 32, i32 33, i32 34, i32 35>
+ %28 = or <4 x i32> %14, %27
+ %29 = sub <4 x i32> zeroinitializer, %28
+ %30 = icmp ult <4 x i32> %29, splat (i32 101)
+ %31 = sub <4 x i32> zeroinitializer, %17
+ %32 = icmp ult <4 x i32> %31, splat (i32 101)
+ %33 = sub <4 x i32> zeroinitializer, %19
+ %34 = icmp ult <4 x i32> %33, splat (i32 101)
+ %35 = sub <4 x i32> zeroinitializer, %21
+ %36 = icmp ult <4 x i32> %35, splat (i32 101)
+ %37 = icmp slt <4 x i32> %24, zeroinitializer
+ %38 = icmp slt <4 x i32> %28, zeroinitializer
+ %39 = icmp slt <4 x i32> %17, zeroinitializer
+ %40 = icmp slt <4 x i32> %19, zeroinitializer
+ %41 = icmp slt <4 x i32> %21, zeroinitializer
+ %42 = and <4 x i1> %37, %26
+ %43 = and <4 x i1> %38, %30
+ %44 = and <4 x i1> %40, %34
+ %45 = and <4 x i1> %41, %36
+ %46 = select <4 x i1> %42, <4 x float> %3, <4 x float> zeroinitializer
+ %47 = bitcast <4 x i32> %11 to <8 x bfloat>
+ %48 = tail call <16 x float> @llvm.amdgcn.mfma.f32.32x32x16.bf16(<8 x bfloat> zeroinitializer, <8 x bfloat> zeroinitializer, <16 x float> zeroinitializer, i32 0, i32 0, i32 0)
+ %49 = tail call <16 x float> @llvm.amdgcn.mfma.f32.32x32x16.bf16(<8 x bfloat> zeroinitializer, <8 x bfloat> %47, <16 x float> %48, i32 0, i32 0, i32 0)
+ %50 = shufflevector <16 x float> %49, <16 x float> zeroinitializer, <4 x i32> <i32 0, i32 1, i32 2, i32 3>
+ %51 = bitcast <4 x i32> %13 to <4 x float>
+ %52 = fadd <4 x float> %50, %51
+ %53 = select <4 x i1> %43, <4 x float> %52, <4 x float> zeroinitializer
+ %54 = and <4 x i1> %39, %32
+ %55 = shufflevector <16 x float> %48, <16 x float> zeroinitializer, <4 x i32> <i32 12, i32 13, i32 14, i32 15>
+ %56 = select <4 x i1> <i1 false, i1 true, i1 false, i1 false>, <4 x float> %3, <4 x float> zeroinitializer
+ %57 = fadd <4 x float> %55, %56
+ %58 = fmul <4 x float> %46, %53
+ %59 = select <4 x i1> %54, <4 x float> zeroinitializer, <4 x float> splat (float -inf)
+ %60 = fmul <4 x float> %58, %59
+ %61 = select <4 x i1> %44, <4 x float> splat (float +qnan), <4 x float> zeroinitializer
+ %62 = fmul <4 x float> %60, %61
+ %63 = select <4 x i1> %45, <4 x float> %57, <4 x float> zeroinitializer
+ %64 = fmul <4 x float> %62, %63
+ %65 = tail call float @llvm.vector.reduce.fmaximum.v4f32(<4 x float> %64)
+ tail call void @llvm.amdgcn.raw.ptr.buffer.store.f32(float %65, ptr addrspace(8) null, i32 0, i32 0, i32 0)
+ %66 = tail call ptr addrspace(8) @llvm.amdgcn.make.buffer.rsrc.p8.p1.i32(ptr addrspace(1) null, i16 0, i32 0, i32 1)
+ tail call void @llvm.amdgcn.raw.ptr.buffer.store.v4i32(<4 x i32> zeroinitializer, ptr addrspace(8) %66, i32 0, i32 0, i32 0)
+ br label %6
+}
+
+; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
+declare noundef range(i32 0, 1024) i32 @llvm.amdgcn.workitem.id.x() #1
+
+; Function Attrs: nocallback nofree nosync nounwind willreturn memory(argmem: read)
+declare <4 x i32> @llvm.amdgcn.raw.ptr.buffer.load.v4i32(ptr addrspace(8) readonly captures(none), i32, i32, i32 immarg) #2
+
+; Function Attrs: nocallback nofree nounwind willreturn memory(argmem: readwrite)
+declare void @llvm.amdgcn.raw.ptr.buffer.load.async.lds(ptr addrspace(8) readonly captures(none), ptr addrspace(3) writeonly captures(none), i32 immarg, i32, i32, i32 immarg, i32 immarg) #3
+
+; Function Attrs: convergent nocallback nocreateundeforpoison nofree nosync nounwind willreturn memory(none)
+declare <16 x float> @llvm.amdgcn.mfma.f32.32x32x16.bf16(<8 x bfloat>, <8 x bfloat>, <16 x float>, i32 immarg, i32 immarg, i32 immarg) #4
+
+; Function Attrs: nocallback nofree nosync nounwind willreturn memory(argmem: write)
+declare void @llvm.amdgcn.raw.ptr.buffer.store.f32(float, ptr addrspace(8) writeonly captures(none), i32, i32, i32 immarg) #5
+
+; Function Attrs: nocallback nofree nosync nounwind willreturn memory(argmem: write)
+declare void @llvm.amdgcn.raw.ptr.buffer.store.v4i32(<4 x i32>, ptr addrspace(8) writeonly captures(none), i32, i32, i32 immarg) #5
+
+; Function Attrs: nocallback nocreateundeforpoison nofree nosync nounwind speculatable willreturn memory(none)
+declare ptr addrspace(8) @llvm.amdgcn.make.buffer.rsrc.p8.p1.i32(ptr addrspace(1) readnone, i16, i32, i32) #6
+
+; Function Attrs: nocallback nocreateundeforpoison nofree nosync nounwind speculatable willreturn memory(none)
+declare float @llvm.vector.reduce.fmaximum.v4f32(<4 x float>) #6
+
+; uselistorder directives
+uselistorder ptr @llvm.amdgcn.mfma.f32.32x32x16.bf16, { 1, 0 }
+uselistorder ptr @llvm.amdgcn.make.buffer.rsrc.p8.p1.i32, { 2, 1, 0 }
+
+attributes #0 = { "amdgpu-agpr-alloc"="0" "amdgpu-no-queue-ptr" }
+attributes #1 = { nocallback nofree nosync nounwind speculatable willreturn memory(none) }
+attributes #2 = { nocallback nofree nosync nounwind willreturn memory(argmem: read) }
+attributes #3 = { nocallback nofree nounwind willreturn memory(argmem: readwrite) }
+attributes #4 = { convergent nocallback nocreateundeforpoison nofree nosync nounwind willreturn memory(none) }
+attributes #5 = { nocallback nofree nosync nounwind willreturn memory(argmem: write) }
+attributes #6 = { nocallback nocreateundeforpoison nofree nosync nounwind speculatable willreturn memory(none) }
|
All siblings of an original register share one stack slot. Live range splitting can create a sibling that only defines some lanes:
When such a sibling is spilled, the store after the copy (or the store that
hoistSpillInsideBBmoves to the copy source) writes the full register, including lanes that hold no value, into the slot. If the original register is still live in those lanes, a later reload of another sibling reads garbage there. On AMDGPU this corrupted the base address of a loop-carried buffer resource that was spilled before a loop and reloaded on every iteration (wrong results at runtime on gfx950).The existing subrange checks (#177703) do not catch this because the new sibling has no subrange at all for the lanes it does not define.
Fix, when a sibling copy defines only some lanes and the original register is live in the other lanes:
The check is lane-aware (undefined lanes intersected with the lanes of the original that are live at the copy), so nothing changes when the other lanes are dead. The change is target-independent and needs no new target hooks.
Test:
CodeGen/AMDGPU/inline-spiller-partial-split-def-spill.ll, reduced with llvm-reduce from the failing kernel. On current main the bad split only shows up with-split-spill-mode=speed -greedy-compact-slot-indexes=false, so the RUN line uses those; without the fix the slot is clobbered before the loop reload.Testing / measurements:
checkon CodeGen + DebugInfo: no failures, no existing test changes..llintest/CodeGen/{AMDGPU,X86,AArch64,RISCV}(about 11k files) with and without the patch: 0 files with different code size.s_readlaneper kernel (+32 to +40 bytes out of 40-300 KB). Where the bug does not fire the output is identical. Compile time is within noise.Related to #225054.
Relation to #226689: that PR fixes the same problem more completely for AMDGPU SGPR tuples by storing only the defined lanes through a new lane-aware
storeRegToStackSlot, and also removes some redundant spills. This patch is a minimal, target-independent alternative: it covers every register class, including ones that cannot store a lane subset (the fallback question raised in the #226689 review), with no codegen change outside the buggy case. The two are complementary; if #226689 lands, this path still serves classes that do not opt in. #232650 took a similar reload-first approach but changed more tests because it was not lane-aware.Assisted-by: Claude Code