GCC:__ATOMIC_ALWAYS_LOCK_FREE与-O3编译,但不使用-O0

发布于 2025-01-20 03:16:40 字数 497 浏览 3 评论 0原文

示例代码:

int *s;

int foo(void)
{
  return 4;
}

int bar(void)
{
  return __atomic_always_lock_free(foo(), s);
}

调用:

$ gcc t0.c -O3 -c
<nothing>

$ gcc t0.c -O0 -c
t0.c:10:10: error: non-constant argument 1 to '__atomic_always_lock_free'

有什么想法吗?

相关: https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-内置.html

Sample code:

int *s;

int foo(void)
{
  return 4;
}

int bar(void)
{
  return __atomic_always_lock_free(foo(), s);
}

Invocations:

$ gcc t0.c -O3 -c
<nothing>

$ gcc t0.c -O0 -c
t0.c:10:10: error: non-constant argument 1 to '__atomic_always_lock_free'

Any ideas?

Relevant: https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帅冕 2025-01-27 03:16:40

这似乎并不奇怪。您链接的文档说“ size必须解决到编译时常数”,因此可以预期,通过foo(),您可能会出现错误。但是,典型的是,如果GCC能够在编译时确定表达式的值,那么即使它不符合语言对常数表达式的基本定义,它也会将其视为编译时间常数。这可能被认为是扩展名,并由C17标准在6.6p10中明确允许。

优化级别与编译器在编译时试图评估表达式的尝试相关。通过优化,它的作用仅仅是标准所需的基本常数折叠(例如2*4)。通过优化,您将获得其完整的恒定传播通行证以及功能内部的好处。

因此,从本质上讲,在-O0下,编译器没有注意到foo()始终返回相同的值,因为您已经禁用了将其允许其进入的优化得出这个结论。使用-O3它可以,因此它将其作为常数接受。

This doesn't seem surprising. The documentation you linked says that "size must resolve to a compile-time constant" and so it's to be expected that you might get an error when passing foo(). However, it's typical that if GCC is able to determine the value of an expression at compile time, then it will treat it as a compile-time constant, even if it doesn't meet the language's basic definition of a constant expression. This may be considered an extension and is explicitly allowed by the C17 standard at 6.6p10.

The optimization level is relevant to what the compiler tries in attempting to evaluate an expression at compile time. With optimizations off, it does little more than the basic constant folding that the standard requires (e.g. 2*4). With optimizations on, you get the benefit of its full constant propagation pass, as well as function inlining.

So in essence, under -O0, the compiler doesn't notice that foo() always returns the same value, because you've disabled the optimizations that would allow it to reach that conclusion. With -O3 it does and so it accepts it as a constant.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文