llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[IPRA] IPRA Skips Saving Used Callee-Saved Registers in Prologue/Epilogue

Open vigbalu opened this issue 6 months ago • 1 comments

When IPRA is enabled, the callee-saved register (CSR) set considered during prologue/epilogue construction is restricted to RBP. This can cause callee-saved registers that are actually used by a function (e.g., R13, R14) to be neither saved nor restored.

Test Case:

; RUN: llc -enable-ipra < %s -o - | FileCheck %s

target triple = "x86_64-unknown-unknown"

; Prologue/Epilogue should not skip R13 and R14 when IPRA enabled since it is used.
; CHECK-LABEL: function1:
; CHECK:    pushq   %r14
; CHECK:    pushq   %r13

define internal void @function1() norecurse noinline {
  call void asm sideeffect "movl %r13d, %eax\0A addl %r14d, %eax", "~{eax},~{r13},~{r14}"()
  ret void
}

; r13 and r14 live across call to function1 so it must be saved by callee before use.
; CHECK-LABEL: function2:
; CHECK:    pushq   %r14
; CHECK:    pushq   %r13
define void @function2(i32 %x) noinline {
  call void asm sideeffect "movl %edi, %r13d\0A movl %edi, %r14d", "~{r13},~{r14}"()
  call void @function1()
  call void asm sideeffect "movl %r13d, %eax\0A addl %r14d, %eax", "~{eax},~{r13},~{r14}"()
  ret void
}

define i32 @main() {
  call void @function2(i32 7)
  ret i32 0
}

vigbalu avatar May 11 '26 01:05 vigbalu

The ASM constraints you have are wrong. A clobber constraint (for example ~{r14d}) means that the value of %r14d will be arbitrarily altered by the assembly, so the register allocator cannot keep any value in it it would like to preserve. However it does not mean that there are any guaranteed values in those registers when execution of the asm string starts.

If fixed your example should look like this:

target triple = "x86_64-unknown-unknown"

; (...)
define i32 @function2(i32 %x) noinline {
  %val = call {i32, i32} asm sideeffect "movl %edi, %r13d\0A movl %edi, %r14d", "={r13},={r14},{edi}"(i32 %x)
  call void @function1()
  %val.0 = extractvalue {i32, i32} %val, 0
  %val.1 = extractvalue {i32, i32} %val, 1
  %ret = call i32 asm sideeffect "movl %r13d, %eax\0A addl %r14d, %eax", "={eax},{r13},{r14}"(i32 %val.0, i32 %val.1)
  ret i32 %ret
}

And it correctly saves and restore the value of r13 and r14 as expected. See it on compiler explorer.

Maetveis avatar May 25 '26 09:05 Maetveis