https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69845
Bug ID: 69845 Summary: Expression getting incorrectly optimized after being rewritten by compiler Product: gcc Version: 5.3.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: tree-optimization Assignee: unassigned at gcc dot gnu.org Reporter: mdaniels at qnx dot com Target Milestone: --- Created attachment 37709 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=37709&action=edit Test case In the given example, when evaluating the expression for 'C', there should be no overflow. I am however, seeing the compiler rewrite the expressions into a form that will overflow. I have only tested this on x86 and x86_64, and according to 5.1.2.3p14, since these archs do not trap on overflow this is legal behaviour. Because of the phrasing that the expression can only be rewritten if the same results occur, I have to assume this means the newly added overflow does not cause undefined behaviour. The compiler added it knowing that it will not trap and that positive and negative overflow cancel after all. With that in mind, it looks like one of the optimization passes is taking advantage of this and causing incorrect results (optimizes everything to a call to puts("failed\n")). When I compile the test case with -O0 it will pass, but -O1 and above will cause the test case to fail. Given the problem description, it should come as no surprise that the problem is not seen when -fwrapv or -ftrapv are used. I have tested on Ubuntu 14.04 x86_64 with GCC 4.8.3, 4.9.3, and 5.3.0. 4.8.3 does not reproduce, 4.9.3 and 5.3.0 do.