[llvm-bugs] [Bug 35068] New: Possible bad optimisation of unsigned atomic fetch_sub(1) > 1 on x64
llvm-bugs at lists.llvm.org
Tue Oct 24 17:19:27 PDT 2017
Bug ID: 35068
Summary: Possible bad optimisation of unsigned atomic
fetch_sub(1) > 1 on x64
OS: Windows NT
Component: Backend: X86
Assignee: unassignedbugs at nondot.org
Reporter: lewissbaker at gmail.com
CC: llvm-bugs at lists.llvm.org
I have some C++ coroutine code that appears to be generating incorrect assembly
for some atomic operations used to perform reference counting.
The issue arose when testing the 'generic_ops' branch of cppcoro
(https://github.com/lewissbaker/cppcoro/tree/generic_ops) and seems to be
causing many of the 'shared_task' tests to fail under clang optimised builds.
I have reduced the issue down to what I believe is the root cause:
I have an await_suspend() method that looks like:
bool await_suspend(std::experimental::coroutine_handle<promise_type> h)
// Decrement reference count and return true to suspend if there are
// still outstanding references.
// Note that m_refCount has type std::atomic<std::uint32_t>.
return h.promise().m_refCount.fetch_sub(1, std::memory_order_acq_rel) > 1;
When targeting clang x64 -O3 builds this generates assembly which looks like:
add dword ptr [rdi + 16], -1
In this instance, the code generated should only be taking the branch if
await_suspend() returns false (ie. the initial value was 0 or 1).
The jbe instruction takes the branch if either ZF=1 or CF=1.
ZF=1 would only occur if the result of the add is zero (ie. initial value was
However, since we're adding -1 (0xFFFFFFFF), I'm assuming this would cause
unsigned integer overflow and thus set CF=1 for all values except an initial
value of zero.
Thus the branch would seem to be taken if initial value > 0 rather than if the
initial value was 0 or 1, as required.
Should it be using a 'lock sub' instruction instead of 'lock add'?
sub dword ptr [rdi + 16], 1
The sub instruction would only trigger unsigned overflow (ie. set CF=1) if the
original value is 0, and would only set ZF=1 if result is zero (ie. original
value is 1), which would give the desired result when used with subsequent jbe
Example source code that reproduces the issue is available here:
You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the llvm-bugs