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

    <tr>
        <th>Summary</th>
        <td>
            Suboptimal code generated for inline asm doing `pop %0` to a memory operand
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            bug,
            backend:X86,
            llvm:codegen,
            regalloc
      </td>
    </tr>

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

    <tr>
      <th>Reporter</th>
      <td>
          ramosian-glider
      </td>
    </tr>
</table>

<pre>
    Godbolt link: https://godbolt.org/z/x9s3Toxbz

For the following code snippet:

```
/*
 * Code snippet taken from the Linux kernel except for the flags = 0
 * assignment, which is excessive.
 */
extern unsigned long native_save_fl(void)
{
        unsigned long flags = 0;

        /*
         * "=rm" is safe here, because "pop" adjusts the stack before
         * it evaluates its effective address -- this is part of the
         * documented behavior of the "pop" instruction.
         */
        asm volatile("# __raw_save_flags\n\t"
                     "pushf ; pop %0"
                     : "=rm" (flags)
                     : /* no input */
                     : "memory");

        return flags;
}
```

trunk Clang with `-O3` generates unnecessary memory accesses to a local, failing to place it onto a register:

```
native_save_fl:                         # @native_save_fl
        movq    $0, -8(%rsp)
        pushfq
        popq    -8(%rsp)
        movq    -8(%rsp), %rax
        retq
```

, whereas GCC just reuses `%rax`:

```
native_save_fl:
        pushf ; pop %rax
        ret
```

Removing the assignment of 0 to `flags` does save a memory store, but Clang's output is still different from what GCC does:

```
native_save_fl:                         # @native_save_fl
        pushfq
        popq    -8(%rsp)
        movq    -8(%rsp), %rax
        retq
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJzFVkuT4jYQ_jXmooLyAwM--DDD1OwlVVu1ySG3KdlqYy2y5JFkYPbXp1uG4TGEVC4J2MZq9fPrh6iM-Ci_GVEZ5ZmSehtlT6z1vnf4EqWveG3G3ZmxG1z9wvtQuOwPc6h-RfFLFD-Nz1djmW-BNUYps5d6w2ojg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