[BUG] benchmark::DoNotOptimize does not prevent a reference from being optimized away.

オープン
#1,773 コメント 4 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
35/100
issue の種類
バグ
明瞭さ
説明が足りない
活発さ
停滞
技術スタック
cpp
領域
performance

調査の方向性

benchmark::DoNotOptimize から始め、提供された再現コードを GCC と Clang でコンパイルし、ループ内の参照がある場合とない場合で生成されるアセンブリを比較します。リンクされている Compiler Explorer の例を使って動作を検証します。意味論が確認されて文書化されるか、具体的な変更が定義された時点で issue は完了です。

索引モデルが issue の本文から書いたものです。

説明

Describe the bug
benchmark::DoNotOptimize() does not prevent a reference from being optimized away.

System
OS: Ubuntu 20.04 LTS, Compiler explorer
Compiler: GCC 9.04, GCC trunk, Clang trunk

To reproduce
Compiler Explorer that works: https://godbolt.org/z/c3d5sc8s3
Compiler Explorer that does not: https://godbolt.org/z/3bMMvaecr

Alternatively, compile the following code

#include <vector>
#include <benchmark/benchmark.h>
static void bm_traverse(benchmark::State& state) {
    const size_t N = 500;
    std::vector<int> vec;
    for (size_t j = 0; j < N; ++j) vec.push_back(j);
    for (auto _ : state) {
        for (auto& value : vec) {
            asm("nop"); // just to locate asm point faster
            benchmark::DoNotOptimize(value);
        }
        benchmark::DoNotOptimize(vec);
    }
    state.SetComplexityN(N);
}
BENCHMARK(bm_traverse);
BENCHMARK_MAIN();

Expected behavior
DoNotOptimize should have preserved the loop read. I understand that the reference is basically a pointer but users typically would expect that the reference represents the actual lvalue.

Screenshots

With the "&" reference in the inner loop, a vec load is not generated.

.LBB0_31:                               #   Parent Loop BB0_6 Depth=1
        nop
        addq    $4, %rax
        cmpq    %rcx, %rax
        jne     .LBB0_31

If you remove the reference the vec load is generated.

.LBB0_31:                               #   Parent Loop BB0_6 Depth=1
        movl    (%rax), %edx   # <<<< HERE
        movl    %edx, 12(%rsp)
        nop
        addq    $4, %rax
        cmpq    %rcx, %rax
        jne     .LBB0_31

Additional context

I understand this is a matter of semantics that might have been discussed in the past. In this case, I'd just like confirmation of this behavior.

主要言語
C++
スター
10.5k
フォーク
1.8k
平均マージ
1日 15時間
マージ済み PR(30日)
28

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

google/benchmark のほかの issue

google/benchmark の issue をすべて見る

似ている issue

C++ の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。