user3128376
user3128376

Reputation: 994

What does JS do in Assembly x86?

cmp %al, %cl
js x

I'm confused on what the js (jump on sign) is doing. Is it saying that if al is positive and cl is negative vice versa then jump?

Also, what happens if %cl is 0?

Upvotes: 14

Views: 53613

Answers (2)

Sep Roland
Sep Roland

Reputation: 39166

cmp %al, %cl
js  ...

This cmp instruction, as written in the AT&T syntax, compares the %al and %cl registers to each other. The comparison is made by subtracting the source operand from the destination operand. And because this is AT&T, the source operand is the leftmost operand (so %al) and the destination operand is the rightmost operand (so %cl). Thus the CPU calculates %cl - %al. None of these registers gets modified during the operation.
Both these registers are byte-sized, therefore the temporary result is also considered a byte. Whenever the CPU sees a byte, it considers the eighth bit (so bit 7) as the sign bit of that value. Only if this particular bit is in the set state (holding a 1), will the CPU raise its sign flag SF, part of the EFLAGS register.
Finally, if the SF is set, the js ... instruction will perform the jump. If the SF is not set then the execution just continues sequentially.

Also, what happens if %cl is 0 ?

With a zero in the %cl destination register, the outcome will depend on the value in the %al source register.

  • For all %al = [1,128] the temporary byte-sized value that the CPU calculates will result in a negative number and so the jump is taken.
  • For all %al = {0,[129,255]} the temporary byte-sized value that the CPU calculates will result in a non-negative number and so the jump is not taken.

And what would happen if %al were 0 ?

Then no matter the value in %cl the temporary byte-sized value that the CPU calculates (which is %cl - %al ergo %cl - 0) will result in the value that %cl already holds. Therefore the jump would be taken only if %cl itself were negative. But if that really is our intent then we'd normally be using the test instruction: test %cl, %cl js .... (This alleviates the need for a zero-holding second register to compare with).

Upvotes: 2

Aki Suihkonen
Aki Suihkonen

Reputation: 20017

JS will jump if the sign flag is set (by an earlier instruction). CMP will always modify the flags by performing a subtraction, in this case %cl - %al.
(This is AT&T syntax, so cmp %al, %cl is the same as Intel syntax cmp cl, al)

Because of the operand-size of the instructions, the sign will be bit 7 of the expression %cl-%al (which is thrown away; EFLAGS is updated just like sub, but not al.)

If al == 0, then the temporary value will be cl exactly and the sign will be the sign of the register cl. Thus a jump is taken if cl is negative.

Here's a reference for all the conditional jumps.

Upvotes: 25

Related Questions