Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clang++ v6, 7 & 8 bug/wrong result when computing a simple finite difference with optimization flag

Tags:

c++

clang++

A colleague of mine found this interesting/surprising bug.

It affects clang++ version 6, 7 and 8 when compiling with optimization flag (typically -O2)

The code is really simple, it must compute a finite difference:

a[i] = x[i+1]-x[i]
b[i] = (y[i+1]-y[i])/a[i]

The associate code demo is as follows:

#include <iostream>
#include <vector>

class Foo {
private:
    std::vector<double> _a;
    std::vector<double> _d;

public:
    Foo(const std::vector<double> &x, const std::vector<double> &y)
        : _a(x.size()), _d(x.size()) {

        for (unsigned int i = 0; i < x.size() - 1; i++) {
            _a[i] = x[i + 1] - x[i];
            _d[i] = (y[i + 1] - y[i]) / _a[i];
        }
    }

    const std::vector<double> &a() const noexcept { return _a; }
};

int main() {

    // Read input file
    std::vector<double> x, y;
    while (std::cin) {
        double xi, yi;
        if (std::cin >> xi >> yi) {
            x.push_back(xi);
            y.push_back(yi);
        }
    }

    // Create Foo instance
    Foo foo(x, y);

    // Print computed data
    for (auto a : foo.a()) std::cout << a << '\n';

    return 0;
}

When you use unoptimized clang compilation:

$> clang++-6.0 -std=c++11 -o bug  bug.cpp
$> paste <(seq 1 5) <(seq 1 5) | ./bug

you get the expected result:

1
1
1
1
0

however when optimizing (the -O2 option):

$> clang++-6.0 -std=c++11 -O2 -o bug  bug.cpp
$> paste <(seq 1 5) <(seq 1 5) | ./bug

you get a wrong result:

1
2
2
0
0
  • Can you reproduce ?
  • Is it fixed ?
like image 266
Picaud Vincent Avatar asked Sep 13 '18 16:09

Picaud Vincent


1 Answers

The bug has been confirmed (with a "release blocker" priority) and is now fixed since 2 days: see details here

Please note:

  • valgrind reports nothing <-> hard to isolate this bug
  • g++ is not affected

I thought that this bug deserved a mention because it is likely to seriously, but silently, affect a numerical computation code.

like image 131
Picaud Vincent Avatar answered Sep 30 '22 23:09

Picaud Vincent