[llvm-bugs] [Bug 24807] New: clang++ -O1 evaluates wrong branch in C++ ternary operator ?:

via llvm-bugs llvm-bugs at lists.llvm.org
Sun Sep 13 20:42:07 PDT 2015


https://llvm.org/bugs/show_bug.cgi?id=24807

            Bug ID: 24807
           Summary: clang++ -O1 evaluates wrong branch in C++ ternary
                    operator ?:
           Product: new-bugs
           Version: 3.7
          Hardware: PC
                OS: Linux
            Status: NEW
          Severity: normal
          Priority: P
         Component: new bugs
          Assignee: unassignedbugs at nondot.org
          Reporter: d.grellscheid+llvm at gmail.com
                CC: llvm-bugs at lists.llvm.org
    Classification: Unclassified

Created attachment 14875
  --> https://llvm.org/bugs/attachment.cgi?id=14875&action=edit
Test case for mis-optimized ternary operator

When compiled with clang++ -O1, the following code can trigger floating-point
division-by-zero exceptions for a==b==0, even though they should be guarded by
the (c2 > 0.0) test. 

"clang version 3.7.0 (tags/RELEASE_370/final)" compiled with cmake from tarball
on Ubuntu 12.04.5 LTS.

double foo(double a, double b)
{
    double c2 = a*a + b*b;
    double c2inv = c2 > 0.0 ? 1.0/c2 : 0.0;
    return c2inv;
}

clang++ -O1 -S -emit-llvm shows that the division is performed irrespective of
the fcmp outcome:

; Function Attrs: nounwind readnone uwtable
define double @_Z3foodd(double %a, double %b) #0 {
  %1 = fmul double %a, %a
  %2 = fmul double %b, %b
  %3 = fadd double %1, %2
  %4 = fcmp ogt double %3, 0.000000e+00
  %5 = fdiv double 1.000000e+00, %3
  %6 = select i1 %4, double %5, double 0.000000e+00
  ret double %6
}

Reproduce with attached testcase:

$ clang++ -O1 test.cc
$ ./a.out 0 0
Floating point exception (core dumped)

Expected result is obtained with -O0:

$ clang++ -O0 test.cc
$ ./a.out 0 0
$ echo $?
0



The current LLVM on OS X does this optimization right:

"Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)"

; Function Attrs: nounwind readnone ssp uwtable
define double @_Z3foodd(double %a, double %b) #0 {
  %1 = fmul double %a, %a
  %2 = fmul double %b, %b
  %3 = fadd double %1, %2
  %4 = fcmp ogt double %3, 0.000000e+00
  br i1 %4, label %5, label %7

; <label>:5                                       ; preds = %0
  %6 = fdiv double 1.000000e+00, %3
  br label %7

; <label>:7                                       ; preds = %0, %5
  %8 = phi double [ %6, %5 ], [ 0.000000e+00, %0 ]
  ret double %8
}

-- 
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/20150914/c323bc9a/attachment.html>


More information about the llvm-bugs mailing list