# 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.

文章评论

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

 发表你的评论如果你想针对此文发表评论, 请填写下列表单: 姓名: * 必填 (Twitter 用户可输入以 @ 开头的用户名, Steemit 用户可输入 @@ 开头的用户名) E-mail: 可选 (不会被公开。如果我回复了你的评论，你将会收到邮件通知) 反垃圾广告: 为了防止广告机器人自动发贴, 请计算下列表达式的值: 7 x 5 + 4 = * 必填 评论内容: * 必填 你可以使用下列标签修饰文字: [b] 文字 [/b]: 加粗文字 [quote] 文字 [/quote]: 引用文字