Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the sign flag calculated with the imul instruction?

Tags:

x86

assembly

The documentation for imul states that:

SF is updated according to the most significant bit of the operand-size-truncated result in the destination.

For a 64-bit operation, then, my understanding is that SF = (a * b) >> 63, or more simply if a and b are signed, SF = a * b < 0.

However, I'm getting an unexpected result multiplying two large numbers:

mov rax, 0x9090909090909095
mov rdx, 0x4040404040404043
imul rax, rdx

The result of 0x9090909090909095 * 0x4040404040404043 is 0xefcba7835f3b16ff. It has the sign bit set, however the SF flag is cleared after the imul instruction. What's going on?


This was cross-posted to the Intel forums some time ago.

like image 316
zneak Avatar asked Apr 27 '15 16:04

zneak


People also ask

How do I know my sign flag?

The desciption of the sign flag in Intel's manual is "Set equal to the most-significant bit of the result, which is the sign bit of a signed integer. (0 indicates a positive value and 1 indicates a negative value.)". 0xFC clearly has the most significant bit set.

What is the function of Imul instruction?

Description. The single-operand form of imul executes a signed multiply of a byte, word, or long by the contents of the AL, AX, or EAX register and stores the product in the AX, DX:AX or EDX:EAX register respectively.

What is sign flag in assembly language?

The Sign flag indicates that an operation produced a negative result. If the most significant bit of the destination operand is set, the Sign flag is set. • The Parity flag counts the number of 1 bits in the least significant byte of the destination operand.

How many form does Imul instruction have?

This instruction has three forms, depending on the number of operands.


1 Answers

Other sources say that SF is undefined after imul. This most likely means that the result of SF is well-defined on newer processors, but older ones don't offer the feature. My computer being 5 years old, I probably fall with the second category.

EDIT: using Archive.org's Wayback Machine, I found that the documentation changed from stating that SF is undefined to SF is defined in the September 2014 revision. The previous revision, June 2014, still says that SF is undefined. This is documented in the accompanying Documentation Changes document, though the rationale for the change is not.

EDIT 2 My CPU is an i7 M 620. I had access to an even older Core2Duo P7550 and was able to confirm that imul doesn't set SF on it either.

EDIT 3 Starting from the September 2016 edition, IMUL says that SF is undefined, so this resolves the issue.

like image 160
zneak Avatar answered Oct 10 '22 08:10

zneak