[SimpifyCFG] Speculate a store preceded by a local non-escaping load
authorMomchil Velikov <momchil.velikov@arm.com>
Thu, 5 Aug 2021 14:37:19 +0000 (15:37 +0100)
committerMomchil Velikov <momchil.velikov@arm.com>
Thu, 5 Aug 2021 14:54:42 +0000 (15:54 +0100)
commitf171149e0d541ca7da7af5fe59bd6d9a77267d24
treef00edd1db0d8e33e7c11895228b389faacfd025a
parentfc545c52cdfe1593967598ac9c3645095d5405c6
[SimpifyCFG] Speculate a store preceded by a local non-escaping load

In SimplifyCFG we may simplify the CFG by speculatively executing
certain stores, when they are preceded by a store to the same
location.  This patch allows such speculation also when the stores are
similarly preceded by a load.

In order for this transformation to be correct we need to ensure that
the memory location is writable and the store in the new location does
not introduce a data race.

Local objects (created by an `alloca` instruction) are always
writable, so once we are past a read from a location it is valid to
also write to that same location.

Seeing just a load does not guarantee absence of a data race (unlike
if we see a store) - the load may still be part of a race, just not
causing undefined behaviour
(cf. https://llvm.org/docs/Atomics.html#optimization-outside-atomic).

In the original program, a data race might have been prevented by the
condition, but once we move the store outside the condition, we must
be sure a data race wasn't possible anyway, no matter what the
condition evaluates to.

One way to be sure that a local object is never concurrently
read/written is check that its address never escapes the function.

Hence this transformation is restricted to local, non-escaping
objects.

Reviewed By: nikic, lebedev.ri

Differential Revision: https://reviews.llvm.org/D107281
llvm/lib/Transforms/Utils/SimplifyCFG.cpp
llvm/test/Transforms/SimplifyCFG/speculate-store.ll