为什么clang中的-O2或更高优化会破坏此代码?

时间:2016-08-06 14:28:07

标签: c++ clang c++14 compiler-optimization chrono

我在网站上检查了类似的问题,但我找不到符合我的方案的任何内容。这是我试图运行的代码(需要C ++ 14):

#include <iostream>
#include <chrono>
#include <thread>
using namespace std;

class countdownTimer {
public:
    using duration_t = chrono::high_resolution_clock::duration;

    countdownTimer(duration_t duration) : duration{ duration }, paused{ true } {}

    countdownTimer(const countdownTimer&)               = default;
    countdownTimer(countdownTimer&&)                    = default;
    countdownTimer& operator=(countdownTimer&&)         = default;
    countdownTimer& operator=(const countdownTimer&)    = default;

    void start() noexcept {
        if (started) return;
        startTime = chrono::high_resolution_clock::now();
        endTime = startTime + duration;
        started = true;
        paused = false;
    }

    void pause() noexcept {
        if (paused || !started) return;
        pauseBegin = chrono::high_resolution_clock::now();
        paused = true;
    }

    void resume() noexcept {
        if (!paused || !started) return;
        auto pauseDuration = chrono::high_resolution_clock::now() - pauseBegin;
        startTime += pauseDuration;
        endTime += pauseDuration;
        paused = false;
    }

    double remainingSeconds() const noexcept {
        auto ret = double{ 0.0 };
        if (!started) ret = chrono::duration_cast<chrono::duration<double>>(duration).count();
        else if (paused) ret = chrono::duration_cast<chrono::duration<double>>(duration - (pauseBegin - startTime)).count();
        else ret = chrono::duration_cast<chrono::duration<double>>(duration - (chrono::high_resolution_clock::now() - startTime)).count();
        return (ret < 0.0) ? 0.0 : ret;
    }

    duration_t remainingTime() const noexcept {
        auto ret = duration_t{ 0ms };
        if (!started) ret = chrono::duration_cast<duration_t>(duration);
        else if (paused) ret = chrono::duration_cast<duration_t>(duration - (pauseBegin - startTime));
        else ret = chrono::duration_cast<duration_t>(duration - (chrono::high_resolution_clock::now() - startTime));
        return (ret < 0ms) ? 0ms : ret;
    }

    bool isPaused() const noexcept { return paused; }

    bool hasFinished() const noexcept { return remainingTime() == 0s; }

    void reset() noexcept {
        started = false;
        paused = true;
    }

private:
    chrono::high_resolution_clock::time_point startTime;
    chrono::high_resolution_clock::time_point endTime;
    chrono::high_resolution_clock::time_point pauseBegin;
    duration_t duration;
    bool paused;
    bool started;
};

int main() {
    countdownTimer timer(10s);
    timer.start();

    while (!timer.hasFinished()) {
        cout << timer.remainingSeconds() << endl;
        this_thread::sleep_for(1s);
    }
}

这是我为我的一个项目编写的一个简单的倒数计时器类。 main()中的客户端代码非常明显,它应该从10输出倒计时到0,然后退出程序。没有优化或-O / -O1,它就是这样做的:

10
8.99495
7.98992
6.9849
5.97981
4.9748
3.96973
2.9687
1.9677
0.966752
Program ended with exit code: 0

但如果我将优化升级到&gt; = -O2,程序只会输出10,并永远运行。倒计时根本不起作用,它停留在起始值。

我在OS X上使用最新的Xcode。clang --versionApple LLVM version 7.3.0 (clang-703.0.31)

奇怪的是,我的代码不包含任何奇怪的自编循环,未定义的行为或类似的东西,它几乎只是标准的库调用,所以优化打破它是非常奇怪的。

有什么想法吗?

PS:我没有在其他编译器上尝试过,但我很乐意。我会用这些结果更新问题。

2 个答案:

答案 0 :(得分:9)

bool started未初始化。 如果您将其初始化为false,则可以使用-O2

live example

您可以使用未定义的行为清理程序找到这样的错误:

$ g++ -std=c++14 -O2 -g -fsanitize=undefined -fno-omit-frame-pointer main.cpp && ./a.out

main.cpp:18:9: runtime error: load of value 106, which is not a valid value for type 'bool'

答案 1 :(得分:6)

错误在你的构造函数中:

 countdownTimer(duration_t duration)
 : duration{ duration }, paused{ true } {}

您忘记初始化started。当您调用start()时,这会触发未定义的行为。

我没有方便访问的clang版本会诊断出这个错误,但是GCC版本5和6(在Linux上 - 我的Mac上没有GCC)将会:

$ g++ -O2 -Wall -Wextra -std=c++14 test.cc
test.cc: In function ‘int main()’:
test.cc:18:13: warning: ‘*((void*)& timer +33)’ is used uninitialized in this function [-Wuninitialized]
         if (started) return;
             ^~~~~~~
test.cc:74:20: note: ‘*((void*)& timer +33)’ was declared here
     countdownTimer timer(10s);
                    ^~~~~

(我的Xcode副本似乎有点过时,Apple LLVM version 7.0.2 (clang-700.1.81);它不会改变-O2程序的行为。你的如果你打开警告,clang会诊断出这个错误。)

(我已在诊断中提交了关于IR gobbledygook的bug report with GCC。)