汇编语言条件跳转与标志位疑问:JAE指令测试条件解析
Hey there! Let's unpack this confusion step by step—this is a super common hurdle when learning assembly flag-based jumps, so you're not alone.
First, let's recap what you already know to ground this:
CMP R1, R2executesR1 - R2under the hood, discards the result, and only updates the CPU's status flags: Carry (CF), Zero (ZF), Sign (SF), Overflow (OF), etc.- Jump instructions like
JAEdon't "know" about R1 and R2 directly—they only check the current state of those flags. The "Tested Conditions" you're seeing are the exact flag combinations each jump instruction looks for.
Let's break down your example: CMP R1, R2 ; JAE somewhere
You're right that this jumps when unsigned R1 >= R2—but why does that map to a specific flag condition?
- For unsigned arithmetic, when you do
R1 - R2, a borrow occurs (CF gets set to 1) only ifR1 < R2. IfR1 >= R2, there's no borrow, so CF stays 0. - That means the "Tested Condition" for
JAEis simplyCF = 0. The jump triggers if this condition is true.
The key here is separating the human-readable semantic (R1 >= R2 for unsigned) from the low-level flag check (CF = 0). The "Tested Conditions" are the latter—the actual logic the CPU uses to decide whether to jump.
Common Jump Instructions & Their Tested Conditions
To make this concrete, here's a breakdown of the most common jump mnemonics, their semantic meaning, and the flag conditions they check:
Unsigned Comparisons (used after CMP for unsigned values)
JA(Jump if Above):CF = 0 AND ZF = 0→R1 > R2(no borrow, and result isn't zero)JAE(Jump if Above or Equal):CF = 0→R1 >= R2(no borrow)JB(Jump if Below):CF = 1→R1 < R2(borrow occurred)JBE(Jump if Below or Equal):CF = 1 OR ZF = 1→R1 <= R2(borrow occurred, or result was zero)
Signed Comparisons (used after CMP for signed values)
Signed comparisons rely on the relationship between Sign (SF) and Overflow (OF) flags:
JG(Jump if Greater):SF = OF AND ZF = 0→R1 > R2(sign matches overflow, result isn't zero)JGE(Jump if Greater or Equal):SF = OF→R1 >= R2(sign matches overflow)JL(Jump if Less):SF != OF→R1 < R2(sign doesn't match overflow)JLE(Jump if Less or Equal):SF != OF OR ZF = 1→R1 <= R2(sign doesn't match overflow, or result was zero)
Why This Matters Beyond CMP
The "Tested Conditions" aren't just for CMP—they work with any instruction that updates flags (like SUB, ADD, AND, etc.). For example, if you run SUB R1, R2 instead of CMP R1, R2, JAE somewhere will still check CF = 0—which corresponds to R1 >= R2 (unsigned) just like it did after CMP, since CMP is essentially a SUB that discards the result.
Once you wrap your head around the fact that jumps only care about the flag states, the "Tested Conditions" stop feeling like arbitrary rules and start making sense as the CPU's way of translating arithmetic results into branch decisions.
内容的提问来源于stack exchange,提问作者hskim

