22.4. Avoiding conditional jumps by using flags (all processors)


日期: 2000-04-01 14:00 | 联系我
关注我: Telegram, Twitter

22.4. Avoiding conditional jumps by using flags (all processors)

The most important jumps to eliminate are conditional jumps, especially if they are poorly predictable. Sometimes it is possible to obtain the same effect as a branch by ingenious manipulation of bits and flags. For example you may calculate the absolute value of a signed number without branching:

CDQ XOR EAX,EDX SUB EAX,EDX(On PPlain and PMMX, use MOV EDX,EAX / SAR EDX,31 instead of CDQ).

The carry flag is particularly useful for this kind of tricks:

Setting carry if a value is zero: CMP [VALUE],1

Setting carry if a value is not zero: XOR EAX,EAX / CMP EAX,[VALUE]

Incrementing a counter if carry: ADC EAX,0

Setting a bit for each time the carry is set: RCL EAX,1

Generating a bit mask if carry is set: SBB EAX,EAX

Setting a bit on an arbitrary condition: SETcond AL

Setting all bits on an arbitrary condition: XOR EAX,EAX / SETNcond AL / DEC EAX

(remember to reverse the condition in the last example)

The following example finds the minimum of two unsigned numbers: if (b < a) a = b;

SUB EBX,EAX SBB ECX,ECX AND ECX,EBX ADD EAX,ECX

The next example chooses between two numbers: if (a != 0) a = b; else a = c;

CMP EAX,1 SBB EAX,EAX XOR ECX,EBX AND EAX,ECX XOR EAX,EBX

Whether or not such tricks are worth the extra code depends on how predictable a conditional jump would be, whether the extra pairing or scheduling opportunities of the branch-free code can be utilized, and whether there are other jumps following immediately after which could suffer the penalties of consecutive jumps.

标签: MMX 优化

 文章评论
目前没有任何评论.

↓ 快抢占第1楼,发表你的评论和意见 ↓

当前页面是本站的 Google AMP 版本。
欲查看完整版本和发表评论请点击:完整版 »

 

程序员小辉 建站于 1997
Copyright © XiaoHui.com; 保留所有权利。