Hi,
On Tue, Jul 02, 2013 at 01:37:28AM +0800, Godbach wrote:
> HiWilly,
> There are two patches for your informationwith patch 0002 is just a typo
> fix.
OK applied, thanks.
> For patch 0001, the orignal code confuses me that why bitwise OR isused
> to check if the buffer is empty or not as below:
> static inline int buffer_not_empty(const struct buffer *buf)
> {
> return buf->i | buf->o;
> }
>
> In my opinion, buffer_not_empty() returns a bool type, and logical OR is
> a better choiceas follow:
> static inline int buffer_not_empty(const struct buffer *buf)
> {
> return buf->i || buf->o;
> }
No it's not an error, it's intentional. The result is the same
(eg: only i==0 && o==0 will return 0), except that the bitwise
OR produces more efficient code than the logical one which
depending on the compiler and code will produce conditional jumps
and explicit setting to 1 or 0. Since a boolean true is anything
not zero, we don't care about the output value and we can safely
use a bitwise OR.
Here's a typical example :
int bitwise_or(int a, int b)
{
return a | b;
}
int logical_or(int a, int b)
{
return a || b;
}
The ASM code gives this with gcc 4.2 in x86 mode :
00000000 <bitwise_or>:
0: 8b 44 24 08 mov 0x8(%esp),%eax
4: 0b 44 24 04 or 0x4(%esp),%eax
8: c3 ret
9: 8d 76 00 lea 0x0(%esi),%esi
0000000c <logical_or>:
c: 8b 44 24 04 mov 0x4(%esp),%eax
10: 85 c0 test %eax,%eax
12: 74 08 je 1c <logical_or+0x10>
14: b8 01 00 00 00 mov $0x1,%eax
19: c3 ret
1a: 89 f6 mov %esi,%esi
1c: 31 c0 xor %eax,%eax
1e: 83 7c 24 08 00 cmpl $0x0,0x8(%esp)
23: 0f 95 c0 setne %al
26: c3 ret
Two instructions for the first one, 8 for the second. Some compiler
versions produce better code (especially the older ones), it really
depends in fact. Anyway the first one is always better since it does
not have to build new values.
Best regards,
Willy