Understanding the flag of the sign and overflow in the assembly

This question is about cmp instructions in the assembly. I can’t understand how my books talk about the SF and OF flags.

  cmp vleft, vright 

According to my book: for signed integers, three flags are important: the flag (ZF) , the overflow flag (OF) and the sign (SF) . The overflow flag is set if the result of the operation is overflowed (or overflowed). The sign flag is set if the result of the operation is negative. If vleft = vright , ZF set (as for unsigned integers). If vleft > vright , ZF not specified and SF = OF . If vleft < vright , ZF not specified and SF != OF . Remember that other instructions can also change the case of FLAGS, not just cmp .

First, consider the case vleft > vright . My book says the following:

Why is SF = OF if vleft> vright? If overflow does not occur, the difference will have the correct value and should be non-negative. Thus, SF = OF = 0. However, if there is an overflow, the difference will not have the correct value (and will actually be negative). Thus, SF = OF = 1.

In the first part, I understand that SF = OF = 0 . It could be, for example:

0111 - 0101 = 0111 + 1010 + 1 = 10010 = 7 - 5 = 2

This would not set the OF or SF flag.

A case may also be:

1100 - 0101 = 1100 + 1010 + 1 = 10111 = -4 - 5 = 7 (-9 if we had more bits)

This would not set the SF flag (since the answer is affirmative 7), but would set OF = 1 , thus SF != OF . This is clearly contrary to the explanation of my book, which states that they should be equal.

What am I missing here?

Thanks!

+4
source share
2 answers

You're about to hit your head on the wall, sorry for that :)

In your example, -4 is not more than 5 ! So yes, OF will be 1 , and SF will be 0 , and they will not be equal, which means that -4 is less than 5, and rightly so.

To illustrate the case of SF = OF = 1 , flip the operands: check if 5 > -4 by doing

5 - (-4) = 5 + 4 = 1001b = -7

+5
source

Your book is right about OF == (SF! = CF), when both operands have the same sign. When the operands have a different sign, there cannot be OF.

However, at the RTL level, the OF flag is most often calculated as the difference carry_in! = Carry_out calculated on the sign.

 ie for 1100-0101 = 1100+1010+1 bit position 0: c_in=c_0= 1, a_0 = 0, b_0 = 0; result=1, c_out=0 1: c_in=c_1= 0, a_1 = 0, b_1 = 1; result=1, c_out=0 2: c_in=c_2= 0, a_2 = 1, b_2 = 0; result=1, c_out=0 3: c_in=c_3= 0, a_3 = 1, b_3 = 1; result=0, c_out=1 

Here c_in_3! = C_out_3, which means overflow.

+2
source

All Articles