[llvm-bugs] [Bug 46710] New: Clang optimizer leads to wrong if-clause result
via llvm-bugs
llvm-bugs at lists.llvm.org
Tue Jul 14 01:55:25 PDT 2020
https://bugs.llvm.org/show_bug.cgi?id=46710
Bug ID: 46710
Summary: Clang optimizer leads to wrong if-clause result
Product: clang
Version: 6.0
Hardware: Macintosh
OS: MacOS X
Status: NEW
Severity: normal
Priority: P
Component: -New Bugs
Assignee: unassignedclangbugs at nondot.org
Reporter: kianoosh.abbasi76 at gmail.com
CC: htmldeveloper at gmail.com, llvm-bugs at lists.llvm.org,
neeilans at live.com, richard-llvm at metafoo.co.uk
Consider the following code:
#include <iostream>
int main()
{
int a; // Enter 2000000000 (2*10^9)
int b; // Enter 1000000000 (10^9)
std::cin >> a >> b;
if (a + b >= a)
std::cout << "Yes" << std::endl;
else
std::cout << "No" << std::endl;
}
If you assign 2000000000 and 1000000000 to `a` and `b` from the input
(respectively), `a + b` will overflow and become a negative integer, which will
obviously be less than `a` itself, so if the code is run without any
optimization flags, the result will be `No`.
However, when run with an optimization flags (e.g.: `-O2`), the optimizer
simplifies the `a + b >= a` inequality into `b >= 0` (by deducting `a` from
both sides). Therefore, without any checks for the possible overflow, the
condition will be evaluated to true and the output will be `Yes`.
The code and the results can be fount at https://rextester.com/OBZ78859
The problem is, both GCC and VC++ compilers take care of the possible overflows
and will output `No`, so it causes a major discrepancy between different C++
compilers whose reason might be very tough to figure out. It also makes the
output different by adding an optimization flag on the same Clang compiler. All
of these may drive programmers' attention to undefined behaviors and they may
spend a lot of time looking at their codes trying to find out any of those,
which actually is not an undefined behavior.
You could find the GCC and VC++ equivalents at https://rextester.com/CZZY67858
and https://rextester.com/SJDB96931, respectively.
Please note that on all of the above links, the default compiler arguments
include the `-O2` flag, but you could see the different by removing the flag
for the Clang code.
--
You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20200714/9d9f28e9/attachment.html>
More information about the llvm-bugs
mailing list