gpt4 book ai didi

c++ - 为什么 gcc 不能去虚拟化这个函数调用?

转载 作者:IT老高 更新时间:2023-10-28 12:46:11 24 4
gpt4 key购买 nike

#include <cstdio>
#include <cstdlib>
struct Interface {
virtual void f() = 0;
};

struct Impl1: Interface {
void f() override {
std::puts("foo");
}
};

// or __attribute__ ((visibility ("hidden")))/anonymous namespace
static Interface* const ptr = new Impl1 ;

int main() {
ptr->f();
}

用g++-7编译时-O3 -flto -fdevirtualize-at-ltrans -fipa-pta -fuse-linker-plugin,上面的ptr->f() code> call 不能被去虚拟化。

似乎没有外部库可以修改ptr。这是 GCC 优化器的缺陷,还是因为某些其他来源在这种情况下使去虚拟化不可用?

Godbolt link

更新:看来clang-7 with -flto -O3 -fwhole-program-vtables -fvisibility=hidden is the only compiler+flags (as in 2018/03) that can devirtualize this program .

最佳答案

如果您将 ptr 移到 main 函数中,结果会非常有说服力,并强烈暗示 gcc 为什么不想对指针进行去虚拟化。

disassembly for this表明如果 'has the static been initialized flag' 为 false,它会初始化 static,然后直接跳回到虚函数调用,即使在这之间可能没有发生任何事情。

这告诉我 gcc 天生就相信任何类型的全局持久指针都必须始终被视为指向未知类型的指针。

事实上,情况比这还要糟糕。如果添加局部变量,那么在创建局部变量和调用 f 之间是否发生对静态指针上的 f 的调用很重要。显示 f 插入案例的程序集在这里:Another godbolt link ;并且很容易自己在网站上重新安排它,看看一旦没有插入另一个调用,程序集如何变成 f 的内联。

因此,gcc 必须假定,每当控制流出于任何原因离开函数时,指针所指的实际类型可能会发生变化。并且它是否被声明 const 是无关紧要的。如果它的地址被占用或其他任何事情,它也无关紧要。

clang 做同样的事情。这对我来说似乎过于谨慎,但我不是编译器编写者。

关于c++ - 为什么 gcc 不能去虚拟化这个函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48906338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com