<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/59102>59102</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            Bad Codegen with PUSHF and POPF
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          bwendling
      </td>
    </tr>
</table>

<pre>
    Note that replicating this issue is best done at SHA1 6eb0f8e28598658b4f5df27b35a5ea98bad68049.

There seems to be bad codegen in some instances when reading `EFLAGS`. The attached issue has this code:

```
94:                                               ; preds = %90, %87
  %95 = call i64 @llvm.x86.flags.read.u64() #5
  call void @llvm.memcpy.p0.p0.i64(ptr align 1 %12, ptr nonnull align 16 undef, i64 %89, i1 false) #5
  call void @llvm.x86.flags.write.u64(i64 %95) #5
  br label %96
```

The generated code is:

```
llc -O2 -o - bugpoint-reduced-simplified.bc
        .text
        .file   "alternative.c"
        .globl  apply_alternatives              # -- Begin function apply_alternatives
        .p2align        4, 0x90
        .type   apply_alternatives,@function
apply_alternatives:                     # @apply_alternatives
  ... ### snip ###
.LBB0_31:                               #   in Loop: Header=BB0_2 Depth=1
        movslq  %r13d, %rdx
        pushfq
        popq    %rbp
        movq    %r12, %rdi
        callq   memcpy@PLT
        pushq   %rbp
        movq    8(%rsp), %rbp                   # 8-byte Reload
        popfq
.LBB0_32:                               #   in Loop: Header=BB0_2 Depth=1
```

The issue is that between `pushq` and `popfq` the `%rbp` register is being reloaded. However, it's reloaded from the wrong slot. `pushq` changes the `%rsp` register, but the reload is still using the stack slot from before `pushfq`.

[bugpoint-reduced-simplified.bc.txt](https://github.com/llvm/llvm-project/files/10053462/bugpoint-reduced-simplified.bc.txt)

</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJytVUtv2zgQ_jXyZWBBoh6WDjrEzXpzCLbBpj0XlDSy2KVFlaTs5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