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

    <tr>
        <th>Summary</th>
        <td>
            Avoid cmov for conditional negation
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

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

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

<pre>
    A typical way to do conditional negation would look like:

```c++
int64_t maybeNegateCMOV(uint64_t value, bool neg) {
    return neg ? -value : value;
}
```

Which generates the following codegen:
```x64
maybeNegateCMOV(unsigned long, bool): # @maybeNegateCMOV(unsigned long, bool)
        mov     rax, rdi
        neg     rax
        test    esi, esi
        cmove rax, rdi
        ret
```

However, it is possible to do the same computation using math, and avoid the cmov, the following way:
```c++
int64_t maybeNegateMATH(uint64_t value, bool neg) {
 return (value - neg) ^ -neg;
}
```

Which generate the following codegen:
```x64
maybeNegateMATH(unsigned long, bool): # @maybeNegateMATH(unsigned long, bool)
        mov     eax, esi
 sub     rdi, rax
        neg     rax
        xor     rax, rdi
 ret
```

This is a fairly common pattern, and would benefit from being recognized, IMO.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyklM1u4zgMx59GvhAJHMmJ44MPabtB99Dtpdg9LmSLtjWVpUCS8zFPP6CTtJNp2qIzgREZIv80Sf1EGYJuLWLJ5jdsfpfIIXbOlwqlksbqfVI5dShXEA8bXUsDO3mA6EA5qJ1VOmpnpQGLraRX2LnBKDDOPYPRz8jEiqV3LD3_L9LjUzN-Q8-4q21cZP9H6OWhwn8oEt4-PP7L-HI4m7bSDMj4LVTOjV9jvACWnwIAAHiMg7dkAibWMBkVwMTqpBUnX5bf_ZLLzwn-1-m6gxYtehkxQOwQGmeM22nbQu0UtmhfizqH2C-y486VEuzYX-qJbc8VMF5QZowLYFn6BdFLufTr3XZcvdyTj1f60k69ONsvDBFDpBWDJiEtF_a6d1t8N6zH-EEH790Ot-hJqSPoABsXgq4MnqihjgbZI9Su3wzxSM0QqL29jB3ppFUgt06r0ZmSod3Lo9jJw9tj-Iyqh9XT_ReoOiHF-PII0-TFZf4XTOj9d6D6E6bOBXyJqc9EV5nC4-G_ohGG6nj6amTmDVPvwrZ3_jqlH3P01OlA-EhopPbmQLz0zsJGxojenjk5zpsKLTY6QuNdDxVSXz3WrrX6Oypy_fvhcZqoUqhCFDLBcrbI-SKfL4pl0pW8bhpRF7mSucJGVanIslRUGU-zmVo2ItElT7lIZymfLdLlbDkt8maZy6zOCyVUKiTLUuylNlNjtv3U-TbRIQxYzou8mCVGVmjCOGA5t7iD0cg4p3nrS9JMqqENLEuNDjG8Rok6GixX412gewCN81fnbjJ4U3YxbgKBxNeMr1sdu6Ga1q5nfE0RT8tk4903rCPj6zGPwPh6zPNHAAAA__-BQswA">