本文介绍了为什么noreturn/__ builtin_unreachable阻止尾部调用优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现,如果一个被调用的函数不返回(即标记为 _Noreturn / [[noreturn]] ),则所有主要的编译器都不会进行尾部调用优化.或通话后有 __ builtin_unreachable()).这是预期的行为,而不是错过的优化吗?如果是,为什么?

I have come to fact that all major compilers will not do tail call optimization if a called function does not return (i.e. marked as _Noreturn/[[noreturn]] or there is a __builtin_unreachable() after the call). Is this an intended behavior and not a missed optimization, and if so why?

示例1:

#ifndef __cplusplus
#define NORETURN _Noreturn
#else
#define NORETURN [[noreturn]]
#endif

void canret(void);
NORETURN void noret(void);

void foo(void) { canret(); }
void bar(void) { noret(); }

C: https://godbolt.org/z/pJfEe- C ++: https://godbolt.org/z/-4c78K

示例2:

#ifdef _MSC_VER
#define UNREACHABLE __assume(0)
#else
#define UNREACHABLE __builtin_unreachable()
#endif

void f(void);

void foo(void) { f(); }
void bar(void) { f(); UNREACHABLE; }

https://godbolt.org/z/PFhWKR

推荐答案

这是有意的,尽管可能会引起争议,因为它会严重损害堆栈的使用属性.出于这个原因,我什至使欺骗编译器以为无法返回的函数可以.原因是许多noreturn函数类似于 abort (甚至调用 abort ),并且运行调试器的某人可能希望能够看到调用发生的位置来自-会因尾部呼叫而丢失的信息.

It's intentional, though perhaps controversial since it can seriously harm stack usage properties; for this reason I've even resorted to tricking the compiler to think a function that can't return can. The reasoning is that many noreturn functions are abort-like (or even call abort), and that it's likely someone running a debugger wants to be able to see where the call happened from -- information which would be lost by a tail call.

引用:

这篇关于为什么noreturn/__ builtin_unreachable阻止尾部调用优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 05:20