编译器是否可以删除具有相同定义的重复 Lambda 表达式?

huangapple go评论73阅读模式
英文:

It is possible for compilers to remove duplicate lambdas with the same definitions?

问题

完整的代码可在此处找到:https://godbolt.org/z/7sbxeM3WP

我很好奇编译器是否可以优化以下代码:

constexpr auto lambda = [](){return 5;};
constexpr auto lambda_same_definition = [](){return 5;};

使得只生成一个函数对象。我知道Lambda表达式在底层是如何工作的,为每个表达式创建匿名函数对象。但至少在这里,因为这两个表达式从字符到字符都是相同的,而且它们被存储为constexpr,所以似乎编译器可以将这两个函数对象合并成一个。当然,我怀疑在一般情况下无法做出这种推理,判断两个函数是否相同在一般情况下可能是不可判定的,我猜测。

不幸的是,从我的Godbolt代码片段来看,似乎对于类型名称*NL6lambdaMUlvE_E1NL22lambda_same_definitionMUlvE_E都有信息。

所以我的问题是,这是实现质量的问题吗?还是标准中有什么东西禁止了这种优化?

英文:

Full code available here: https://godbolt.org/z/7sbxeM3WP

I was curious if it would be possible for a compiler to optimize

constexpr auto lambda = [](){return 5;};
constexpr auto lambda_same_definition = [](){return 5;};

such that there would only be one generated functor. I am aware of how lambda expressions work under the hood, creating anonymous functors for each expression. But at least here it looks pretty obvious since the expressions are literally the same, char for char, plus they're stored as constexpr, that it doesn't seem out of the question that the compiler could fold the two functors into one. Of course I doubt this type of reasoning is doable in the general case, determining if two functions are the same sounds would probably be undecidable in the general case I'm guessing.

Unfortunately, it doesn't look like that's the case from my Godbolt snippet, it seems to have info for both under the type names*NL6lambdaMUlvE_E1 and NL22lambda_same_definitionMUlvE_E.

So my question is, is this a quality of implementation issue? Or is there something in the Standard that forbids this optimization?

答案1

得分: 4

每个 lambda 都是一个独特的匿名类。这将是起点。

C++标准允许编译器实施任何没有可观察效果的优化。如果编译器能够证明使用匿名类的单一实例不会产生可观察效果,那么编译器就允许实施它。

所以,如果有人想知道是否“可能”做到这一点,答案是:是的,这是可能的。

您的编译器是否成功实施此优化,只能通过检查编译器生成的实际代码来确定。

英文:

Each lambda is a unique anonymous class. This is going to be the starting point.

The C++ standard allows a compiler to implement any optimization that has no observable effects. If the compiler can prove that using a single instance of the anonymous class will have no observable effects than the compiler is allowed to implement it.

So if someone is wondering "if it would be possible" to do that, the answer is: yes, it's possible.

Whether or not your compiler successfully implements this optimization can only be determined by inspecting the actual code produced by your compiler.

huangapple
  • 本文由 发表于 2023年5月25日 06:40:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76327824.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定