Unsound optimization with `error`, introduced in GHC 8.2
We discovered an unsound optimization (see https://github.com/agda/agda-stdlib/pull/1512) in GHC starting with 8.2. I managed to shrink it down to the following code:
-- Unsound compiler optimization in presence of @error@.
foo :: String -> String
foo d1@(_:_)
| not (all (== '-') d1)
, last d1 == '\r'
= error "OK1"
foo _ = error "OK2"
main = putStr $ foo "Hello, world!"
With -O0, or until GHC 8.0.2, this outputs
<main>: OK2
CallStack (from HasCallStack):
error, called at <loc> in main:Main
With -O1 or -O2 and GHC 8.2 - 9.0.1, (I tested from 8.2.2), this gives:
Prelude.last: empty list