Intel 64 and IA-32 Architectures Software Developers Manual Volume 1, Basic Architecture

Vol. 1 D-17
GUIDELINES FOR WRITING X87 FPU EXCEPTION HANDLERS
invoked, synchronization must always be considered to assure reliable perfor-
mance.
Example D-1 and Example D-2, below, illustrate the need to always consider excep-
tion synchronization when writing numeric code, even when the code is initially
intended for execution with exceptions masked.
D.3.3.2 Exception Synchronization Examples
In the following examples, three instructions are shown to load an integer, calculate
its square root, then increment the integer. The synchronous execution of the x87
FPU will allow both of these programs to execute correctly, with INC COUNT being
executed in parallel in the processor, as long as no exceptions occur on the FILD
instruction. However, if the code is later moved to an environment where exceptions
are unmasked, the code in Example D-1 will not work correctly:
Example D-1. Incorrect Error Synchronization
FILD COUNT ;x87 FPU instruction
INC COUNT ;integer instruction alters operand
FSQRT ;subsequent x87 FPU instruction -- error
;from previous x87 FPU instruction detected here
Example D-2. Proper Error Synchronization
FILD COUNT ;x87 FPU instruction
FSQRT ;subsequent x87 FPU instruction -- error from
;previous x87 FPU instruction detected here
INC COUNT ;integer instruction alters operand
In some operating systems supporting the x87 FPU, the numeric register stack is
extended to memory. To extend the x87 FPU stack to memory, the invalid exception
is unmasked. A push to a full register or pop from an empty register sets SF (Stack
Fault flag) and causes an invalid operation exception. The recovery routine for the
exception must recognize this situation, fix up the stack, then perform the original
operation. The recovery routine will not work correctly in Example D-1. The problem
is that the value of COUNT increments before the exception handler is invoked, so
that the recovery routine will load an incorrect value of COUNT, causing the program
to fail or behave unreliably.
D.3.3.3 Proper Exception Synchronization
As explained in Section D.2.1.2, “Recommended External Hardware to Support the
MS-DOS Compatibility Sub-mode,” if the x87 FPU encounters an unmasked exception
condition a software exception handler is invoked before execution of the next WAIT
or floating-point instruction. This is because an unmasked floating-point exception