内建函数

GCC 提供了大量的内建函数,其中很多是标准 C 库函数的内建版本,比如 memcpy,它们与对应的 C
库函数功能相同,这里就不再进行介绍。
还有很多内建函数的名字通常以 __builtin 开始,下面只对__builtin_expect 进行分析并示例,其他
__builtin_xxx 函数的分析可参考这个分析过程。
__builtin_expect (long exp, long c)
遇到这类很陌生的使用方式,GCC 参考手册是我们最好的参考资料。下面是 GCC 参考手册里对
__builtin_expect 的介绍。
long __builtin_expect (long exp, long c)
You may use __builtin_expect to provide the compiler with branch prediction information. In
general, you should prefer to use actual profile feedback for this (‘-fprofile-arcs’), as programmers
are notoriously bad at predicting how their programs actually perform. However, there are
applications in which this data is hard to collect.
The return value is the value of exp, which should be an integral expression. The value of c must
be a compile-time constant. The semantics of the built-in are that it is expected that exp == c.
For example:
if (__builtin_expect (x, 0))
foo ();
would indicate that we do not expect to call foo, since we expect x to be zero. Since
you are limited to integral expressions for exp, you should use constructions such
as
if (__builtin_expect (ptr != NULL, 1))
error ();
when testing pointer or floating-point values

大意是,由于大部分代码在分支预测方面做的比较糟糕,所以 GCC 提供了这个内建的函数来帮助处
理分支预测、优化程序。它的第一个参数 exp 为一个整型的表达式,返回值也是这个 exp。它的第二个参
数 c 的值必须是一个编译期的常量。这个内建函数的意思就是 exp 的预期值为 c,编译器可以根据这个信
息适当地重排条件语句块的顺序,将符合这个条件的分支放在合适的地方。
具体到内核里,比如

++++ include/linux/compiler.h
60 #define likely(x) __builtin_expect(!!(x), 1)
61 #define unlikely(x) __builtin_expect(!!(x), 0)

unlikely(x)用于告诉编译器,条件 x 发生的可能性不大,likely 则相反。它们一般用在条件语句里,if
语句不变,
只是当 if 条件为 1,
即为真的可能性非常小的时候,
可以在条件表达式外面包装一个 unlikely(),
那么这个条件块里语句的目标码可能就会被放在一个比较远的位置,以保证经常执行的目标码更紧凑。如
果可能性非常大,则使用 likely()包装。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值