c++ - 将 C++ 映射到程序集

标签 c++ assembly clang

当使用 clang 3.9.1 和优化 (-O2) 编译一些代码时,我在运行时遇到了一些在其他编译器(clang 3.8 和 gcc 6.3)中没有见过的意外行为。

我认为我可能有一些无意的未定义行为(使用 ubsan 编译删除了意外行为)所以我试图简化程序并发现一个特定的函数似乎导致了行为差异。

现在,我正在将程序集映射回 C++,以查看出错的地方,并尝试确定发生这种情况的原因,并且有几个部分我很难映射回。

Godbolt link

C++:

#include <atomic>
#include <cstdint>
#include <cstdlib>
#include <thread>
#include <cstdio>

enum class FooState { A, B };

struct Foo {
  std::atomic<std::int64_t> counter{0};
  std::atomic<std::int64_t> counter_a{0};
  std::atomic<std::int64_t> counter_b{0};
};

//__attribute__((noinline))
FooState to_state(const std::int64_t c) {
  return c >= 0 ? FooState::A : FooState::B;
}

static const int NUM_MODIFIES = 100;

int value_a = 0, value_b = 0;
Foo foo;
std::atomic<std::int64_t> total_sum{0};

void test_function() {
  bool done = false;
  while (!done) {
    const std::int64_t count =
        foo.counter.fetch_add(1, std::memory_order_seq_cst);
    const FooState state = to_state(count);

    int &val = FooState::A == state ? value_a : value_b;
    if (val == NUM_MODIFIES) {
      total_sum += val;
      done = true;
    }

    std::atomic<std::int64_t> &c =
        FooState::A == state ? foo.counter_a : foo.counter_b;
    c.fetch_add(1, std::memory_order_seq_cst);
  }
}

程序集:

test_function():                     # @test_function()
        test    rax, rax
        setns   al
        lock
        inc     qword ptr [rip + foo]
        mov     ecx, value_a
        mov     edx, value_b
        cmovg   rdx, rcx
        cmp     dword ptr [rdx], 100
        je      .LBB1_3
        mov     ecx, foo+8
        mov     edx, value_a
.LBB1_2:                                # =>This Inner Loop Header: Depth=1
        test    al, 1
        mov     eax, foo+16
        cmovne  rax, rcx
        lock
        inc     qword ptr [rax]
        test    rax, rax
        setns   al
        lock
        inc     qword ptr [rip + foo]
        mov     esi, value_b
        cmovg   rsi, rdx
        cmp     dword ptr [rsi], 100
        jne     .LBB1_2
.LBB1_3:
        lock
        add     qword ptr [rip + total_sum], 100
        test    al, al
        mov     eax, foo+8
        mov     ecx, foo+16
        cmovne  rcx, rax
        lock
        inc     qword ptr [rcx]
        ret

我发现将 to_state 标记为 noinline 或将 done 更改为全局似乎可以“修复”意外行为。

我看到的意外行为是,当 counter >= 0 时,counter_a 应该递增,否则 counter_b 应该递增。据我所知,有时这并没有发生,但很难确定确切的时间/原因。

我可以使用一些帮助的程序集的一部分是 test rax, rax; setns altest al, 1 部分。似乎初始测试不会确定性地设置 al 然后该值用于确定要递增的计数器,但也许我误解了一些东西。

下面是一个演示此问题的小示例。当使用 clang 3.9 和 -O2 编译时,它通常会永远挂起,否则会运行到完成。

#include <atomic>
#include <cstdint>
#include <cstdlib>
#include <thread>
#include <cstdio>

enum class FooState { A, B };

struct Foo {
  std::atomic<std::int64_t> counter{0};
  std::atomic<std::int64_t> counter_a{0};
  std::atomic<std::int64_t> counter_b{0};
};

//__attribute__((noinline))
FooState to_state(const std::int64_t c) {
  return c >= 0 ? FooState::A : FooState::B;
}

//__attribute__((noinline))
FooState to_state2(const std::int64_t c) {
  return c >= 0 ? FooState::A : FooState::B;
}

static const int NUM_MODIFIES = 100;

int value_a = 0, value_b = 0;
Foo foo;
std::atomic<std::int64_t> total_sum{0};

void test_function() {
  bool done = false;
  while (!done) {
    const std::int64_t count =
        foo.counter.fetch_add(1, std::memory_order_seq_cst);
    const FooState state = to_state(count);

    int &val = FooState::A == state ? value_a : value_b;
    if (val == NUM_MODIFIES) {
      total_sum += val;
      done = true;
    }

    std::atomic<std::int64_t> &c =
        FooState::A == state ? foo.counter_a : foo.counter_b;
    c.fetch_add(1, std::memory_order_seq_cst);
  }
}

int main() {
  std::thread thread = std::thread(test_function);

  for (std::size_t i = 0; i <= NUM_MODIFIES; ++i) {
    const std::int64_t count =
        foo.counter.load(std::memory_order_seq_cst);
    const FooState state = to_state2(count);

    unsigned log_count = 0;

    auto &inactive_val = FooState::A == state ? value_b : value_a;
    inactive_val = i;

    if (FooState::A == state) {
      foo.counter_b.store(0, std::memory_order_seq_cst);
      const auto accesses_to_wait_for =
          foo.counter.exchange((std::numeric_limits<std::int64_t>::min)(),
                               std::memory_order_seq_cst);
      while (accesses_to_wait_for !=
             foo.counter_a.load(std::memory_order_seq_cst)) {
        std::this_thread::yield();

        if(++log_count <= 10) {
          std::printf("#1 wait_for=%ld, val=%ld\n", accesses_to_wait_for, 
            foo.counter_a.load(std::memory_order_seq_cst));
        }
      }
    } else {
      foo.counter_a.store(0, std::memory_order_seq_cst);

      auto temp = foo.counter.exchange(0, std::memory_order_seq_cst);
      std::int64_t accesses_to_wait_for = 0;
      while (temp != INT64_MIN) {
        ++accesses_to_wait_for;
        --temp;
      }

      while (accesses_to_wait_for !=
             foo.counter_b.load(std::memory_order_seq_cst)) {
        std::this_thread::yield();

        if (++log_count <= 10) {
          std::printf("#2 wait_for=%ld, val=%ld\n", accesses_to_wait_for, 
            foo.counter_b.load(std::memory_order_seq_cst));
        }
      }
    }

    std::printf("modify #%lu complete\n", i);
  }

  std::printf("modifies complete\n");

  thread.join();

  const std::size_t expected_result = NUM_MODIFIES;
  std::printf("%s\n", total_sum == expected_result ? "ok" : "fail");
}

最佳答案

我不是 100% 确定(没有调试它,只是在头脑中模拟),但我认为这两个对 test rax,rax + setns al正在测试错误。

第一个结果取决于是否rax < 0调用函数 (UB) 后,循环内的其他测试将始终为“NS”(测试 rax 中的 32b 地址 => SF=0 => al =1),因此固定 al == 1 对于剩余的循环将始终选择 counter_a .

现在我看了你的问题,你也有同样的怀疑(我只是先看了代码)。

关于c++ - 将 C++ 映射到程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41597341/

相关文章:

assembly - Windows 使用 intel 汇编而 *nix 使用 at&t 是真的吗?

c - 在用 C 语言设计编译器时如何集成汇编代码?

c - 是否可以将汇编指令放入 CUDA 代码中?

c++ - llvm ir 回到人类可读的源语言?

c++ - 如何使用 clang++ 作为编译器链接我的控制台应用程序以 boost OSX 环境中/usr/local/lib 中存在的库

c++ - MSVC 的问题包括

c++ - 为什么int&a=10;在古代 C++ 编译器中有效吗?

c++ - 结构成员的实际总大小

c++ - clang的-Wweak-vtables是什么意思?

c++ - 在 Eigen c++ 中,如何将 NxM 矩阵的每一行乘以 Nx1 标量的 vector ?